\input texinfo    @c -*-texinfo-*-
%
% wrs-build.in - main file for the documentation
%
%%%%

%------------------------------------------------------------------------------
%
%                         NOTE FOR THE UNAWARE USER
%                         =========================
%
%    This file is a texinfo source. It isn't the binary file of some strange
%    editor of mine. If you want ASCII, you should "make wrs-build.txt".
%
%------------------------------------------------------------------------------

%
% This is not a conventional info file...
% I use three extra features:
%   - The '%' as a comment marker, if at beginning of line ("\%" -> "%")
%   - leading blanks are allowed (this is something I cannot live without)
%   - braces are automatically escaped when they appear in example blocks
%

@comment %**start of header
@documentlanguage en
@documentencoding ISO-8859-1
@setfilename wrs-build.info
@settitle wrs-build
@iftex
@afourpaper
@end iftex
@paragraphindent none
@comment %**end of header

@setchapternewpage off

@set update-month August 2012

@finalout

@titlepage
@title White Rabbit Switch: software build scripts
@subtitle @value{update-month}
@subtitle How to rebuild the whole software package from sources
@author Alessandro Rubini, Benoit Rat, Federico Vaga et al.
@end titlepage
@headings single

@c ##########################################################################
@iftex
@contents
@end iftex

@c ##########################################################################
@node Top
@top Introduction

This document describes the software build procedures for the White
Rabbit Switch.  The procedure described is for version 3 of the
hardware project, which  has been successfully booted for the first
time on Sep 13th 2011.
The different steps focus on the v3.2, however you can find some
(though limited)
documentation for v3.0 & v3.1 in @ref{Older Hardware Releases}

