This User's Guide documents release 0.10.0, dated 8 February 2019, of
the Open On-Chip Debugger (OpenOCD).

   * Copyright (C) 2008 The OpenOCD Project
   * Copyright (C) 2007-2008 Spencer Oliver <spen@spen-soft.co.uk>
   * Copyright (C) 2008-2010 Oyvind Harboe <oyvind.harboe@zylin.com>
   * Copyright (C) 2008 Duane Ellis <openocd@duaneellis.com>
   * Copyright (C) 2009-2010 David Brownell

     Permission is granted to copy, distribute and/or modify this
     document under the terms of the GNU Free Documentation License,
     Version 1.2 or any later version published by the Free Software
     Foundation; with no Invariant Sections, with no Front-Cover Texts,
     and with no Back-Cover Texts.  A copy of the license is included in
     the section entitled "GNU Free Documentation License".

17 JTAG Commands
****************

Most general purpose JTAG commands have been presented earlier.  (see
JTAG Speed, Reset Configuration, and TAP Declaration.)
Lower level JTAG commands, as presented here, may be
needed to work with targets which require special attention during
operations such as reset or initialization.

To use these commands you will need to understand some of the basics of
JTAG, including:

   * A JTAG scan chain consists of a sequence of individual TAP devices
     such as a CPUs.
   * Control operations involve moving each TAP through the same
     standard state machine (in parallel) using their shared TMS and
     clock signals.
   * Data transfer involves shifting data through the chain of
     instruction or data registers of each TAP, writing new register
     values while the reading previous ones.
   * Data register sizes are a function of the instruction active in a
     given TAP, while instruction register sizes are fixed for each TAP.
     All TAPs support a BYPASS instruction with a single bit data
     register.
   * The way OpenOCD differentiates between TAP devices is by shifting
     different instructions into (and out of) their instruction
     registers.

17.1 Low Level JTAG Commands
============================

These commands are used by developers who need to access JTAG
instruction or data registers, possibly controlling the order of TAP
state transitions.  If you're not debugging OpenOCD internals, or
bringing up a new JTAG adapter or a new type of TAP device (like a CPU
or JTAG router), you probably won't need to use these commands.  In a
debug session that doesn't use JTAG for its transport protocol, these
commands are not available.

 -- Command: drscan tap [numbits value]+ ['-endstate' tap_state]
     Loads the data register of TAP with a series of bit fields that
     specify the entire register.  Each field is NUMBITS bits long with
     a numeric VALUE (hexadecimal encouraged).  The return value holds
     the original value of each of those fields.

     For example, a 38 bit number might be specified as one field of 32
     bits then one of 6 bits.  _For portability, never pass fields which
     are more than 32 bits long.  Many OpenOCD implementations do not
     support 64-bit (or larger) integer values._

     All TAPs other than TAP must be in BYPASS mode.  The single bit in
     their data registers does not matter.

     When TAP_STATE is specified, the JTAG state machine is left in that
     state.  For example DRPAUSE might be specified, so that more
     instructions can be issued before re-entering the RUN/IDLE state.
     If the end state is not specified, the RUN/IDLE state is entered.

          Warning: OpenOCD does not record information about data
          register lengths, so _it is important that you get the bit
          field lengths right_.  Remember that different JTAG
          instructions refer to different data registers, which may have
          different lengths.  Moreover, those lengths may not be fixed;
          the SCAN_N instruction can change the length of the register
          accessed by the INTEST instruction (by connecting a different
          scan chain).

 -- Command: flush_count
     Returns the number of times the JTAG queue has been flushed.  This
     may be used for performance tuning.

     For example, flushing a queue over USB involves a minimum latency,
     often several milliseconds, which does not change with the amount
     of data which is written.  You may be able to identify performance
     problems by finding tasks which waste bandwidth by flushing small
     transfers too often, instead of batching them into larger
     operations.

 -- Command: irscan [tap instruction]+ ['-endstate' tap_state]
     For each TAP listed, loads the instruction register with its
     associated numeric INSTRUCTION.  (The number of bits in that
     instruction may be displayed using the 'scan_chain' command.)  For
     other TAPs, a BYPASS instruction is loaded.

     When TAP_STATE is specified, the JTAG state machine is left in that
     state.  For example IRPAUSE might be specified, so the data
     register can be loaded before re-entering the RUN/IDLE state.  If
     the end state is not specified, the RUN/IDLE state is entered.

          Note: OpenOCD currently supports only a single field for
          instruction register values, unlike data register values.  For
          TAPs where the instruction register length is more than 32
          bits, portable scripts currently must issue only BYPASS
          instructions.

 -- Command: jtag_reset trst srst
     Set values of reset signals.  The TRST and SRST parameter values
     may be '0', indicating that reset is inactive (pulled or driven
     high), or '1', indicating it is active (pulled or driven low).  The
     'reset_config' command should already have been used to configure
     how the board and JTAG adapter treat these two signals, and to say
     if either signal is even present.  See Reset Configuration.

     Note that TRST is specially handled.  It actually signifies JTAG's
     RESET state.  So if the board doesn't support the optional TRST
     signal, or it doesn't support it along with the specified SRST
     value, JTAG reset is triggered with TMS and TCK signals instead of
     the TRST signal.  And no matter how that JTAG reset is triggered,
     once the scan chain enters RESET with TRST inactive, TAP
     'post-reset' events are delivered to all TAPs with handlers for
     that event.

 -- Command: pathmove start_state [next_state ...]
     Start by moving to START_STATE, which must be one of the _stable_
     states.  Unless it is the only state given, this will often be the
     current state, so that no TCK transitions are needed.  Then, in a
     series of single state transitions (conforming to the JTAG state
     machine) shift to each NEXT_STATE in sequence, one per TCK cycle.
     The final state must also be stable.

 -- Command: runtest NUM_CYCLES
     Move to the RUN/IDLE state, and execute at least NUM_CYCLES of the
     JTAG clock (TCK). Instructions often need some time to execute
     before they take effect.

 -- Command: verify_ircapture ('enable'|'disable')
     Verify values captured during IRCAPTURE and returned during IR
     scans.  Default is enabled, but this can be overridden by
     'verify_jtag'.  This flag is ignored when validating JTAG chain
     configuration.

 -- Command: verify_jtag ('enable'|'disable')
     Enables verification of DR and IR scans, to help detect programming
     errors.  For IR scans, 'verify_ircapture' must also be enabled.
     Default is enabled.

17.2 TAP state names
====================

The TAP_STATE names used by OpenOCD in the 'drscan', 'irscan', and
'pathmove' commands are the same as those used in SVF boundary scan
documents, except that SVF uses IDLE instead of RUN/IDLE.

   * RESET ...  _stable_ (with TMS high); acts as if TRST were pulsed
   * RUN/IDLE ...  _stable_; don't assume this always means IDLE
   * DRSELECT
   * DRCAPTURE
   * DRSHIFT ...  _stable_; TDI/TDO shifting through the data register
   * DREXIT1
   * DRPAUSE ...  _stable_; data register ready for update or more
     shifting
   * DREXIT2
   * DRUPDATE
   * IRSELECT
   * IRCAPTURE
   * IRSHIFT ...  _stable_; TDI/TDO shifting through the instruction
     register
   * IREXIT1
   * IRPAUSE ...  _stable_; instruction register ready for update or
     more shifting
   * IREXIT2
   * IRUPDATE

Note that only six of those states are fully "stable" in the face of TMS
fixed (low except for RESET) and a free-running JTAG clock.  For all the
others, the next TCK transition changes to a new state.

   * From DRSHIFT and IRSHIFT, clock transitions will produce side
     effects by changing register contents.  The values to be latched in
     upcoming DRUPDATE or IRUPDATE states may not be as expected.
   * RUN/IDLE, DRPAUSE, and IRPAUSE are reasonable choices after
     'drscan' or 'irscan' commands, since they are free of JTAG side
     effects.
   * RUN/IDLE may have side effects that appear at non-JTAG levels, such
     as advancing the ARM9E-S instruction pipeline.  Consult the
     documentation for the TAP(s) you are working with.

18 Boundary Scan Commands
*************************

One of the original purposes of JTAG was to support boundary scan based
hardware testing.  Although its primary focus is to support On-Chip
Debugging, OpenOCD also includes some boundary scan commands.

18.1 SVF: Serial Vector Format
==============================

The Serial Vector Format, better known as "SVF", is a way to represent
JTAG test patterns in text files.  In a debug session using JTAG for its
transport protocol, OpenOCD supports running such test files.

 -- Command: svf filename ['quiet']
     This issues a JTAG reset (Test-Logic-Reset) and then runs the SVF
     script from 'filename'.  Unless the 'quiet' option is specified,
     each command is logged before it is executed.

18.2 XSVF: Xilinx Serial Vector Format
======================================

The Xilinx Serial Vector Format, better known as "XSVF", is a binary
representation of SVF which is optimized for use with Xilinx devices.
In a debug session using JTAG for its transport protocol, OpenOCD
supports running such test files.

     Important: Not all XSVF commands are supported.

 -- Command: xsvf (tapname|'plain') filename ['virt2'] ['quiet']
     This issues a JTAG reset (Test-Logic-Reset) and then runs the XSVF
     script from 'filename'.  When a TAPNAME is specified, the commands
     are directed at that TAP. When 'virt2' is specified, the XRUNTEST
     command counts are interpreted as TCK cycles instead of
     microseconds.  Unless the 'quiet' option is specified, messages are
     logged for comments and some retries.

The OpenOCD sources also include two utility scripts for working with
XSVF; they are not currently installed after building the software.  You
may find them useful:

   * _svf2xsvf_ ...  converts SVF files into the extended XSVF syntax
     understood by the 'xsvf' command; see notes below.
   * _xsvfdump_ ...  converts XSVF files into a text output format;
     understands the OpenOCD extensions.

The input format accepts a handful of non-standard extensions.  These
include three opcodes corresponding to SVF extensions from Lattice
Semiconductor (LCOUNT, LDELAY, LDSR), and two opcodes supporting a more
accurate translation of SVF (XTRST, XWAITSTATE). If _xsvfdump_ shows a
file is using those opcodes, it probably will not be usable with other
XSVF tools.

19 Utility Commands
*******************

19.1 RAM testing
================

There is often a need to stress-test random access memory (RAM) for
errors.  OpenOCD comes with a Tcl implementation of well-known memory
testing procedures allowing the detection of all sorts of issues with
electrical wiring, defective chips, PCB layout and other common hardware
problems.

To use them, you usually need to initialise your RAM controller first;
consult your SoC's documentation to get the recommended list of register
operations and translate them to the corresponding 'mww'/'mwb' commands.

Load the memory testing functions with

     source [find tools/memtest.tcl]

to get access to the following facilities:

 -- Command: memTestDataBus address
     Test the data bus wiring in a memory region by performing a walking
     1's test at a fixed address within that region.

 -- Command: memTestAddressBus baseaddress size
     Perform a walking 1's test on the relevant bits of the address and
     check for aliasing.  This test will find single-bit address
     failures such as stuck-high, stuck-low, and shorted pins.

 -- Command: memTestDevice baseaddress size
     Test the integrity of a physical memory device by performing an
     increment/decrement test over the entire region.  In the process
     every storage bit in the device is tested as zero and as one.

 -- Command: runAllMemTests baseaddress size
     Run all of the above tests over a specified memory region.

19.2 Firmware recovery helpers
==============================

OpenOCD includes an easy-to-use script to facilitate mass-market devices
recovery with JTAG.

For quickstart instructions run:
     openocd -f tools/firmware-recovery.tcl -c firmware_help

20 TFTP
*******

If OpenOCD runs on an embedded host (as ZY1000 does), then TFTP can be
used to access files on PCs (either the developer's PC or some other
PC).

The way this works on the ZY1000 is to prefix a filename by "/tftp/ip/"
and append the TFTP path on the TFTP server (tftpd).  For example,

     load_image /tftp/10.0.0.96/c:\temp\abc.elf

will load c:\temp\abc.elf from the developer pc (10.0.0.96) into memory
as if the file was hosted on the embedded host.

In order to achieve decent performance, you must choose a TFTP server
that supports a packet size bigger than the default packet size (512
bytes).  There are numerous TFTP servers out there (free and commercial)
and you will have to do a bit of googling to find something that fits
your requirements.

21 GDB and OpenOCD
******************

OpenOCD complies with the remote gdbserver protocol and, as such, can be
used to debug remote targets.  Setting up GDB to work with OpenOCD can
involve several components:

   * The OpenOCD server support for GDB may need to be configured.
     See GDB Configuration.
   * GDB's support for OpenOCD may need configuration, as shown in this
     chapter.
   * If you have a GUI environment like Eclipse, that also will probably
     need to be configured.

Of course, the version of GDB you use will need to be one which has been
built to know about the target CPU you're using.  It's probably part of
the tool chain you're using.  For example, if you are doing
cross-development for ARM on an x86 PC, instead of using the native x86
'gdb' command you might use 'arm-none-eabi-gdb' if that's the tool chain
used to compile your code.

21.1 Connecting to GDB
======================

Use GDB 6.7 or newer with OpenOCD if you run into trouble.  For instance
GDB 6.3 has a known bug that produces bogus memory access errors, which
has since been fixed; see
<http://osdir.com/ml/gdb.bugs.discuss/2004-12/msg00018.html>

OpenOCD can communicate with GDB in two ways:

  1. A socket (TCP/IP) connection is typically started as follows:
          target remote localhost:3333
     This would cause GDB to connect to the gdbserver on the local pc
     using port 3333.

     It is also possible to use the GDB extended remote protocol as
     follows:
          target extended-remote localhost:3333
  2. A pipe connection is typically started as follows:
          target remote | openocd -c "gdb_port pipe; log_output openocd.log"
     This would cause GDB to run OpenOCD and communicate using pipes
     (stdin/stdout).  Using this method has the advantage of GDB
     starting/stopping OpenOCD for the debug session.  log_output sends
     the log output to a file to ensure that the pipe is not saturated
     when using higher debug level outputs.

To list the available OpenOCD commands type 'monitor help' on the GDB
command line.

21.2 Sample GDB session startup
===============================

With the remote protocol, GDB sessions start a little differently than
they do when you're debugging locally.  Here's an example showing how to
start a debug session with a small ARM program.  In this case the
program was linked to be loaded into SRAM on a Cortex-M3.  Most programs
would be written into flash (address 0) and run from there.

     $ arm-none-eabi-gdb example.elf
     (gdb) target remote localhost:3333
     Remote debugging using localhost:3333
     ...
     (gdb) monitor reset halt
     ...
     (gdb) load
     Loading section .vectors, size 0x100 lma 0x20000000
     Loading section .text, size 0x5a0 lma 0x20000100
     Loading section .data, size 0x18 lma 0x200006a0
     Start address 0x2000061c, load size 1720
     Transfer rate: 22 KB/sec, 573 bytes/write.
     (gdb) continue
     Continuing.
     ...

You could then interrupt the GDB session to make the program break, type
'where' to show the stack, 'list' to show the code around the program
counter, 'step' through code, set breakpoints or watchpoints, and so on.

21.3 Configuring GDB for OpenOCD
================================

OpenOCD supports the gdb 'qSupported' packet, this enables information
to be sent by the GDB remote server (i.e.  OpenOCD) to GDB. Typical
information includes packet size and the device's memory map.  You do
not need to configure the packet size by hand, and the relevant parts of
the memory map should be automatically set up when you declare (NOR)
flash banks.

However, there are other things which GDB can't currently query.  You
may need to set those up by hand.  As OpenOCD starts up, you will often
see a line reporting something like:

     Info : lm3s.cpu: hardware has 6 breakpoints, 4 watchpoints

You can pass that information to GDB with these commands:

     set remote hardware-breakpoint-limit 6
     set remote hardware-watchpoint-limit 4

With that particular hardware (Cortex-M3) the hardware breakpoints only
work for code running from flash memory.  Most other ARM systems do not
have such restrictions.