If you have an older Version-2 switch, please refer to the v2 branch
of the repository at
@code{git://ohwr.org/white-rabbit/wr-switch-sw.git}
(or @code{git@@ohwr.org:white-rabbit/wr-switch-sw.git} if you are
granted write access).

@menu
* Overview::                    
* Building::                    
* Flashing of WRS-3::           
* Booting with Barebox::        
* The Individual Build Steps::  
* Code layout in a production switch::  
* Schematics are Available::    
* Older Hardware Releases::     
* Installing from Jtag::        
* Troubleshooting::             
@end menu

@c ##########################################################################
@node Overview
@chapter Overview

The scripts build over previous work by Tomasz Wlostowski, who first
made the whole thing work and stick together -- a serious result from
serious efforts, I am really amazed by his achievements.

The rewriting described in this document (and embodied in the @code{build/}
subdirectory of the @code{wr-switch-sw} package) is meant to make the stuff
more maintainable over time.  I am an old-fashioned follower of the rule
``first make it work then make it work well'', and this step is expected
to make it work well for everybody.

The purpose of the build-script rewrite is achieving the following targets:

@itemize @bullet
@item One-command build.
	The non-technical user should be able to rebuild the whole software
        package with a single command. This includes the IPL and boot-loader
        even though they are expected to be pre-installed in the switch with
        no real need for upgrading.
@item Sub-package separation.
	Users and developers should be able to rebuild each
        sub-package by itself. Sub-packages are the kernel,
	@i{buildroot}, libraries and so on. If you have a problem (or a
        customization you need on one sub-package), you should be able to work
        on the specific part ignoring the whole as much as possible.
@item Documentation.
	The steps are documented as much as possible, because mishaps
        do happen, and you should easily understand where the problem is.
@item Avoid redundant downloads.
	People with non-mainstream network connections would rather
	avoid downloading the same package over and over. Thus, a centralized
	download directory is defined where all external packages are
        retrieved. Even if you ``make distclean'' in the build scripts you
        will not need re-get everything from the network.  In a similar
        mood, people who already have a local copy of the big packages
        (kernel, u-boot, white-rabbit svn) will not need to re-download not
        even the first time they build the WRS software.
@end itemize

The build system is set up as a mix of scripts and makefiles. Every
sub-package is built by its own script and/or Makefile, and configuration is
passed over through environment variables. The top-level build script
sets all environment variables, while keeping defaults from your
preexisting environment -- so you can override anything even when
rebuilding it all from scratch.

@menu
* Portability::                 
* Environment Variables::       
* Downloading Files::           
@end menu

@c ==========================================================================
@node Portability
@section Portability

The scripts in their current status are not expected to be very
portable. I am sure a number of @i{bashisms} exist, and I did no effort
to even identify them.  To relieve the user from possible pain,
internally the name @i{bash} is used instead of @i{sh}, so things
should work even if your default shell is @i{ash} or @i{dash};
actually the scripts have been tested in one system where the
default @i{sh} is @i{dash}.

Similarly, the scripts are likely to fail if you use spaces in directory
names; that is because not all
uses of shell variables are properly quoted. I urge you to use directory names
with no spaces in them, or to submit a patch to fix the scripts.

It should go without saying that the build environment is expected to
be a native GNU/Linux system; success reports about other environments
(e.g. cygwin) are welcome, possibly with associated patches.

@c ==========================================================================
@node Environment Variables
@section Environment Variables

The scripts use a number of environment variables; you can pre-set
them as you wish. If they are not pre-set, defaults apply as
described below.

When rebuilding everything, the defaults are applied for each unset
variable; but when rebuilding a sub-package you will need to set the
variables beforehand.  Each sub-package complains if it needs variables
that are not set in your environment.

The following variables are used in one or more parts of the scripts;
let me restate, though, that sensible default values apply by default,
so this list is mainly for your curiosity unless you are a developer.

They are listed in an order that seems logical to me, but may sound
random to a different person, please forgive this.  Most of the
variables are prefixed with @code{WRS_} to make them easily identified
in the overall mess of variables and command names (all scripts used here
have a similar prefix for the same reason).

@table @code
@item WRS_BASE_DIR
	The absolute pathname of the build directory (i.e., the @code{build/}
        subdirectory of @code{wr-switch-sw}).
        The variable is internally set to the directory
        name of the main script. Note that the script cannot
        be run from the same directory or from the wr-switch-sw project
        directory (i.e.: @code{./wrs_build-all} @code{./build/wrs_build-all}
        are not allowed), you must call it from your output directory
        using a pathname to  invoke it.  This variable cannot be
        overridden in the main script, but must be pre-set if you run
        a sub-script to rebuild only part of the software suite.

@item WRS_OUTPUT_DIR
	The absolute pathname of the directory where output is placed. It 
	defaults
        to the current directory whence you invoke the script (i.e., you
        can invoke @code{/path/to/wrs_build-all} to have all output
        in the current directory).  Compilation
        happens in a @i{build} subdirectory of @code{WRS_OUTPUT_DIR},
        done-markers are placed in a @i{_done} subdirectory
        and final images are placed in a @i{images} subdirectory.

@item WRS_DOWNLOAD_DIR
	The absolute pathname of the directory where downloaded files 
	are placed. If unset
        it defaults to @code{$WRS_OUTPUT_DIR/downloads}, which is
        created if needed.  By pre-setting this variable you can
        simply recursively delete
        the output directory to force a full rebuild, without
        the overhead of re-downloading everything.

@item WRS_HW_DIR
	The absolute pathname of the directory where you build HDL, if any.
        If this variable is set, FPGA binaries will be copied from there
        instead of being extracted by the official archive on @code{owhr.org}.

@item CROSS_COMPILE
	The variable is the usual cross-compilation prefix. For example,
        @code{arm-linux-} if you have @i{arm-linux-gcc} in your path,
        or a full pathname without the trailing @code{gcc}. If unset,
        it defaults to the compiler that @i{buildroot} self-builds.
        See @ref{The Compiler} for some more details.

@end table

Other variables are used internally in the script; since they are only
useful to people working on the script itself, they are documented in
place.

If you compiled for version 2 you will notice we do not have
@code{WRS_WR_REPOSITORY} any more. We used to rely on upstream
archives to be part of the @i{White Rabbit} subversion tree, but I
did not add the new archives in there because of their size.

@c ==========================================================================
@node Downloading Files
@section Downloading Files

Every downloaded file is saved to the @code{download} directory 
(if set @code{WRS_DOWNLOAD_DIR} else the default
@code{$WRS_OUPUT_DIR/downloads}). You should
arrange not to remove that directory when you recompile over and over
during development. I chose to make the first
script download everything, because I think this eases development in a
way: you first wait a while but can tell download errors from other
issues, and then you can build it all even without a network connection.

For each upstream archive needed, the following steps are performed:

@itemize @bullet
@item If the file exists in the download directory, the @i{md5sum} is
      checked; on success, nothing else is done.
@item If the previous step fails, the file is retrieved from upstream.
@item If the previous step fails, the file is downloaded from the
      buildroot web site.
@end itemize

The policy just described is implemented in @i{wrs_download}, in the file
@code{scripts/wrs_functions}, based on @code{download-info} in the
main build directory.

The messages of a download run are like the following ones:

@smallexample
   2012-01-12 18:30:46: --- Downloading all files
   2012-01-12 18:30:53: Retrieved at91bootstrap-3-3.0.tar.gz from upstream
   2012-01-12 18:31:00: Retrieved buildroot-2011.11.tar.bz2 from upstream
   [...]
   2012-01-12 18:37:53: Retrieved uClibc-0.9.32.tar.bz2 from upstream
   2012-01-12 18:37:56: Retrieved zlib-1.2.5.tar.bz2 from upstream
@end smallexample

@c ##########################################################################
@node Building
@chapter Building

@menu
* Building Procedure::          
* Build Script Description::    
@end menu

@c ==========================================================================
@node Building Procedure
@section Building Procedure
If you just want to build stuff, with no concern about network
downloads and without even knowing what is happening, just create a
directory where you want the output to be generated and start
compilation. Note that it takes around 3GB of storage.

Then run this (but please read more for a better command):

@example
   /path/to/wr-switch-sw/build/wrs_build-all
@end example

Note that progress messages are sent to @i{stderr}, so you may want to
save @i{stdout} to a file, like this (again, it is recommended you read
further for a better command):

@example
   /path/to/wr-switch-sw/build/wrs_build-all > logfile
@end example

Please note that there are also a number of warning messages being
printed to @i{stderr}. It is a few hundred lines over the many
minutes it takes to build @i{buildroot}, but you can safely ignore them,
trusting the build process will complete successfully.

The progress messages look like what is shown here below.  The log
file will be rather big (6 or 7MB or so), as all the compilation steps are
quite verbose.

The following example shows a run on a quad core system (18k
bogoMips in total). If files had already been downloaded, the first
step takes only a pair of seconds to verify the checksums:

@smallexample
2012-07-06 17:23:57: --- Downloading all files
2012-07-06 17:24:02: --- Buildroot compiler and filesystem
2012-07-06 17:24:02: Uncompressing buildroot
2012-07-06 17:24:02: Patching buildroot
2012-07-06 17:24:02: Reconfiguring buildroot
2012-07-06 17:24:04: Compiling buildroot
2012-07-06 17:48:46: --- AT91Boot
2012-07-06 17:48:46: Patching AT91Boot
2012-07-06 17:48:46: Building AT91Boot
2012-07-06 17:48:50: --- Barebox
2012-07-06 17:48:50: Patching Barebox
2012-07-06 17:48:50: Building Barebox
2012-07-06 17:48:59: --- Linux kernel for switch
2012-07-06 17:50:32: --- Kernel modules from this package
2012-07-06 17:50:35: --- PTP daemon (noposix repository as a submodule)
2012-07-06 17:50:38: --- User space tools
2012-07-06 17:50:39: --- Deploying FPGA firmware
2012-07-06 17:50:39: --- Wrapping filesystem
2012-07-06 17:50:53: Complete build succeeded, apparently
@end smallexample

You may prefer to save @i{stderr} with @i{stdout} to the log file
but still see the time-stamped messages from the scripts. In this
case you can issue the following command -- which is what I used
to generate the terse output shown above:

@example
   /path/to/wr-switch-sw/build/wrs_build-all 2>&1 | tee logfile \
        | grep "^20..-..-.. ..:"
@end example

If you are lucky, everything completes by itself. The time taken
depends on you CPU, disk and network speed.
At the end you will find your final files in the @code{images}
subdirectory.  If you are not too lucky, the build stops because
you have found a bug in the build scripts; most likely because your
setup differs from the ones we have been testing on.

In order to re-run the build from the beginning, please remove (or
rename) the output directory and reissue the command.  To only
redo one step, you can remove the marker in @code{build/_done}
(the markers are empty files with name like @code{01-buildroot}
and @code{04-kernel}).

@c ==========================================================================
@node Build Script Description
@section Build Script Description

The @code{wrs_build-all} can be used to quickly build the White Rabbit 
Software as seen above. However it admits other functionalities detailed
in this chapter. You might also want to check its embedded documentation using:

@example
   /path/to/wr-switch-sw/build/wrs_build-all --help
@end example

@menu
* Release Package::             
* Rebuilding Parts::            
* Rebuilding From Scratch::     
@end menu

@c ==========================================================================
@node Release Package
@subsection Release Package

Once all the building steps have succeed, you can easily create a 
package in @code{WRS_OUTPUT_DIR} using the following command:

@example
   /path/to/wr-switch-sw/build/wrs_build-all --pack
@end example 

This will generate a @code{tar.gz} package. The name of the package is composed
by the prefix and the description of the current status of the git repository.
This is the same naming policy the kernel and other packages.

The prefix is @code{wrs-firmware-}; the information about the current status are
retrived by using the git commmand @code{git describe --always --dirty}.
For example, if you are building the tag @code{wr-switch-sw-v3.0}, your package
name will be @code{wrs-firmware-wr-switch-sw-v3.0.tag.gz}. If you are building
on some personal commit the name includes some extra information to describe
your commit: number of commits form the last tag (if any), SHA1 code of the
commit. IF you have uncommited changed, the suffix @code{-dirty} is there too.

@c ==========================================================================
@node Rebuilding Parts
@subsection Rebuilding Parts

When the main script succeeds in building one part (sub-package),
it creates a file in the @code{build/_done} directory.

When you rebuild everything, steps for which the marker file exists
are not rebuilt. To force rebuilding of one specific part, just remove
the marker.  Markers are numbered, reflecting the order of compilation
steps, but they also have a name: names like @code{04-kernel} should be
self-explicative. 

To ease the rebuilding of a specific module a shortcut has been created 
in the @code{wrs_build-all} script. For example if you want to recompile
kernel you should execute.

@example
   /path/to/wr-switch-sw/build/wrs_build-all --step=04
@end example

You can list all compiled module by calling

@example
   /path/to/wr-switch-sw/build/wrs_build-all --list
@end example
 

As an alternative, you can run the individual script from within
@i{scripts/}, after setting the proper environment variables.


@c ==========================================================================
@node Rebuilding From Scratch
@subsection Rebuilding From Scratch

If you have updated the repository with new modifications, you might want 
to check that you can rebuild from scratch. To clean your output 
directory by deleting all compiled modules (except downloaded files), just call:

@example
   /path/to/wr-switch-sw/build/wrs_build-all --clean
@end example


@c ##########################################################################
@node Flashing of WRS-3
@chapter Flashing of WRS-3

This chapter describes the different steps to install the WRS-3 with the 
correct firmware. This procedure describes the installation of the switch
with a @i{SCB v3.2} and a @i{Mini-Backplane v3.2}. If you have an older 
version you might look at the @ref{Older Hardware Releases} and the footnotes.

@menu
* USB connections::             
* Flashing Procedure::          
@end menu

@c ==========================================================================
@node USB connections
@section USB connections

In order to perform the flashing operation easily, you should connect
two @i{mini-USB} cables to the two front panel sockets. One is used
to communicate with the intarnal ROM of the CPU, the other is a serial
port used to interact with the various applications and FPGA. One
of the GPIO pins of the CPU is connected to a switch, so that the
same serial port can be used for either device (CPU and FPGA) in
different times.

@sp 1
@center @image{frontpanel, 7cm,,front panel of the switch}
@sp 1

The diagnostic serial port is the
@b{right} mini-USB @i{(Test)} port of the switch. This is the debug UART
of the ARM (default at boot time) and can later be switched to the FPGA.
Once connected
@code{/dev/ttyUSB0} should appears on your machine, and you can connect
using minicom @footnote{You can use other programs for accessing serial ports, for example @uref{http://brokestream.com/tinyserial.html, tinyserial}} like this:

@example
	minicom -D /dev/ttyUSB0 -b 115200
@end example

Unfortunately, the preferred way to communicate with the CPU internal ROM
is through the other USB port, using the @b{left} mini-USB port of the switch. 
When the ROM is unable to boot user code from its SPI flash memory, it
accepts to be enumerated by the host. You can see the enumerated
device in your own host:

@smallexample
   $ lsusb | grep Atmel
   Bus 001 Device 025: ID 03eb:6124 Atmel Corp. at91sam SAMBA bootloader
@end smallexample

The kernel should automatically load the proper device driver, and you
are expected to see @code{/dev/ttyACM0} or equivalent in your system.

If the device is not enumerated,
this mean that there is already some code in the
@i{dataflash}, which the switch tries to boot. In order to disable the 
dataflash you need to open the switch box and fit a 1mm jumper
@footnote{On v3.0 & v3.1 this jumper does not exist. Refer to 
@ref{Flashing v3.1/v3.0}}
on the @i{DFEN} pin as shown in picture below.  Most of the switches are
shipped with a jumper already plugged between two GND pins. If your switch
has a jumper plugged, you can use it to disable the @i{dataflash}.
a jumper in the switch, 

@sp 1
@center @image{jumpers, 10cm,,Booting jumpers}
@sp 2

With the jumper in place, you should reset the machine pressing 
the button near the 20-pin JTAG connector.  When you see that the
USB device has been enumerated, you should remove the jumper so the
programming procedure can access the @i{dataflash} device.

@c =============================================================================
@node Flashing Procedure
@section Flashing Procedure

The tool used to flash the firmware into the switch is the @i{USB-loader}
we inherited from Atmel. The @file{flash-wrs} script is what
you'll use to run the loader with appropriate parameters.

The script can be invoked in the following way to flash a
 package@footnote{read
@ref{Release Package} to understand how to create a package.} into
the switch:

@example
    /path/to/wr-switch-sw/build/flash-wrs -e wrs-firmware-<revision>.tar.gz 
@end example

The process calls the flasher program twice (so you'll see the
initialization strings two times) an takes around 3 minutes.
This is the a summary of the output you are expected to see,
trimmed to save pages:

@smallexample
   Initializing SAM-BA: CPU ID: 0x819b05a2
   Initializing DDR...
   loading applet isp-extram-at91sam9g45 at 0x00300000
   [...]
   Programming DataFlash...
            @ 0x70000000 : /tmp/at91bootstrap.bin ; size 0xf7c (3Kb)
   DataFlash: Writing 197452 bytes at offset 0x8400 buffer 70000000....
   Programming DataFlash Done!!!
   [...]
   Programming NandFlash...
        @ 0x70100000 : /tmp/zImage ; size 0x1666c4 (1433Kb)
   [...]
   Programming NandFlash Done!!!
   Closing...
@end smallexample

If you look at the serial port, during programming, you will see
messages like these:

@smallexample
   -I- Statup: PMC_MCKR 1202 MCK = 100000000 command = 0
   -I- -- EXTRAM ISP Applet 2.9 --
   -I- -- AT91SAM9G45-EK
   [...]
   -I-     End of applet (command : 2 --- status : 0)
@end smallexample

@menu
* Flash Script Description::    
@end menu

@c -------------------------------------------------------------------
@node Flash Script Description
@subsection Flash Script Description

The @code{flash-wrs} script can be used to quickly flash the White Rabbit switch
as seen above. However it admits other functionalities detailed in this chapter.
You might also want to check its embedded documentations using:

@smallexample
$ ./build/flash-wrs --help
Usage: ./build/flash-wrs [options] MAC [<firmware>.tar.gz] [DEV]

MAC:     MAC address in hexadecimal seperated by ':' (i.e, 00:01:02:03:04:05)
<firmware>.tar.gz: Use the file in the firmware to flash the device
DEV:     The usb device (by default it is /dev/ttyACM0)
Options: 
  -h|--help      Show this help message
  -m|--mode      can be: default, df (dataflash), nf (nandflash), test.
  -e             Completely erase the memory (Can erase your configuration)
  -b|--build     Use file that you have build in the WRS_OUTPUT_DIR
  --test         Use file for testing the switch (not available)
  --silent       Don't ask MAC or S/N and use default 02:0B:AD:C0:FF:EE
@end smallexample

The @i{DEV} is optional. It defaults to @code{/dev/ttyACM0}.
If your system maps the Atmel ROM to a different device name, please
pass the name on the command line. The script wants a full pathname 
starting with @code{/}.

If the @code{--silent} flag is used the MAC will be by default
02:0B:AD:C0:FF:EE; otherwise MAC is mandatory. If MAC is not specified
the script exit.

If you want to flash your own @i{at91boot.bin} or @i{barebox.bin} you
can just place them in the @i{binaries} subdirectory before calling
the script.

You can also flash the image you have build using @ref{Building} by
adding the tag @code{-b|--build}.

Finally you can select a mode using the @code{-m|--mode} flag to choose
to write in dataflash (df), nandflash (nf), both (default) or ddr memories (ddr).
You can also erase the selected memory before write your binaries; to do this
add the option @code{-e}.


The script performs the following steps:

@itemize @bullet
@item It compiles the loader (@i{usb-loader/} subdir).
@item Check if SAMBA bootloader is present.
@item It picks the correct binaries according to the options.
@item Optionally, it changes the default MAC address in @i{barebox}
      default environment, so you can make all switches different.
@item It erases the memory selected by mode.
@item And finally, it writes the corresponding binaries to @i{dataflash}, 
@i{nandflash} or @i{ddr}.
@end itemize

@c ############################################################################
@node Booting with Barebox
@chapter Booting with Barebox

After initial installation, you should reach the following menu.

@example
 Welcome on WRSv3 Boot Sequence
      1: boot from nand (default)      
      2: boot from dataflash (failsafe)
      3: boot from script        
      4: edit & save config            
      5: shell (prompt terminal)       
      6: reset barebox    
@end example

You have multiple choise to boot your switch. The default is the boot
from NAND memory, but you need to install the Linux kernel and the
file system on it before succesfully boot the switch. Please see
@ref{Install Kernel to NAND} to install the kernel and the file system
on the NAND memory.
You can also boot from the DataFlash; this is the failsafe mode, you can
use it when the NAND memory is corrupted.
@c FIXME how can I install on DataFlash?

Script option requires an active network connection and a
TFTP server, optionally a DHCP server. By defaul it uses a DHCP server to
obtain the IP address to connect to the TFTP server.

However, if you do not want to use DHCP you must edit the configuration and
add the following lines@footnote{replace IP addresses with your local
addressing}:


@example
   eth0.ipaddr=192.168.16.9
   eth0.serverip=192.168.16.1
@end example


The script booting procedure asks to the TFTP server a script named
@file{wrboot}. This file can be placed in the root TFTP directory, or
in its direct sub-directory named with the MAC address of the destination
switch. Once the script is loaded, the switch execute it within barabox
to boot the system. You can use this option to write costum kernel
commandline.

Finally in save & edit config you have some parameters to easily fit
the booting process to your need. i.e, Selecting alternative boot method,
forcing alternative boot, etc.

@menu
* Booting from NFS::            
* Install Kernel to NAND::      
@end menu

@c ==========================================================================
@node Booting from NFS
@section Booting from NFS

Assuming you have a known-working NFS-Root installation, a TFTP
server and you don't use the DHCP server; you can write a @file{wrboot}
script to boot the Linux kernel loaded with TFTP and the file system on NFS.
Following an example of a @file{wrboot} script used too boot from NFS.

@example
   eth0.ipaddr=192.168.16.9
   eth0.serverip=192.168.16.1
   addpart /dev/mem  0x400000@@0x71000000(kernel)
   tftp zImage /dev/mem.kernel
   bootargs="$bootargs mem=64m root=nfs nfsroot=/opt/root/wrs,tcp "
   bootargs="$bootargs ip=192.168.16.9:192.168.16.1:255.255.255.0"
   bootz /dev/mem.kernel
@end example

As described above, by using the @i{boot from script} option, barebox 
automatically load your @file{wrboot} script @footnote{See
@ref{Booting with Barebox} to know where place your @file{wrboot}}.

@c ==========================================================================
@node Install Kernel to NAND
@section Install Kernel to NAND

In order to boot from NAND memory, you must install the kernel and
the filesystem  to NAND memory, so you can have a self-hosted switch.
If you already done this step you can skip this procedure and directly
boot from NAND. Pleae note this is not the production release, as some
shortcuts have been taken.

After a successful NFS-Root (See @ref{Booting from NFS}), you'll notice
the system identified two flash devices, for a total of 3 partitions.
Note however that NAND memory may have bad blocks:

@example
   # dmesg | grep -i mtd
   Creating 2 MTD partitions on "atmel_nand":
   mtd_dataflash spi0.0: AT45DB642x (8448 KBytes) pagesize 1056 bytes (OTP)

   # cat /proc/mtd
   dev:    size   erasesize  name
   mtd0: 04000000 00020000 "Partition 1"
   mtd1: 1c000000 00020000 "Partition 2"
   mtd2: 00840000 00000420 "spi0.0-AT45DB642x"

   # dmesg | grep -i bad
   Scanning device for bad blocks
   Bad eraseblock 2 at 0x000000040000
   Bad eraseblock 914 at 0x000007240000
   Bad eraseblock 2649 at 0x000014b20000
   Bad eraseblock 2944 at 0x000017000000
@end example

To set up a boot procedure that doesn't depend on the network,
we need to choose where the place the kernel and filesystem. To
avoid repartitioning the NAND memory let's use the two
partitions we have: mtd0 to fit the kernel and mtd1 for the filesystem.

Please note that the environment of @i{barebox} is stored in NAND
memory from 256k to 512k. The size is so big because @i{barebox}
will skip badblocks within that are.

The suggested setup, thus, is the following:

@example
   0x0000.0000 - 0x0004.0000    Empty (space for a barebox)
   0x0004.0000 - 0x0008.0000    Barebox environment
   0x0008.0000 - 0x0010.0000    Empty (up to 1MB)
   0x0010.0000 - 0x0090.0000    Kernel (plenty of space)
   0x0090.0000 - 0x0400.0000    Empty (up to the end of /dev/mtd0)
   0x0400.0000 - 0x2000.0000    Filesystem space, jffs2
@end example

With this in mind, the installation procedure is as follow:

@table @i

@item  Erase the filesystem partion if needed

	@code{flash_eraseall -j /dev/mtd1}

@item Mount as @i{jffs2}

        @code{mount -t jffs2 /dev/mtdblock1 /mnt}

@item Copy your filesystem data, possibly from the cpio archive

	@code{cd /mnt; zcat /tmp2/wrs-image.cpio.gz | cpio --extract}

	Here, you may want to copy the current NFS-Root filesystem,
        but the @i{cp} command we have on the target lacks the
	@code{-x} (@code{--one-file-system}) option.

@item Umount the filesystem

	@code{cd /; umount /mnt}

@item Erase space for the kernel

	@code{flash_erase /dev/mtd0 0x100000 0x40}

	Note that the offset is in bytes (1MB) and the lenght is in
        number of blocks (each block is 128kB

@item Copy the kernel to nand

	@code{cat /path/to/zImage /dev/zero | cat | dd bs=1k count=2048 > /tmp/k}
        @code{dd if=/tmp/k bs=128k of=/dev/mtd0 seek=8}

	The former command is needed to pad the kernel to a multiple
        of 128kB, as the flash has 128k-sized blocks. The size here
        is 2MB, which is more than enough for our current kernel.

	The latter command copies to @code{/dev/mtd0} as offset 1MB.

@end table

The following repeats the commands in a format that is simpler to cut
and paste to your serial port:

@smallexample
    flash_eraseall -j /dev/mtd1
    mount -t jffs2 /dev/mtdblock1 /mnt
    cd /mnt; zcat /tmp2/wrs-image.cpio.gz | cpio --extract
    cd /; umount /mnt
    flash_erase /dev/mtd0 0x100000 0x40
    cat /path/to/zImage /dev/zero | cat | dd bs=1k count=2048 > /tmp/k
    dd if=/tmp/k bs=128k of=/dev/mtd0 seek=8
@end smallexample

Now, we need to go to @i{barebox} and change the default boot command.
To do it, you need to call @code{edit /env/config} and later
@code{saveenv}.  The internal editor of @i{barebox} is pretty basic, but
it use the arrow keys (it is not like @i{vi}, for your pleasure but
not for mine). To save and exit use @i{ctrl-D}.

@c ##########################################################################
@node The Individual Build Steps
@chapter The Individual Build Steps

This chapter details the individual build steps, for the users that want
to customize their switch in any way. 

@menu
* The Compiler::                
* Buildroot::                   
* The IPL::                     
* The Boot Loader::             
* The Linux Kernel::            
* Kernel Modules::              
* PTPd::                        
* User Space Applications::     
* VHDL Binaries::               
* The Complete Filesystem::     
@end menu

@c ==========================================================================
@node The Compiler
@section The Compiler

The predefined compiler used here is the one built by @i{buildroot}.
The default configuration selects this choice.  If you pre-set a
different @code{CROSS_COMPILE} prefix in your environment, your own
choice will be used by modifying the @i{buildroot} configuration file.
Note, however, that not all cross-compilers will work (@i{buildroot}
wants one that has been configured with @code{--sysroot} and it is
quite unlikely yours has been).

In practice, you may want to set @code{CROSS_COMPILE} when you compile
the boot loader and kernel by themselves, and avoid it when compiling
the complete package.

@c ==========================================================================
@node Buildroot
@section Buildroot

The distribution being used here is @i{buildroot}. It is the first
step being built, because it creates the cross-compiler it will use. This
compiler is later used to compile all other software for the White
Rabbit Switch.

The configuration for @i{buildroot} comes from
@code{patches/buildroot/buildroot-config-wrswitch}. The configuration
is then changed only if you pre-set your own @code{CROSS_COMPILE}
variable.

@c The following can be shown in a set of commands instead of this hard
@c to read explanation.

If you want to change the configuration, you can do so after the first
build iteration: change directory to @code{build/buildroot-2011.11}
and run @code{make menuconfig}. After making your choices, copy back
the file @code{.config} to
@code{patches/buildroot/buildroot-config-wrswitch} in this package.

You can also set @code{WRS_BUILDROOT_CONFIG} to the full pathname of
your configuration file of choice. The file must be a copy of the
@code{.config} after the @code{make menuconfig} step described above.
Note that if the variable is not pointing to a regular file it is
ignored with a simple warning -- rather than stopping the build procedure.

@c ==========================================================================
@node The IPL
@section The IPL

The version of @i{at91bootstrap} being used in the switch as
@i{Initial Program Loader} is version 3.3, download from  @code{timesys.com/}
(the full URL is in @i{build/download-info}.
The patches we applied are in the directory @i{patches/at91boot/v3.3},
and we are piggy-backing on the Atmel
evaluation board without even changing the board name):

@example
   0001-printf-added-files-from-pptp-unchanged.patch
   0002-printf-fixes-and-addition-to-makefile.patch
   0003-build-Add-gitversion-to-binary-and-a-script-to-compi.patch
   0004-board-9g45ek-fix-ddr-config-for-WRS-V3.patch
   0005-boot-disable-watchdog-asap-added-flip_leds-count-run.patch
   0006-boot-Correct-crash-due-to-an-Atmel-bug-during-boot-w.patch
   0007-gpios-Correct-FPGA-LED-problems-and-add-CPU-LEDs-FAN.patch
@end example

The script @i{wrs_build_at91boot} uncompresses, patches and builds, leaving
@code{images/at91bootstrap.bin} after it is over. This file is
the one to be loaded in the hardware.
For simplicity, a known-working binary is part of the @i{binaries}
directory of this package as @code{at91bootstrap.bin}, the same name used
later in the installation instructions.

If you build using a local @i{git} repository, we suggest to use
@code{git am --whitespace=nowarn} because we have a number of
white space errors, and we apologize for that.

@b{Warning}: with most distributions, this compilation step will print
a scary message about memory corruption. The message is reporting a bug in
the configuration program which has no actual effects and can be ignored.
Maybe we will switch to another version in the future that doesn't show
the bug, or to the newer @i{barebox} that obsoletes @i{at91boot}.

@c ==========================================================================
@node The Boot Loader
@section The Boot Loader

The switch uses @i{barebox} as a boot loader. We are running version
2012-05, with a few local patches and the chosen configuration
file. Note that we are piggy-backing on the Ronetix PM9G45 board, out
of laziness.

The patches are part of this package in @i{patches/barebox} and
the set is made up of the following ones:

@smallexample
   0001-sam945-include-mtd-nand.h-in-device-file.patch
   0002-arm-config-added-wrs3_defconfig-and-fixed-default-at.patch
   0003-nand-wrs-it-s-16-bits-not-8.patch
   0004-add-DHCP-retries-by-tom.patch
   0005-gpio-add-function-to-check-them.patch
   0006-startup-load-default-environment-when-loading-env-fa.patch
   0007-nand-Fix-wrongly-removed-line-for-16bits-NAND.patch
   0008-wrs-init-config-script-with-menu-support-v3.2.patch
@end smallexample

If you build using a local @i{git} repository, we suggest to use
@code{git am --whitespace=nowarn} because we have a number of
white space errors, and we apologize for that.

After patching, the build scripts compile with the following commands, where the
cross-compiler is the one built by @i{buildroot}. If you run these
by hand you can use a different compiler (as shown):

@example
   export CROSS_COMPILE=/opt/arm-2010q1/bin/arm-none-eabi-
   export ARCH=arm
   make wrs3_defconfig
   make
   cp barebox.bin /tftpboot/bb.bin
@end example

To use the compiler the scripts use, you need this setting (which is split
in two lines with a local variable to fit the page with in documentation):

@smallexample
   BR=${WRS_OUTPUT_DIR}/build/buildroot-2011.11
   export CROSS_COMPILE=${BR}/output/host/usr/bin/arm-linux-
@end smallexample

A pre-built binary is available as @code{binaries/barebox.bin}.

The ELF version is copied to @i{images} as well, as
@code{images/barebox}; this file includes the symbol table and may (or may not) be
useful.

@c ==========================================================================
@node The Linux Kernel
@section The Linux Kernel

The kernel is currently version 2.6.39, compiled from an uncompressed
tar file (so not within a @i{git} repository).  The upstream
vanilla kernel is downloaded, then
local patches are applied (they come from a @i{git}
repository, but they are currently applied with a simple @i{patch}
command).

The relevant patches are available in @i{patches/kernel/v2.6.39},
and are currently the following ones:

@example
   0001-wrs3-changes-to-g45ek.patch
   0002-initramfs-stop-after-one-cpio-archive.patch
   0003-at91-NR_IRQS-increase-by-64-to-fit-custom-muxes.patch
   0004-irq-export-symbols-for-external-irq-controller.patch
   0005-fix-nand-parition-layout-and-usb-vbus.patch
   0006-fiq-support.patch
@end example

The configuration we use to build the kernel is not a patch but a plan
@code{.config} file, in the same directory as the patches, so you
can change it easily, if needed. As an alternative,
you can also set @code{WRS_KERNEL_CONFIG} to the full pathname of
your configuration file of choice. The file must be a copy of the
@code{.config} found in the main kernel directory,
(for example the one left after the @code{make menuconfig} step).
Note that if the @code{WRS_KERNEL_CONFIG}
variable is not pointing to a regular file it is
ignored with a simple warning, without stopping the build procedure.

The build scripts copy both @i{zImage} and all compiled kernel
modules to the @i{images/} directory of the build place. This currently
includes modules 

@c ==========================================================================
@node Kernel Modules
@section Kernel Modules

In the next step the scripts compile modules that are part of this
package.  The step depends on the kernel being available in the
build directory. The modules are then copied into the @code{images}
subdirectory of the main build directory.

Please note that modules (and later user-space) are compiled in-place;
ie. not in the output directory.  The disadvantage is that your repository
becomes dirty with output and intermediate files. The advantage is that
any modification you make to the code is already in the repository
for your to commit.

Currently, the modules build built are @i{wr_vic.ko} (the interrupt
controller) and @i{wr-nic.ko} (the network ``card'' driver).  The
@i{wr_rtu.ko} driver is compiled too, but it is not currently used nor
has it been tested.

@b{Warning}: I plan to soon rename all modules to have a hyphen
instead of an underscore in the name.

@c ==========================================================================
@node PTPd
@section PTPd

The Precision Time Protocol Daemon being used is hosted in a different
repository, but it is registered as a @i{git} submodule in this package.
The repository itself is on @code{ohwr}, like others.
We are working on a better code base for a portable PTP, but it is
not yet ready as of this release.

A plain @i{make} in the @i{ptp-noposix} directory might fail, because of
missing environment variables. 
because after building
@i{ptpd} other steps are tried, but they are only needed for
the freestanding environment (i.e., LM32 with supporting code) and will
fail for this @i{arm-linux} hosted build.

Additionally,  the script installs headers for the HAL
and @i{libptpnetif}.

@c ==========================================================================
@node User Space Applications
@section User Space Applications

The filesystem of the switch includes some user-space applications
and tools.  Some of the @i{tools} are actually used by the init
scripts and some are just utilities for the developer.

The subdirectories in @file{userspace} include the various applications
needed for the operation of the switch itself, as well as support libraries
used by the applications themselves.

The main components are:

@table @i

@item mini-rpc
	A remote procedure call library used by most other programs
        to exchange information among themselves or query the LM32
        that is running on the FPGA.

@item libswitchhw

	A series of utility functions to access the switch itself.

@item wrsw_hal
	The main application program for the White Rabbit Switch
        operation. The script installs the executable in @code{images/wr/bin}.

@item wrsw_rtud
	The daemon for the routing table unit, used for routing around
        data frames. It is installed in
        @code{images/wr/bin}.

@end table

The most important tools in @file{userspace/tools} are the following:

@table @file

@item load-virtex
@itemx load-lm32

	They load into the FPGA the gateware and the LM32 application.
        They are used by the init scripts of the Linux system.


@item mapper
@itemx wmapper
	The former reads from a file using @i{mmap}
        (usually you run it on @i{/dev/mem}) and writes to @i{stdout}.
        The latter read from @i{stdin} and writes using @i{mmap}.
        They are classic tools distributed in the @i{Linux Device Drivers}
        examples since 1998.

@item com
	The program is a simple program for talking with serial ports.

@item wr_phytool
	A tool to read and write PHY registers in the switch

@item wr_mon
	A simple monitor of White Rabbit status. It prints to @i{stdout}
        using the standard escape sequences.

@end table

Please note that to compile the applications and tools outside of the build
scripts you need to specify both the kernel
directory (@code{LINUX=}) and the cross-compiler to use
(@code{CROSS_COMPILE=}).

@c ==========================================================================
@node VHDL Binaries
@section VHDL and LM32 Binaries

The gateware binaries that are needed to run the FPGA are added to the
target filesystem by the @file{wrs_build_gateware} script. If the
variable @code{WRS_HW_DIR} is set, the script uses it to retrieve the
binaries you just compiled (but the script is not compiling gateware).

If the variable is not set, the script extract a tar file downloaded
from @code{ohwr.org} as part of the initial download step. The tar is
currently called @code{wrs3-gw-v3.0-20120801.tar.gz} and has been
build from the @code{wr-switch-sw-v3.0} of the @code{wr-switch-hdl}
repository.  Please note that the repository uses @i{git} submodules,
so it depends on other @code{ohwr} repositories too, which in turn
have not been tagged because the submodule mechanism ensures you'll
get the exact version you need.

The LM32 program is provided as a precompiled binary in
@code{binaries/rt_cpu.bin}. The respective source code is in the
@file{rt} directory of this package, but the build scripts don't deal
with it to avoid requiring an LM32 development environment.

@c ==========================================================================
@node The Complete Filesystem
@section The Complete Filesystem

The final step in compiling the filesystem is making the CPIO archive
with the overall filesystem contents.  This archive can be used as an
@i{initramfs} or uncompressed to some directory.  The build procedure
does not leave a directory tree on disk because that would require
administrator privileges. I think it is best not to call @i{sudo} from
within build scripts, to respect our users' security concerns.

The output file is called @i{images/wrs-image.cpio.gz} in the build
directory.  You can uncompress it, for example to run NFS-root,
with the following command in a newly-created empty directory:

@example
   zcat $WRS_OUTPUT_DIR/images/wrs-image.cpio.gz | sudo cpio --extract
@end example

The @i{cpio} archive includes a number of device special files in
@i{dev}, even though the configured @i{buildroot} uses @code{mdev -s}
to build all needed devices. The pre-created devices come from
@i{userspace/devices.tar.gz}. Note that the buildroot output
directory, @i{build/buildroot-2011.11/output/target} does not
include any target (and no white-rabbit specific files), so it
cannot be used as a root filesystem by itself.

The @i{cpio} filesystem is built by copying the @i{buildroot} file
tree and overlaying it with @code{userspace/rootfs_override/}; device
files, as said,  are extracted from @code{userspace/devices.tar.gz}.

The @i{root} user has an empty password (set forth in
@code{userspace/rootfs_override/}) and authorizes a few @i{ssh} keys,
to allow @i{ssh} login (and @i{scp}) without the need to provide a
password -- though empty.  The script authorizes the key of the user
running the script and all keys listed in the file @code{authorized_keys}
in the main directory of this package, if present.

@c ##########################################################################
@node Code layout in a production switch
@chapter Code layout in a production switch

@b{NOTE}: This chapter might be out-dated

This is the suggested arrangement of the various binary blobs in the
final switch. Any comment and suggestion is welcome, as nothing
is cast in stone at this point.

The basic idea is to have two systems installed: one is the production
system, that boots by default, and the other is the fail-safe system that
users will be able to boot if they messed up badly with the production
code base.  There will be a button to select the fail-safe system when
needed.

The two boot procedures will be like this:

@table @i

@item Fail-safe boot

	This is using the binaries that are already built by the
        package in its current status.  The IPL lives in @i{dataflash};
        if loads @i{barebox} from @i{dataflash} and the configuration
        fetches the boot procedure from the network.  This gives
        technicians complete freedom to boot whatever they want, either
        fore development or recovery purposes

@item Production boot

	During normal work the switch would boot from NAND flash. The
        IPL lives in NAND memory (the manufactures certifies that the
        first block can never be bad) and it loads a @i{barebox} binary
        from @i{dataflash}. This is a different @i{barebox} than the
        one used in fail-safe boot.  This @i{barebox} loads a kernel
        from NAND memory and runs it, mounting the root filesystem
        from another NAND partition.

@end table

With this setup, the @i{dataflash} can be made read-only when accessed
by Linux, for better safety.  Normal use cases will be able to change
either the kernel or the filesystem (or both) without touching
@i{dataflash}. On the other hand, @i{at91boot} is unable to deal with
bad blocks in NAND, or with correction of single-bit errors; that is
why it will load its @i{barebox} from @i{dataflash}.

The internal CPU ROM will boot from NAND if it finds the magic
signature in there. If no signature is there, it will bot from
@i{dataflash}.  Thus, the production boot will be entered by default;
it will boot the fail-safe sequence only if the NAND flash is erased
(or has never been programmed) or somebody pressed the spacial
@i{fail-safe} at power-up.  The button simply disables the
@i{chip-select} pin of NAND memory; the ROM will fail reading NAND and
will go on booting from @i{dataflash}.

We foresee no issues in making the @i{dataflash} read-only, because
user customization is expected to be limited to the kernel and the
filesystem; we therefor think that preventing accidental erasure of
@i{dataflash} is good policy.  Those users who want to replace their
@i{at91boot} or @i{barebox} will be able to do that anyways, either
from @i{barebox} itself or from a custom build of the kernel.

Later releases of this document will include the complete recovery
procedures, as well as building rules for the production versions of
@i{at91boot} and @i{barebox}.




@c ##########################################################################
@node Schematics are Available
@appendix Schematics are Available

The switch schematics for all PCB versions (3.0, 3.1 and 3.2 of the
SCB as well as both 3.1 and 3.2 of the backplane)
are available on the Open Hardware Repository, at
@uref{http://www.ohwr.org/documents/180}, which can also be reached
from the @i{Documents} tab of the @i{White Rabbit} project.

Plese note that only version 3.2 of both the motherboard and the backplane
has been shipped commercially; you are interested in previous versions only
if you are an early developer and have one of those in your hands.


@c ##########################################################################
@node Older Hardware Releases
@appendix Older Hardware Releases

So, if you have an older PCB in your hands, your hardware is unsupported,
but here are some notes that may be useful.  The differences are minor,
mainly in GPIO routing, but there is no complete list of changes
readily available, unfortunately.

@menu
* Flashing v3.1/v3.0::          
* Serial Ports in 3.0/3.1::     
@end menu

@c ==========================================================================
@node Flashing v3.1/v3.0
@section Flashing v3.1/v3.0

To flash any switch using the USB flasher, you need to force the ROM to 
run the boot protocol called SAMBA Monitor which mean that you must 
prevent the ARM from finding valid code in the @i{data-flash}.

In version 3.2 (see @ref{USB connections}) there is a jumper to
disable dataflash, however for version v3.0 & v3.1 it does not exist. 
Thus, you need to short pins 1 and 4 of the dataflash chip,
so the @code{CS*} pin never goes low and the internal ROM won't be
able to access your @i{at91boot} code.

I used two wires to be shorted together as needed. The next figure
shows both the shorted pins (the @i{dataflash} is on the left and there
are two arrowheads pointing to them) and the
USB cable (on the right).
@sp 1
@center @image{flasher, 14cm}
@sp 1

After shorting the pins you can press reset (the button near the USB
connector). If things go well, the device is enumerated as shown;
you must un-short the wires at this point or you will not be able
to write the new information to @i{dataflash}.

@smallexample
   brezza% lsusb | grep Atmel
   Bus 001 Device 025: ID 03eb:6124 Atmel Corp. at91sam SAMBA bootloader
@end smallexample

The device should also appear as @code{/dev/ttyACM0} or equivalent, and
the further flashing procedure is the same as in versione 3.2.

@c ==========================================================================
@node Serial Ports in 3.0/3.1
@section Serial Ports in 3.0/3.1

If you have a 6-port @i{mini-backplane}, you can connect the 6 pins of P2 to
the similar connector on the backplane labeled as @code{Connect to
MCH/P2}. The backplane hosts a CP2102 USB adapter and a mini-USB
socket.  Note that you may connect all 6 pins, but only TX and RX
signals are needed. If you need more details for this setup, please
write to the mailing list.

The port uses 2.5V signals, but a level converter for 3.3V usually works
without issues or damages; the figure below shows the connection
(black is GND, orange is RX and white is TX).
@sp 1
@center @image{wrs-v3-uart, 5cm}
@sp 1

@c ##########################################################################
@node Installing from Jtag
@appendix Installing from Jtag

As an alternative to the serial flasher, you can take control of the
system with a JTAG debugger. Please note that 
the @i{USB Flasher} is @b{really} the preferred technique, but in case
it doesn't work for your, JTAG is the only way to
communicate with the switch.

Each debugger has its own command language, so you will need to adapt 
to yours. What is shown here refers to the @i{peedi} & @i{sam-ice} tools.
These notes are only aimed at low-level developers and leave a lot
unsaid.

@menu
* Using PEEDI::                 
* Using SAM-ICE::               
* Installation the Boot Loader from JTAG::  
@end menu

@c ==========================================================================
@node Using PEEDI
@section Using PEEDI

As a first step, you will need to ensure the JTAG clock is slow enough.
The clock can be no faster than 1/6th of the CPU clock, so you need
3kHz at most (the G45 starts up with an internal oscillator, which has
an unpredictable value between 20kHz and 40kHz).  Then, I would verify
that the internal SRAM is working; I do that with cool food and bad
coffee instead of the usual smelly dead beef.

@smallexample
   clock init
   mem write 0x300000 0xc001f00d
   mem write 0x300004 0xbadc0ffe
   mem read  0x300000 2
   ==> 0x300000: 0xC001F00D 0xBADC0FFE
@end smallexample

Now, you can load your @i{at91bootstrap} to the internal SRAM,
retrieving it from the network or your host filesystem.  Since no boot
loader is there, you should place a breakpoint after @i{at91bootstrap}
initialized SDRAM and the PLL. Finally you can load @i{barebox} and jump
to it. Such step is better performed with the full JTAG clock, or
it would take several dozen minutes.

@smallexample
  mem load at91bootstrap.bin 0x300000
  break add hard 0x300088
  go
  ## wait for the breakpoint to happen
  break del all
  clock normal
  mem load barebox.bin 0x73f00000
  go
@end smallexample

@c ==========================================================================
@node Using SAM-ICE
@section Using SAM-ICE

This section follows the same steps as in @ref{Using PEEDI}, but using
the syntax of the SAM-ICE tool recommended by Atmel

@example
./start
@end example

Checking SRAM

@smallexample
speed 2
w4 0x300000 0xc001f00d
w4 0x300004 0xcbadc0ffe
mem32 0x300000 2
@end smallexample

Uploading at91bootstrap & barebox to DDR

@smallexample
speed 2
r
wreg "R15 (PC)" 300000
loadbin /tftpboot/at91bootstrap.bin 0x300000
SetBP 0x300088 H #Check 0x300088
g
speed a
loadbin /tftpboot/barebox.bin 0x73f00000
ClrBP 1
g
@end smallexample


@c ==========================================================================
@node Installation the Boot Loader from JTAG
@section Installing the Boot Loader from JTAG

After tou managed to load and run @i{barebox.bin},
you will see the following messages on the serial port, at 115200,8N1.
The first 4 lines are printed by @i{at91bootstrap}, the rest by @i{barebox}.

@c FIXME: the messages and prompts
@smallexample
   Start AT91Bootstrap...
   Begin to load image...
   ++++++++
   Loading image done.


   barebox 2011.09.0-dirty (Sep 12 2011 - 17:09:12)

   Board: Ronetix PM9G45
   Clocks: CPU 400 MHz, master 133 MHz, main 12.000 MHz
   registered netconsole as cs1
   Malloc space: 0x73b00000 -> 0x73f00000 (size  4 MB)
   Stack space : 0x73af8000 -> 0x73b00000 (size 32 kB)
   Open /dev/env0 No such file or directory
   no valid environment found on /dev/env0. Using default environment
   running /env/bin/init...

   Hit any key to stop autoboot:  2
   barebox@@Ronetix PM9G45:/
@end smallexample

When the boot loader is running, you can boot a kernel and use its
own @i{/dev/mtd} devices to write to the DataFlash and NAND memories.

According to the partition table you have in your kernel sources, you will
see a different set of @i{mtd} files, but you can identify them by looking
at @code{/proc/mtd}:

@c FIXME: mtd layout
@example
   # cat /proc/mtd
   dev:    size   erasesize  name
   mtd0: 04000000 00020000 "Partition 1"
   mtd1: 1c000000 00020000 "Partition 2"
   mtd2: 00840000 00000420 "spi0.0-AT45DB642x"
@end example

Here above, the DataFlash is @i{/dev/mtd2}, whereas the former partitions
refer to NAND memory.  You should then write @i{at91boot} to offset 0
of the DataFlash and @i{barebox} to offset 0x8400 (33792):

@example
   cat at91bootstrap.bin > /dev/mtd2
   dd bs=33792 seek=1 if=barebox.bin of=/dev/mtd2
@end example

Now you can detach the debugger, press reset and see @i{barebox} starting
without the need for the JTAG any more. The following stes are the same
as already described.

@c ##########################################################################
@node Troubleshooting
@appendix Troubleshooting

This chapter includes notes about issues we found and how to address them,
or extra tools. The information is not exaustive nor complete, but we
hope to extend this chapter over time, if any of our users have
problems with the released package.

@menu
* Testing SDRAM::               
@end menu

@c ==========================================================================
@node Testing SDRAM
@section Testing SDRAM

@b{Note}: This section is imcomplete, if needed please ask to the
mailing list.

In case you suspect to have RAM issues and are not even able to boot
@i{barebox}, this package offers the program @i{g45memtest}. It is a
merge of @i{at91boot} and @code{commands/memtest.c} from barebox, with
the small @i{printf} I use in other projects (e.g. @i{pptp}).

The binary is included in the package as @code{binaries/g45memtest}.
It should be loaded like @code{at91boot}: it configures the RAM and
the PLL, and then runs the test.

The source is distributed as a patch-set over @i{at91boot} (the same
version we use to boot the switch), in @code{patches/g45memtest}.  To
compile, untar the source, apply the patches and compile.  The
following commands are what I used to compile it (you will need to set
@code{CROSS_COMPILE} first, though).

@example
   tar xzf ${WRS_DOWNLOAD_DIR}/at91bootstrap-3-3.0.tar.gz
   cd at91bootstrap-3-3.0
   git init
   git add .
   git commit -m "original code"
   git am --whitespace=nowarn $WRS_BASE_DIR/../patches/g45memtest/00*
   make at91sam9g45ek_defconfig
   make
@end example

The output binary is the only file called ``@code{binaries/*.bin}'',
that should be renamed to @code{g45memtest}.

@c ##########################################################################
@bye


@c  LocalWords:  gnudd titlepage iftex texinfo CERN timestamping smallexample
@c  LocalWords:  LocalWords ietf timestamp misc timestamps ttstamp onestamp
@c  LocalWords:  Tomasz Wlostowski buildroot distclean defconfig wrswitch REPO
@c  LocalWords:  menuconfig config dataflash whiterabbit stdout stderr svnsync
@c  LocalWords:  filesystem diff ohwr http mkdir linux rubini itemize PTPd VHDL
@c  LocalWords:  noposix ptpd userspace libswitchhw DataFlash NAND barebox FPGA
@c  LocalWords:  Atmel