Another example of useful GDB configuration came from a user who found
that single stepping his Cortex-M3 didn't work well with IRQs and an
RTOS until he told GDB to disable the IRQs while stepping:

     define hook-step
     mon cortex_m maskisr on
     end
     define hookpost-step
     mon cortex_m maskisr off
     end

Rather than typing such commands interactively, you may prefer to save
them in a file and have GDB execute them as it starts, perhaps using a
'.gdbinit' in your project directory or starting GDB using 'gdb -x
filename'.

21.4 Programming using GDB
==========================

By default the target memory map is sent to GDB. This can be disabled by
the following OpenOCD configuration option:
     gdb_memory_map disable
For this to function correctly a valid flash configuration must also be
set in OpenOCD. For faster performance you should also configure a valid
working area.

Informing GDB of the memory map of the target will enable GDB to protect
any flash areas of the target and use hardware breakpoints by default.
This means that the OpenOCD option 'gdb_breakpoint_override' is not
required when using a memory map.  See gdb_breakpoint_override.

To view the configured memory map in GDB, use the GDB command 'info
mem'.  All other unassigned addresses within GDB are treated as RAM.

GDB 6.8 and higher set any memory area not in the memory map as
inaccessible.  This can be changed to the old behaviour by using the
following GDB command
     set mem inaccessible-by-default off

If 'gdb_flash_program enable' is also used, GDB will be able to program
any flash memory using the vFlash interface.

GDB will look at the target memory map when a load command is given, if
any areas to be programmed lie within the target flash area the vFlash
packets will be used.

If the target needs configuring before GDB programming, an event script
can be executed:
     $_TARGETNAME configure -event EVENTNAME BODY

To verify any flash programming the GDB command 'compare-sections' can
be used.

21.5 Using OpenOCD SMP with GDB
===============================

For SMP support following GDB serial protocol packet have been defined :
   * j - smp status request
   * J - smp set request

OpenOCD implements :
   * 'jc' packet for reading core id displayed by GDB connection.  Reply
     is 'XXXXXXXX' (8 hex digits giving core id) or 'E01' for target not
     smp.
   * 'JcXXXXXXXX' (8 hex digits) packet for setting core id displayed at
     next GDB continue (core id -1 is reserved for returning to normal
     resume mode).  Reply 'E01' for target not smp or 'OK' on success.

Handling of this packet within GDB can be done :
   * by the creation of an internal variable (i.e '_core') by mean of
     function allocate_computed_value allowing following GDB command.
          set $_core 1
          #Jc01 packet is sent
          print $_core
          #jc packet is sent and result is affected in $

   * by the usage of GDB maintenance command as described in following
     example (2 cpus in SMP with core id 0 and 1 Define CPU targets working in SMP).

          # toggle0 : force display of coreid 0
          define toggle0
          maint packet Jc0
          continue
          main packet Jc-1
          end
          # toggle1 : force display of coreid 1
          define toggle1
          maint packet Jc1
          continue
          main packet Jc-1
          end

21.6 RTOS Support
=================

OpenOCD includes RTOS support, this will however need enabling as it
defaults to disabled.  It can be enabled by passing '-rtos' arg to the
target.  See RTOS Type.

See Debugging Programs with Multiple Threads (gdb), for
details about relevant GDB commands.

An example setup is below:

     $_TARGETNAME configure -rtos auto

This will attempt to auto detect the RTOS within your application.

Currently supported rtos's include:
   * 'eCos'
   * 'ThreadX'
   * 'FreeRTOS'
   * 'linux'
   * 'ChibiOS'
   * 'embKernel'
   * 'mqx'
   * 'uCOS-III'

     Note: Before an RTOS can be detected, it must export certain
     symbols; otherwise, it cannot be used by OpenOCD. Below is a list
     of the required symbols for each supported RTOS.

'eCos symbols'
     Cyg_Thread::thread_list, Cyg_Scheduler_Base::current_thread.
'ThreadX symbols'
     _tx_thread_current_ptr, _tx_thread_created_ptr,
     _tx_thread_created_count.
'FreeRTOS symbols'
'linux symbols'
     init_task.
'ChibiOS symbols'
     rlist, ch_debug, chSysInit.
'embKernel symbols'
     Rtos::sCurrentTask, Rtos::sListReady, Rtos::sListSleep,
     Rtos::sListSuspended, Rtos::sMaxPriorities,
     Rtos::sCurrentTaskCount.
'mqx symbols'
     _mqx_kernel_data, MQX_init_struct.
'uC/OS-III symbols'
     OSRunning, OSTCBCurPtr, OSTaskDbgListPtr, OSTaskQty

For most RTOS supported the above symbols will be exported by default.
However for some, eg.  FreeRTOS and uC/OS-III, extra steps must be
taken.

These RTOSes may require additional OpenOCD-specific file to be linked
along with the project:

'FreeRTOS'
     contrib/rtos-helpers/FreeRTOS-openocd.c
'uC/OS-III'
     contrib/rtos-helpers/uCOS-III-openocd.c

22 Tcl Scripting API
********************

22.1 API rules
==============

Tcl commands are stateless; e.g.  the 'telnet' command has a concept of
currently active target, the Tcl API proc's take this sort of state
information as an argument to each proc.

There are three main types of return values: single value, name value
pair list and lists.

Name value pair.  The proc 'foo' below returns a name/value pair list.

     >  set foo(me)  Duane
     >  set foo(you) Oyvind
     >  set foo(mouse) Micky
     >  set foo(duck) Donald

If one does this:

     >  set foo

The result is:

     me Duane you Oyvind mouse Micky duck Donald

Thus, to get the names of the associative array is easy:

foreach { name value } [set foo] {
        puts "Name: $name, Value: $value"
}

Lists returned should be relatively small.  Otherwise, a range should be
passed in to the proc in question.

22.2 Internal low-level Commands
================================

By "low-level," we mean commands that a human would typically not invoke
directly.

Some low-level commands need to be prefixed with "ocd_"; e.g.
'ocd_flash_banks' is the low-level API upon which 'flash banks' is
implemented.

   * mem2array <VARNAME> <WIDTH> <ADDR> <NELEMS>

     Read memory and return as a Tcl array for script processing
   * array2mem <VARNAME> <WIDTH> <ADDR> <NELEMS>

     Convert a Tcl array to memory locations and write the values
   * ocd_flash_banks <DRIVER> <BASE> <SIZE> <CHIP_WIDTH> <BUS_WIDTH>
     <TARGET> ['driver options' ...]

     Return information about the flash banks

   * capture <COMMAND>

     Run <COMMAND> and return full log output that was produced during
     its execution.  Example:

          > capture "reset init"

OpenOCD commands can consist of two words, e.g.  "flash banks".  The
'startup.tcl' "unknown" proc will translate this into a Tcl proc called
"flash_banks".

22.3 OpenOCD specific Global Variables
======================================

Real Tcl has ::tcl_platform(), and platform::identify, and many other
variables.  JimTCL, as implemented in OpenOCD creates $ocd_HOSTOS which
holds one of the following values:

   * cygwin Running under Cygwin
   * darwin Darwin (Mac-OS) is the underlying operating sytem.
   * freebsd Running under FreeBSD
   * openbsd Running under OpenBSD
   * netbsd Running under NetBSD
   * linux Linux is the underlying operating sytem
   * mingw32 Running under MingW32
   * winxx Built using Microsoft Visual Studio
   * ecos Running under eCos
   * other Unknown, none of the above.

Note: 'winxx' was choosen because today (March-2009) no distinction is
made between Win32 and Win64.

     Note: We should add support for a variable like Tcl variable
     'tcl_platform(platform)', it should be called 'jim_platform'
     (because it is jim, not real tcl).

22.4 Tcl RPC server
===================

OpenOCD provides a simple RPC server that allows to run arbitrary Tcl
commands and receive the results.

To access it, your application needs to connect to a configured TCP port
(see 'tcl_port').  Then it can pass any string to the interpreter
terminating it with '0x1a' and wait for the return value (it will be
terminated with '0x1a' as well).  This can be repeated as many times as
desired without reopening the connection.

Remember that most of the OpenOCD commands need to be prefixed with
'ocd_' to get the results back.  Sometimes you might also need the
'capture' command.

See 'contrib/rpc_examples/' for specific client implementations.

22.5 Tcl RPC server notifications
=================================

Notifications are sent asynchronously to other commands being executed
over the RPC server, so the port must be polled continuously.

Target event, state and reset notifications are emitted as Tcl
associative arrays in the following format.

type target_event event [event-name]
type target_state state [state-name]
type target_reset mode [reset-mode]

 -- Command: tcl_notifications [on/off]
     Toggle output of target notifications to the current Tcl RPC
     server.  Only available from the Tcl RPC server.  Defaults to off.

22.6 Tcl RPC server trace output
================================

Trace data is sent asynchronously to other commands being executed over
the RPC server, so the port must be polled continuously.

Target trace data is emitted as a Tcl associative array in the following
format.

type target_trace data [trace-data-hex-encoded]

 -- Command: tcl_trace [on/off]
     Toggle output of target trace data to the current Tcl RPC server.
     Only available from the Tcl RPC server.  Defaults to off.

     See an example application here:
     <https://github.com/apmorton/OpenOcdTraceUtil> [OpenOcdTraceUtil]

23 FAQ
******

  1. RTCK, also known as: Adaptive Clocking - What is it?

     In digital circuit design it is often refered to as "clock
     synchronisation" the JTAG interface uses one clock (TCK or TCLK)
     operating at some speed, your CPU target is operating at another.
     The two clocks are not synchronised, they are "asynchronous"

     In order for the two to work together they must be synchronised
     well enough to work; JTAG can't go ten times faster than the CPU,
     for example.  There are 2 basic options:
       1. Use a special "adaptive clocking" circuit to change the JTAG
          clock rate to match what the CPU currently supports.
       2. The JTAG clock must be fixed at some speed that's enough
          slower than the CPU clock that all TMS and TDI transitions can
          be detected.

     Does this really matter?  For some chips and some situations, this
     is a non-issue, like a 500MHz ARM926 with a 5 MHz JTAG link; the
     CPU has no difficulty keeping up with JTAG. Startup sequences are
     often problematic though, as are other situations where the CPU
     clock rate changes (perhaps to save power).

     For example, Atmel AT91SAM chips start operation from reset with a
     32kHz system clock.  Boot firmware may activate the main oscillator
     and PLL before switching to a faster clock (perhaps that 500 MHz
     ARM926 scenario).  If you're using JTAG to debug that startup
     sequence, you must slow the JTAG clock to sometimes 1 to 4kHz.
     After startup completes, JTAG can use a faster clock.

     Consider also debugging a 500MHz ARM926 hand held battery powered
     device that enters a low power "deep sleep" mode, at 32kHz CPU
     clock, between keystrokes unless it has work to do.  When would
     that 5 MHz JTAG clock be usable?

     Solution #1 - A special circuit

     In order to make use of this, your CPU, board, and JTAG adapter
     must all support the RTCK feature.  Not all of them support this;
     keep reading!

     The RTCK ("Return TCK") signal in some ARM chips is used to help
     with this problem.  ARM has a good description of the problem
     described at this link:
     <http://www.arm.com/support/faqdev/4170.html> [checked
     28/nov/2008].  Link title: "How does the JTAG synchronisation logic
     work?  / how does adaptive clocking work?".

     The nice thing about adaptive clocking is that "battery powered
     hand held device example" - the adaptiveness works perfectly all
     the time.  One can set a break point or halt the system in the deep
     power down code, slow step out until the system speeds up.

     Note that adaptive clocking may also need to work at the board
     level, when a board-level scan chain has multiple chips.  Parallel
     clock voting schemes are good way to implement this, both within
     and between chips, and can easily be implemented with a CPLD. It's
     not difficult to have logic fan a module's input TCK signal out to
     each TAP in the scan chain, and then wait until each TAP's RTCK
     comes back with the right polarity before changing the output RTCK
     signal.  Texas Instruments makes some clock voting logic available
     for free (with no support) in VHDL form; see
     <http://tiexpressdsp.com/index.php/Adaptive_Clocking>

     Solution #2 - Always works - but may be slower

     Often this is a perfectly acceptable solution.

     In most simple terms: Often the JTAG clock must be 1/10 to 1/12 of
     the target clock speed.  But what that "magic division" is varies
     depending on the chips on your board.  ARM rule of thumb Most ARM
     based systems require an 6:1 division; ARM11 cores use an 8:1
     division.  Xilinx rule of thumb is 1/12 the clock speed.

     Note: most full speed FT2232 based JTAG adapters are limited to a
     maximum of 6MHz.  The ones using USB high speed chips (FT2232H)
     often support faster clock rates (and adaptive clocking).

     You can still debug the 'low power' situations - you just need to
     either use a fixed and very slow JTAG clock rate ...  or else
     manually adjust the clock speed at every step.  (Adjusting is
     painful and tedious, and is not always practical.)

     It is however easy to "code your way around it" - i.e.: Cheat a
     little, have a special debug mode in your application that does a
     "high power sleep".  If you are careful - 98% of your problems can
     be debugged this way.

     Note that on ARM you may need to avoid using the _wait for
     interrupt_ operation in your idle loops even if you don't otherwise
     change the CPU clock rate.  That operation gates the CPU clock, and
     thus the JTAG clock; which prevents JTAG access.  One consequence
     is not being able to 'halt' cores which are executing that _wait
     for interrupt_ operation.

     To set the JTAG frequency use the command:

          # Example: 1.234MHz
          adapter_khz 1234

  2. Win32 Pathnames Why don't backslashes work in Windows paths?

     OpenOCD uses Tcl and a backslash is an escape char.  Use { and }
     around Windows filenames.

          > echo \a

          > echo {\a}
          \a
          > echo "\a"

          >

  3. Missing: cygwin1.dll OpenOCD complains about a missing cygwin1.dll.

     Make sure you have Cygwin installed, or at least a version of
     OpenOCD that claims to come with all the necessary DLLs.  When
     using Cygwin, try launching OpenOCD from the Cygwin shell.

  4. Breakpoint Issue I'm trying to set a breakpoint using GDB (or a
     frontend like Insight or Eclipse), but OpenOCD complains that
     "Info: arm7_9_common.c:213 arm7_9_add_breakpoint(): sw breakpoint
     requested, but software breakpoints not enabled".

     GDB issues software breakpoints when a normal breakpoint is
     requested, or to implement source-line single-stepping.  On ARMv4T
     systems, like ARM7TDMI, ARM720T or ARM920T, software breakpoints
     consume one of the two available hardware breakpoints.

  5. LPC2000 Flash When erasing or writing LPC2000 on-chip flash, the
     operation fails at random.

     Make sure the core frequency specified in the 'flash lpc2000' line
     matches the clock at the time you're programming the flash.  If
     you've specified the crystal's frequency, make sure the PLL is
     disabled.  If you've specified the full core speed (e.g.  60MHz),
     make sure the PLL is enabled.

  6. Amontec Chameleon When debugging using an Amontec Chameleon in its
     JTAG Accelerator configuration, I keep getting "Error:
     amt_jtagaccel.c:184 amt_wait_scan_busy(): amt_jtagaccel timed out
     while waiting for end of scan, rtck was disabled".

     Make sure your PC's parallel port operates in EPP mode.  You might
     have to try several settings in your PC BIOS (ECP, EPP, and
     different versions of those).

  7. Data Aborts When debugging with OpenOCD and GDB (plain GDB,
     Insight, or Eclipse), I get lots of "Error: arm7_9_common.c:1771
     arm7_9_read_memory(): memory read caused data abort".

     The errors are non-fatal, and are the result of GDB trying to trace
     stack frames beyond the last valid frame.  It might be possible to
     prevent this by setting up a proper "initial" stack frame, if you
     happen to know what exactly has to be done, feel free to add this
     here.

     Simple: In your startup code - push 8 registers of zeros onto the
     stack before calling main().  What GDB is doing is "climbing" the
     run time stack by reading various values on the stack using the
     standard call frame for the target.  GDB keeps going - until one of
     2 things happen #1 an invalid frame is found, or #2 some huge
     number of stackframes have been processed.  By pushing zeros on the
     stack, GDB gracefully stops.

     Debugging Interrupt Service Routines - In your ISR before you call
     your C code, do the same - artifically push some zeros onto the
     stack, remember to pop them off when the ISR is done.

     Also note: If you have a multi-threaded operating system, they
     often do not in the intrest of saving memory waste these few bytes.
     Painful...

  8. JTAG Reset Config I get the following message in the OpenOCD
     console (or log file): "Warning: arm7_9_common.c:679
     arm7_9_assert_reset(): srst resets test logic, too".

     This warning doesn't indicate any serious problem, as long as you
     don't want to debug your core right out of reset.  Your .cfg file
     specified 'jtag_reset trst_and_srst srst_pulls_trst' to tell
     OpenOCD that either your board, your debugger or your target uC
     (e.g.  LPC2000) can't assert the two reset signals independently.
     With this setup, it's not possible to halt the core right out of
     reset, everything else should work fine.

  9. USB Power When using OpenOCD in conjunction with Amontec JTAGkey
     and the Yagarto toolchain (Eclipse, arm-elf-gcc, arm-elf-gdb), the
     debugging seems to be unstable.  When single-stepping over large
     blocks of code, GDB and OpenOCD quit with an error message.  Is
     there a stability issue with OpenOCD?

     No, this is not a stability issue concerning OpenOCD. Most users
     have solved this issue by simply using a self-powered USB hub,
     which they connect their Amontec JTAGkey to.  Apparently, some
     computers do not provide a USB power supply stable enough for the
     Amontec JTAGkey to be operated.

     Laptops running on battery have this problem too...

  10. GDB Disconnects When using the Amontec JTAGkey, sometimes OpenOCD
     crashes with the following error message: "Error: gdb_server.c:101
     gdb_get_char(): read: 10054".  What does that mean and what might
     be the reason for this?

     Error code 10054 corresponds to WSAECONNRESET, which means that the
     debugger (GDB) has closed the connection to OpenOCD. This might be
     a GDB issue.

  11. LPC2000 Flash In the configuration file in the section where flash
     device configurations are described, there is a parameter for
     specifying the clock frequency for LPC2000 internal flash devices
     (e.g.  'flash bank $_FLASHNAME lpc2000 0x0 0x40000 0 0 $_TARGETNAME
     lpc2000_v1 14746 calc_checksum'), which must be specified in
     kilohertz.  However, I do have a quartz crystal of a frequency that
     contains fractions of kilohertz (e.g.  14,745,600 Hz, i.e.
     14,745.600 kHz).  Is it possible to specify real numbers for the
     clock frequency?

     No.  The clock frequency specified here must be given as an
     integral number.  However, this clock frequency is used by the
     In-Application-Programming (IAP) routines of the LPC2000 family
     only, which seems to be very tolerant concerning the given clock
     frequency, so a slight difference between the specified clock
     frequency and the actual clock frequency will not cause any
     trouble.

  12. Command Order Do I have to keep a specific order for the commands
     in the configuration file?

     Well, yes and no.  Commands can be given in arbitrary order, yet
     the devices listed for the JTAG scan chain must be given in the
     right order (jtag newdevice), with the device closest to the
     TDO-Pin being listed first.  In general, whenever objects of the
     same type exist which require an index number, then these objects
     must be given in the right order (jtag newtap, targets and flash
     banks - a target references a jtag newtap and a flash bank
     references a target).

     You can use the "scan_chain" command to verify and display the tap
     order.

     Also, some commands can't execute until after 'init' has been
     processed.  Such commands include 'nand probe' and everything else
     that needs to write to controller registers, perhaps for setting up
     DRAM and loading it with code.

  13. JTAG TAP Order Do I have to declare the TAPS in some particular
     order?

     Yes; whenever you have more than one, you must declare them in the
     same order used by the hardware.

     Many newer devices have multiple JTAG TAPs.  For example: ST
     Microsystems STM32 chips have two TAPs, a "boundary scan TAP" and
     "Cortex-M3" TAP. Example: The STM32 reference manual, Document ID:
     RM0008, Section 26.5, Figure 259, page 651/681, the "TDI" pin is
     connected to the boundary scan TAP, which then connects to the
     Cortex-M3 TAP, which then connects to the TDO pin.

     Thus, the proper order for the STM32 chip is: (1) The Cortex-M3,
     then (2) The boundary scan TAP. If your board includes an
     additional JTAG chip in the scan chain (for example a Xilinx CPLD
     or FPGA) you could place it before or after the STM32 chip in the
     chain.  For example:

        * OpenOCD_TDI(output) -> STM32 TDI Pin (BS Input)
        * STM32 BS TDO (output) -> STM32 Cortex-M3 TDI (input)
        * STM32 Cortex-M3 TDO (output) -> SM32 TDO Pin
        * STM32 TDO Pin (output) -> Xilinx TDI Pin (input)
        * Xilinx TDO Pin -> OpenOCD TDO (input)

     The "jtag device" commands would thus be in the order shown below.
     Note:

        * jtag newtap Xilinx tap -irlen ...
        * jtag newtap stm32 cpu -irlen ...
        * jtag newtap stm32 bs -irlen ...
        * # Create the debug target and say where it is
        * target create stm32.cpu -chain-position stm32.cpu ...

  14. SYSCOMP Sometimes my debugging session terminates with an error.
     When I look into the log file, I can see these error messages:
     Error: arm7_9_common.c:561 arm7_9_execute_sys_speed(): timeout
     waiting for SYSCOMP

     TODO.

24 Tcl Crash Course
*******************

Not everyone knows Tcl - this is not intended to be a replacement for
learning Tcl, the intent of this chapter is to give you some idea of how
the Tcl scripts work.

This chapter is written with two audiences in mind.  (1) OpenOCD users
who need to understand a bit more of how Jim-Tcl works so they can do
something useful, and (2) those that want to add a new command to
OpenOCD.

24.1 Tcl Rule #1
================

There is a famous joke, it goes like this:
  1. Rule #1: The wife is always correct
  2. Rule #2: If you think otherwise, See Rule #1

The Tcl equal is this:

  1. Rule #1: Everything is a string
  2. Rule #2: If you think otherwise, See Rule #1

As in the famous joke, the consequences of Rule #1 are profound.  Once
you understand Rule #1, you will understand Tcl.

24.2 Tcl Rule #1b
=================

There is a second pair of rules.
  1. Rule #1: Control flow does not exist.  Only commands
     For example: the classic FOR loop or IF statement is not a control
     flow item, they are commands, there is no such thing as control
     flow in Tcl.
  2. Rule #2: If you think otherwise, See Rule #1
     Actually what happens is this: There are commands that by
     convention, act like control flow key words in other languages.
     One of those commands is the word "for", another command is "if".

24.3 Per Rule #1 - All Results are strings
==========================================

Every Tcl command results in a string.  The word "result" is used
deliberatly.  No result is just an empty string.  Remember: Rule #1 -
Everything is a string

24.4 Tcl Quoting Operators
==========================

In life of a Tcl script, there are two important periods of time, the
difference is subtle.
  1. Parse Time
  2. Evaluation Time

The two key items here are how "quoted things" work in Tcl.  Tcl has
three primary quoting constructs, the [square-brackets] the
{curly-braces} and "double-quotes"

By now you should know $VARIABLES always start with a $DOLLAR sign.
BTW: To set a variable, you actually use the command "set", as in "set
VARNAME VALUE" much like the ancient BASIC langauge "let x = 1"
statement, but without the equal sign.

   * [square-brackets]
     [square-brackets] are command substitutions.  It operates much like
     Unix Shell 'back-ticks'.  The result of a [square-bracket]
     operation is exactly 1 string.  Remember Rule #1 - Everything is a
     string.  These two statements are roughly identical:
              # bash example
              X=`date`
              echo "The Date is: $X"
              # Tcl example
              set X [date]
              puts "The Date is: $X"
   * "double-quoted-things"
     "double-quoted-things" are just simply quoted text.  $VARIABLES and
     [square-brackets] are expanded in place - the result however is
     exactly 1 string.  Remember Rule #1 - Everything is a string
              set x "Dinner"
              puts "It is now \"[date]\", $x is in 1 hour"
   * {Curly-Braces}
     {Curly-Braces} are magic: $VARIABLES and [square-brackets] are
     parsed, but are NOT expanded or executed.  {Curly-Braces} are like
     'single-quote' operators in BASH shell scripts, with the added
     feature: {curly-braces} can be nested, single quotes can not.
     {{{this is nested 3 times}}} NOTE: [date] is a bad example; at this
     writing, Jim/OpenOCD does not have a date command.

24.5 Consequences of Rule 1/2/3/4
=================================

The consequences of Rule 1 are profound.

24.5.1 Tokenisation & Execution.
--------------------------------

Of course, whitespace, blank lines and #comment lines are handled in the
normal way.

As a script is parsed, each (multi) line in the script file is tokenised
and according to the quoting rules.  After tokenisation, that line is
immedatly executed.

Multi line statements end with one or more "still-open" {curly-braces}
which - eventually - closes a few lines later.

24.5.2 Command Execution
------------------------

Remember earlier: There are no "control flow" statements in Tcl.
Instead there are COMMANDS that simply act like control flow operators.

Commands are executed like this:

  1. Parse the next line into (argc) and (argv[]).
  2. Look up (argv[0]) in a table and call its function.
  3. Repeat until End Of File.

It sort of works like this:
         for(;;){
             ReadAndParse( &argc, &argv );

             cmdPtr = LookupCommand( argv[0] );

             (*cmdPtr->Execute)( argc, argv );
         }

When the command "proc" is parsed (which creates a procedure function)
it gets 3 parameters on the command line.  1 the name of the proc
(function), 2 the list of parameters, and 3 the body of the function.
Not the choice of words: LIST and BODY. The PROC command stores these
items in a table somewhere so it can be found by "LookupCommand()"

24.5.3 The FOR command
----------------------

The most interesting command to look at is the FOR command.  In Tcl, the
FOR command is normally implemented in C. Remember, FOR is a command
just like any other command.

When the ascii text containing the FOR command is parsed, the parser
produces 5 parameter strings, (If in doubt: Refer to Rule #1) they are:

  0. The ascii text 'for'
  1. The start text
  2. The test expression
  3. The next text
  4. The body text

Sort of reminds you of "main( int argc, char **argv )" does it not?
Remember Rule #1 - Everything is a string.  The key point is this: Often
many of those parameters are in {curly-braces} - thus the variables
inside are not expanded or replaced until later.

Remember that every Tcl command looks like the classic "main( argc, argv
)" function in C. In JimTCL - they actually look like this:

     int
     MyCommand( Jim_Interp *interp,
                int *argc,
                Jim_Obj * const *argvs );

Real Tcl is nearly identical.  Although the newer versions have
introduced a byte-code parser and intepreter, but at the core, it still
operates in the same basic way.

24.5.4 FOR command implementation
---------------------------------

To understand Tcl it is perhaps most helpful to see the FOR command.
Remember, it is a COMMAND not a control flow structure.

In Tcl there are two underlying C helper functions.

Remember Rule #1 - You are a string.

The first helper parses and executes commands found in an ascii string.
Commands can be seperated by semicolons, or newlines.  While parsing,
variables are expanded via the quoting rules.

The second helper evaluates an ascii string as a numerical expression
and returns a value.

Here is an example of how the FOR command could be implemented.  The
pseudo code below does not show error handling.
     void Execute_AsciiString( void *interp, const char *string );

     int Evaluate_AsciiExpression( void *interp, const char *string );

     int
     MyForCommand( void *interp,
                   int argc,
                   char **argv )
     {
        if( argc != 5 ){
            SetResult( interp, "WRONG number of parameters");
            return ERROR;
        }

        // argv[0] = the ascii string just like C

        // Execute the start statement.
        Execute_AsciiString( interp, argv[1] );

        // Top of loop test
        for(;;){
             i = Evaluate_AsciiExpression(interp, argv[2]);
             if( i == 0 )
                 break;

             // Execute the body
             Execute_AsciiString( interp, argv[3] );

             // Execute the LOOP part
             Execute_AsciiString( interp, argv[4] );
         }

         // Return no error
         SetResult( interp, "" );
         return SUCCESS;
     }

Every other command IF, WHILE, FORMAT, PUTS, EXPR, everything works in
the same basic way.

24.6 OpenOCD Tcl Usage
======================

24.6.1 source and find commands
-------------------------------

Where: In many configuration files
Example: source [find FILENAME]
Remember the parsing rules
  1. The 'find' command is in square brackets, and is executed with the
     parameter FILENAME. It should find and return the full path to a
     file with that name; it uses an internal search path.  The RESULT
     is a string, which is substituted into the command line in place of
     the bracketed 'find' command.  (Don't try to use a FILENAME which
     includes the "#" character.  That character begins Tcl comments.)
  2. The 'source' command is executed with the resulting filename; it
     reads a file and executes as a script.

24.6.2 format command
---------------------

Where: Generally occurs in numerous places.
Tcl has no command like printf(), instead it has format, which is really
more like sprintf().  Example
         set x 6
         set y 7
         puts [format "The answer: %d" [expr $x * $y]]
  1. The SET command creates 2 variables, X and Y.
  2. The double [nested] EXPR command performs math
     The EXPR command produces numerical result as a string.
     Refer to Rule #1
  3. The format command is executed, producing a single string
     Refer to Rule #1.
  4. The PUTS command outputs the text.

24.6.3 Body or Inlined Text
---------------------------

Where: Various TARGET scripts.
     #1 Good
        proc someproc {} {
            ... multiple lines of stuff ...
        }
        $_TARGETNAME configure -event FOO someproc
     #2 Good - no variables
        $_TARGETNAME confgure -event foo "this ; that;"
     #3 Good Curly Braces
        $_TARGETNAME configure -event FOO {
             puts "Time: [date]"
        }
     #4 DANGER DANGER DANGER
        $_TARGETNAME configure -event foo "puts \"Time: [date]\""
  1. The $_TARGETNAME is an OpenOCD variable convention.
     $_TARGETNAME represents the last target created, the value changes
     each time a new target is created.  Remember the parsing rules.
     When the ascii text is parsed, the $_TARGETNAME becomes a simple
     string, the name of the target which happens to be a TARGET
     (object) command.
  2. The 2nd parameter to the '-event' parameter is a TCBODY
     There are 4 examples:
       1. The TCLBODY is a simple string that happens to be a proc name
       2. The TCLBODY is several simple commands seperated by semicolons
       3. The TCLBODY is a multi-line {curly-brace} quoted string
       4. The TCLBODY is a string with variables that get expanded.

     In the end, when the target event FOO occurs the TCLBODY is
     evaluated.  Method #1 and #2 are functionally identical.  For
     Method #3 and #4 it is more interesting.  What is the TCLBODY?

     Remember the parsing rules.  In case #3, {curly-braces} mean the
     $VARS and [square-brackets] are expanded later, when the EVENT
     occurs, and the text is evaluated.  In case #4, they are replaced
     before the "Target Object Command" is executed.  This occurs at the
     same time $_TARGETNAME is replaced.  In case #4 the date will never
     change.  {BTW: [date] is a bad example; at this writing,
     Jim/OpenOCD does not have a date command}

24.6.4 Global Variables
-----------------------

Where: You might discover this when writing your own procs
In simple terms: Inside a PROC, if you need to access a global variable
you must say so.  See also "upvar".  Example:
     proc myproc { } {
          set y 0 #Local variable Y
          global x #Global variable X
          puts [format "X=%d, Y=%d" $x $y]
     }

24.7 Other Tcl Hacks
====================

Dynamic variable creation
     # Dynamically create a bunch of variables.
     for { set x 0 } { $x < 32 } { set x [expr $x + 1]} {
         # Create var name
         set vn [format "BIT%d" $x]
         # Make it a global
         global $vn
         # Set it.
         set $vn [expr (1 << $x)]
     }
Dynamic proc/command creation
     # One "X" function - 5 uart functions.
     foreach who {A B C D E}
        proc [format "show_uart%c" $who] { } "show_UARTx $who"
     }

Appendix A The GNU Free Documentation License.
**********************************************

                      Version 1.2, November 2002

     Copyright (C) 2000,2001,2002 Free Software Foundation, Inc.
     51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA

     Everyone is permitted to copy and distribute verbatim copies
     of this license document, but changing it is not allowed.

  0. PREAMBLE

     The purpose of this License is to make a manual, textbook, or other
     functional and useful document "free" in the sense of freedom: to
     assure everyone the effective freedom to copy and redistribute it,
     with or without modifying it, either commercially or
     noncommercially.  Secondarily, this License preserves for the
     author and publisher a way to get credit for their work, while not
     being considered responsible for modifications made by others.

     This License is a kind of "copyleft", which means that derivative
     works of the document must themselves be free in the same sense.
     It complements the GNU General Public License, which is a copyleft
     license designed for free software.

     We have designed this License in order to use it for manuals for
     free software, because free software needs free documentation: a
     free program should come with manuals providing the same freedoms
     that the software does.  But this License is not limited to
     software manuals; it can be used for any textual work, regardless
     of subject matter or whether it is published as a printed book.  We
     recommend this License principally for works whose purpose is
     instruction or reference.

  1. APPLICABILITY AND DEFINITIONS

     This License applies to any manual or other work, in any medium,
     that contains a notice placed by the copyright holder saying it can
     be distributed under the terms of this License.  Such a notice
     grants a world-wide, royalty-free license, unlimited in duration,
     to use that work under the conditions stated herein.  The
     "Document", below, refers to any such manual or work.  Any member
     of the public is a licensee, and is addressed as "you".  You accept
     the license if you copy, modify or distribute the work in a way
     requiring permission under copyright law.

     A "Modified Version" of the Document means any work containing the
     Document or a portion of it, either copied verbatim, or with
     modifications and/or translated into another language.

     A "Secondary Section" is a named appendix or a front-matter section
     of the Document that deals exclusively with the relationship of the
     publishers or authors of the Document to the Document's overall
     subject (or to related matters) and contains nothing that could
     fall directly within that overall subject.  (Thus, if the Document
     is in part a textbook of mathematics, a Secondary Section may not
     explain any mathematics.)  The relationship could be a matter of
     historical connection with the subject or with related matters, or
     of legal, commercial, philosophical, ethical or political position
     regarding them.

     The "Invariant Sections" are certain Secondary Sections whose
     titles are designated, as being those of Invariant Sections, in the
     notice that says that the Document is released under this License.
     If a section does not fit the above definition of Secondary then it
     is not allowed to be designated as Invariant.  The Document may
     contain zero Invariant Sections.  If the Document does not identify
     any Invariant Sections then there are none.

     The "Cover Texts" are certain short passages of text that are
     listed, as Front-Cover Texts or Back-Cover Texts, in the notice
     that says that the Document is released under this License.  A
     Front-Cover Text may be at most 5 words, and a Back-Cover Text may
     be at most 25 words.

     A "Transparent" copy of the Document means a machine-readable copy,
     represented in a format whose specification is available to the
     general public, that is suitable for revising the document
     straightforwardly with generic text editors or (for images composed
     of pixels) generic paint programs or (for drawings) some widely
     available drawing editor, and that is suitable for input to text
     formatters or for automatic translation to a variety of formats
     suitable for input to text formatters.  A copy made in an otherwise
     Transparent file format whose markup, or absence of markup, has
     been arranged to thwart or discourage subsequent modification by
     readers is not Transparent.  An image format is not Transparent if
     used for any substantial amount of text.  A copy that is not
     "Transparent" is called "Opaque".

     Examples of suitable formats for Transparent copies include plain
     ASCII without markup, Texinfo input format, LaTeX input format,
     SGML or XML using a publicly available DTD, and standard-conforming
     simple HTML, PostScript or PDF designed for human modification.
     Examples of transparent image formats include PNG, XCF and JPG.
     Opaque formats include proprietary formats that can be read and
     edited only by proprietary word processors, SGML or XML for which
     the DTD and/or processing tools are not generally available, and
     the machine-generated HTML, PostScript or PDF produced by some word
     processors for output purposes only.

     The "Title Page" means, for a printed book, the title page itself,
     plus such following pages as are needed to hold, legibly, the
     material this License requires to appear in the title page.  For
     works in formats which do not have any title page as such, "Title
     Page" means the text near the most prominent appearance of the
     work's title, preceding the beginning of the body of the text.

     A section "Entitled XYZ" means a named subunit of the Document
     whose title either is precisely XYZ or contains XYZ in parentheses
     following text that translates XYZ in another language.  (Here XYZ
     stands for a specific section name mentioned below, such as
     "Acknowledgements", "Dedications", "Endorsements", or "History".)
     To "Preserve the Title" of such a section when you modify the
     Document means that it remains a section "Entitled XYZ" according
     to this definition.

     The Document may include Warranty Disclaimers next to the notice
     which states that this License applies to the Document.  These
     Warranty Disclaimers are considered to be included by reference in
     this License, but only as regards disclaiming warranties: any other
     implication that these Warranty Disclaimers may have is void and
     has no effect on the meaning of this License.

  2. VERBATIM COPYING

     You may copy and distribute the Document in any medium, either
     commercially or noncommercially, provided that this License, the
     copyright notices, and the license notice saying this License
     applies to the Document are reproduced in all copies, and that you
     add no other conditions whatsoever to those of this License.  You
     may not use technical measures to obstruct or control the reading
     or further copying of the copies you make or distribute.  However,
     you may accept compensation in exchange for copies.  If you
     distribute a large enough number of copies you must also follow the
     conditions in section 3.

     You may also lend copies, under the same conditions stated above,
     and you may publicly display copies.

  3. COPYING IN QUANTITY

     If you publish printed copies (or copies in media that commonly
     have printed covers) of the Document, numbering more than 100, and
     the Document's license notice requires Cover Texts, you must
     enclose the copies in covers that carry, clearly and legibly, all
     these Cover Texts: Front-Cover Texts on the front cover, and
     Back-Cover Texts on the back cover.  Both covers must also clearly
     and legibly identify you as the publisher of these copies.  The
     front cover must present the full title with all words of the title
     equally prominent and visible.  You may add other material on the
     covers in addition.  Copying with changes limited to the covers, as
     long as they preserve the title of the Document and satisfy these
     conditions, can be treated as verbatim copying in other respects.

     If the required texts for either cover are too voluminous to fit
     legibly, you should put the first ones listed (as many as fit
     reasonably) on the actual cover, and continue the rest onto
     adjacent pages.

     If you publish or distribute Opaque copies of the Document
     numbering more than 100, you must either include a machine-readable
     Transparent copy along with each Opaque copy, or state in or with
     each Opaque copy a computer-network location from which the general
     network-using public has access to download using public-standard
     network protocols a complete Transparent copy of the Document, free
     of added material.  If you use the latter option, you must take
     reasonably prudent steps, when you begin distribution of Opaque
     copies in quantity, to ensure that this Transparent copy will
     remain thus accessible at the stated location until at least one
     year after the last time you distribute an Opaque copy (directly or
     through your agents or retailers) of that edition to the public.

     It is requested, but not required, that you contact the authors of
     the Document well before redistributing any large number of copies,
     to give them a chance to provide you with an updated version of the
     Document.

  4. MODIFICATIONS

     You may copy and distribute a Modified Version of the Document
     under the conditions of sections 2 and 3 above, provided that you
     release the Modified Version under precisely this License, with the
     Modified Version filling the role of the Document, thus licensing
     distribution and modification of the Modified Version to whoever
     possesses a copy of it.  In addition, you must do these things in
     the Modified Version:

       A. Use in the Title Page (and on the covers, if any) a title
          distinct from that of the Document, and from those of previous
          versions (which should, if there were any, be listed in the
          History section of the Document).  You may use the same title
          as a previous version if the original publisher of that
          version gives permission.

       B. List on the Title Page, as authors, one or more persons or
          entities responsible for authorship of the modifications in
          the Modified Version, together with at least five of the
          principal authors of the Document (all of its principal
          authors, if it has fewer than five), unless they release you
          from this requirement.

       C. State on the Title page the name of the publisher of the
          Modified Version, as the publisher.

       D. Preserve all the copyright notices of the Document.

       E. Add an appropriate copyright notice for your modifications
          adjacent to the other copyright notices.

       F. Include, immediately after the copyright notices, a license
          notice giving the public permission to use the Modified
          Version under the terms of this License, in the form shown in
          the Addendum below.

       G. Preserve in that license notice the full lists of Invariant
          Sections and required Cover Texts given in the Document's
          license notice.

       H. Include an unaltered copy of this License.

       I. Preserve the section Entitled "History", Preserve its Title,
          and add to it an item stating at least the title, year, new
          authors, and publisher of the Modified Version as given on the
          Title Page.  If there is no section Entitled "History" in the
          Document, create one stating the title, year, authors, and
          publisher of the Document as given on its Title Page, then add
          an item describing the Modified Version as stated in the
          previous sentence.

       J. Preserve the network location, if any, given in the Document
          for public access to a Transparent copy of the Document, and
          likewise the network locations given in the Document for
          previous versions it was based on.  These may be placed in the
          "History" section.  You may omit a network location for a work
          that was published at least four years before the Document
          itself, or if the original publisher of the version it refers
          to gives permission.

       K. For any section Entitled "Acknowledgements" or "Dedications",
          Preserve the Title of the section, and preserve in the section
          all the substance and tone of each of the contributor
          acknowledgements and/or dedications given therein.

       L. Preserve all the Invariant Sections of the Document, unaltered
          in their text and in their titles.  Section numbers or the
          equivalent are not considered part of the section titles.

       M. Delete any section Entitled "Endorsements".  Such a section
          may not be included in the Modified Version.

       N. Do not retitle any existing section to be Entitled
          "Endorsements" or to conflict in title with any Invariant
          Section.

       O. Preserve any Warranty Disclaimers.

     If the Modified Version includes new front-matter sections or
     appendices that qualify as Secondary Sections and contain no
     material copied from the Document, you may at your option designate
     some or all of these sections as invariant.  To do this, add their
     titles to the list of Invariant Sections in the Modified Version's
     license notice.  These titles must be distinct from any other
     section titles.

     You may add a section Entitled "Endorsements", provided it contains
     nothing but endorsements of your Modified Version by various
     parties--for example, statements of peer review or that the text
     has been approved by an organization as the authoritative
     definition of a standard.

     You may add a passage of up to five words as a Front-Cover Text,
     and a passage of up to 25 words as a Back-Cover Text, to the end of
     the list of Cover Texts in the Modified Version.  Only one passage
     of Front-Cover Text and one of Back-Cover Text may be added by (or
     through arrangements made by) any one entity.  If the Document
     already includes a cover text for the same cover, previously added
     by you or by arrangement made by the same entity you are acting on
     behalf of, you may not add another; but you may replace the old
     one, on explicit permission from the previous publisher that added
     the old one.

     The author(s) and publisher(s) of the Document do not by this
     License give permission to use their names for publicity for or to
     assert or imply endorsement of any Modified Version.

  5. COMBINING DOCUMENTS

     You may combine the Document with other documents released under
     this License, under the terms defined in section 4 above for
     modified versions, provided that you include in the combination all
     of the Invariant Sections of all of the original documents,
     unmodified, and list them all as Invariant Sections of your
     combined work in its license notice, and that you preserve all
     their Warranty Disclaimers.

     The combined work need only contain one copy of this License, and
     multiple identical Invariant Sections may be replaced with a single
     copy.  If there are multiple Invariant Sections with the same name
     but different contents, make the title of each such section unique
     by adding at the end of it, in parentheses, the name of the
     original author or publisher of that section if known, or else a
     unique number.  Make the same adjustment to the section titles in
     the list of Invariant Sections in the license notice of the
     combined work.

     In the combination, you must combine any sections Entitled
     "History" in the various original documents, forming one section
     Entitled "History"; likewise combine any sections Entitled
     "Acknowledgements", and any sections Entitled "Dedications".  You
     must delete all sections Entitled "Endorsements."

  6. COLLECTIONS OF DOCUMENTS

     You may make a collection consisting of the Document and other
     documents released under this License, and replace the individual
     copies of this License in the various documents with a single copy
     that is included in the collection, provided that you follow the
     rules of this License for verbatim copying of each of the documents
     in all other respects.

     You may extract a single document from such a collection, and
     distribute it individually under this License, provided you insert
     a copy of this License into the extracted document, and follow this
     License in all other respects regarding verbatim copying of that
     document.

  7. AGGREGATION WITH INDEPENDENT WORKS

     A compilation of the Document or its derivatives with other
     separate and independent documents or works, in or on a volume of a
     storage or distribution medium, is called an "aggregate" if the
     copyright resulting from the compilation is not used to limit the
     legal rights of the compilation's users beyond what the individual
     works permit.  When the Document is included in an aggregate, this
     License does not apply to the other works in the aggregate which
     are not themselves derivative works of the Document.

     If the Cover Text requirement of section 3 is applicable to these
     copies of the Document, then if the Document is less than one half
     of the entire aggregate, the Document's Cover Texts may be placed
     on covers that bracket the Document within the aggregate, or the
     electronic equivalent of covers if the Document is in electronic
     form.  Otherwise they must appear on printed covers that bracket
     the whole aggregate.

  8. TRANSLATION

     Translation is considered a kind of modification, so you may
     distribute translations of the Document under the terms of section
     4.  Replacing Invariant Sections with translations requires special
     permission from their copyright holders, but you may include
     translations of some or all Invariant Sections in addition to the
     original versions of these Invariant Sections.  You may include a
     translation of this License, and all the license notices in the
     Document, and any Warranty Disclaimers, provided that you also
     include the original English version of this License and the
     original versions of those notices and disclaimers.  In case of a
     disagreement between the translation and the original version of
     this License or a notice or disclaimer, the original version will
     prevail.

     If a section in the Document is Entitled "Acknowledgements",
     "Dedications", or "History", the requirement (section 4) to
     Preserve its Title (section 1) will typically require changing the
     actual title.

  9. TERMINATION

     You may not copy, modify, sublicense, or distribute the Document
     except as expressly provided for under this License.  Any other
     attempt to copy, modify, sublicense or distribute the Document is
     void, and will automatically terminate your rights under this
     License.  However, parties who have received copies, or rights,
     from you under this License will not have their licenses terminated
     so long as such parties remain in full compliance.

  10. FUTURE REVISIONS OF THIS LICENSE

     The Free Software Foundation may publish new, revised versions of
     the GNU Free Documentation License from time to time.  Such new
     versions will be similar in spirit to the present version, but may
     differ in detail to address new problems or concerns.  See
     <http://www.gnu.org/copyleft/>.

     Each version of the License is given a distinguishing version
     number.  If the Document specifies that a particular numbered
     version of this License "or any later version" applies to it, you
     have the option of following the terms and conditions either of
     that specified version or of any later version that has been
     published (not as a draft) by the Free Software Foundation.  If the
     Document does not specify a version number of this License, you may
     choose any version ever published (not as a draft) by the Free
     Software Foundation.

ADDENDUM: How to use this License for your documents
====================================================

To use this License in a document you have written, include a copy of
the License in the document and put the following copyright and license
notices just after the title page:

       Copyright (C)  YEAR  YOUR NAME.
       Permission is granted to copy, distribute and/or modify this document
       under the terms of the GNU Free Documentation License, Version 1.2
       or any later version published by the Free Software Foundation;
       with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
       Texts.  A copy of the license is included in the section entitled ``GNU
       Free Documentation License''.

If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
replace the "with...Texts."  line with this:

         with the Invariant Sections being LIST THEIR TITLES, with
         the Front-Cover Texts being LIST, and with the Back-Cover Texts
         being LIST.

If you have Invariant Sections without Cover Texts, or some other
combination of the three, merge those two alternatives to suit the
situation.

If your document contains nontrivial examples of program code, we
recommend releasing these examples in parallel under your choice of free
software license, such as the GNU General Public License, to permit
their use in free software.