documentation/ethercat_doc.tex
changeset 370 148155bb9abc
parent 369 7920ca086e5c
child 371 97f684433d3b
equal deleted inserted replaced
369:7920ca086e5c 370:148155bb9abc
       
     1 %------------------------------------------------------------------------------
       
     2 %
       
     3 %  IgH EtherCAT Master Documentation
       
     4 %
       
     5 %  $Id$
       
     6 %
       
     7 %------------------------------------------------------------------------------
       
     8 
       
     9 \documentclass[a4paper,12pt,BCOR6mm,bibtotoc,idxtotoc]{scrbook}
       
    10 
       
    11 \usepackage[latin1]{inputenc}
       
    12 \usepackage[automark,headsepline]{scrpage2}
       
    13 \usepackage{graphicx}
       
    14 \usepackage{makeidx}
       
    15 \usepackage[refpage]{nomencl}
       
    16 \usepackage{listings}
       
    17 \usepackage{svn}
       
    18 \usepackage{textcomp}
       
    19 \usepackage{url}
       
    20 \usepackage{hyperref}
       
    21 
       
    22 \setlength{\parskip}{0.8ex plus 0.8ex minus 0.5ex}
       
    23 \setlength{\parindent}{0mm}
       
    24 
       
    25 \setcounter{secnumdepth}{\subsubsectionlevel}
       
    26 
       
    27 \DeclareFontShape{OT1}{cmtt}{bx}{n}
       
    28 {
       
    29   <5><6><7><8><9><10><10.95><12><14.4><17.28><20.74><24.88>cmttb10
       
    30 }{}
       
    31 
       
    32 \lstset{basicstyle=\ttfamily\small,numberstyle=\tiny,aboveskip=4mm,
       
    33   belowskip=2mm,gobble=2,escapechar=`}
       
    34 \renewcommand\lstlistlistingname{List of Listings}
       
    35 
       
    36 \renewcommand\nomname{Glossary}
       
    37 
       
    38 \newcommand{\IgH}{\raisebox{-0.7667ex}
       
    39   {\includegraphics[height=2.2ex]{images/ighsign}}}
       
    40 
       
    41 \SVN $Date$
       
    42 \SVN $Revision$
       
    43 
       
    44 \makeindex
       
    45 \makeglossary
       
    46 
       
    47 %------------------------------------------------------------------------------
       
    48 
       
    49 \begin{document}
       
    50 
       
    51 \pagenumbering{roman}
       
    52 \pagestyle{empty}
       
    53 
       
    54 \begin{titlepage}
       
    55   \begin{center}
       
    56     \rule{\textwidth}{1.5mm}
       
    57 
       
    58     {\Huge\bf IgH \includegraphics[height=2.4ex]{images/ethercat}
       
    59       Master 1.1\\[1ex]
       
    60       Documentation}
       
    61 
       
    62     \vspace{1ex}
       
    63     \rule{\textwidth}{1.5mm}
       
    64 
       
    65     \vspace{\fill}
       
    66     {\Large Florian Pose, \url{fp@igh-essen.com}\\[1ex]
       
    67       Ingenieurgemeinschaft \IgH}
       
    68 
       
    69     \vspace{\fill}
       
    70     {\Large Essen, \SVNDate\\[1ex]
       
    71       Revision \SVNRevision}
       
    72   \end{center}
       
    73 \end{titlepage}
       
    74 
       
    75 %------------------------------------------------------------------------------
       
    76 
       
    77 \tableofcontents
       
    78 \listoftables
       
    79 \listoffigures
       
    80 \lstlistoflistings
       
    81 
       
    82 %------------------------------------------------------------------------------
       
    83 
       
    84 \newpage
       
    85 \pagestyle{scrheadings}
       
    86 
       
    87 \section*{Conventions}
       
    88 \addcontentsline{toc}{section}{Conventions}
       
    89 \markleft{Conventions}
       
    90 
       
    91 The following typographic conventions are used:
       
    92 
       
    93 \begin{itemize}
       
    94 \item \textit{Italic face} is used for newly introduced terms, file
       
    95   names, parameter names and in-text source code elements.
       
    96 \item \texttt{Typewriter face} is used for code examples and
       
    97   command line output.
       
    98 \item \texttt{\textbf{Bold typewriter face}} is used for user input in
       
    99   command lines.
       
   100 \end{itemize}
       
   101 
       
   102 Data values and addresses are specified as hexadecimal values with the
       
   103 prefix 0x. Example: 0x88A4. Unless otherwise noted, address values are
       
   104 specified as byte addresses.
       
   105 
       
   106 Concerning bit operations, the phrase ``setting a bit'', stands for
       
   107 setting the bit to $1$, ``clearing a bit'' means setting it to $0$,
       
   108 respectively.
       
   109 
       
   110 Function names are always printed with parentheses, but without
       
   111 parameters. So, if a function \textit{ecrt\_request\_master()} has
       
   112 empty parentheses, this does not mean, that it has no parameters.
       
   113 
       
   114 If shell commands have to be entered, this is marked by a prompt:
       
   115 
       
   116 \begin{lstlisting}[gobble=2]
       
   117   host>
       
   118 \end{lstlisting}
       
   119 
       
   120 Further, if a shell command has to be entered as the superuser, the
       
   121 prompt ends with a mesh:
       
   122 
       
   123 \begin{lstlisting}[gobble=2]
       
   124   host#
       
   125 \end{lstlisting}
       
   126 
       
   127 %------------------------------------------------------------------------------
       
   128 
       
   129 \chapter{The IgH EtherCAT Master}
       
   130 \label{chapter:master}
       
   131 \pagenumbering{arabic}
       
   132 
       
   133 This section will first introduce the master's general features and
       
   134 the concepts used for master development and will then explain the
       
   135 master's general architecture and offer details of the different
       
   136 modules. In addition, it will cover state machine definitions, mailbox
       
   137 protocol implementation and the user space interface. The last section
       
   138 will deal with timing aspects.
       
   139 
       
   140 %------------------------------------------------------------------------------
       
   141 
       
   142 \section{Feature Summary}
       
   143 \label{sec:summary}
       
   144 \index{Master!Features}
       
   145 
       
   146 The list below gives a short summary of the features of the
       
   147 implemented EtherCAT master.
       
   148 
       
   149 \begin{itemize}
       
   150 \item The master runs as a kernel module for Linux 2.6.
       
   151 \item It comes with EtherCAT-capable network driver for RealTek
       
   152   RTL8139 (and compatible) network interface cards.
       
   153   \begin{itemize}
       
   154   \item The Ethernet hardware is operated without interrupts.
       
   155   \item Drivers for additional Ethernet hardware can easily be
       
   156     implemented due to a common device interface provided by the
       
   157     master.
       
   158   \end{itemize}
       
   159 \item The master module supports multiple EtherCAT masters on one
       
   160   machine.
       
   161 \item The master code supports any Linux realtime extension through
       
   162   its independent architecture.
       
   163   \begin{itemize}
       
   164   \item RTAI\nomenclature{RTAI}{RealTime Application Interface},
       
   165     ADEOS\nomenclature{ADEOS}{Adaptive Domain Environment for
       
   166       Operating Systems}, etc.
       
   167   \item It runs well even without realtime extensions.
       
   168   \end{itemize}
       
   169 \item Common ``realtime interface'' for modules, that want to use
       
   170   EtherCAT functionality.
       
   171   \begin{itemize}
       
   172   \item Synchronous and asynchronous sending and receiving of frames
       
   173     is supported.
       
   174   \item Avoidance of unnecessary copy operations for process data.
       
   175   \end{itemize}
       
   176 \item \textit{Domains} are introduced, to allow grouping of process
       
   177   data objects.
       
   178   \begin{itemize}
       
   179   \item Handling of multiple domains with different sampling rates.
       
   180   \item Automatic calculation of process data mapping, FMMU and sync manager
       
   181     configuration within each domain.
       
   182   \end{itemize}
       
   183 \item Communication through serveral finite state machines.
       
   184   \begin{itemize}
       
   185   \item Bus monitoring possible during realtime operation.
       
   186   \item Automatic reconfiguration of slaves on bus power failure
       
   187     during realtime operation.
       
   188   \item Controlling of single slaves during realtime operation.
       
   189   \end{itemize}
       
   190 \item Master idle mode.
       
   191   \begin{itemize}
       
   192   \item Automatic scanning of slaves upon topology changes.
       
   193   \item Bus visualisation and EoE processing without a realtime module
       
   194     connected.
       
   195   \end{itemize}
       
   196 \item Implementation of the CANopen-over-EtherCAT (CoE) protocol.
       
   197   \begin{itemize}
       
   198   \item Configuration of CoE-capable slaves via SDO interface.
       
   199   \end{itemize}
       
   200 \item Implementation of the Ethernet-over-EtherCAT (EoE) protocol.
       
   201   \begin{itemize}
       
   202   \item Each master creates virtual network devices that are
       
   203     automatically coupled to EoE-cap\-able slaves found.
       
   204   \item This implementation natively supports either a switched or a
       
   205     routed EoE network architecture.
       
   206   \end{itemize}
       
   207 \item User space interface via the System Filesystem
       
   208   (Sysfs)\nomenclature{Sysfs}{System Filesystem}.
       
   209   \begin{itemize}
       
   210   \item User space tool for bus visualisation.
       
   211   \item Slave E$^2$PROM image reading and writing.
       
   212   \end{itemize}
       
   213 \item Seamless system integration though LSB\nomenclature{LSB}{Linux
       
   214     Standard Base} compliance.
       
   215   \begin{itemize}
       
   216   \item Master and network device configuration via Sysconfig files.
       
   217   \item Linux Standard Base compatible init script for master control.
       
   218   \end{itemize}
       
   219 \item Virtual read-only network interface for monitoring and debugging
       
   220   purposes.
       
   221 \end{itemize}
       
   222 
       
   223 %------------------------------------------------------------------------------
       
   224 
       
   225 \section{License}
       
   226 \label{sec:license}
       
   227 
       
   228 The master code is released under the terms and conditions of the GNU
       
   229 General Public License\index{GPL} \cite{gpl} (version 2). Other
       
   230 developers, that want to use EtherCAT with Linux systems, are invited
       
   231 to use the master code or even participate on development.
       
   232 
       
   233 %------------------------------------------------------------------------------
       
   234 
       
   235 \section{General Master Architecture}
       
   236 \label{sec:masterarch}
       
   237 \index{Master!Architecture}
       
   238 
       
   239 The EtherCAT master is integrated into the Linux 2.6 kernel. This was
       
   240 an early design decision, which has been made for serveral reasons:
       
   241 
       
   242 \begin{itemize}
       
   243 \item Kernel code has significantly better realtime characteristics,
       
   244   i.~e. less jitter than user space code. It was foreseeable, that a
       
   245   fieldbus master has a lot of cyclic work to do. Cyclic work is
       
   246   usually triggered by timer interrupts inside the kernel. The
       
   247   execution delay of a function that processes timer interrupts is
       
   248   less, when it resides in kernel space, because there is no need of
       
   249   time-consuming context switches to a user space process.
       
   250 \item It was also foreseeable, that the master code has to directly
       
   251   communicate with the Ethernet hardware. This has to be done in the
       
   252   kernel anyway (through network device drivers), which is one more
       
   253   reason for the master code being in kernel space.
       
   254 \end{itemize}
       
   255 
       
   256 A general overview of the master architecture can be seen in
       
   257 figure~\ref{fig:masterarch}.
       
   258 
       
   259 \begin{figure}[htbp]
       
   260   \centering
       
   261   \includegraphics[width=.9\textwidth]{images/masterarch}
       
   262   \caption{Master architecture}
       
   263   \label{fig:masterarch}
       
   264 \end{figure}
       
   265 
       
   266 \paragraph{Master Module}
       
   267 \index{Master module}
       
   268 
       
   269 The EtherCAT master mainly consists of the master module, containing
       
   270 one or more EtherCAT masters (section~\ref{sec:mastermod}), the
       
   271 ``Device Interface'' (section~\ref{sec:ecdev}) and the ``Realtime
       
   272 Interface'' (section~\ref{sec:ecrt}).
       
   273 
       
   274 \paragraph{Device Modules}
       
   275 \index{Device modules}
       
   276 
       
   277 Furthermore there are EtherCAT-capable network device driver
       
   278 modules\index{Device modules}, that connect to the EtherCAT master via
       
   279 the device interface. These modified network drivers can handle both
       
   280 network devices used for EtherCAT operation and ``normal'' Ethernet
       
   281 devices. The common case is, that the master module offers a single
       
   282 EtherCAT master: An EtherCAT-capable network device driver module
       
   283 connects one network device to this master, that is now able to send
       
   284 and receive EtherCAT frames, while all other network devices handled
       
   285 by the network driver get connected to the kernel's network stack as
       
   286 usual.
       
   287 
       
   288 \paragraph{Realtime Modules}
       
   289 
       
   290 A ``realtime module''\index{Realtime module} is a kernel module, that
       
   291 uses the EtherCAT master for cyclic exchange of process data with
       
   292 EtherCAT slaves. Realtime modules are not part of the EtherCAT master
       
   293 code\footnote{Although there are serveral examples provided in the
       
   294   \textit{examples} directory, see chapter~\ref{chapter:usage} for
       
   295   more information}, so anybody wanting to use the master has to write
       
   296 one. A realtime module can ``request'' a master through the realtime
       
   297 interface. If this succeeds, the module has the control over the
       
   298 master. It can now configure slaves and set up a process data image
       
   299 (see section~\ref{sec:processdata}) for cyclic exchange. This cyclic
       
   300 code has to be provided by the realtime module, so it is in hands of
       
   301 the developer, which mechanism to use for this. Moreover he has to
       
   302 decide, whether or not using a Linux realtime extension.
       
   303 
       
   304 \paragraph{Why ``Realtime'' Module?}
       
   305 
       
   306 The name shall not imply, that a linux realtime extension is
       
   307 mandatory: The master runs well even without realtime extensions, as
       
   308 section~\ref{sec:mini} shows. However, the code using the master is
       
   309 time-critical, because process data IO has to be done in cyclic work.
       
   310 Some EtherCAT slaves support watchdog units, that stop driving the
       
   311 outputs when process data was not exchanged for some time. So the
       
   312 names ``realtime interface'' and ``realtime module'' are quite
       
   313 appropriate.
       
   314 
       
   315 %------------------------------------------------------------------------------
       
   316 
       
   317 \subsection{Handling of Process Data}
       
   318 \label{sec:processdata}
       
   319 
       
   320 \paragraph{Process Data Image}
       
   321 \index{Process data}
       
   322 
       
   323 The slaves offer their inputs and outputs by presenting the master
       
   324 so-called ``Process Data Objects'' (PDOs\index{PDO}). The available
       
   325 PDOs can be determined by reading out the slave's TXPDO and RXPDO
       
   326 E$^2$PROM categories. The realtime module can register the PDOs for
       
   327 data exchange during cyclic operation. The sum of all registered PDOs
       
   328 defines the ``process data image'', which is exchanged via the
       
   329 ``Logical ReadWrite'' datagrams introduced
       
   330 in~\cite[section~5.4.2.4]{dlspec}.
       
   331 
       
   332 \paragraph{Process Data Domains}
       
   333 \index{Domain}
       
   334 
       
   335 The process data image can be easily managed by creating co-called
       
   336 ``domains'', which group PDOs and allocate the datagrams needed to
       
   337 exchange them. Domains are mandatory for process data exchange, so
       
   338 there has to be at least one. They were introduced for the following
       
   339 reasons:
       
   340 
       
   341 \begin{itemize}
       
   342 \item The maximum size of a ``Logical ReadWrite'' datagram is limited
       
   343   due to the limited size of an Ethernet frame: The maximum data size
       
   344   is the Ethernet data field size minus the EtherCAT frame header,
       
   345   EtherCAT datagram header and EtherCAT datagram footer: $1500 - 2 -
       
   346   12 - 2 = 1484$ octets. If the size of the process data image exceeds
       
   347   this limit, multiple frames have to be sent, and the image has to be
       
   348   partitioned for the use of multiple datagrams. A domain manages this
       
   349   automatically.
       
   350 \item Not every PDO has to be exchanged with the same frequency: The
       
   351   values of PDOs can vary slowly over time (for example temperature
       
   352   values), so exchanging them with a high frequency would just waste
       
   353   bus bandwidth. For this reason, multiple domains can be created, to
       
   354   group different PDOs and so allow separate exchange.
       
   355 \end{itemize}
       
   356 
       
   357 There is no upper limit for the number of domains, but each domain
       
   358 occupies one FMMU in each slave involved, so the maximum number of
       
   359 domains is also limited by the slaves' capabilities.
       
   360 
       
   361 \paragraph{FMMU Configuration}
       
   362 \index{FMMU!Configuration}
       
   363 
       
   364 A realtime module can register PDOs for process data exchange. Every
       
   365 PDO is part of a memory area in the slave's physical memory, that is
       
   366 protected by a sync manager \cite[section~6.7]{dlspec} for
       
   367 synchronized access. In order to make a sync manager react on a
       
   368 datagram accessing its memory, it is necessary to access the last byte
       
   369 covered by the sync manager. Otherwise the sync manager will not react
       
   370 on the datagram and no data will be exchanged. That is why the whole
       
   371 synchronized memory area has to be included into the process data
       
   372 image: For example, if a certain PDO of a slave is registered for
       
   373 exchange with a certain domain, one FMMU will be configured to map the
       
   374 complete sync-manager-protected memory, the PDO resides in. If a
       
   375 second PDO of the same slave is registered for process data exchange
       
   376 within the same domain, and this PDO resides in the same
       
   377 sync-manager-protected memory as the first PDO, the FMMU configuration
       
   378 is not touched, because the appropriate memory is already part of the
       
   379 domain's process data image.  If the second PDO belongs to another
       
   380 sync-manager-protected area, this complete area is also included into
       
   381 the domains process data image. See figure~\ref{fig:fmmus} for an
       
   382 overview, how FMMU's are configured to map physical memory to logical
       
   383 process data images.
       
   384 
       
   385 \begin{figure}[htbp]
       
   386   \centering
       
   387   \includegraphics[width=\textwidth]{images/fmmus}
       
   388   \caption{FMMU configuration for serveral domains}
       
   389   \label{fig:fmmus}
       
   390 \end{figure}
       
   391 
       
   392 \paragraph{Process Data Pointers}
       
   393 
       
   394 The figure also demonstrates the way, the realtime module can access the
       
   395 exchanged process data: At PDO registration, the realtime module has
       
   396 to provide the address of a process data pointer. Upon calculation of
       
   397 the domain image and allocation of process data memory, this pointer
       
   398 is redirected to the appropriate location inside the domain's process
       
   399 data memory and can later be easily dereferenced by the module code.
       
   400 
       
   401 %------------------------------------------------------------------------------
       
   402 
       
   403 \subsection{Operation Modes}
       
   404 \index{Master modes}
       
   405 
       
   406 The EtherCAT master has serveral modes of operation:
       
   407 
       
   408 \begin{description}
       
   409 \item[Orphaned Mode] This mode takes effect, when the master has no
       
   410   EtherCAT-capable network device connected. No bus communication is
       
   411   possible, so this mode is not of further interest.
       
   412 \item[Idle Mode]\index{Idle mode} takes effect when the master is
       
   413   unused (i.~e. there is no realtime module, that reserved the
       
   414   master). In this case, the master has the ability to scan the bus by
       
   415   itsself and generously allow bus access from user space.  This mode
       
   416   is meant for maintenance and visualisation.
       
   417 \item[Operation Mode]\index{Operation mode} The master is reserved for
       
   418   exclusive access by a realtime module. In this mode, the master is
       
   419   adjusted for availability and monitoring. Access from user space is
       
   420   very restrictive and mostly limited to reading direction.
       
   421 
       
   422 \end{description}
       
   423 
       
   424 Figure~\ref{fig:modes} shows the three modes and the possible mode
       
   425 transitions.
       
   426 
       
   427 \begin{figure}[htbp]
       
   428   \centering
       
   429   \includegraphics[width=.9\textwidth]{images/modes}
       
   430   \caption{Master modes and transitions}
       
   431   \label{fig:modes}
       
   432 \end{figure}
       
   433 
       
   434 \subsubsection{Idle Mode}
       
   435 \index{Idle mode}
       
   436 
       
   437 The master enters idle mode upon connection of a device module (see
       
   438 section~\ref{sec:device}) or releasing by a realtime module. The
       
   439 master owns a kernel workqueue and a suitable work structure, which is
       
   440 used to cyclically process the ``Idle state machine'' (see
       
   441 section~\ref{sec:fsm-idle}). This state machine automatically scans
       
   442 the bus for slaves (and re-scans upon topology changes), configures
       
   443 slaves for idle operation and executes pending operations from the
       
   444 user space interface (for example E$^2$PROM writing). On device
       
   445 disconnection or realtime request, the idle mode is stopped by
       
   446 cancelling the work and flushing the workqueue.
       
   447 
       
   448 \subsubsection{Operation Mode}
       
   449 \index{Operation mode}
       
   450 
       
   451 Operation mode is entered when a realtime module requests the master.
       
   452 The idle mode is stopped and the bus is scanned by getting the number
       
   453 of slaves and executing the ``Slave scan state machine'' (see
       
   454 section~\ref{sec:fsm-scan}) for each slave. The master is now ready to
       
   455 create domains and accept PDO registrations and slave configurations.
       
   456 After that, cyclic communication can be done by the realtime module.
       
   457 
       
   458 \paragraph{Master Phases}
       
   459 
       
   460 Every realtime module should use the master in three phases:
       
   461 
       
   462 \begin{enumerate}
       
   463 \item \textit{Startup} - The master is requested and the bus is
       
   464   validated. Domains are created and PDOs are registered. Slave
       
   465   configurations are applied.
       
   466 \item \textit{Operation} - Cyclic code is run, process data is
       
   467   exchanged and the master state machine is executed.
       
   468 \item \textit{Shutdown} - Cyclic code is stopped and the master
       
   469   is released.
       
   470 \end{enumerate}
       
   471 
       
   472 %------------------------------------------------------------------------------
       
   473 
       
   474 \section{Device Modules}
       
   475 \label{sec:device}
       
   476 \index{Device modules}
       
   477 
       
   478 Device modules are network device driver modules that handle Ethernet
       
   479 devices, which the master can use to connect to an EtherCAT bus.
       
   480 
       
   481 Section~\ref{sec:networkdrivers} offers an overview of general Linux
       
   482 network driver modules, while section~\ref{sec:requirements} will show
       
   483 the requirements to an EtherCAT-enabled network driver. Finally,
       
   484 sections~\ref{sec:seldev} to~\ref{sec:patching} show how to fulfill
       
   485 these requirements and implement such a driver module.
       
   486 
       
   487 %------------------------------------------------------------------------------
       
   488 
       
   489 \subsection{Network Driver Basics}
       
   490 \label{sec:networkdrivers}
       
   491 \index{Network drivers}
       
   492 
       
   493 EtherCAT relies on Ethernet hardware and the master needs a physical
       
   494 Ethernet device to communicate with the bus. Therefore it is necessary
       
   495 to understand how Linux handles network devices and their drivers,
       
   496 respectively.
       
   497 
       
   498 \paragraph{Tasks of a Network Driver}
       
   499 
       
   500 Network device drivers handle the lower two layers of the OSI model,
       
   501 that is the physical layer and the data-link layer. A network device
       
   502 itself natively handles the physical layer issues: It represents the
       
   503 hardware to connect to the medium and to send and receive data in the
       
   504 way, the physical layer protocol describes. The network device driver
       
   505 is responsible for getting data from the kernel's networking stack and
       
   506 forwarding it to the hardware, that does the physical transmission.
       
   507 If data is received by the hardware respectively, the driver is
       
   508 notified (usually by means of an interrupt) and has to read the data
       
   509 from the hardware memory and forward it to the network stack. There
       
   510 are a few more tasks, a network device driver has to handle, including
       
   511 queue control, statistics and device dependent features.
       
   512 
       
   513 \paragraph{Driver Startup}
       
   514 
       
   515 Usually, a driver searches for compatible devices on module loading.
       
   516 For PCI drivers, this is done by scanning the PCI bus and checking for
       
   517 known device IDs. If a device is found, data structures are allocated
       
   518 and the device is taken into operation.
       
   519 
       
   520 \paragraph{Interrupt Operation}
       
   521 \index{Interrupt}
       
   522 
       
   523 A network device usually provides a hardware interrupt that is used to
       
   524 notify the driver of received frames and success of transmittion, or
       
   525 errors, respectively. The driver has to register an interrupt service
       
   526 routine (ISR\index{ISR}\nomenclature{ISR}{Interrupt Service Routine}),
       
   527 that is executed each time, the hardware signals such an event. If the
       
   528 interrupt was thrown by the own device (multiple devices can share one
       
   529 hardware interrupt), the reason for the interrupt has to be determined
       
   530 by reading the device's interrupt register. For example, if the flag
       
   531 for received frames is set, frame data has to be copied from hardware
       
   532 to kernel memory and passed to the network stack.
       
   533 
       
   534 \paragraph{The net\_device structure}
       
   535 \index{net\_device}
       
   536 
       
   537 The driver registers a \textit{net\_device} structure for each device
       
   538 to communicate with the network stack and to create a ``network
       
   539 interface''. In case of an Ethernet driver, this interface appears as
       
   540 \textit{ethX}, where X is a number assigned by the kernel on
       
   541 registration. The \textit{net\_device} structure receives events
       
   542 (either from user space or from the network stack) via serveral
       
   543 callbacks, which have to be set before registration. Not every
       
   544 callback is mandatory, but for reasonable operation the ones below are
       
   545 needed in any case:
       
   546 
       
   547 \begin{description}
       
   548 \item[int (*open)(struct net\_device *)] This function is called when
       
   549   network communication has to be started, for example after a command
       
   550   \textit{ifconfig ethX up} from user space. Frame reception has to be
       
   551   enabled by the driver.
       
   552 \item[int (*stop)(struct net\_device *)] The purpose of this callback
       
   553   is to ``close'' the device, i.~e. make the hardware stop receiving
       
   554   frames.
       
   555 \item[int (*hard\_start\_xmit)(struct sk\_buff *, struct net\_device
       
   556   *)] This function is cal\-led for each frame that has to be
       
   557   transmitted.  The network stack passes the frame as a pointer to an
       
   558   \textit{sk\_buff} structure (``socket buffer''\index{Socket buffer},
       
   559   see below), which has to be freed after sending.
       
   560 \item[struct net\_device\_stats *(*get\_stats)(struct net\_device *)]
       
   561   This call has to return a pointer to the device's
       
   562   \textit{net\_device\_stats} structure, which permanently has to be
       
   563   filled with frame statistics. This means, that everytime a frame is
       
   564   received, sent, or an error happened, the appropriate counter in
       
   565   this structure has to be increased.
       
   566 \end{description}
       
   567 
       
   568 The actual registration is done with the \textit{register\_netdev()}
       
   569 call, unregistering is done with \textit{unregister\_netdev()}.
       
   570 
       
   571 \paragraph{The netif Interface}
       
   572 \index{netif}
       
   573 
       
   574 All other communication in the direction interface $\to$ network stack
       
   575 is done via the \textit{netif\_*} calls. For example, on successful
       
   576 device opening, the network stack has to be notified, that it can now
       
   577 pass frames to the interface. This is done by calling
       
   578 \textit{netif\_start\_queue()}. After this call, the
       
   579 \textit{hard\_start\_xmit()} callback can be called by the network
       
   580 stack. Furthermore a network driver usually manages a frame
       
   581 transmission queue. If this gets filled up, the network stack has to
       
   582 be told to stop passing further frames for a while. This happens with
       
   583 a call to \textit{netif\_stop\_queue()}. If some frames have been
       
   584 sent, and there is enough space again to queue new frames, this can be
       
   585 notified with \textit{netif\_wake\_queue()}. Another important call is
       
   586 \textit{netif\_receive\_skb()}\footnote{This function is part of the
       
   587   NAPI (``New API''), that replaces the ``old'' kernel 2.4 technique
       
   588   for interfacing to the network stack (with \textit{netif\_rx()}).
       
   589   NAPI is a technique to improve network performance on Linux. Read
       
   590   more in
       
   591   http://www.cyberus.ca/\textasciitilde{}hadi/usenix-paper.tgz}: It
       
   592 passes a frame to the network stack, that was just received by the
       
   593 device.  Frame data has to be packed into a so-called ``socket
       
   594 buffer'' for that (see below).
       
   595 
       
   596 \paragraph{Socket Buffers}
       
   597 \index{Socket buffer}
       
   598 
       
   599 Socket buffers are the basic data type for the whole network stack.
       
   600 They serve as containers for network data and are able to quickly add
       
   601 data headers and footers, or strip them off again. Therefore a socket
       
   602 buffer consists of an allocated buffer and serveral pointers that mark
       
   603 beginning of the buffer (\textit{head}), beginning of data
       
   604 (\textit{data}), end of data (\textit{tail}) and end of buffer
       
   605 (\textit{end}). In addition, a socket buffer holds network header
       
   606 information and (in case of received data) a pointer to the
       
   607 \textit{net\_device}, it was received on. There exist functions that
       
   608 create a socket buffer (\textit{dev\_alloc\_skb()}), add data either
       
   609 from front (\textit{skb\_push()}) or back (\textit{skb\_put()}),
       
   610 remove data from front (\textit{skb\_pull()}) or back
       
   611 (\textit{skb\_trim()}), or delete the buffer (\textit{kfree\_skb()}).
       
   612 A socket buffer is passed from layer to layer, and is freed by the
       
   613 layer that uses it the last time. In case of sending, freeing has to
       
   614 be done by the network driver.
       
   615 
       
   616 %------------------------------------------------------------------------------
       
   617 
       
   618 \subsection{EtherCAT Network Drivers}
       
   619 \label{sec:requirements}
       
   620 
       
   621 There are a few requirements for Ethernet network devices to function
       
   622 as EtherCAT devices, when connected to an EtherCAT bus.
       
   623 
       
   624 \paragraph{Dedicated Interfaces}
       
   625 
       
   626 For performance and realtime purposes, the EtherCAT master needs
       
   627 direct and exclusive access to the Ethernet hardware. This implies
       
   628 that the network device must not be connected to the kernel's network
       
   629 stack as usual, because the kernel would try to use it as an ordinary
       
   630 Ethernet device.
       
   631 
       
   632 \paragraph{Interrupt-less Operation}
       
   633 \index{Interrupt}
       
   634 
       
   635 EtherCAT frames travel through the logical EtherCAT ring and are then
       
   636 sent back to the master. Communication is highly deterministic: A
       
   637 frame is sent and will be received again after a constant time.
       
   638 Therefore, there is no need to notify the driver about frame
       
   639 reception: The master can instead query the hardware for received
       
   640 frames.
       
   641 
       
   642 Figure~\ref{fig:interrupt} shows two workflows for cyclic frame
       
   643 transmittion and reception with and without interrupts.
       
   644 
       
   645 \begin{figure}[htbp]
       
   646   \centering
       
   647   \includegraphics[width=.8\textwidth]{images/interrupt}
       
   648   \caption{Interrupt Operation versus Interrupt-less Operation}
       
   649   \label{fig:interrupt}
       
   650 \end{figure}
       
   651 
       
   652 In the left workflow ``Interrupt Operation'', the data from the last
       
   653 cycle is first processed and a new frame is assembled with new
       
   654 datagrams, which is then sent.  The cyclic work is done for now.
       
   655 Later, when the frame is received again by the hardware, an interrupt
       
   656 is triggered and the ISR is executed. The ISR will fetch the frame
       
   657 data from the hardware and initiate the frame dissection: The
       
   658 datagrams will be processed, so that the data is ready for processing
       
   659 in the next cycle.
       
   660 
       
   661 In the right workflow ``Interrupt-less Operation'', there is no
       
   662 hardware interrupt enabled.  Instead, the hardware will be polled by
       
   663 the master by executing the ISR. If the frame has been received in the
       
   664 meantime, it will be dissected. The situation is now the same as at
       
   665 the beginning of the left workflow: The received data is processed and
       
   666 a new frame is assembled and sent. There is nothing to do for the rest
       
   667 of the cycle.
       
   668 
       
   669 The interrupt-less operation is desirable, because there is simply no
       
   670 need for an interrupt. Moreover hardware interrupts are not conducive
       
   671 in improving the driver's realtime behaviour: Their undeterministic
       
   672 incidences contribute to increasing the jitter. Besides, if a realtime
       
   673 extension (like RTAI) is used, some additional effort would have to be
       
   674 made to priorize interrupts.
       
   675 
       
   676 \paragraph{Ethernet and EtherCAT Devices}
       
   677 
       
   678 Another issue lies in the way Linux handles devices of the same type.
       
   679 For example, a PCI\nomenclature{PCI}{Peripheral Component
       
   680   Interconnect, Computer Bus} driver scans the PCI bus for devices it
       
   681 can handle. Then it registers itself as the responsible driver for all
       
   682 of the devices found. The problem is, that an unmodified driver can
       
   683 not be told to ignore a device because it will be used for EtherCAT
       
   684 later. There must be a way to handle multiple devices of the same
       
   685 type, where one is reserved for EtherCAT, while the other is treated
       
   686 as an ordinary Ethernet device.
       
   687 
       
   688 For all this reasons, the author has decided that the only acceptable
       
   689 solution is to modify standard Ethernet drivers in a way that they
       
   690 keep their normal functionality, but gain the ability to treat one or
       
   691 more of the devices as EtherCAT-capable.
       
   692 
       
   693 Below are the advantages of this solution:
       
   694 
       
   695 \begin{itemize}
       
   696 \item No need to tell the standard drivers to ignore certain devices.
       
   697 \item One networking driver for EtherCAT and non-EtherCAT devices.
       
   698 \item No need to implement a network driver from scratch and running
       
   699   into issues, the former developers already solved.
       
   700 \end{itemize}
       
   701 
       
   702 The chosen approach has the following disadvantages:
       
   703 
       
   704 \begin{itemize}
       
   705 \item The modified driver gets more complicated, as it must handle
       
   706   EtherCAT and non-EtherCAT devices.
       
   707 \item Many additional case differentiations in the driver code.
       
   708 \item Changes and bugfixes on the standard drivers have to be ported
       
   709   to the Ether\-CAT-capable versions from time to time.
       
   710 \end{itemize}
       
   711 
       
   712 %------------------------------------------------------------------------------
       
   713 
       
   714 \subsection{Device Selection}
       
   715 \label{sec:seldev}
       
   716 
       
   717 After loading the master module, at least one EtherCAT-capable network
       
   718 driver module has to be loaded, that connects one of its devices to
       
   719 the master. To specify an EtherCAT device and the master to connect
       
   720 to, all EtherCAT-capable network driver modules should provide two
       
   721 module parameters:
       
   722 
       
   723 \begin{description}
       
   724 \item[ec\_device\_index] PCI device index of the device that is
       
   725   connected to the EtherCAT bus. If this parameter is left away, all
       
   726   devices found are treated as ordinary Ethernet devices. Default:
       
   727   $-1$
       
   728 \item[ec\_master\_index] Index of the master to connect to. Default:
       
   729   $0$
       
   730 \end{description}
       
   731 
       
   732 The following command loads the EtherCAT-capable RTL8139 device
       
   733 driver, telling it to handle the second device as an EtherCAT device
       
   734 and connecting it to the first master:
       
   735 
       
   736 \begin{lstlisting}
       
   737   host# `\textbf{modprobe ec\_8139too ec\_device\_index=1}`
       
   738 \end{lstlisting}
       
   739 
       
   740 Usually, this command does not have to be entered manually, but is
       
   741 called by the EtherCAT init script. See section~\ref{sec:init} for
       
   742 more information.
       
   743 
       
   744 %------------------------------------------------------------------------------
       
   745 
       
   746 \subsection{The Device Interface}
       
   747 \label{sec:ecdev}
       
   748 \index{Device interface}
       
   749 
       
   750 An anticipation to the section about the master module
       
   751 (section~\ref{sec:mastermod}) has to be made in order to understand
       
   752 the way, a network device driver module can connect a device to a
       
   753 specific EtherCAT master.
       
   754 
       
   755 The master module provides a ``device interface'' for network device
       
   756 drivers. To use this interface, a network device driver module must
       
   757 include the header
       
   758 \textit{devices/ecdev.h}\nomenclature{ecdev}{EtherCAT Device}, coming
       
   759 with the EtherCAT master code. This header offers a function interface
       
   760 for EtherCAT devices which is explained below. All functions of the
       
   761 device interface are named with the prefix \textit{ecdev}.
       
   762 
       
   763 \paragraph{Device Registration}
       
   764 
       
   765 A network device driver can connect a physical device to an EtherCAT
       
   766 master with the \textit{ecdev\_register()} function.
       
   767 
       
   768 \begin{lstlisting}[language=C]
       
   769   ec_device_t *ecdev_register(unsigned int master_index,
       
   770                               struct net_device *net_dev,
       
   771                               ec_isr_t isr,
       
   772                               struct module *module);
       
   773 \end{lstlisting}
       
   774 
       
   775 The first parameter \textit{master\_index} must be the index of the
       
   776 EtherCAT master to connect to (see section~\ref{sec:mastermod}),
       
   777 followed by \textit{net\_dev}, the pointer to the corresponding
       
   778 net\_device structure, which represents the network device to connect.
       
   779 The third parameter \textit{isr} must be a pointer to the interrupt
       
   780 service routine (ISR\index{ISR}) handling the device. The master will
       
   781 later execute the ISR in order to receive frames and to update the
       
   782 device status. The last parameter \textit{module} must be the pointer
       
   783 to the device driver module, which is usually accessible via the macro
       
   784 \textit{THIS\_MODULE} (see next paragraph). On success, the function
       
   785 returns a pointer to an \textit{ec\_device\_t} object, which has to be
       
   786 specified when calling further functions of the device interface.
       
   787 Therefore the device module has to store this pointer for future use.
       
   788 In error case, the \textit{ecdev\_register()} returns \textit{NULL},
       
   789 which means that the device could not be registered.  The reason for
       
   790 this is printed to \textit{syslog}\index{syslog}. In this case, the
       
   791 device module is supposed to abort the module initialisation and let
       
   792 the \textit{insmod} command fail.
       
   793 
       
   794 \paragraph{Implicit Dependencies}
       
   795 
       
   796 The reason for the module pointer has to be specified at device
       
   797 registration is a non-trivial one: The master has to know about the
       
   798 module, because there will be an implicit dependency between the
       
   799 device module and a later connected realtime module: When a realtime
       
   800 module connects to the master, the use count of the master module will
       
   801 be increased, so that the master module can not be unloaded for the
       
   802 time of the connection. This is reasonable, and so automatically done
       
   803 by the kernel. The kernel knows about this dependency, because the
       
   804 realtime module uses kernel symbols provided by the master module.
       
   805 Moreover it is mandatory, that the device module can be unloaded
       
   806 neither, because it is implicitely used by the realtime module, too.
       
   807 Unloading it would lead to a fatal situation, because the master would
       
   808 have no device to send and receive frames for the realtime module.
       
   809 This dependency can not be detected automatically, because the
       
   810 realtime module does not use any symbols of the device module.
       
   811 Therefore the master explicitly increments the use counter of the
       
   812 connected device module upon connection of a realtime module and
       
   813 decrements it, if the realtime module disconnects. In this manner, it
       
   814 is impossible to unload a device module while the master is in use.
       
   815 This is done with the kernel function pair \textit{try\_module\_get()}
       
   816 \index{try\_module\_get@\textit{try\_module\_get()}} and
       
   817 \textit{module\_put()} \index{module\_put@\textit{module\_put()}}. The
       
   818 first one increases the use count of a module and only fails, if the
       
   819 module is currenly being unloaded. The last one decreases the use
       
   820 count again and never fails. Both functions take a pointer to the
       
   821 module as their argument, which the device module therefore has to
       
   822 specify upon device registration.
       
   823 
       
   824 \paragraph{Device Unregistering}
       
   825 
       
   826 The unregistration of a device is usually done in the device module's
       
   827 cleanup function, by calling the \textit{ecdev\_unregister()} function
       
   828 and specifying the master index and a pointer to the device object
       
   829 again.
       
   830 
       
   831 \begin{lstlisting}[language=C]
       
   832   void ecdev_unregister(unsigned int master_index,
       
   833                         ec_device_t *device);
       
   834 \end{lstlisting}
       
   835 
       
   836 This function can fail too (if the master index is invalid, or the
       
   837 given device was not registered), but due to the fact, that this
       
   838 failure can not be dealt with appropriately, because the device module
       
   839 is unloading anyway, the failure code would not be of any interest. So
       
   840 the function has a void return value.
       
   841 
       
   842 \paragraph{Starting the Master}
       
   843 
       
   844 When a device has been initialized completely and is ready to send and
       
   845 receive frames, the master has to be notified about this by calling
       
   846 the \textit{ecdev\_start()} function.
       
   847 
       
   848 \begin{lstlisting}[language=C]
       
   849   int ecdev_start(unsigned int master_index);
       
   850 \end{lstlisting}
       
   851 
       
   852 The master will then enter ``Idle Mode'' and start scanning the bus
       
   853 (and possibly handling EoE slaves). Moreover it will make the bus
       
   854 accessible via Sysfs interface and react to user interactions. The
       
   855 function takes one parameter \textit{master\_index}, which has to be
       
   856 the same as at the call to \textit{ecdev\_register()}. The return
       
   857 value will be non-zero if the starting process failed. In this case
       
   858 the device module is supposed to abort the init sequence and make the
       
   859 init function return an error code.
       
   860 
       
   861 \paragraph{Stopping the Master}
       
   862 
       
   863 Before a device can be unregistered, the master has to be stopped by
       
   864 calling the \textit{ecdev\_stop()} function. It will stop processing
       
   865 messages of EoE slaves and leave ``Idle Mode''. The only parameter is
       
   866 \textit{master\_index}. This function can not fail.
       
   867 
       
   868 \begin{lstlisting}[language=C]
       
   869   void ecdev_stop(unsigned int master_index);
       
   870 \end{lstlisting}
       
   871 
       
   872 A subsequent call to \textit{ecdev\_unregister()} will now unregister
       
   873 the device savely.
       
   874 
       
   875 \paragraph{Receiving Frames}
       
   876 
       
   877 The interrupt service routine handling device events usually has a
       
   878 section where new frames are fetched from the hardware and forwarded
       
   879 to the kernel network stack via \textit{netif\_receive\_skb()}. For an
       
   880 EtherCAT-capable device, this has to be replaced by calling the
       
   881 \textit{ecdev\_receive()} function to forward the received data to the
       
   882 connected EtherCAT master instead.
       
   883 
       
   884 \begin{lstlisting}[language=C]
       
   885   void ecdev_receive(ec_device_t *device,
       
   886                      const void *data,
       
   887                      size_t size);
       
   888 \end{lstlisting}
       
   889 
       
   890 This function takes 3 arguments, a pointer to the device object
       
   891 (\textit{device}), a pointer to the received data, and the size of the
       
   892 received data. The data range has to include the Ethernet headers
       
   893 starting with the destination address and reach up to the last octet
       
   894 of EtherCAT data, excluding the FCS. Most network devices handle the
       
   895 FCS in hardware, so it is not seen by the driver code and therefore
       
   896 doesn't have to be cut off manually.
       
   897 
       
   898 \paragraph{Handling the Link Status}
       
   899 
       
   900 Information about the link status (i.~e. if there is a carrier signal
       
   901 detected on the physical port) is also important to the master. This
       
   902 information is usually gathered by the ISR and should be forwarded to
       
   903 the master by calling the \textit{ecdev\_link\_state()} function. The
       
   904 master then can react on this and warn the realtime module of a lost
       
   905 link.
       
   906 
       
   907 \begin{lstlisting}[language=C]
       
   908   void ecdev_link_state(ec_device_t *device,
       
   909                         uint8_t new_state);
       
   910 \end{lstlisting}
       
   911 
       
   912 The parameter \textit{device} has to be a pointer to the device object
       
   913 returned by \textit{ecdev\_\-register()}. With the second parameter
       
   914 \textit{new\_state}, the new link state is passed: 1, if the link went
       
   915 up, and 0, if it went down.
       
   916 
       
   917 %------------------------------------------------------------------------------
       
   918 
       
   919 \subsection{Patching Network Drivers}
       
   920 \label{sec:patching}
       
   921 \index{Network drivers}
       
   922 
       
   923 This section will demonstrate, how to make a standard Ethernet driver
       
   924 EtherCAT-capable. The below code examples are taken out of the
       
   925 modified RealTek RTL8139 driver coming with the EtherCAT master
       
   926 (\textit{devices/8139too.c}). The driver was originally developed by
       
   927 Donald Becker, and is currently maintained by Jeff Garzik.
       
   928 
       
   929 Unfortunately, there is no standard procedure to enable an Ethernet
       
   930 driver for use with the EtherCAT master, but there are a few common
       
   931 techniques, that are described in this section.
       
   932 
       
   933 \begin{enumerate}
       
   934 \item A first simple rule is, that \textit{netif\_*()}-calls must be
       
   935   strictly avoided for all EtherCAT devices. As mentioned before,
       
   936   EtherCAT devices have no connection to the network stack, and
       
   937   therefore must not call its interface functions.
       
   938 \item Another important thing is, that EtherCAT devices should be
       
   939   operated without interrupts. So any calls of registering interrupt
       
   940   handlers and enabling interrupts at hardware level must be avoided,
       
   941   too.
       
   942 \item The master does not use a new socket buffer for each send
       
   943   operation: Instead there is a fix one allocated on master
       
   944   initialization. This socket buffer is filled with an EtherCAT frame
       
   945   with every send operation and passed to the
       
   946   \textit{hard\_start\_xmit()} callback. For that it is necessary,
       
   947   that the socket buffer is not be freed by the network driver as
       
   948   usual.
       
   949 \end{enumerate}
       
   950 
       
   951 As mentioned before, the driver will handle both EtherCAT and ordinary
       
   952 Ethernet devices. This implies, that for each device-dependent
       
   953 operation, it has to be checked if an EtherCAT device is involved, or
       
   954 just an Ethernet device. For means of simplicity, this example driver
       
   955 will only handle one EtherCAT device. This makes the case
       
   956 differentiations easier.
       
   957 
       
   958 \paragraph{Global Variables}
       
   959 
       
   960 First of all, there have to be additional global variables declared,
       
   961 as shown in the listing:
       
   962 
       
   963 \begin{lstlisting}[language=C,numbers=left]
       
   964   static int ec_device_index = -1;
       
   965   static int ec_device_master_index = 0;
       
   966   static ec_device_t *rtl_ec_dev;
       
   967   struct net_device *rtl_ec_net_dev = NULL;
       
   968 \end{lstlisting}
       
   969 
       
   970 \begin{description}
       
   971 \item[\normalfont\textcircled{\tiny 1} -- \textcircled{\tiny 2}] To
       
   972   comply to the requirements for parameters of EtherCAT device modules
       
   973   described in section~\ref{sec:seldev}, there have to be additional
       
   974   parameter variables: \textit{ec\_\-device\_\-index} holds the index
       
   975   of the EtherCAT device and defaults to $-1$ (no EtherCAT device),
       
   976   while \textit{ec\_device\_master\_index} stores index of the master,
       
   977   the single device will be connected to. Default: $0$
       
   978 \item[\normalfont\textcircled{\tiny 3}] \textit{rtl\_ec\_dev} will be
       
   979   the pointer to the later registered RealTek EtherCAT device, which
       
   980   can be used as a parameter for device methods.
       
   981 \item[\normalfont\textcircled{\tiny 4}] \textit{rtl\_ec\_net\_dev} is
       
   982   a pointer to the \textit{net\_device} structure of the dedicated
       
   983   device and is set while scanning the PCI bus and finding the device
       
   984   with the specified index. This is done inside the
       
   985   \textit{pci\_module\_init()} function executed as the first thing on
       
   986   module loading.
       
   987 \end{description}
       
   988 
       
   989 \paragraph{Module Initialization}
       
   990 
       
   991 Below is the (shortened) coding of the device driver's module init
       
   992 function:
       
   993 
       
   994 \begin{lstlisting}[language=C,numbers=left]
       
   995   static int __init rtl8139_init_module(void)
       
   996   {
       
   997           if (pci_module_init(&rtl8139_pci_driver) < 0) {
       
   998                   printk(KERN_ERR "Failed to init PCI mod.\n");
       
   999                   goto out_return;
       
  1000           }
       
  1001 
       
  1002           if (rtl_ec_net_dev) {
       
  1003                   printk(KERN_INFO "Registering"
       
  1004                          " EtherCAT device...\n");
       
  1005                   if (!(rtl_ec_dev =
       
  1006                           ecdev_register(ec_device_master_index,
       
  1007                                          rtl_ec_net_dev,
       
  1008                                          rtl8139_interrupt,
       
  1009                                          THIS_MODULE))) {
       
  1010                           printk(KERN_ERR "Failed to reg."
       
  1011                                           " EtherCAT device!\n");
       
  1012                           goto out_unreg_pci;
       
  1013                   }
       
  1014 
       
  1015                   printk(KERN_INFO "Starting EtherCAT"
       
  1016                          " device...\n");
       
  1017                   if (ecdev_start(ec_device_master_index)) {
       
  1018                           printk(KERN_ERR "Failed to start"
       
  1019                                  " EtherCAT device!\n");
       
  1020                           goto out_unreg_ec;
       
  1021                   }
       
  1022           } else {
       
  1023                   printk(KERN_WARNING "No EtherCAT device"
       
  1024                          " registered!\n");
       
  1025           }
       
  1026 
       
  1027           return 0;
       
  1028 
       
  1029       out_unreg_ec:
       
  1030           ecdev_unregister(ec_device_master_index, rtl_ec_dev);
       
  1031       out_unreg_pci:
       
  1032           pci_unregister_driver(&rtl8139_pci_driver);
       
  1033       out_return:
       
  1034           return -1;
       
  1035   }
       
  1036 \end{lstlisting}
       
  1037 
       
  1038 \begin{description}
       
  1039 \item[\normalfont\textcircled{\tiny 3}] This call initializes all
       
  1040   RTL8139-compatible devices found on the pci bus. If a device with
       
  1041   index \textit{ec\_device\_index} is found, a pointer to its
       
  1042   \textit{net\_device} structure is stored in
       
  1043   \textit{rtl\_ec\_net\_dev} for later use (see next listings).
       
  1044 \item[\normalfont\textcircled{\tiny 8}] If the specified device was
       
  1045   found, \textit{rtl\_ec\_net\_dev} is non-zero.
       
  1046 \item[\normalfont\textcircled{\tiny 11}] The device is connected to
       
  1047   the specified master with a call to \textit{ecdev\_register()}. If
       
  1048   this fails, module loading is aborted.
       
  1049 \item[\normalfont\textcircled{\tiny 23}] The device registration was
       
  1050   successful and the master is started. This can fail, which aborts
       
  1051   module loading.
       
  1052 \item[\normalfont\textcircled{\tiny 29}] If no EtherCAT device was
       
  1053   found, a warning is output.
       
  1054 \end{description}
       
  1055 
       
  1056 \paragraph{Device Searching}
       
  1057 
       
  1058 During the PCI initialization phase, a variable \textit{board\_idx} is
       
  1059 increased for each RTL8139-compatible device found. The code below is
       
  1060 executed for each device:
       
  1061 
       
  1062 \begin{lstlisting}[language=C,numbers=left]
       
  1063   if (board_idx == ec_device_index) {
       
  1064           rtl_ec_net_dev = dev;
       
  1065           strcpy(dev->name, "ec0");
       
  1066   }
       
  1067 \end{lstlisting}
       
  1068 
       
  1069 \begin{description}
       
  1070 \item[\normalfont\textcircled{\tiny 1}] The device with the specified
       
  1071   index will be the EtherCAT device.
       
  1072 \end{description}
       
  1073 
       
  1074 \paragraph{Avoiding Device Registration}
       
  1075 
       
  1076 Later in the PCI initialization phase, the net\_devices get
       
  1077 registered. This has to be avoided for EtherCAT devices and so this is
       
  1078 a typical example for an EtherCAT case differentiation:
       
  1079 
       
  1080 \begin{lstlisting}[language=C,numbers=left]
       
  1081   if (dev != rtl_ec_net_dev) {
       
  1082           i = register_netdev(dev);
       
  1083           if (i) goto err_out;
       
  1084   }
       
  1085 \end{lstlisting}
       
  1086 
       
  1087 \begin{description}
       
  1088 \item[\normalfont\textcircled{\tiny 1}] If the current net\_device is
       
  1089   not the EtherCAT device, it is registered at the network stack.
       
  1090 \end{description}
       
  1091 
       
  1092 \paragraph{Avoiding Interrupt Registration}
       
  1093 
       
  1094 In the next two listings, there is an interrupt requested and the
       
  1095 device's interrupts are enabled. This also has to be encapsulated by
       
  1096 if-clauses, because interrupt operation is not wanted for EtherCAT
       
  1097 devices.
       
  1098 
       
  1099 \begin{lstlisting}[language=C,numbers=left]
       
  1100   if (dev != rtl_ec_net_dev) {
       
  1101           retval = request_irq(dev->irq, rtl8139_interrupt,
       
  1102                                SA_SHIRQ, dev->name, dev);
       
  1103           if (retval) return retval;
       
  1104   }
       
  1105 \end{lstlisting}
       
  1106 
       
  1107 \begin{lstlisting}[language=C,numbers=left]
       
  1108   if (dev != rtl_ec_net_dev) {
       
  1109           /* Enable all known interrupts by setting
       
  1110              the interrupt mask. */
       
  1111           RTL_W16(IntrMask, rtl8139_intr_mask);
       
  1112   }
       
  1113 \end{lstlisting}
       
  1114 
       
  1115 \paragraph{Frame Sending}
       
  1116 
       
  1117 The listing below shows an exerpt of the function representing the
       
  1118 \textit{hard\_start\_xmit()} callback of the net\_device.
       
  1119 
       
  1120 \begin{lstlisting}[language=C,numbers=left]
       
  1121   /* Note: the chip doesn't have auto-pad! */
       
  1122   if (likely(len < TX_BUF_SIZE)) {
       
  1123           if (len < ETH_ZLEN)
       
  1124                   memset(tp->tx_buf[entry], 0, ETH_ZLEN);
       
  1125           skb_copy_and_csum_dev(skb, tp->tx_buf[entry]);
       
  1126           if (dev != rtl_ec_net_dev) {
       
  1127                   dev_kfree_skb(skb);
       
  1128           }
       
  1129   } else {
       
  1130           if (dev != rtl_ec_net_dev) {
       
  1131                   dev_kfree_skb(skb);
       
  1132           }
       
  1133           tp->stats.tx_dropped++;
       
  1134           return 0;
       
  1135   }
       
  1136 \end{lstlisting}
       
  1137 
       
  1138 \begin{description}
       
  1139 \item[\normalfont\textcircled{\tiny 6} + \textcircled{\tiny 10}] The
       
  1140   master uses a fixed socket buffer for transmission, which is reused
       
  1141   and may not be freed.
       
  1142 \end{description}
       
  1143 
       
  1144 \paragraph{Frame Receiving}
       
  1145 
       
  1146 During ordinary frame reception, a socket buffer is created and filled
       
  1147 with the received data. This is not necessary for an EtherCAT device:
       
  1148 
       
  1149 \begin{lstlisting}[language=C,numbers=left]
       
  1150   if (dev != rtl_ec_net_dev) {
       
  1151           /* Malloc up new buffer, compatible with net-2e. */
       
  1152           /* Omit the four octet CRC from the length. */
       
  1153 
       
  1154           skb = dev_alloc_skb (pkt_size + 2);
       
  1155           if (likely(skb)) {
       
  1156                   skb->dev = dev;
       
  1157                   skb_reserve(skb, 2); /* 16 byte align
       
  1158                                           the IP fields. */
       
  1159                   eth_copy_and_sum(skb, &rx_ring[ring_off + 4],
       
  1160                                    pkt_size, 0);
       
  1161                   skb_put(skb, pkt_size);
       
  1162                   skb->protocol = eth_type_trans(skb, dev);
       
  1163 
       
  1164                   dev->last_rx = jiffies;
       
  1165                   tp->stats.rx_bytes += pkt_size;
       
  1166                   tp->stats.rx_packets++;
       
  1167 
       
  1168                   netif_receive_skb (skb);
       
  1169           } else {
       
  1170                   if (net_ratelimit())
       
  1171                           printk(KERN_WARNING
       
  1172                                  "%s: Memory squeeze, dropping"
       
  1173                                  " packet.\n", dev->name);
       
  1174                   tp->stats.rx_dropped++;
       
  1175           }
       
  1176   } else {
       
  1177           ecdev_receive(rtl_ec_dev,
       
  1178                         &rx_ring[ring_offset + 4], pkt_size);
       
  1179           dev->last_rx = jiffies;
       
  1180           tp->stats.rx_bytes += pkt_size;
       
  1181           tp->stats.rx_packets++;
       
  1182   }
       
  1183 \end{lstlisting}
       
  1184 
       
  1185 \begin{description}
       
  1186 \item[\normalfont\textcircled{\tiny 28}] If the device is an EtherCAT
       
  1187   device, no socket buffer is allocated. Instead a pointer to the data
       
  1188   (which is still in the device's receive ring) is passed to the
       
  1189   EtherCAT master. Unnecessary copy operations are avoided.
       
  1190 \item[\normalfont\textcircled{\tiny 30} -- \textcircled{\tiny 32}] The
       
  1191   device's statistics are updated as usual.
       
  1192 \end{description}
       
  1193 
       
  1194 \paragraph{Link State}
       
  1195 
       
  1196 The link state (i.~e. if there is a carrier signal detected on the
       
  1197 receive port) is determined during execution of the ISR. The listing
       
  1198 below shows the different processing for Ethernet and EtherCAT
       
  1199 devices:
       
  1200 
       
  1201 \begin{lstlisting}[language=C,numbers=left]
       
  1202   if (dev != rtl_ec_net_dev) {
       
  1203           if (tp->phys[0] >= 0) {
       
  1204                   mii_check_media(&tp->mii, netif_msg_link(tp),
       
  1205                                   init_media);
       
  1206           }
       
  1207   } else {
       
  1208           void __iomem *ioaddr = tp->mmio_addr;
       
  1209           uint16_t link = RTL_R16(BasicModeStatus)
       
  1210                           & BMSR_LSTATUS;
       
  1211           ecdev_link_state(rtl_ec_dev, link ? 1 : 0);
       
  1212   }
       
  1213 \end{lstlisting}
       
  1214 
       
  1215 \begin{description}
       
  1216 \item[\normalfont\textcircled{\tiny 3}] The ``media check'' is done
       
  1217   via the media independent interface (MII\nomenclature{MII}{Media
       
  1218     Independent Interface}), a standard interface for Fast Ethernet
       
  1219   devices.
       
  1220 \item[\normalfont\textcircled{\tiny 7} -- \textcircled{\tiny 10}] For
       
  1221   EtherCAT devices, the link state is fetched manually from the
       
  1222   appropriate device register, and passed to the EtherCAT master by
       
  1223   calling \textit{ecdev\_\-link\_\-state()}.
       
  1224 \end{description}
       
  1225 
       
  1226 \paragraph{Module Cleanup}
       
  1227 
       
  1228 Below is the module's cleanup function:
       
  1229 
       
  1230 \begin{lstlisting}[language=C,numbers=left]
       
  1231   static void __exit rtl8139_cleanup_module (void)
       
  1232   {
       
  1233           printk(KERN_INFO "Cleaning up RTL8139-EtherCAT"
       
  1234                  " module...\n");
       
  1235 
       
  1236           if (rtl_ec_net_dev) {
       
  1237                   printk(KERN_INFO "Stopping device...\n");
       
  1238                   ecdev_stop(ec_device_master_index);
       
  1239                   printk(KERN_INFO "Unregistering device...\n");
       
  1240                   ecdev_unregister(ec_device_master_index,
       
  1241                                    rtl_ec_dev);
       
  1242                   rtl_ec_dev = NULL;
       
  1243           }
       
  1244 
       
  1245           pci_unregister_driver(&rtl8139_pci_driver);
       
  1246 
       
  1247           printk(KERN_INFO "RTL8139-EtherCAT module"
       
  1248                  " cleaned up.\n");
       
  1249   }
       
  1250 \end{lstlisting}
       
  1251 
       
  1252 \begin{description}
       
  1253 \item[\normalfont\textcircled{\tiny 6}] Stopping and unregistration is
       
  1254   only done, if a device was registered before.
       
  1255 \item[\normalfont\textcircled{\tiny 8}] The master is first stopped,
       
  1256   so it does not access the device any more.
       
  1257 \item[\normalfont\textcircled{\tiny 10}] After this, the device is
       
  1258   unregistered. The master is now ``ophaned''.
       
  1259 \end{description}
       
  1260 
       
  1261 %------------------------------------------------------------------------------
       
  1262 
       
  1263 \section{The Master Module}
       
  1264 \label{sec:mastermod}
       
  1265 \index{Master module}
       
  1266 
       
  1267 The EtherCAT master is designed to run as a kernel module. Moreover
       
  1268 the master kernel module \textit{ec\_master} can handle multiple
       
  1269 masters at the same time: The number of masters has to be passed to
       
  1270 the module with the parameter \textit{ec\_master\_count}, that
       
  1271 defaults to $1$. A certain master can later be addressed by its index.
       
  1272 For example, if the master module has been loaded with the command
       
  1273 
       
  1274 \begin{lstlisting}
       
  1275   host# `\textbf{modprobe ec\_master ec\_master\_count=2}`
       
  1276 \end{lstlisting}
       
  1277 
       
  1278 the two masters can be addressed by their indices 0 and 1 respectively
       
  1279 (see figure~\ref{fig:masters}). This master index mandatory for
       
  1280 certain functions of the master interfaces.
       
  1281 
       
  1282 \begin{figure}[htbp]
       
  1283   \centering
       
  1284   \includegraphics[width=.5\textwidth]{images/masters}
       
  1285   \caption{Multiple masters in one module}
       
  1286   \label{fig:masters}
       
  1287 \end{figure}
       
  1288 
       
  1289 \paragraph{Master Log Messages}
       
  1290 
       
  1291 The master module gives information about it's state and events via
       
  1292 the syslog interface. The module loading command above should result
       
  1293 in the following syslog messages:
       
  1294 
       
  1295 \begin{lstlisting}
       
  1296   EtherCAT: Master driver, 1.1 (stable) - rev. 513,
       
  1297             compiled by fp at Aug  09 2006 09:43:50
       
  1298   EtherCAT: Initializing 2 EtherCAT master(s)...
       
  1299   EtherCAT: Initializing master 0.
       
  1300   EtherCAT: Initializing master 1.
       
  1301   EtherCAT: Master driver initialized.
       
  1302 \end{lstlisting}
       
  1303 
       
  1304 The master provides information about it's version number, subversion
       
  1305 revision number and compile information, like the date of compilation
       
  1306 and the user, who compiled. All messages are prefixed either with
       
  1307 \texttt{EtherCAT:}, \texttt{EtherCAT WARNING:} or \texttt{EtherCAT
       
  1308   ERROR:}, which makes searching the logs easier.
       
  1309 
       
  1310 %------------------------------------------------------------------------------
       
  1311 
       
  1312 \subsection{Class Reference}
       
  1313 \label{sec:classes}
       
  1314 
       
  1315 This section is not intended to be a complete reference of master
       
  1316 classes and functions\footnote{The comprehensive master reference can
       
  1317   be obtained at http://etherlab.org/download/download-en.html}, but
       
  1318 will give a general survey of the master's classes, and how they
       
  1319 interact.
       
  1320 
       
  1321 Figure~\ref{fig:uml-all} shows an UML class diagram of the master
       
  1322 classes.
       
  1323 
       
  1324 \begin{figure}[htbp]
       
  1325   \centering
       
  1326   \includegraphics[width=\textwidth]{images/uml-all}
       
  1327   \caption{UML class diagram with associations}
       
  1328   \label{fig:uml-all}
       
  1329 \end{figure}
       
  1330 
       
  1331 The following subsections introduce serveral classes with their
       
  1332 attributes and methods.
       
  1333 
       
  1334 %------------------------------------------------------------------------------
       
  1335 
       
  1336 \subsubsection{The Master Class}
       
  1337 \label{sec:class-master}
       
  1338 \index{Master!Class}
       
  1339 
       
  1340 Figure~\ref{fig:uml-master} shows an UML class diagram of the master
       
  1341 class. There is a short explanation of the attributes and methods
       
  1342 below.
       
  1343 
       
  1344 \begin{figure}[htbp]
       
  1345   \centering
       
  1346   \includegraphics[width=.8\textwidth]{images/uml-master}
       
  1347   \caption{Master UML class diagram}
       
  1348   \label{fig:uml-master}
       
  1349 \end{figure}
       
  1350 
       
  1351 \paragraph{Master Attributes}
       
  1352 
       
  1353 \begin{description}
       
  1354 \item[list] is a listhead structure that is needed to manage the list
       
  1355   of masters in the master module (see section~\ref{sec:mastermod}).
       
  1356 \item[reserved] is a flag, that marks the master as reserved for a
       
  1357   realtime module, so that a call to \textit{ecrt\_request\_master()}
       
  1358   fails, if another module is already using the master.
       
  1359 \item[index] contains the number of the master. The first master will
       
  1360   get index 0, the second index 1, and so on.
       
  1361 \item[kobj] In order to make the master object available via Sysfs
       
  1362   (see section~\ref{sec:sysfs}), this structure is needed inside the
       
  1363   master object (see section~\ref{sec:sysfs}).
       
  1364 \item[slaves] is the list of slaves. It consists of objects of the
       
  1365   \textit{ec\_slave\_t} class (see section~\ref{sec:class-slave}).
       
  1366 \item[slave\_count] is the number of slaves in the list.
       
  1367 \item[device] points to the network device that is used by the master
       
  1368   to send and receive frames (see section~\ref{sec:class-device}). It
       
  1369   is \textit{NULL}, if no device is connected.
       
  1370 \item[datagram\_queue] is a list of datagrams (see
       
  1371   section~\ref{sec:class-datagram}) that have to be sent by the
       
  1372   master, or have already been sent and wait to be received again.
       
  1373   Upon reception or error, the datagrams are dequeued.
       
  1374 \item[datagram\_index] contains the index value for the next datagram.
       
  1375   The master stores this incrementing index into every datagram, to
       
  1376   make it easier to assign a received datagram to the one sent before.
       
  1377 \item[domains] contains the list of domains created by the realtime
       
  1378   module (section~\ref{sec:class-domain}).
       
  1379 \item[debug\_level] controls, how much debugging output is printed by
       
  1380   the master: 0 means no debugging output, 1 means to output certain
       
  1381   executing marks and actions, and 2 means to output frame contents in
       
  1382   addition. This value can be changed at runtime via the Sysfs
       
  1383   interface (see section~\ref{sec:sysfs}).
       
  1384 \item[stats] is a statistics object that contains certain counters
       
  1385   (like the number of missed frames).  These statistics are output on
       
  1386   demand, but at most once a second.
       
  1387 \item[workqueue] is the kernel workqueue used for idle mode.
       
  1388 \item[idle\_work] is the work object, that is queued.
       
  1389 \item[fsm] The attribute \textit{fsm} represents the master's finite
       
  1390   state machine, that does all the slave processing. See
       
  1391   sections~\ref{sec:class-fsm} and~\ref{sec:fsm} for further details.
       
  1392 \item[mode] contains the current master mode, if it is orphaned, idle,
       
  1393   or in operation mode.
       
  1394 \item[eoe\_timer] is the kernel timer used for EoE\index{EoE}
       
  1395   processing.
       
  1396 \item[eoe\_running] marks the state of EoE processing.
       
  1397 \item[eoe\_handlers] is the list of EoE handlers (see
       
  1398   section~\ref{sec:class-eoe}).
       
  1399 \item[internal\_lock] is a spinlock used in idle mode, that controls
       
  1400   the concurrency of the idle and EoE processes.
       
  1401 \item[request\_cb] The ``request lock'' callback function, the master
       
  1402   has to provide for foreign instances, which want to access the
       
  1403   master (see section~\ref{sec:concurr}).
       
  1404 \item[release\_cb] The callback function that will release the master
       
  1405   lock.
       
  1406 \item[cb\_data] This value will be passed as an argument to each
       
  1407   callback.
       
  1408 \item[eeprom\_write\_enable] flag can be written via Sysfs to enable
       
  1409   the general writing of E$^2$PROM contents.
       
  1410 \end{description}
       
  1411 
       
  1412 \paragraph{Public Master Methods}
       
  1413 
       
  1414 \begin{description}
       
  1415 \item[ec\_master\_init()] is the master's constructor. It initializes
       
  1416   all attributes, creates the workqueue, creates EoE handlers and the
       
  1417   state machine object, and adds the kernel object to the Sysfs
       
  1418   hierarchy.
       
  1419 \item[ec\_master\_clear()] is the destructor and undoes all these
       
  1420   actions.
       
  1421 \item[ec\_master\_reset()] clears the master, but initializes it
       
  1422   again. This is needed, when a realtime module disconnects: Slaves
       
  1423   and other attributes are cleared and are later rebuilt by the idle
       
  1424   process.
       
  1425 \item[ec\_master\_idle\_start/stop()] These methods enable or disable
       
  1426   the idle process.
       
  1427 \item[ec\_master\_eoe\_start/stop()] These methods do the same for the
       
  1428   EoE timer.
       
  1429 \item[ec\_master\_receive\_datagrams()] This method is called by the
       
  1430   device, which uses it to pass received frames to the master.  The
       
  1431   frame is dissected and the contained datagrams are assigned to the
       
  1432   datagram objects in the datagram queue, which are dequeued on
       
  1433   reception or error.
       
  1434 \item[ec\_master\_queue\_datagram()] This method is used to queue a
       
  1435   new datagram for sending and receiving.
       
  1436 \item[ec\_master\_output\_stats()] This method is cyclically called to
       
  1437   output a summary of the \textit{stats} attribute at most once a
       
  1438   second.
       
  1439 \item[ec\_master\_clear\_slaves()] clears the list of slaves. This is
       
  1440   needed on connection/disconnection of a realtime module or at a
       
  1441   topology change in idle mode, when all slaves objects are rebuilt.
       
  1442 \end{description}
       
  1443 
       
  1444 \paragraph{Private Master Methods}
       
  1445 
       
  1446 A few of a master's methods are private, meaning, that they can only
       
  1447 be called from other master methods:
       
  1448 
       
  1449 \begin{description}
       
  1450 \item[ec\_master\_send\_datagrams()] searches the datagram queue for
       
  1451   unsent datagrams, allocates frames to send them, does the actual
       
  1452   sending and marks the datagrams as sent.
       
  1453 \item[ec\_master\_idle\_run()] is the work function for the idle mode.
       
  1454   It executes the idle state machine, described in
       
  1455   section~\ref{sec:fsm-idle}.
       
  1456 \item[ec\_master\_eoe\_run()] is called by the EoE timer and is
       
  1457   responsible for communicating with EoE-capable slaves. See
       
  1458   section~\ref{sec:eoeimp} for more information.
       
  1459 \end{description}
       
  1460 
       
  1461 \paragraph{Master Methods (Realtime Interface)}
       
  1462 
       
  1463 The master methods belonging to the Eth\-er\-CAT realtime
       
  1464 interface\index{ecrt@\textit{ecrt}}\nomenclature{ecrt}{EtherCAT
       
  1465   Realtime Interface} begin with the prefix \textit{ecrt} instead of
       
  1466 \textit{ec}. The functions of the realtime interface are explained in
       
  1467 section~\ref{sec:ecrt-master}.
       
  1468 
       
  1469 %------------------------------------------------------------------------------
       
  1470 
       
  1471 \subsubsection{The Slave Class}
       
  1472 \label{sec:class-slave}
       
  1473 \index{Slave!Class}
       
  1474 
       
  1475 Figure~\ref{fig:uml-slave} shows an UML class diagram of the slave
       
  1476 class. There is a short explanation of the attributes and methods
       
  1477 below.
       
  1478 
       
  1479 \begin{figure}[htbp]
       
  1480   \centering
       
  1481   \includegraphics[width=.8\textwidth]{images/uml-slave}
       
  1482   \caption{Slave UML class diagram}
       
  1483   \label{fig:uml-slave}
       
  1484 \end{figure}
       
  1485 
       
  1486 \paragraph{Slave Attributes}
       
  1487 
       
  1488 \begin{description}
       
  1489 \item[list] The master holds a slave list, therefore the slave class
       
  1490   must contain this structure used as an anchor for the linked
       
  1491   list.
       
  1492 \item[kobj] This pointer serves as base object for the slave's Sysfs
       
  1493   representation.
       
  1494 \item[master] is the pointer to the master owning this slave object.
       
  1495 \item[ring\_position] is the logical position in the logical ring
       
  1496   topology.
       
  1497 \item[station\_address] is the configured station address. This is
       
  1498   always the ring position~+~$1$).
       
  1499 \item[coupler\_index] is the index of the last bus coupler.
       
  1500 \item[coupler\_subindex] is the slave's position, counted from the
       
  1501   last bus coupler. See section~\ref{sec:addr} for more information.
       
  1502 \item[base\_*] These attributes contain base information about the
       
  1503   slave, that are read from the ``DL Information'' attribute.
       
  1504 \item[dl\_*] These fields store information of the ``DL Status''
       
  1505   attribute, for example states of the the communication ports.
       
  1506 \item[sii\_*] These attributes contain values from the ``Slave
       
  1507   Information Interface'' \cite[section~6.4]{dlspec}, mostly identity
       
  1508   and mailbox information, but also the list of sync manager
       
  1509   configurations and PDOs.
       
  1510 \item[registered] This flag is set, if one or more PDOs of the slave
       
  1511   have been registered for process data exchange. Otherwise a warning
       
  1512   is output, because the slave is unused.
       
  1513 \item[fmmus] Is an array of FMMU configurations, that have to be
       
  1514   applied to the slave.
       
  1515 \item[fmmu\_count] contains number of FMMUs used.
       
  1516 \item[eeprom\_*] These fields contain E$^2$PROM contents and the
       
  1517   extracted category information \cite[section~5.4]{alspec}.
       
  1518 \item[new\_eeprom\_data] If this pointer is not \textit{NULL}, it
       
  1519   points to new E$^2$PROM contents, that have to be written to the
       
  1520   slave.
       
  1521 \item[new\_eeprom\_size] This field represents the size of the new
       
  1522   E$^2$PROM data.
       
  1523 \item[requested\_state] is the requested slave state.
       
  1524 \item[current\_state] is the current slave state.
       
  1525 \item[error\_flag] is used by the operation and idle state machines
       
  1526   to indicate, that a state transisition has failed and should not be
       
  1527   tried again until an external event happens.
       
  1528 \item[online] This flag contains the online state of the slave (i.~e.
       
  1529   if it currently responds to the masters commands). Changes of the
       
  1530   online state are always reported.
       
  1531 \item[varsize\_fields] is only suitable for slaves that provide PDOs
       
  1532   of variable size (like slaves that manage a sub-fieldbus) and
       
  1533   contains information about what size this fields actually should
       
  1534   have.
       
  1535 \end{description}
       
  1536 
       
  1537 \paragraph{Public Slave Methods}
       
  1538 
       
  1539 \begin{description}
       
  1540 \item[ec\_slave\_init()] The slave's constructor.
       
  1541 \item[ec\_slave\_clear()] The slave's destructor.
       
  1542 \item[ec\_prepare\_fmmu()] prepares an FMMU configuration. The FMMU is
       
  1543   configured for a certain sync manager and domain.
       
  1544 \item[ec\_fetch\_*()] Serveral methods to extract information of the
       
  1545   E$^2$PROM category contents.
       
  1546 \item[ec\_slave\_locate\_string()] extracts a string out of a STRING
       
  1547   category and allocates string memory.
       
  1548 \item[ec\_slave\_calc\_sync\_size()] calculates the size of sync
       
  1549   manager contents, because they can be variable due to variable-sized
       
  1550   PDOs.
       
  1551 \item[ec\_slave\_info()] This method prints all slave information into
       
  1552   a buffer for Sysfs reading.
       
  1553 \item[ec\_slave\_mbox\_*()] These functions prepare datagrams for
       
  1554   mailbox communication, or process mailbox responses, respectively.
       
  1555 \end{description}
       
  1556 
       
  1557 \paragraph{Private Slave Methods}
       
  1558 
       
  1559 \begin{description}
       
  1560 \item[ec\_slave\_write\_eeprom()] This function accepts E$^2$PROM data
       
  1561   from user space, does a quick validation of the contents and
       
  1562   schedules them for writing through the idle state machine.
       
  1563 \end{description}
       
  1564 
       
  1565 \paragraph{Slave Methods (Realtime Interface)}
       
  1566 
       
  1567 \begin{description}
       
  1568 \item[ecrt\_slave\_conf\_sdo*()] These methods accept SDO
       
  1569   configurations, that are applied on slave activation (i.~e.
       
  1570   everytime the slave is configured). The methods differ only in the
       
  1571   data size of the SDO (8, 16 or 32 bit).
       
  1572 \item[ecrt\_slave\_pdo\_size()] This method specifies the size of a
       
  1573   variable-sized PDO.
       
  1574 \end{description}
       
  1575 
       
  1576 %------------------------------------------------------------------------------
       
  1577 
       
  1578 \subsubsection{The Device Class}
       
  1579 \label{sec:class-device}
       
  1580 \index{Device!Class}
       
  1581 
       
  1582 The device class is responsible for communicating with the connected
       
  1583 EtherCAT-enabled network driver. Figure~\ref{fig:uml-device} shows its
       
  1584 UML class diagram.
       
  1585 
       
  1586 \begin{figure}[htbp]
       
  1587   \centering
       
  1588   \includegraphics[width=.3\textwidth]{images/uml-device}
       
  1589   \caption{Device UML class diagram}
       
  1590   \label{fig:uml-device}
       
  1591 \end{figure}
       
  1592 
       
  1593 \paragraph{Device Attributes}
       
  1594 
       
  1595 \begin{description}
       
  1596 \item[master] A pointer to the master, which owns the device object.
       
  1597 \item[dev] This is the pointer to the \textit{net\_device} structure
       
  1598   of the connected network device driver.
       
  1599 \item[open] This flag stores, if the network device is ``opened'' and
       
  1600   ready for transmitting and receiving frames.
       
  1601 \item[tx\_skb] The transmittion socket buffer. Instead of allocating a
       
  1602   new socket buffer for each frame, the same socket buffer is recycled
       
  1603   and used for every frame.
       
  1604 \item[isr] The pointer to the network device's interrupt service
       
  1605   routine. \textit{ec\_isr\_t} is a type definition in the device
       
  1606   interface, which looks like below:
       
  1607   \begin{lstlisting}[gobble=4,language=C]
       
  1608     typedef irqreturn_t (*ec_isr_t)(int, void *,
       
  1609                                     struct pt_regs *);
       
  1610   \end{lstlisting}
       
  1611 \item[module] A pointer to the network driver module, to increase and
       
  1612   decrease the use counter (see paragraph ``Implicit Dependencies'' in
       
  1613   section~\ref{sec:ecdev}).
       
  1614 \item[link\_state] The current link state. It can be 0 ``down'' or 1
       
  1615   ``up''.
       
  1616 \item[dbg] Every device objects contains a debugging interface (see
       
  1617   sectios~\ref{sec:class-debug} and~\ref{sec:debug}).
       
  1618 \end{description}
       
  1619 
       
  1620 \paragraph{Public Device Methods}
       
  1621 
       
  1622 \begin{description}
       
  1623 \item[ec\_device\_init()] The device constructor.
       
  1624 \item[ec\_device\_clear()] The device destructor.
       
  1625 \item[ec\_device\_open()] ``Opens'' the device for transmittion and
       
  1626   reception of frames. This is equivalent to the \textit{ifconfig up}
       
  1627   command for ordinary Ethernet devices.
       
  1628 \item[ec\_device\_close()] Stops frame transmittion and reception.
       
  1629   This is equivalent to the \textit{ifconfig down} command for
       
  1630   ordinary Ethernet devices.
       
  1631 \item[ec\_device\_call\_isr()] Calls the interrupt service routine of
       
  1632   the device.
       
  1633 \item[ec\_device\_tx\_data()] Returns a pointer into the memory of the
       
  1634   transmittion socket buffer \textit{tx\_skb}. This is used by the
       
  1635   master to assemble a new EtherCAT frame.
       
  1636 \item[ec\_device\_send()] Sends an assembled frame by passing it to
       
  1637   the device's \textit{hard\_\-start\_\-xmit()} callback.
       
  1638 \end{description}
       
  1639 
       
  1640 \paragraph{Device Methods (Device Interface)}
       
  1641 
       
  1642 The device methods belonging to the device interface are explained in
       
  1643 section~\ref{sec:ecdev}.
       
  1644 
       
  1645 %------------------------------------------------------------------------------
       
  1646 
       
  1647 \subsubsection{The Datagram Class}
       
  1648 \label{sec:class-datagram}
       
  1649 \index{Datagram!Class}
       
  1650 
       
  1651 So send and receive a datagram, an object of the
       
  1652 \textit{ec\_datagram\_t} class is needed. It can be initialized with a
       
  1653 datagram type \cite[section~5.4]{dlspec} and length (optionally filled
       
  1654 with data) and appended to the master's datagram queue.
       
  1655 Figure~\ref{fig:uml-datagram} shows its UML class diagram.
       
  1656 
       
  1657 \begin{figure}[htbp]
       
  1658   \centering
       
  1659   \includegraphics[width=.3\textwidth]{images/uml-datagram}
       
  1660   \caption{Datagram UML class diagram}
       
  1661   \label{fig:uml-datagram}
       
  1662 \end{figure}
       
  1663 
       
  1664 \paragraph{Datagram Attributes}
       
  1665 
       
  1666 \begin{description}
       
  1667 \item[list] This attribute is needed to make a list of datagrams, as
       
  1668   used in the domain class (see section~\ref{sec:class-domain}).
       
  1669 \item[queue] This attribute is the anchor to the master's datagram
       
  1670   queue, which is implemented as a linked list.
       
  1671 \item[type] The datagram type. \textit{ec\_\-datagram\_\-type\_\-t} is
       
  1672   an enumeration, which can have the values
       
  1673   \textit{EC\_\-DATAGRAM\_\-APRD}, \textit{EC\_\-DATAGRAM\_\-APWR},
       
  1674   \textit{EC\_\-DATAGRAM\_\-NPRD}, \textit{EC\_\-DATAGRAM\_\-NPWR},
       
  1675   \textit{EC\_\-DATAGRAM\_\-BRD}, \textit{EC\_\-DATAGRAM\_\-BWR} or
       
  1676   \textit{EC\_\-DATAGRAM\_\-LRW}.
       
  1677 \item[address] The slave address. For all addressing schemes take 4
       
  1678   bytes, \textit{ec\_address\_t} is a union type:
       
  1679   \begin{lstlisting}[gobble=4,language=C]
       
  1680     typedef union {
       
  1681             struct {
       
  1682                     uint16_t slave; /**< configured or
       
  1683                                          autoincrement
       
  1684                                          address */
       
  1685                     uint16_t mem; /**< physical memory
       
  1686                                        address */
       
  1687             } physical; /**< physical address */
       
  1688             uint32_t logical; /**< logical address */
       
  1689     } ec_address_t;
       
  1690   \end{lstlisting}
       
  1691 \item[data] The actual data of the datagram. These are either filled
       
  1692   in before sending (at writing access) or are inserted by the
       
  1693   adressed slave(s) (at reading access). In any case, the data memory
       
  1694   must be dynamically allocated. Besides, this can be done before
       
  1695   cyclic processing with the \textit{ec\_datagram\_prealloc()} method
       
  1696   (see below).
       
  1697 \item[mem\_size] The size of the allocated memory, \textit{data}
       
  1698   points to.
       
  1699 \item[data\_size] The size of the actual data in the \textit{data}
       
  1700   memory.
       
  1701 \item[index] The sequential EtherCAT datagram index. This value is set
       
  1702   by the master on sending, to easier assign a received datagram to a
       
  1703   queued datagram object.
       
  1704 \item[working\_counter] The working counter of the datagram. This is
       
  1705   set to zero on sending and filled with the real value of the working
       
  1706   counter on datagram reception.
       
  1707 \item[state] The state of the datagram.
       
  1708   \textit{ec\_\-datagram\_\-state\_\-t} is an enumeration and can be
       
  1709   \textit{EC\_\-DATA\-GRAM\_\-INIT},
       
  1710   \textit{EC\_\-DATA\-GRAM\_\-QUEU\-ED},
       
  1711   \textit{EC\_\-DATA\-GR\-AM\_\-SEN\-T},
       
  1712   \textit{EC\_\-DATA\-GRAM\_\-REC\-EIVED},
       
  1713   \textit{EC\_\-DATA\-GRAM\_\-TIMED\_\-OUT} or
       
  1714   \textit{EC\_\-DA\-TA\-GRAM\_\-ERR\-OR}.
       
  1715 \item[t\_sent] This attribute is set to the timestamp, when the
       
  1716   datagram was sent, to later detect a timeout.
       
  1717 \end{description}
       
  1718 
       
  1719 \paragraph{Public Datagram Methods}
       
  1720 
       
  1721 \begin{description}
       
  1722 \item[ec\_datagram\_init()] The datagram's constructor.
       
  1723 \item[ec\_datagram\_clear()] The datagram's destructor.
       
  1724 \item[ec\_datagram\_prealloc()] Allocates memory for the datagram
       
  1725   data. This is especially needed, if the datagram structure will
       
  1726   later be used in a context, where no dynamic memory allocation is
       
  1727   allowed.
       
  1728 \item[ec\_datagram\_nprd()] Initializes a ``Node-Addressed Physical
       
  1729   Read'' datagram \cite[section~5.4.1.2]{dlspec}.
       
  1730 \item[ec\_datagram\_npwr()] Initializes a ``Node-Addressed Physical
       
  1731   Write'' datagram \cite[section~5.4.2.2]{dlspec}.
       
  1732 \item[ec\_datagram\_aprd()] Initializes a ``Auto-Increment Physical
       
  1733   Read'' datagram \cite[section~5.4.1.1]{dlspec}.
       
  1734 \item[ec\_datagram\_apwr()] Initializes a ``Auto-Increment Physical
       
  1735   Write'' datagram \cite[section~5.4.2.1]{dlspec}.
       
  1736 \item[ec\_datagram\_brd()] Initializes a ``Broadcast Read'' datagram
       
  1737   \cite[section~5.4.1.3]{dlspec}.
       
  1738 \item[ec\_datagram\_bwr()] Initializes a ``Broadcast Write'' datagram
       
  1739   \cite[section~5.4.2.3]{dlspec}.
       
  1740 \item[ec\_datagram\_lrw()] Initializes a ``Logical ReadWrite''
       
  1741   datagram \cite[section~5.4.3.4]{dlspec}.
       
  1742 \end{description}
       
  1743 
       
  1744 %------------------------------------------------------------------------------
       
  1745 
       
  1746 \subsubsection{The Domain Class}
       
  1747 \label{sec:class-domain}
       
  1748 \index{Domain!Class}
       
  1749 
       
  1750 The domain class encapsules PDO registration and management of the
       
  1751 process data image and its exchange. The UML class diagram can be seen
       
  1752 in figure~\ref{fig:uml-domain}.
       
  1753 
       
  1754 \begin{figure}[htbp]
       
  1755   \centering
       
  1756   \includegraphics[width=.4\textwidth]{images/uml-domain}
       
  1757   \caption{Domain UML class diagram}
       
  1758   \label{fig:uml-domain}
       
  1759 \end{figure}
       
  1760 
       
  1761 \paragraph{Domain Attributes}
       
  1762 
       
  1763 \begin{description}
       
  1764 \item[kobj] This \textit{kobject} structure is needed for the Sysfs
       
  1765   representation of the domain.
       
  1766 \item[list] The master manages a list of domains, so this list anchor
       
  1767   is needed.
       
  1768 \item[index] The domain's index. The first domain will get index 0,
       
  1769   the second index 1, and so on.
       
  1770 \item[master] A pointer to the master owning the domain.
       
  1771 \item[data\_size] The size of the domain's process data image.
       
  1772 \item[datagram] A linked list with the datagram objects, the domain
       
  1773   needs for process data exchange (see
       
  1774   section~\ref{sec:class-datagram}).
       
  1775 \item[base\_address] This attribute stores the logical offset, to
       
  1776   which the domain's process data are mapped.
       
  1777 \item[response\_count] The sum of the datagrams' working counters at
       
  1778   the last process data exchange. Changes are always reported.
       
  1779 \item[data\_regs] The (linked) list of PDO registrations. The realtime
       
  1780   module requests the exchange of certain PDOs and supplies the
       
  1781   address of process data pointers, that will later point to the
       
  1782   respective locations in the process data image. These ``data
       
  1783   registrations'' are saved in the \textit{data\_regs} list.
       
  1784 \item[working\_counter\_changes] This field stores the number of
       
  1785   working counter changes since the last notification. This helps to
       
  1786   reduce syslog output in case of frequent changes.
       
  1787 \item[t\_last] The timestamp of the last working counter change
       
  1788   notification.
       
  1789 \end{description}
       
  1790 
       
  1791 \paragraph{Public Domain Methods}
       
  1792 
       
  1793 \begin{description}
       
  1794 \item[ec\_domain\_init()] The domain's constructor.
       
  1795 \item[ec\_domain\_clear()] The domain's destructor.
       
  1796 \item[ec\_domain\_alloc()] Allocates the process data image and the
       
  1797   respective datagrams based on the process data registrations.
       
  1798 \item[ec\_domain\_queue()] Queues the domain's datagrams for exchange
       
  1799   via the master.
       
  1800 \end{description}
       
  1801 
       
  1802 \paragraph{Private Domain Methods}
       
  1803 
       
  1804 \begin{description}
       
  1805 \item[ec\_domain\_reg\_pdo\_entry()] This method is used to do a PDO
       
  1806   registration. It finds the appropriate sync manager covering the PDO
       
  1807   data, calculates its offset in the sync-manager-protected memory and
       
  1808   prepares the FMMU configurations for the related slave. Then the PDO
       
  1809   registration is appended to the list.
       
  1810 \item[ec\_domain\_clear\_data\_regs()] Clearing all process data
       
  1811   registrations is needed in serveral places and therefore has been
       
  1812   sourced out to an own method.
       
  1813 \item[ec\_domain\_add\_datagram()] This methods allocates a datagram
       
  1814   and appends it to the list. This is done during domain allocation.
       
  1815 \end{description}
       
  1816 
       
  1817 \paragraph{Domain Methods (Realtime Interface)}
       
  1818 
       
  1819 The domain methods belonging to the realtime interface are introduced
       
  1820 in section~\ref{sec:ecrt-domain}.
       
  1821 
       
  1822 %------------------------------------------------------------------------------
       
  1823 
       
  1824 \subsubsection{The Finite State Machine Class}
       
  1825 \label{sec:class-fsm}
       
  1826 \index{FSM!Class}
       
  1827 
       
  1828 This class encapsules all state machines, except the EoE state
       
  1829 machine. Its UML class diagram can be seen in
       
  1830 figure~\ref{fig:uml-fsm}.
       
  1831 
       
  1832 \begin{figure}[htbp]
       
  1833   \centering
       
  1834   \includegraphics[width=.9\textwidth]{images/uml-fsm}
       
  1835   \caption{Finite State Machine UML class diagram}
       
  1836   \label{fig:uml-fsm}
       
  1837 \end{figure}
       
  1838 
       
  1839 \paragraph{FSM Attributes}
       
  1840 
       
  1841 \begin{description}
       
  1842 \item[master] A pointer to the master owning the FSM object.
       
  1843 \item[slave] Serveral sub state machines are executed for single
       
  1844   slaves. This pointer stores the current slave for these FSMs.
       
  1845 \item[datagram] The FSM class has its own datagram, which is used in
       
  1846   every state and sub-state.
       
  1847 \item[master\_state] This function pointer stores the current state
       
  1848   function for one of the master's state machines.
       
  1849 \item[master\_slaves\_responding] This attribute is used in the
       
  1850   operation state machine (see section~\ref{sec:fsm-op}) to store the
       
  1851   number of slaves, that responded to the last broadcast command.
       
  1852 \item[master\_slave\_states] This attribute stores the slave states,
       
  1853   that were determined by the last broadcast command.
       
  1854 \item[master\_validation] This flag is used by the operation state
       
  1855   machine and is non-zero, if a bus validation has to be done.
       
  1856 \item[slave\_state] This function pointer stores the current state of
       
  1857   the slave scan state machine (see section~\ref{sec:fsm-scan}) or the
       
  1858   slave configuration state machine (see section~\ref{sec:fsm-conf}).
       
  1859 \item[sii\_state] This function pointer stores the current state of
       
  1860   the SII state machine (see section~\ref{sec:fsm-sii}).
       
  1861 \item[sii\_offset] This attribute is used by the SII state machine to
       
  1862   store the word address for the current read or write cycle.
       
  1863 \item[sii\_mode] If this attribute is zero, the SII access is done
       
  1864   with ``auto-increment'' datagrams \cite[section~5.4]{dlspec}.
       
  1865   If it is non-zero, ``station-address'' datagrams are used.
       
  1866 \item[sii\_value] This attribute stores the value to write, or the
       
  1867   read value, respectively.
       
  1868 \item[sii\_start] A timestamp attribute, that stores the beginning
       
  1869   time of an SII operation to detect a timeout.
       
  1870 \item[change\_state] This function pointer stores the current state of
       
  1871   the state change state machine.
       
  1872 \item[change\_new] This attribute stores the requested state for the
       
  1873   state change state machine.
       
  1874 \item[change\_start] A timestamp attribute to detect a timeout while
       
  1875   changing slave states.
       
  1876 \item[coe\_state] This function pointer stores the current state of
       
  1877   the CoE state machines.
       
  1878 \item[sdodata] This is an SDO data object that stores information
       
  1879   about the current SDO to write.
       
  1880 \item[coe\_start] A timestamp attribute to detect timeouts during CoE
       
  1881   configuration.
       
  1882 \end{description}
       
  1883 
       
  1884 \paragraph{Public FSM Methods}
       
  1885 
       
  1886 \begin{description}
       
  1887 \item[ec\_fsm\_init()] Constructor of the FSM class.
       
  1888 \item[ec\_fsm\_clear()] Destructor of the FSM class.
       
  1889 \item[ec\_fsm\_reset()] Resets the whole FSM object. This is needed to
       
  1890   restart the master state machines.
       
  1891 \item[ec\_fsm\_execute()] Executes one state of the current state
       
  1892   machine and then returns.
       
  1893 \item[ec\_fsm\_startup()] Initializes the master startup state
       
  1894   machine, which determines the number of slaves and executes the
       
  1895   slave scan state machine for each slave.
       
  1896 \item[ec\_fsm\_startup\_running()] Returns non-zero, if the startup
       
  1897   state machine did not terminate yet.
       
  1898 \item[ec\_fsm\_startup\_success()] Returns non-zero, if the startup
       
  1899   state machine terminated with success.
       
  1900 \item[ec\_fsm\_configuration()] Initializes the master configuration
       
  1901   state machine, which executes the slave configuration state machine
       
  1902   for each slave.
       
  1903 \item[ec\_fsm\_configuration\_running()] Returns non-zero, if the
       
  1904   configuration state machine did not terminate yet.
       
  1905 \item[ec\_fsm\_configuration\_success()] Returns non-zero, if the
       
  1906   configuration state machine terminated with success.
       
  1907 \end{description}
       
  1908 
       
  1909 \paragraph{FSM State Methods}
       
  1910 
       
  1911 The rest of the methods showed in the UML class diagram are state
       
  1912 methods of the state machines. These states are described in
       
  1913 section~\ref{sec:fsm}.
       
  1914 
       
  1915 %------------------------------------------------------------------------------
       
  1916 
       
  1917 \subsubsection{The EoE Class}
       
  1918 \label{sec:class-eoe}
       
  1919 \index{EoE!Class}
       
  1920 
       
  1921 Objects of the \textit{ec\_eoe\_t} class are called EoE handlers. Each
       
  1922 EoE handler represents a virtual network interface and can be coupled
       
  1923 to a EoE-capable slave on demand. The UML class diagram can be seen in
       
  1924 figure~\ref{fig:uml-eoe}.
       
  1925 
       
  1926 \begin{figure}[htbp]
       
  1927   \centering
       
  1928   \includegraphics[width=.4\textwidth]{images/uml-eoe}
       
  1929   \caption{EoE UML class diagram}
       
  1930   \label{fig:uml-eoe}
       
  1931 \end{figure}
       
  1932 
       
  1933 \paragraph{EoE Attributes}
       
  1934 
       
  1935 \begin{description}
       
  1936 \item[list] The master class maintains a list of EoE handlers.
       
  1937   Therefore this list anchor is needed.
       
  1938 \item[slave] If an EoE handler is coupled to a slave, this pointer
       
  1939   points to the related slave object. Otherwise it is \textit{NULL}.
       
  1940 \item[datagram] Every EoE handler owns a datagram object to exchange
       
  1941   data with the coupled slave via its state machine.
       
  1942 \item[state] This function pointer points to the current state of the
       
  1943   EoE state machine (see section~\ref{sec:eoeimp}).
       
  1944 \item[dev] A pointer to the \textit{net\_device} structure that
       
  1945   represents the network interface to the kernel.
       
  1946 \item[stats] The statistics object for the network interface.
       
  1947 \item[opened] This flag stores, if the network interface was opened.
       
  1948   No EoE processing will be done, if the device is not opened.
       
  1949 \item[t\_last] This timestamp attribute stores the time of the last
       
  1950   bit rate measurement.
       
  1951 \item[rx\_skb] A pointer to the current receive socket buffer. On
       
  1952   every first fragment of a received frame, a new receive socket
       
  1953   buffer is allocated. On every last fragment, this buffer will be
       
  1954   passed to the network stack.
       
  1955 \item[rx\_skb\_offset] This attribute stores the offset for the next
       
  1956   fragment data in the receive socket buffer.
       
  1957 \item[rx\_skb\_size] This attribute stores the current data size of
       
  1958   the receive socket buffer.
       
  1959 \item[rx\_expected\_fragment] The expected number of the next
       
  1960   fragment. If a fragment with an invalid number is received, the
       
  1961   whole frame will be dropped.
       
  1962 \item[rx\_counter] This is the sum of the octets received since the
       
  1963   last bit rate measurement.
       
  1964 \item[rx\_rate] This attribute stores the receive bit rate in bps.
       
  1965 \item[tx\_queue] Each EoE handler maintains a transmittion queue for
       
  1966   frames, that come in via the network interface. This queue is
       
  1967   implemented with a linked list and protected by a spinlock.
       
  1968 \item[tx\_queue\_active] This flag stores, if the transmittion queue
       
  1969   is currently accepting frames from the network stack. If the queue
       
  1970   gets filled up, frame transmittion is suspended with a call to
       
  1971   \textit{netif\_stop\_queue()}. If the fill state decreases below the
       
  1972   half capacity, frame transmittion is restarted with
       
  1973   \textit{netif\_wake\_queue()}.
       
  1974 \item[tx\_queued\_frames] The number of frames in the transmittion
       
  1975   queue.
       
  1976 \item[tx\_queue\_lock] The spinlock used to protect the transmittion
       
  1977   queue. This is needed, because the queue is accessed both from
       
  1978   network stack context and from the master's EoE timer.
       
  1979 \item[tx\_frame] The frame that is currently sent. The
       
  1980   \textit{ec\_eoe\_frame\_t} structure combines the socket buffer
       
  1981   structure with a list head to append it to the transmittion queue.
       
  1982 \item[tx\_frame\_number] The EoE protocol demands to maintain a
       
  1983   sequencial frame number, that must be increased with every frame
       
  1984   sent.
       
  1985 \item[tx\_fragment\_number] The sequencial number of the next fragment
       
  1986   to transmit.
       
  1987 \item[tx\_offset] Current frame data offset for the next fragment to
       
  1988   transmit.
       
  1989 \item[tx\_counter] The number of octets transferred since the last bit
       
  1990   rate measurement.
       
  1991 \item[tx\_rate] The recent transmittion bit rate in bps.
       
  1992 \end{description}
       
  1993 
       
  1994 \paragraph{Public EoE Methods}
       
  1995 
       
  1996 \begin{description}
       
  1997 \item[ec\_eoe\_init()] The EoE handler's constructor. The network
       
  1998   interface is allocated and registered.
       
  1999 \item[ec\_eoe\_clear()] The EoE handler's destructor. The network
       
  2000   interface is unregistered and all allocated memory is freed.
       
  2001 \item[ec\_eoe\_run()] Executes the EoE state machine (see
       
  2002   section~\ref{sec:eoeimp}) for this handler.
       
  2003 \item[ec\_eoe\_active()] Returns true, if the handler has a slave
       
  2004   coupled and the network interface is opened.
       
  2005 \end{description}
       
  2006 
       
  2007 \paragraph{Private EoE Methods}
       
  2008 
       
  2009 \begin{description}
       
  2010 \item[ec\_eoe\_flush()] Clears the transmittion queue and drops all
       
  2011   frames queued for sending.
       
  2012 \item[ec\_eoe\_send()] Sends one fragment of the current frame.
       
  2013 \end{description}
       
  2014 
       
  2015 
       
  2016 \paragraph{EoE State Methods}
       
  2017 
       
  2018 The rest of the private methods are state functions for the EoE state
       
  2019 machine, which is discussed in section~\ref{sec:eoeimp}.
       
  2020 
       
  2021 %------------------------------------------------------------------------------
       
  2022 
       
  2023 \subsubsection{The Debug Class}
       
  2024 \label{sec:class-debug}
       
  2025 
       
  2026 The debug class maintains a virtual network interface. All frames that
       
  2027 are sent and received by the master will be forwarded to this network
       
  2028 interface, so that bus monitoring can be done with third party tools
       
  2029 (see section~\ref{sec:debug}). Figure~\ref{fig:uml-debug} shows the
       
  2030 UML class diagram.
       
  2031 
       
  2032 \begin{figure}[htbp]
       
  2033   \centering
       
  2034   \includegraphics[width=.3\textwidth]{images/uml-debug}
       
  2035   \caption{Debug UML class diagram}
       
  2036   \label{fig:uml-debug}
       
  2037 \end{figure}
       
  2038 
       
  2039 \paragraph{Debug Attributes}
       
  2040 
       
  2041 \begin{description}
       
  2042 \item[dev] A pointer to the allocated \textit{net\_device} structure
       
  2043   that represents the network interface in the kernel.
       
  2044 \item[stats] An object for interface statistics.
       
  2045 \item[opened] Stores the state of the device. Frames will only be
       
  2046   forwarded, if the device was opened with the \textit{ifconfig up}
       
  2047   command (or something similar).
       
  2048 \end{description}
       
  2049 
       
  2050 \paragraph{Public Debug Methods}
       
  2051 
       
  2052 \begin{description}
       
  2053 \item[ec\_debug\_init()] The constructor.
       
  2054 \item[ec\_debug\_clear()] The destructor.
       
  2055 \item[ec\_debug\_send()] This method forwards a frame to the virtual
       
  2056   network interface. It dynamically allocates a new socket buffer and
       
  2057   passes it to the network stack.
       
  2058 \end{description}
       
  2059 
       
  2060 %------------------------------------------------------------------------------
       
  2061 
       
  2062 \subsection{The Realtime Interface}
       
  2063 \label{sec:ecrt}
       
  2064 \index{Realtime interface}
       
  2065 
       
  2066 The realtime interface provides functions and data structures for
       
  2067 realtime modules to access and use an EtherCAT master.
       
  2068 
       
  2069 \subsubsection{Master Requesting and Releasing}
       
  2070 
       
  2071 Before a realtime module can access am EtherCAT master provided by the
       
  2072 master module, it has to reserve one for exclusive use. After use, it
       
  2073 has to release the requested master and make it available for other
       
  2074 modules. This is done with the following functions:
       
  2075 
       
  2076 \begin{lstlisting}[language=C]
       
  2077   ec_master_t *ecrt_request_master(unsigned int master_index);
       
  2078   void ecrt_release_master(ec_master_t *master);
       
  2079 \end{lstlisting}
       
  2080 
       
  2081 The \textit{ecrt\_request\_master()} function has to be the first
       
  2082 function a module has to call, when using EtherCAT. The function takes
       
  2083 the index of the master as its argument. The first master has index 0,
       
  2084 the $n$th master has index $n - 1$. The number of existent masters has
       
  2085 to be specified when loading the master module (see
       
  2086 section~\ref{sec:mastermod}). The function tries to reserve the
       
  2087 specified master and scans for slaves. It returns a pointer to the
       
  2088 reserved master object upon success, or \textit{NULL} if an error
       
  2089 occured.
       
  2090 
       
  2091 The \textit{ecrt\_release\_master()} function releases a reserved
       
  2092 master after use. It takes the pointer to the master object returned
       
  2093 by \textit{ecrt\_request\_master()} as its argument and can never
       
  2094 fail.
       
  2095 
       
  2096 \subsubsection{Master Methods}
       
  2097 \label{sec:ecrt-master}
       
  2098 
       
  2099 \paragraph{Domain Creation}
       
  2100 
       
  2101 For process data exchange, at least one process data domain is needed
       
  2102 (see section~\ref{sec:processdata}).
       
  2103 
       
  2104 \begin{lstlisting}[language=C]
       
  2105   ec_domain_t *ecrt_master_create_domain(ec_master_t *master);
       
  2106 \end{lstlisting}
       
  2107 
       
  2108 The \textit{ecrt\_master\_create\_domain()} method creates a new
       
  2109 process data domain and returns a pointer to the new domain object.
       
  2110 This object can be used for registering process data objects and
       
  2111 exchange process data in cyclic operation. On failure, the function
       
  2112 returns \textit{NULL}.
       
  2113 
       
  2114 \paragraph{Slave Handlers}
       
  2115 
       
  2116 To access a certain slave, there is a method to get a slave handler:
       
  2117 
       
  2118 \begin{lstlisting}[language=C]
       
  2119   ec_slave_t *ecrt_master_get_slave(const ec_master_t *,
       
  2120                                     const char *);
       
  2121 \end{lstlisting}
       
  2122 
       
  2123 The \textit{ecrt\_master\_get\_slave()} method returns a pointer to a
       
  2124 certain slave object, specified by its ASCII address (see
       
  2125 section~\ref{sec:addr}). If the address is invalid, \textit{NULL} is
       
  2126 returned.
       
  2127 
       
  2128 \paragraph{Master Activation}
       
  2129 
       
  2130 When all domains are created, and all process data objects are
       
  2131 registered, the master can be activated:
       
  2132 
       
  2133 \begin{lstlisting}[language=C]
       
  2134   int ecrt_master_activate(ec_master_t *master);
       
  2135   void ecrt_master_deactivate(ec_master_t *master);
       
  2136 \end{lstlisting}
       
  2137 
       
  2138 By calling the \textit{ecrt\_master\_activate()} method, all slaves
       
  2139 are configured according to the prior method calls and are brought
       
  2140 into \textit{OP} state. In this case, the method has a return value of
       
  2141 0. Otherwise (wrong configuration or bus failure) the method returns
       
  2142 non-zero.
       
  2143 
       
  2144 The \textit{ecrt\_master\_deactivate()} method is the counterpart to
       
  2145 the activate call: It brings all slaves back into \textit{INIT} state
       
  2146 again. This method should be called prior to
       
  2147 \textit{ecrt\_\-master\_\-release()}.
       
  2148 
       
  2149 \paragraph{Locking Callbacks}
       
  2150 
       
  2151 For concurrent master access, the realtime module has to provide a
       
  2152 locking mechanism (see section~\ref{sec:concurr}):
       
  2153 
       
  2154 \begin{lstlisting}[language=C]
       
  2155   void ecrt_master_callbacks(ec_master_t *master,
       
  2156                              int (*request_cb)(void *),
       
  2157                              void (*release_cb)(void *),
       
  2158                              void *cb_data);
       
  2159 \end{lstlisting}
       
  2160 
       
  2161 The ``request lock'' and ``release lock'' callbacks can be set with
       
  2162 the \textit{ecrt\_master\_call\-backs()} method. It takes two function
       
  2163 pointers and a data value as additional arguments. The arbitrary data
       
  2164 value will be passed as argument on every callback. Asynchronous
       
  2165 master access (like EoE processing) is only possible if these
       
  2166 callbacks have been set.
       
  2167 
       
  2168 \paragraph{Preparation of Cyclic Data Exchange}
       
  2169 
       
  2170 Cyclic operation mostly consists of the three steps input, processing
       
  2171 and output. In EtherCAT terms this would mean: Receive datagrams,
       
  2172 evaluate process data and send datagrams. The first cycle differs from
       
  2173 this principle, because no datagrams have been sent yet, so there is
       
  2174 nothing to receive. To avoid having a case differantiation (in terms
       
  2175 of an \textit{if} clause), the following method exists:
       
  2176 
       
  2177 \begin{lstlisting}[language=C]
       
  2178   void ecrt_master_prepare(ec_master_t *master);
       
  2179 \end{lstlisting}
       
  2180 
       
  2181 As a last thing before cyclic operation, a call to the
       
  2182 \textit{ecrt\_master\_prepare()} method should be issued. It makes all
       
  2183 process data domains queue their datagrams and issues a send command,
       
  2184 so that the first receive call in cyclic operation will not fail.
       
  2185 
       
  2186 \paragraph{Frame Sending and Receiving}
       
  2187 
       
  2188 To send all queued datagrams and to later receive the sent datagrams
       
  2189 there are two methods:
       
  2190 
       
  2191 \begin{lstlisting}[language=C]
       
  2192   void ecrt_master_send(ec_master_t *master);
       
  2193   void ecrt_master_receive(ec_master_t *master);
       
  2194 \end{lstlisting}
       
  2195 
       
  2196 The \textit{ecrt\_master\_send()} method takes all datagrams, that
       
  2197 have been queued for transmission, packs them into frames, and passes
       
  2198 them to the network device for sending.
       
  2199 
       
  2200 The \textit{ecrt\_master\_receive()} queries the network device for
       
  2201 received frames (by calling the ISR\index{ISR}), extracts received
       
  2202 datagrams and dispatches the results to the datagram objects in the
       
  2203 queue. Received datagrams, and the ones that timed out, will be
       
  2204 marked, and then dequeued.
       
  2205 
       
  2206 \paragraph{Running the Operation State Machine}
       
  2207 
       
  2208 The master's operation state machine (see section~\ref{sec:fsm-op})
       
  2209 monitors the bus in cyclic operation and reconfigures slaves, if
       
  2210 necessary. Therefore, the following method should be called
       
  2211 cyclically:
       
  2212 
       
  2213 \begin{lstlisting}[language=C]
       
  2214   void ecrt_master_run(ec_master_t *master);
       
  2215 \end{lstlisting}
       
  2216 
       
  2217 The \textit{ecrt\_master\_run()} method executes the master's
       
  2218 operation state machine step by step. It returns after processing one
       
  2219 state and queuing a datagram. Calling this function is not mandatory,
       
  2220 but highly recommended.
       
  2221 
       
  2222 \paragraph{Master Monitoring}
       
  2223 
       
  2224 It is also highly recommended to evaluate the master's error state. In
       
  2225 this way it is possible to notice lost network links, failed bus
       
  2226 segments, and other issues:
       
  2227 
       
  2228 \begin{lstlisting}[language=C]
       
  2229   int ecrt_master_state(const ec_master_t *master);
       
  2230 \end{lstlisting}
       
  2231 
       
  2232 The \textit{ecrt\_master\_state()} method returns the master's error
       
  2233 state. The following states are defined as part of the realtime
       
  2234 interface:
       
  2235 
       
  2236 \begin{description}
       
  2237 \item[EC\_MASTER\_OK] means, that no error has occurred.
       
  2238 \item[EC\_MASTER\_LINK\_ERROR] means, that the network link is
       
  2239   currently down.
       
  2240 \item[EC\_MASTER\_BUS\_ERROR] means, that one or more slaves do not
       
  2241   respond.
       
  2242 \end{description}
       
  2243 
       
  2244 \subsubsection{Domain Methods}
       
  2245 \label{sec:ecrt-domain}
       
  2246 
       
  2247 \paragraph{PDO Registration}
       
  2248 
       
  2249 To access data of a slave's PDO in cyclic operation, it is necessary
       
  2250 to make it part of a process data domain:
       
  2251 
       
  2252 \begin{lstlisting}[language=C]
       
  2253   ec_slave_t *ecrt_domain_register_pdo(ec_domain_t *domain,
       
  2254                                        const char *address,
       
  2255                                        uint32_t vendor_id,
       
  2256                                        uint32_t product_code,
       
  2257                                        const char *pdo_name
       
  2258                                        void **data_ptr);
       
  2259   int ecrt_domain_register_pdo_list(ec_domain_t *domain,
       
  2260                                     const ec_pdo_reg_t *pdos);
       
  2261 \end{lstlisting}
       
  2262 
       
  2263 The \textit{ecrt\_domain\_register\_pdo()} method registers a certain
       
  2264 PDO as part of the domain and takes the address of the process data
       
  2265 pointer. This pointer will be set on master activation and then can be
       
  2266 parameter to the \textit{EC\_READ\_*} and \textit{EC\_WRITE\_*} macros
       
  2267 described below.
       
  2268 
       
  2269 A perhaps easier way to register multiple PDOs at the same time is to
       
  2270 fill an array of \textit{ec\_pdo\_reg\_t} and hand it to the
       
  2271 \textit{ecrt\_domain\_register\_pdo\_list()} method. Attention: This
       
  2272 array has to be terminated by an empty structure (\textit{\{\}})!
       
  2273 
       
  2274 \paragraph{Evaluating Domain Data}
       
  2275 
       
  2276 To evaluate domain data, the following method has to be used:
       
  2277 
       
  2278 \begin{lstlisting}[language=C]
       
  2279   void ecrt_domain_process(ec_domain_t *domain);
       
  2280 \end{lstlisting}
       
  2281 
       
  2282 The \textit{ecrt\_domain\_process()} method sets the domains state and
       
  2283 requeues its datagram for sending.
       
  2284 
       
  2285 \paragraph{Domain State}
       
  2286 
       
  2287 Similar to the master state, a domain has an own error state:
       
  2288 
       
  2289 \begin{lstlisting}[language=C]
       
  2290   int ecrt_domain_state(const ec_domain_t *domain);
       
  2291 \end{lstlisting}
       
  2292 
       
  2293 The \textit{ecrt\_domain\_state()} method returns the domain's error
       
  2294 state. It is non-zero if \underline{not} all process data values could
       
  2295 be exchanged, and zero otherwise.
       
  2296 
       
  2297 \subsubsection{Slave Methods}
       
  2298 \label{sec:ecrt-slave}
       
  2299 
       
  2300 \paragraph{SDO Configuration}
       
  2301 
       
  2302 To configure slave SDOs, the function interface below can be used:
       
  2303 
       
  2304 \begin{lstlisting}[language=C]
       
  2305   int ecrt_slave_conf_sdo8(ec_slave_t *slave,
       
  2306                            uint16_t sdo_index,
       
  2307                            uint8_t sdo_subindex,
       
  2308                            uint8_t value);
       
  2309   int ecrt_slave_conf_sdo16(ec_slave_t *slave,
       
  2310                             uint16_t sdo_index,
       
  2311                             uint8_t sdo_subindex,
       
  2312                             uint16_t value);
       
  2313   int ecrt_slave_conf_sdo32(ec_slave_t *slave,
       
  2314                             uint16_t sdo_index,
       
  2315                             uint8_t sdo_subindex,
       
  2316                             uint32_t value);
       
  2317 \end{lstlisting}
       
  2318 
       
  2319 The \textit{ecrt\_slave\_conf\_sdo*()} methods prepare the
       
  2320 configuration of a certain SDO. The index and subindex of the SDO, and
       
  2321 the value have to be specified. The configuration is done each time,
       
  2322 the slave is reconfigured. The methods only differ in the SDO's data
       
  2323 type. If the configuration could be prepared, zero is returned. If an
       
  2324 error occured, non-zero is returned.
       
  2325 
       
  2326 \paragraph{Variable-sized PDOs}
       
  2327 
       
  2328 For specifying the size of variable-sized PDOs, the following method
       
  2329 can be used:
       
  2330 
       
  2331 \begin{lstlisting}[language=C]
       
  2332   int ecrt_slave_pdo_size(ec_slave_t *slave,
       
  2333                           const char *pdo_name,
       
  2334                           size_t size);
       
  2335 \end{lstlisting}
       
  2336 
       
  2337 The \textit{ecrt\_slave\_pdo\_size()} method takes the name of the PDO
       
  2338 and the size. It returns zero on success, otherwise non-zero.
       
  2339 
       
  2340 \subsubsection{Process Data Access}
       
  2341 \label{sec:macros}
       
  2342 
       
  2343 The endianess of the process data could differ from that of the CPU.
       
  2344 Therefore, process data access has to be done by the macros below,
       
  2345 that are also provided by the realtime interface:
       
  2346 
       
  2347 \begin{lstlisting}[language=C]
       
  2348   #define EC_READ_BIT(DATA, POS)
       
  2349   #define EC_WRITE_BIT(DATA, POS, VAL)
       
  2350 
       
  2351   #define EC_READ_U8(DATA)
       
  2352   #define EC_READ_S8(DATA)
       
  2353   #define EC_READ_U16(DATA)
       
  2354   #define EC_READ_S16(DATA)
       
  2355   #define EC_READ_U32(DATA)
       
  2356   #define EC_READ_S32(DATA)
       
  2357 
       
  2358   #define EC_WRITE_U8(DATA, VAL)
       
  2359   #define EC_WRITE_S8(DATA, VAL)
       
  2360   #define EC_WRITE_U16(DATA, VAL)
       
  2361   #define EC_WRITE_S16(DATA, VAL)
       
  2362   #define EC_WRITE_U32(DATA, VAL)
       
  2363   #define EC_WRITE_S32(DATA, VAL)
       
  2364 \end{lstlisting}
       
  2365 
       
  2366 There are macros for bitwise access (\textit{EC\_READ\_BIT()},
       
  2367 \textit{EC\_WRITE\_BIT()}), and bytewise access
       
  2368 (\textit{EC\_READ\_*()}, \textit{EC\_WRITE\_*()}). The bytewise macros
       
  2369 carry the data type in their name. Example: \textit{EC\_WRITE\_S16()}
       
  2370 writes a 16 bit signed value to EtherCAT data. The \textit{DATA}
       
  2371 parameter is supposed to be a process data pointer, as provided at PDO
       
  2372 registration.
       
  2373 
       
  2374 The macros use the kernel's endianess conversion macros, that are
       
  2375 preprocessed to empty macros in case of equal endianess. This is the
       
  2376 definition for the \textit{EC\_\-READ\_\-U16()} macro:
       
  2377 
       
  2378 \begin{lstlisting}[language=C]
       
  2379   #define EC_READ_U16(DATA) \
       
  2380           ((uint16_t) le16_to_cpup((void *) (DATA)))
       
  2381 \end{lstlisting}
       
  2382 
       
  2383 The \textit{le16\_to\_cpup()} macro converts a little-endian, 16 bit
       
  2384 value to the CPU's architecture and takes a pointer to the input value
       
  2385 as its argument. If the CPU's architecture is little-endian, too (for
       
  2386 example on X86 and compatible), nothing has to be converted. In this
       
  2387 case, the macro is replaced with an empty macro by the preprocessor
       
  2388 and so there is no unneeded function call or case differentiation in
       
  2389 the code.
       
  2390 
       
  2391 For keeping it portable, it is highly recommended to make use of these
       
  2392 macros.
       
  2393 
       
  2394 %------------------------------------------------------------------------------
       
  2395 
       
  2396 \subsection{Slave Addressing}
       
  2397 \label{sec:addr}
       
  2398 \index{Slave!Addressing}
       
  2399 
       
  2400 The master offers the serveral slave addressing schemes (for PDO
       
  2401 registration or configuration) via the realtime interface. For this
       
  2402 reason, slave addresses are ASCII\nomenclature{ASCII}{American
       
  2403   Standard Code for Information Interchange}-coded and passed as a
       
  2404 string. The addressing schemes are independent of the EtherCAT
       
  2405 protocol and represent an additional feature of the master.
       
  2406 
       
  2407 Below, the allowed addressing schemes are described. The descriptions
       
  2408 are followed by a regular expression formally defining the addressing
       
  2409 scheme, and one or more examples.
       
  2410 
       
  2411 \begin{description}
       
  2412 \item[Position Addressing] This is the normal addressing scheme, where
       
  2413   each slave is addressed by its ring position. The first slave has
       
  2414   address 0, and the $n$th slave has address $n - 1$. This addressing
       
  2415   scheme is useful for small busses that have a fixed number of slaves.\\
       
  2416   RegEx: \texttt{[0-9]+} --- Example: \texttt{"42"}
       
  2417 \item[Advanced Position Addressing] Bus couplers segment the bus into
       
  2418   (physical) blocks. Though the logical ring positions keep being the
       
  2419   same, it is easier to address a slave with its block number and the
       
  2420   relative position inside the block. This addressing is done by
       
  2421   passing the (zero-based) index of the bus coupler (not the coupler's
       
  2422   ring position), followed by a colon and the relative position of the
       
  2423   actual slave starting at the bus coupler.\\
       
  2424   RegEx: \texttt{[0-9]+:[0-9]+} --- Examples: \texttt{"0:42"},
       
  2425   \texttt{"2:7"}
       
  2426 \item[Alias Addressing] Each slave can have a ``secondary slave
       
  2427   address'' or ``alias address''\footnote{Information about how to set
       
  2428     the alias can be found in section~\ref{sec:eepromaccess}} stored
       
  2429   in its E$^2$PROM.  The alias is evaluated by the master and can be
       
  2430   used to address the slave, which is useful when a clearly defined
       
  2431   slave has to be addressed and the ring position is not known or can
       
  2432   change over time. This scheme is used by starting the address string
       
  2433   with a mesh (\#) followed by the alias address.  The latter can also
       
  2434   be provided as hexadecimal value, prefixed with \textit{0x}.\\
       
  2435   RegEx: \texttt{\#(0x[0-9A-F]+|[0-9]+)} --- Examples:
       
  2436   \texttt{"\#6622"}, \texttt{"\#0xBEEF"}
       
  2437 \item[Advanced Alias Addressing] This is a mixture of the ``Alias
       
  2438   Addressing'' and ``Advanced Position Addressing'' schemes. A certain
       
  2439   slave is addressed by specifying its relative position after an
       
  2440   aliased slave. This is very useful, if a complete block of slaves
       
  2441   can vary its position in the bus. The bus coupler preceeding the
       
  2442   block should get an alias. The block slaves can then be addressed by
       
  2443   specifying this alias and their position inside the block. This
       
  2444   scheme is used by starting the address string with a mesh (\#)
       
  2445   followed by the alias address (which can be hexadecimal), then a
       
  2446   colon and the relative posision of the slave to
       
  2447   address.\\
       
  2448   RegEx: \texttt{\#(0x[0-9A-F]+|[0-9]+):[0-9]+} --- Examples:
       
  2449   \texttt{"\#0xBEEF:7"}, \texttt{"\#6:2"}
       
  2450 \end{description}
       
  2451 
       
  2452 In anticipation of section~\ref{sec:ecrt}, the functions accepting
       
  2453 these address strings are \textit{ecrt\_\-master\_\-get\_slave()},
       
  2454 \textit{ecrt\_domain\_register\_pdo()} and
       
  2455 \textit{ecrt\_domain\_register\_pdo\_list()} (the latter through the
       
  2456 \textit{ec\_pdo\_reg\_t} structure).
       
  2457 
       
  2458 %------------------------------------------------------------------------------
       
  2459 
       
  2460 \subsection{Concurrent Master Access}
       
  2461 \label{sec:concurr}
       
  2462 \index{Concurrency}
       
  2463 
       
  2464 In some cases, one master is used by serveral instances, for example
       
  2465 when a realtime module does cyclic process data exchange, and there
       
  2466 are EoE-capable slaves that require to exchange Ethernet data with the
       
  2467 kernel (see section~\ref{sec:eoeimp}). For this reason, the master is
       
  2468 a shared resource, and access to it has to be sequenctialized. This is
       
  2469 usually done by locking with semaphores, or other methods to protect
       
  2470 critical sections.
       
  2471 
       
  2472 The master itself can not provide locking mechanisms, because it has
       
  2473 no chance to know the appropriate kind of lock. Imagine, the realtime
       
  2474 module uses RTAI functionality, then ordinary kernel semaphores would
       
  2475 not be sufficient. For that, an important design decision was made:
       
  2476 The realtime module that reserved a master must have the total
       
  2477 control, therefore it has to take responsibility for providing the
       
  2478 appropriate locking mechanisms. If another instance wants to access
       
  2479 the master, it has to request the master lock by callbacks, that have
       
  2480 to be set by the realtime module. Moreover the realtime module can
       
  2481 deny access to the master if it consideres it to be awkward at the
       
  2482 moment.
       
  2483 
       
  2484 \begin{figure}[htbp]
       
  2485   \centering
       
  2486   \includegraphics[width=.6\textwidth]{images/master-locks}
       
  2487   \caption{Concurrent master access}
       
  2488   \label{fig:locks}
       
  2489 \end{figure}
       
  2490 
       
  2491 Figure~\ref{fig:locks} exemplary shows, how two processes share one
       
  2492 master: The realtime module's cyclic thread uses the master for
       
  2493 process data exchange, while the master-internal EoE process uses it
       
  2494 to communicate with EoE-capable slaves. Both have to aquire the master
       
  2495 lock before access: The realtime thread can access the lock natively,
       
  2496 while the EoE process has to use the master callbacks.
       
  2497 Section~\ref{sec:concurrency} gives an example, of how to implement
       
  2498 this.
       
  2499 
       
  2500 %------------------------------------------------------------------------------
       
  2501 
       
  2502 \section{The Master's State Machines}
       
  2503 \label{sec:fsm}
       
  2504 \index{FSM}
       
  2505 
       
  2506 Many parts of the EtherCAT master are implemented as \textit{finite
       
  2507   state machines} (FSMs\nomenclature{FSM}{Finite State Machine}).
       
  2508 Though this leads to a higher grade of complexity in some aspects, is
       
  2509 opens many new possibilities.
       
  2510 
       
  2511 The below short code example exemplary shows how to read all slave
       
  2512 states and moreover illustrates the restrictions of ``sequential''
       
  2513 coding:
       
  2514 
       
  2515 \begin{lstlisting}[language=C,numbers=left]
       
  2516   ec_datagram_brd(datagram, 0x0130, 2); // prepare datagram
       
  2517   if (ec_master_simple_io(master, datagram)) return -1;
       
  2518   slave_states = EC_READ_U8(datagram->data); // process datagram
       
  2519 \end{lstlisting}
       
  2520 
       
  2521 The \textit{ec\_master\_simple\_io()} function provides a simple
       
  2522 interface for synchronously sending a single datagram and receiving
       
  2523 the result\footnote{For all communication issues have been meanwhile
       
  2524   sourced out into state machines, the function is deprecated and
       
  2525   stopped existing. Nevertheless it is adequate for showing it's own
       
  2526   restrictions.}. Internally, it queues the specified datagram,
       
  2527 invokes the \textit{ec\_master\_send\_datagrams()} function to send a
       
  2528 frame with the queued datagram and then waits actively for its
       
  2529 reception.
       
  2530 
       
  2531 This sequential approach is very simple, reflecting in only three
       
  2532 lines of code. The disadvantage is, that the master is blocked for the
       
  2533 time it waits for datagram reception. There is no difficulty when only
       
  2534 one instance is using the master, but if more instances want to
       
  2535 (synchronously\footnote{At this time, synchronous master access will
       
  2536   be adequate to show the advantages of an FSM. The asynchronous
       
  2537   approach will be discussed in section~\ref{sec:eoeimp}}) use the
       
  2538 master, it is inevitable to think about an alternative to the
       
  2539 sequential model.
       
  2540 
       
  2541 Master access has to be sequentialized for more than one instance
       
  2542 wanting to send and receive datagrams synchronously. With the present
       
  2543 approach, this would result in having one phase of active waiting for
       
  2544 each instance, which would be non-acceptable especially in realtime
       
  2545 circumstances, because of the huge time overhead.
       
  2546 
       
  2547 A possible solution is, that all instances would be executed
       
  2548 sequentially to queue their datagrams, then give the control to the
       
  2549 next instance instead of waiting for the datagram reception. Finally,
       
  2550 bus IO is done by a higher instance, which means that all queued
       
  2551 datagrams are sent and received. The next step is to execute all
       
  2552 instances again, which then process their received datagrams and issue
       
  2553 new ones.
       
  2554 
       
  2555 This approach results in all instances having to retain their state,
       
  2556 when giving the control back to the higher instance. It is quite
       
  2557 obvious to use a \textit{finite state machine} model in this case.
       
  2558 Section~\ref{sec:fsmtheory} will introduce some of the theory used,
       
  2559 while the listings below show the basic approach by coding the example
       
  2560 from above as a state machine:
       
  2561 
       
  2562 \begin{lstlisting}[language=C,numbers=left]
       
  2563   // state 1
       
  2564   ec_datagram_brd(datagram, 0x0130, 2); // prepare datagram
       
  2565   ec_master_queue(master, datagram); // queue datagram
       
  2566   next_state = state_2;
       
  2567   // state processing finished
       
  2568 \end{lstlisting}
       
  2569 
       
  2570 After all instances executed their current state and queued their
       
  2571 datagrams, these are sent and received. Then the respective next
       
  2572 states are executed:
       
  2573 
       
  2574 \begin{lstlisting}[language=C,numbers=left]
       
  2575   // state 2
       
  2576   if (datagram->state != EC_DGRAM_STATE_RECEIVED) {
       
  2577           next_state = state_error;
       
  2578           return; // state processing finished
       
  2579   }
       
  2580   slave_states = EC_READ_U8(datagram->data); // process datagram
       
  2581   // state processing finished.
       
  2582 \end{lstlisting}
       
  2583 
       
  2584 See section~\ref{sec:statemodel} for an introduction to the
       
  2585 state machine programming concept used in the master code.
       
  2586 
       
  2587 %------------------------------------------------------------------------------
       
  2588 
       
  2589 \subsection{State Machine Theory}
       
  2590 \label{sec:fsmtheory}
       
  2591 \index{FSM!Theory}
       
  2592 
       
  2593 A finite state machine \cite{automata} is a model of behavior with
       
  2594 inputs and outputs, where the outputs not only depend on the inputs,
       
  2595 but the history of inputs. The mathematical definition of a finite
       
  2596 state machine (or finite automaton) is a six-tuple $(\Sigma, \Gamma,
       
  2597 S, s_0, \delta, \omega)$, with
       
  2598 
       
  2599 \begin{itemize}
       
  2600 \item the input alphabet $\Sigma$, with $\Sigma \neq
       
  2601   \emptyset$, containing all input symbols,
       
  2602 \item the output alphabet $\Gamma$, with $\Gamma \neq
       
  2603   \emptyset$, containing all output symbols,
       
  2604 \item the set of states $S$, with $S \neq \emptyset$,
       
  2605 \item the set of initial states $s_0$ with $s_0 \subseteq S, s_0 \neq
       
  2606   \emptyset$
       
  2607 \item the transition function $\delta: S \times \Sigma \rightarrow S
       
  2608   \times \Gamma$
       
  2609 \item the output function $\omega$.
       
  2610 \end{itemize}
       
  2611 
       
  2612 The state transition function $\delta$ is often specified by a
       
  2613 \textit{state transition table}, or by a \textit{state transition
       
  2614   diagram}. The transition table offers a matrix view of the state
       
  2615 machine behavior (see table~\ref{tab:statetrans}). The matrix rows
       
  2616 correspond to the states ($S = \{s_0, s_1, s_2\}$) and the columns
       
  2617 correspond to the input symbols ($\Gamma = \{a, b, \varepsilon\}$).
       
  2618 The table contents in a certain row $i$ and column $j$ then represent
       
  2619 the next state (and possibly the output) for the case, that a certain
       
  2620 input symbol $\sigma_j$ is read in the state $s_i$.
       
  2621 
       
  2622 \begin{table}[htbp]
       
  2623   \caption{A typical state transition table}
       
  2624   \label{tab:statetrans}
       
  2625   \vspace{2mm}
       
  2626   \centering
       
  2627   \begin{tabular}{l|ccc}
       
  2628     & $a$ & $b$ & $\varepsilon$\\ \hline
       
  2629     $s_0$ & $s_1$ & $s_1$ & $s_2$\\
       
  2630     $s_1$ & $s_2$ & $s_1$ & $s_0$\\
       
  2631     $s_2$ & $s_0$ & $s_0$ & $s_0$\\ \hline
       
  2632   \end{tabular}
       
  2633 \end{table}
       
  2634 
       
  2635 The state diagram for the same example looks like the one in
       
  2636 figure~\ref{fig:statetrans}. The states are represented as circles or
       
  2637 ellipses and the transitions are drawn as arrows between them. Close
       
  2638 to a transition arrow can be the condition that must be fulfilled to
       
  2639 allow the transition. The initial state is marked by a filled black
       
  2640 circle with an arrow pointing to the respective state.
       
  2641 
       
  2642 \begin{figure}[htbp]
       
  2643   \centering
       
  2644   \includegraphics[width=.5\textwidth]{images/statetrans}
       
  2645   \caption{A typical state transition diagram}
       
  2646   \label{fig:statetrans}
       
  2647 \end{figure}
       
  2648 
       
  2649 \paragraph{Deterministic and non-deterministic state machines}
       
  2650 
       
  2651 A state machine can be deterministic, meaning that for one state and
       
  2652 input, there is one (and only one) following state. In this case, the
       
  2653 state machine has exactly one starting state. Non-deterministic state
       
  2654 machines can have more than one transitions for a single state-input
       
  2655 combination. There is a set of starting states in the latter case.
       
  2656 
       
  2657 \paragraph{Moore and Mealy machines}
       
  2658 
       
  2659 There is a distinction between so-called \textit{Moore machines}, and
       
  2660 \textit{Mealy machines}. Mathematically spoken, the distinction lies
       
  2661 in the output function $\omega$: If it only depends on the current
       
  2662 state ($\omega: S \rightarrow \Gamma$), the machine corresponds to the
       
  2663 ``Moore Model''. Otherwise, if $\omega$ is a function of a state and
       
  2664 the input alphabet ($\omega: S \times \Sigma \rightarrow \Gamma$) the
       
  2665 state machine corresponds to the ``Mealy model''. Mealy machines are
       
  2666 the more practical solution in most cases, because their design allows
       
  2667 machines with a minimum number of states. In practice, a mixture of
       
  2668 both models is often used.
       
  2669 
       
  2670 \paragraph{Misunderstandings about state machines}
       
  2671 
       
  2672 There is a phenomenon called ``state explosion'', that is oftenly
       
  2673 taken as a counter-argument against general use of state machines in
       
  2674 complex environments. It has to be mentioned, that this point is
       
  2675 misleading~\cite{fsmmis}. State explosions happen usually as a result
       
  2676 of a bad state machine design: Common mistakes are storing the present
       
  2677 values of all inputs in a state, or not dividing a complex state
       
  2678 machine into simpler sub state machines. The EtherCAT master uses
       
  2679 serveral state machines, that are executed hierarchically and so serve
       
  2680 as sub state machines. These are also described below.
       
  2681 
       
  2682 %------------------------------------------------------------------------------
       
  2683 
       
  2684 \subsection{The Master's State Model}
       
  2685 \label{sec:statemodel}
       
  2686 
       
  2687 This section will introduce the techniques used in the master to
       
  2688 implement state machines.
       
  2689 
       
  2690 \paragraph{State Machine Programming}
       
  2691 
       
  2692 There are certain ways to implement a state machine in \textit{C}
       
  2693 code. An obvious way is to implement the different states and actions
       
  2694 by one big case differentiation:
       
  2695 
       
  2696 \begin{lstlisting}[language=C,numbers=left]
       
  2697   enum {STATE_1, STATE_2, STATE_3};
       
  2698   int state = STATE_1;
       
  2699 
       
  2700   void state_machine_run(void *priv_data) {
       
  2701           switch (state) {
       
  2702                   case STATE_1:
       
  2703                           action_1();
       
  2704                           state = STATE_2;
       
  2705                           break;
       
  2706                   case STATE_2:
       
  2707                           action_2()
       
  2708                           if (some_condition) state = STATE_1;
       
  2709                           else state = STATE_3;
       
  2710                           break;
       
  2711                   case STATE_3:
       
  2712                           action_3();
       
  2713                           state = STATE_1;
       
  2714                           break;
       
  2715           }
       
  2716   }
       
  2717 \end{lstlisting}
       
  2718 
       
  2719 For small state machines, this is an option. The disadvantage is, that
       
  2720 with an increasing number of states the code soon gets complex and an
       
  2721 additional case differentiation is executed each run. Besides, lots of
       
  2722 indentation is wasted.
       
  2723 
       
  2724 The method used in the master is to implement every state in an own
       
  2725 function and to store the current state function with a function
       
  2726 pointer:
       
  2727 
       
  2728 \begin{lstlisting}[language=C,numbers=left]
       
  2729   void (*state)(void *) = state1;
       
  2730 
       
  2731   void state_machine_run(void *priv_data) {
       
  2732           state(priv_data);
       
  2733   }
       
  2734 
       
  2735   void state1(void *priv_data) {
       
  2736           action_1();
       
  2737           state = state2;
       
  2738   }
       
  2739 
       
  2740   void state2(void *priv_data) {
       
  2741           action_2();
       
  2742           if (some_condition) state = state1;
       
  2743           else state = state2;
       
  2744   }
       
  2745 
       
  2746   void state3(void *priv_data) {
       
  2747           action_3();
       
  2748           state = state1;
       
  2749   }
       
  2750 \end{lstlisting}
       
  2751 
       
  2752 In the master code, state pointers of all state machines\footnote{All
       
  2753   except for the EoE state machine, because multiple EoE slaves have
       
  2754   to be handled in parallel. For this reason each EoE handler object
       
  2755   has its own state pointer.} are gathered in a single object of the
       
  2756 \textit{ec\_fsm\_t} class. This is advantageous, because there is
       
  2757 always one instance of every state machine available and can be
       
  2758 started on demand.
       
  2759 
       
  2760 \paragraph{Mealy and Moore}
       
  2761 
       
  2762 If a closer look is taken to the above listing, it can be seen that
       
  2763 the actions executed (the ``outputs'' of the state machine) only
       
  2764 depend on the current state. This accords to the ``Moore'' model
       
  2765 introduced in section~\ref{sec:fsmtheory}. As mentioned, the ``Mealy''
       
  2766 model offers a higher flexibility, which can be seen in the listing
       
  2767 below:
       
  2768 
       
  2769 \begin{lstlisting}[language=C,numbers=left]
       
  2770   void state7(void *priv_data) {
       
  2771           if (some_condition) {
       
  2772                   action_7a();
       
  2773                   state = state1;
       
  2774           }
       
  2775           else {
       
  2776                   action_7b();
       
  2777                   state = state8;
       
  2778           }
       
  2779   }
       
  2780 \end{lstlisting}
       
  2781 
       
  2782 \begin{description}
       
  2783 \item[\normalfont\textcircled{\tiny 3} + \textcircled{\tiny 7}] The
       
  2784   state function executes the actions depending on the state
       
  2785   transition, that is about to be done.
       
  2786 \end{description}
       
  2787 
       
  2788 The most flexible alternative is to execute certain actions depending
       
  2789 on the state, followed by some actions dependent on the state
       
  2790 transition:
       
  2791 
       
  2792 \begin{lstlisting}[language=C,numbers=left]
       
  2793   void state9(void *priv_data) {
       
  2794           action_9();
       
  2795           if (some_condition) {
       
  2796                   action_9a();
       
  2797                   state = state7;
       
  2798           }
       
  2799           else {
       
  2800                   action_9b();
       
  2801                   state = state10;
       
  2802           }
       
  2803   }
       
  2804 \end{lstlisting}
       
  2805 
       
  2806 This model is oftenly used in the master. It combines the best aspects
       
  2807 of both approaches.
       
  2808 
       
  2809 \paragraph{Using Sub State Machines}
       
  2810 
       
  2811 To avoid having too much states, certain functions of the EtherCAT
       
  2812 master state machine have been sourced out into sub state machines.
       
  2813 This helps to encapsule the related workflows and moreover avoids the
       
  2814 ``state explosion'' phenomenon described in
       
  2815 section~\ref{sec:fsmtheory}. If the master would instead use one big
       
  2816 state machine, the number of states would be a multiple of the actual
       
  2817 number. This would increase the level of complexity to a
       
  2818 non-manageable grade.
       
  2819 
       
  2820 \paragraph{Executing Sub State Machines}
       
  2821 
       
  2822 If a state machine starts to execute a sub state machine, it usually
       
  2823 remains in one state until the sub state machine terminates. This is
       
  2824 usually done like in the listing below, which is taken out of the
       
  2825 slave configuration state machine code:
       
  2826 
       
  2827 \begin{lstlisting}[language=C,numbers=left]
       
  2828   void ec_fsm_slaveconf_saveop(ec_fsm_t *fsm)
       
  2829   {
       
  2830           fsm->change_state(fsm); // execute state change
       
  2831                                   // sub state machine
       
  2832 
       
  2833           if (fsm->change_state == ec_fsm_error) {
       
  2834                   fsm->slave_state = ec_fsm_end;
       
  2835                   return;
       
  2836           }
       
  2837 
       
  2838           if (fsm->change_state != ec_fsm_end) return;
       
  2839 
       
  2840           // continue state processing
       
  2841           ...
       
  2842 \end{lstlisting}
       
  2843 
       
  2844 \begin{description}
       
  2845 \item[\normalfont\textcircled{\tiny 3}] \textit{change\_state} is the
       
  2846   state pointer of the state change state machine. The state function,
       
  2847   the pointer points on, is executed\ldots
       
  2848 \item[\normalfont\textcircled{\tiny 6}] \ldots either until the state
       
  2849   machine terminates with the error state \ldots
       
  2850 \item[\normalfont\textcircled{\tiny 11}] \ldots or until the state
       
  2851   machine terminates in the end state. Until then, the ``higher''
       
  2852   state machine remains in the current state and executes the sub
       
  2853   state machine again in the next cycle.
       
  2854 \end{description}
       
  2855 
       
  2856 \paragraph{State Machine Descriptions}
       
  2857 
       
  2858 The below sections describe every state machine used in the EtherCAT
       
  2859 master. The textual descriptions of the state machines contain
       
  2860 references to the transitions in the corresponding state transition
       
  2861 diagrams, that are marked with an arrow followed by the name of the
       
  2862 successive state.  Transitions caused by trivial error cases (i.~e. no
       
  2863 response from slave) are not described explicitly. These transitions
       
  2864 are drawn as dashed arrows in the diagrams.
       
  2865 
       
  2866 %------------------------------------------------------------------------------
       
  2867 
       
  2868 \subsection{The Operation State Machine}
       
  2869 \label{sec:fsm-op}
       
  2870 \index{FSM!Operation}
       
  2871 
       
  2872 The Operation state machine is executed by calling the
       
  2873 \textit{ecrt\_master\_run()} method in cyclic realtime code. Its
       
  2874 purpose is to monitor the bus and to reconfigure slaves after a bus
       
  2875 failure or power failure. Figure~\ref{fig:fsm-op} shows its transition
       
  2876 diagram.
       
  2877 
       
  2878 \begin{figure}[htbp]
       
  2879   \centering
       
  2880   \includegraphics[width=.8\textwidth]{images/fsm-op}
       
  2881   \caption{Transition diagram of the operation state machine}
       
  2882   \label{fig:fsm-op}
       
  2883 \end{figure}
       
  2884 
       
  2885 \begin{description}
       
  2886 \item[START] This is the beginning state of the operation state
       
  2887   machine. There is a datagram issued, that queries the ``AL Control
       
  2888   Response'' attribute \cite[section~5.3.2]{alspec} of all slaves via
       
  2889   broadcast. In this way, all slave states and the number of slaves
       
  2890   responding can be determined.  $\rightarrow$~\textit{BROADCAST}
       
  2891 
       
  2892 \item[BROADCAST] The broadcast datagram is evaluated. A change in the
       
  2893   number of responding slaves is treates as a topology change. If the
       
  2894   number of slaves is not as expected, the bus is marked as
       
  2895   ``tainted''. In this state, no slave reconfiguration is possible,
       
  2896   because the assignment of known slaves and those present on the bus
       
  2897   is ambiguous. If the number of slaves is considered as right, the
       
  2898   bus is marked for validation, because it turned from tainted to
       
  2899   normal state and it has to be checked, if all slaves are valid. Now,
       
  2900   the state of every single slave has to be determined. For that, a
       
  2901   (unicast) datagram is issued, that queries the first slave's ``AL
       
  2902   Control Response'' attribute. $\rightarrow$~\textit{READ STATES}
       
  2903 
       
  2904 \item[READ STATES] If the current slave did not respond to its
       
  2905   configured station address, it is marked as offline, and the next
       
  2906   slave is queried. $\rightarrow$~\textit{READ STATES}
       
  2907 
       
  2908   If the slave responded, it is marked as online and its current state
       
  2909   is stored. The next slave is queried. $\rightarrow$~\textit{READ
       
  2910     STATES}
       
  2911 
       
  2912   If all slaves have been queried, and the bus is marked for
       
  2913   validation, the validation is started by checking the first slaves
       
  2914   vendor ID. $\rightarrow$~\textit{VALIDATE VENDOR}
       
  2915 
       
  2916   If no validation has to be done, it is checked, if all slaves are in
       
  2917   the state they are supposed to be. If not, the first of slave with
       
  2918   the wrong state is reconfigured and brought in the required state.
       
  2919   $\rightarrow$~\textit{CONFIGURE SLAVES}
       
  2920 
       
  2921   If all slaves are in the correct state, the state machine is
       
  2922   restarted. $\rightarrow$~\textit{START}
       
  2923 
       
  2924 \item[CONFIGURE SLAVES] The slave configuration state machine is
       
  2925   executed until termination. $\rightarrow$~\textit{CONFIGURE SLAVES}
       
  2926 
       
  2927   If there are still slaves in the wrong state after another check,
       
  2928   the first of these slaves is configured and brought into the correct
       
  2929   state again. $\rightarrow$~\textit{CONFIGURE SLAVES}
       
  2930 
       
  2931   If all slaves are in the correct state, the state machine is
       
  2932   restarted. $\rightarrow$~\textit{START}
       
  2933 
       
  2934 \item[VALIDATE VENDOR] The SII state machine is executed until
       
  2935   termination. If the slave has the wrong vendor ID, the state machine
       
  2936   is restarted. $\rightarrow$~\textit{START}
       
  2937 
       
  2938   If the slave has the correct vendor ID, its product ID is queried.
       
  2939   $\rightarrow$~\textit{VALIDATE PRODUCT}
       
  2940 
       
  2941 \item[VALIDATE PRODUCT] The SII state machine is executed until
       
  2942   termination. If the slave has the wrong product ID, the state
       
  2943   machine is restarted. $\rightarrow$~\textit{START}
       
  2944 
       
  2945   If the slave has the correct product ID, the next slave's vendor ID
       
  2946   is queried. $\rightarrow$~\textit{VALIDATE VENDOR}
       
  2947 
       
  2948   If all slaves have the correct vendor IDs and product codes, the
       
  2949   configured station addresses can be safely rewritten. This is done
       
  2950   for the first slave marked as offline.
       
  2951   $\rightarrow$~\textit{REWRITE ADDRESSES}
       
  2952 
       
  2953 \item[REWRITE ADDRESSES] If the station address was successfully
       
  2954   written, it is sear\-ched for the next slave marked as offline. If
       
  2955   there is one, its address is reconfigured, too.
       
  2956   $\rightarrow$~\textit{REWRITE ADDRESSES}
       
  2957 
       
  2958   If there are no more slaves marked as offline, the state machine is
       
  2959   restarted. $\rightarrow$~\textit{START}
       
  2960 \end{description}
       
  2961 
       
  2962 %------------------------------------------------------------------------------
       
  2963 
       
  2964 \subsection{The Idle State Machine}
       
  2965 \label{sec:fsm-idle}
       
  2966 \index{FSM!Idle}
       
  2967 
       
  2968 The Idle state machine is executed by a kernel workqueue, if no
       
  2969 realtime module is connected. Its purpose is to make slave information
       
  2970 available to user space, operate EoE-capable slaves, read and write
       
  2971 E$^2$PROM contents and test slave functionality.
       
  2972 Figure~\ref{fig:fsm-idle} shows its transition diagram.
       
  2973 
       
  2974 \begin{figure}[htbp]
       
  2975   \centering
       
  2976   \includegraphics[width=.8\textwidth]{images/fsm-idle}
       
  2977   \caption{Transition diagram of the idle state machine}
       
  2978   \label{fig:fsm-idle}
       
  2979 \end{figure}
       
  2980 
       
  2981 \begin{description}
       
  2982 \item[START] The beginning state of the idle state machine. Similar to
       
  2983   the operation state machine, a broadcast datagram is issued, to
       
  2984   query all slave states and the number of slaves.
       
  2985   $\rightarrow$~\textit{BROADCAST}
       
  2986 
       
  2987 \item[BROADCAST] The number of responding slaves is evaluated. If it
       
  2988   has changed since the last time, this is treated as a topology
       
  2989   change and the internal list of slaves is cleared and rebuild
       
  2990   completely. The slave scan state machine is started for the first
       
  2991   slave. $\rightarrow$~\textit{SCAN FOR SLAVES}
       
  2992 
       
  2993   If no topology change happened, every single slave state is fetched.
       
  2994   $\rightarrow$~\textit{READ STATES}
       
  2995 
       
  2996 \item[SCAN FOR SLAVES] The slave scan state machine is executed until
       
  2997   termination. $\rightarrow$~\textit{SCAN FOR SLAVES}
       
  2998 
       
  2999   If there is another slave to scan, the slave scan state machine is
       
  3000   started again. $\rightarrow$~\textit{SCAN FOR SLAVES}
       
  3001 
       
  3002   If all slave information has been fetched, slave addresses are
       
  3003   calculated and EoE processing is started. Then, the state machine is
       
  3004   restarted. $\rightarrow$~\textit{START}
       
  3005 
       
  3006 \item[READ STATES] If the slave did not respond to the query, it is
       
  3007   marked as offline. The next slave is queried.
       
  3008   $\rightarrow$~\textit{READ STATES}
       
  3009 
       
  3010   If the slave responded, it is marked as online. And the next slave
       
  3011   is queried. $\rightarrow$~\textit{READ STATES}
       
  3012 
       
  3013   If all slave states have been determined, it is checked, if any
       
  3014   slaves are not in the state they supposed to be. If this is true,
       
  3015   the slave configuration state machine is started for the first of
       
  3016   them. $\rightarrow$~\textit{CONFIGURE SLAVES}
       
  3017 
       
  3018   If all slaves are in the correct state, it is checked, if any
       
  3019   E$^2$PROM write operations are pending. If this is true, the first
       
  3020   pending operation is executed by starting the SII state machine for
       
  3021   writing access. $\rightarrow$~\textit{WRITE EEPROM}
       
  3022 
       
  3023   If all these conditions are false, there is nothing to do and the
       
  3024   state machine is restarted. $\rightarrow$~\textit{START}
       
  3025 
       
  3026 \item[CONFIGURE SLAVES] The slave configuration state machine is
       
  3027   executed until termination. $\rightarrow$~\textit{CONFIGURE SLAVES}
       
  3028 
       
  3029   After this, it is checked, if another slave needs a state change. If
       
  3030   this is true, the slave state change state machine is started for
       
  3031   this slave. $\rightarrow$~\textit{CONFIGURE SLAVES}
       
  3032 
       
  3033   If all slaves are in the correct state, it is determined, if any
       
  3034   E$^2$PROM write operations are pending. If this is true, the first
       
  3035   pending operation is executed by starting the SII state machine for
       
  3036   writing access. $\rightarrow$~\textit{WRITE EEPROM}
       
  3037 
       
  3038   If all prior conditions are false, the state machine is restarted.
       
  3039   $\rightarrow$~\textit{START}
       
  3040 
       
  3041 \item[WRITE EEPROM] The SII state machine is executed until
       
  3042   termination. $\rightarrow$~\textit{WRITE EEPROM}
       
  3043 
       
  3044   If the current word has been written successfully, and there are
       
  3045   still word to write, the SII state machine is started for the next
       
  3046   word. $\rightarrow$~\textit{WRITE EEPROM}
       
  3047 
       
  3048   If all words have been written successfully, the new E$^2$PROM
       
  3049   contents are evaluated and the state machine is restarted.
       
  3050   $\rightarrow$~\textit{START}
       
  3051 
       
  3052 \end{description}
       
  3053 
       
  3054 %------------------------------------------------------------------------------
       
  3055 
       
  3056 \subsection{The Slave Scan State Machine}
       
  3057 \label{sec:fsm-scan}
       
  3058 \index{FSM!Slave Scan}
       
  3059 
       
  3060 The slave scan state machine, which can be seen in
       
  3061 figure~\ref{fig:fsm-slavescan}, leads through the process of fetching
       
  3062 all slave information.
       
  3063 
       
  3064 \begin{figure}[htbp]
       
  3065   \centering
       
  3066   \includegraphics[width=.6\textwidth]{images/fsm-slavescan}
       
  3067   \caption{Transition diagram of the slave scan state machine}
       
  3068   \label{fig:fsm-slavescan}
       
  3069 \end{figure}
       
  3070 
       
  3071 \begin{description}
       
  3072 \item[START] In the beginning state of the slave scan state machine,
       
  3073   the station address is written to the slave, which is always the
       
  3074   ring position~+~$1$. In this way, the address 0x0000 (default
       
  3075   address) is not used, which makes it easy to detect unconfigured
       
  3076   slaves.  $\rightarrow$~\textit{ADDRESS}
       
  3077 
       
  3078 \item[ADDRESS] The writing of the station address is verified. After
       
  3079   that, the slave's ``AL Control Response'' attribute is queried.
       
  3080   $\rightarrow$~\textit{STATE}
       
  3081 
       
  3082 \item[STATE] The AL state is evaluated. A warning is output, if the
       
  3083   slave has still the \textit{Change} bit set. After that, the slave's
       
  3084   ``DL Information'' attribute is queried.
       
  3085   $\rightarrow$~\textit{BASE}
       
  3086 
       
  3087 \item[BASE] The queried base data are evaluated: Slave type, revision
       
  3088   and build number, and even more important, the number of supported
       
  3089   sync managers and FMMUs are stored. After that, the slave's data
       
  3090   link layer information is read from the ``DL Status'' attribute at
       
  3091   address 0x0110. $\rightarrow$~\textit{DATALINK}
       
  3092 
       
  3093 \item[DATALINK] In this state, the DL information is evaluated: This
       
  3094   information about the communication ports contains, if the link is
       
  3095   up, if the loop has been closed and if there is a carrier detected
       
  3096   on the RX side of each port.
       
  3097 
       
  3098   Then, the state machine starts measuring the size of the slave's
       
  3099   E$^2$PROM contents. This is done by subsequently reading out each
       
  3100   category header, until the last category is reached (type 0xFFFF).
       
  3101   This procedure is started by querying the first category header at
       
  3102   word address 0x0040 via the SII state machine.
       
  3103   $\rightarrow$~\textit{EEPROM SIZE}
       
  3104 
       
  3105 \item[EEPROM SIZE] The SII state machine is executed until
       
  3106   termination. $\rightarrow$~\textit{EEPROM SIZE}
       
  3107 
       
  3108   If the category type does not mark the end of the categories, the
       
  3109   position of the next category header is determined via the length of
       
  3110   the current category, and the SII state machine is started again.
       
  3111   $\rightarrow$~\textit{EEPROM SIZE}
       
  3112 
       
  3113   If the size of the E$^2$PROM contents has been determined, memory is
       
  3114   allocated, to read all the contents. The SII state machine is
       
  3115   started to read the first word. $\rightarrow$~\textit{EEPROM DATA}
       
  3116 
       
  3117 \item[EEPROM DATA] The SII state machine is executed until
       
  3118   termination. $\rightarrow$~\textit{EEPROM DATA}
       
  3119 
       
  3120   Two words have been read. If more than one word is needed, the two
       
  3121   words are written in the allocated memory. Otherwise only one word
       
  3122   (the last word) is copied. If more words are to read, the SII state
       
  3123   machine is started again to read the next two words.
       
  3124   $\rightarrow$~\textit{EEPROM DATA}
       
  3125 
       
  3126   The complete E$^2$PROM contents have been read. The slave's identity
       
  3127   object and mailbox information are evaluated. Moreover the category
       
  3128   types STRINGS, GENERAL, SYNC and PDO are evaluated. The slave
       
  3129   scanning has been completed. $\rightarrow$~\textit{END}
       
  3130 
       
  3131 \item[END] Slave scanning has been finished.
       
  3132 
       
  3133 \end{description}
       
  3134 
       
  3135 %------------------------------------------------------------------------------
       
  3136 
       
  3137 \subsection{The Slave Configuration State Machine}
       
  3138 \label{sec:fsm-conf}
       
  3139 \index{FSM!Slave Configuration}
       
  3140 
       
  3141 The slave configuration state machine, which can be seen in
       
  3142 figure~\ref{fig:fsm-slaveconf}, leads through the process of
       
  3143 configuring a slave and bringing it to a certain state.
       
  3144 
       
  3145 \begin{figure}[htbp]
       
  3146   \centering
       
  3147   \includegraphics[width=.6\textwidth]{images/fsm-slaveconf}
       
  3148   \caption{Transition diagram of the slave configuration state
       
  3149     machine}
       
  3150   \label{fig:fsm-slaveconf}
       
  3151 \end{figure}
       
  3152 
       
  3153 \begin{description}
       
  3154 \item[INIT] The state change state machine has been initialized to
       
  3155   bring the slave into the \textit{INIT} state. Now, the slave state
       
  3156   change state machine is executed until termination.
       
  3157   $\rightarrow$~\textit{INIT}
       
  3158 
       
  3159   If the slave state change failed, the configuration has to be
       
  3160   aborted. $\rightarrow$~\textit{END}
       
  3161 
       
  3162   The slave state change succeeded and the slave is now in
       
  3163   \textit{INIT} state. If this is the target state, the configuration
       
  3164   is finished. $\rightarrow$~\textit{END}
       
  3165 
       
  3166   If the slave does not support any sync managers, the sync manager
       
  3167   configuration can be skipped. The state change state machine is
       
  3168   started to bring the slave into \textit{PREOP} state.
       
  3169   $\rightarrow$~\textit{PREOP}
       
  3170 
       
  3171   Sync managers are configured conforming to the sync manager category
       
  3172   information provided in the slave's E$^2$PROM. The corresponding
       
  3173   datagram is issued. $\rightarrow$~\textit{SYNC}
       
  3174 
       
  3175 \item[SYNC] If the sync manager configuration datagram is accepted,
       
  3176   the sync manager configuration was successful. The slave may now
       
  3177   enter the \textit{PREOP} state, and the state change state machine
       
  3178   is started. $\rightarrow$~\textit{PREOP}
       
  3179 
       
  3180 \item[PREOP] The state change state machine is executed until
       
  3181   termination. $\rightarrow$~\textit{PREOP}
       
  3182 
       
  3183   If the state change failed, the configuration has to be aborted.
       
  3184   $\rightarrow$~\textit{END}
       
  3185 
       
  3186   If the \textit{PREOP} state was the target state, the configuration
       
  3187   is finished. $\rightarrow$~\textit{END}
       
  3188 
       
  3189   If the slave supports no FMMUs, the FMMU configuration can be
       
  3190   skipped. If the slave has SDOs to configure, it is begun with
       
  3191   sending the first SDO. $\rightarrow$~\textit{SDO\_CONF}
       
  3192 
       
  3193   If no SDO configurations are provided, the slave can now directly be
       
  3194   brought into the \textit{SAVEOP} state and the state change state
       
  3195   machine is started again. $\rightarrow$~\textit{SAVEOP}
       
  3196 
       
  3197   Otherwise, all supported FMMUs are configured according to the PDOs
       
  3198   requested via the master's realtime interface. The appropriate
       
  3199   datagram is issued. $\rightarrow$~\textit{FMMU}
       
  3200 
       
  3201 \item[FMMU] The FMMU configuration datagram was accepted. If the slave
       
  3202   has SDOs to configure, it is begun with sending the first SDO.
       
  3203   $\rightarrow$~\textit{SDO\_CONF}
       
  3204 
       
  3205   Otherwise, the slave can now be brought into the \textit{SAVEOP}
       
  3206   state. The state change state machine is started.
       
  3207   $\rightarrow$~\textit{SAVEOP}
       
  3208 
       
  3209 \item[SDO\_CONF] The CoE state machine is executed until termination.
       
  3210   $\rightarrow$~\textit{SDO\_CONF}
       
  3211 
       
  3212   If another SDO has to be configured, a new SDO download sequence is
       
  3213   begun. $\rightarrow$~\textit{SDO\_CONF}
       
  3214 
       
  3215   Otherwise, the slave can now be brought into the \textit{SAVEOP}
       
  3216   state. The state change state machine is started.
       
  3217   $\rightarrow$~\textit{SAVEOP}
       
  3218 
       
  3219 \item[SAVEOP] The state change state machine is executed until
       
  3220   termination. $\rightarrow$~\textit{SAVEOP}
       
  3221 
       
  3222   If the state change failed, the configuration has to be aborted.
       
  3223   $\rightarrow$~\textit{END}
       
  3224 
       
  3225   If the \textit{SAVEOP} state was the target state, the configuration
       
  3226   is finished. $\rightarrow$~\textit{END}
       
  3227 
       
  3228   The slave can now directly be brought into the \textit{OP} state and
       
  3229   the state change state machine is started a last time.
       
  3230   $\rightarrow$~\textit{OP}
       
  3231 
       
  3232 \item[OP] The state change state machine is executed until
       
  3233   termination. $\rightarrow$~\textit{OP}
       
  3234 
       
  3235   If the state change state machine terminates, the slave
       
  3236   configuration is finished, regardless of its success.
       
  3237   $\rightarrow$~\textit{END}
       
  3238 
       
  3239 \item[END] The termination state.
       
  3240 
       
  3241 \end{description}
       
  3242 
       
  3243 %------------------------------------------------------------------------------
       
  3244 
       
  3245 \subsection{The State Change State Machine}
       
  3246 \label{sec:fsm-change}
       
  3247 \index{FSM!State Change}
       
  3248 
       
  3249 The state change state machine, which can be seen in
       
  3250 figure~\ref{fig:fsm-change}, leads through the process of changing a
       
  3251 slave's state. This implements the states and transitions described in
       
  3252 \cite[section~6.4.1]{alspec}.
       
  3253 
       
  3254 \begin{figure}[htbp]
       
  3255   \centering
       
  3256   \includegraphics[width=.9\textwidth]{images/fsm-change}
       
  3257   \caption{Transition diagram of the state change state machine}
       
  3258   \label{fig:fsm-change}
       
  3259 \end{figure}
       
  3260 
       
  3261 \begin{description}
       
  3262 \item[START] The beginning state, where a datagram with the state
       
  3263   change command is written to the slave's ``AL Control Request''
       
  3264   attribute. Nothing can fail. $\rightarrow$~\textit{CHECK}
       
  3265 
       
  3266 \item[CHECK] After the state change datagram has been sent, the ``AL
       
  3267   Control Response'' attribute is queried with a second datagram.
       
  3268   $\rightarrow$~\textit{STATUS}
       
  3269 
       
  3270 \item[STATUS] The read memory contents are evaluated: While the
       
  3271   parameter \textit{State} still contains the old slave state, the
       
  3272   slave is busy with reacting on the state change command. In this
       
  3273   case, the attribute has to be queried again.
       
  3274   $\rightarrow$~\textit{STATUS}
       
  3275 
       
  3276   In case of success, the \textit{State} parameter contains the new
       
  3277   state and the \textit{Change} bit is cleared. The slave is in the
       
  3278   requested state.  $\rightarrow$~\textit{END}
       
  3279 
       
  3280   If the slave can not process the state change, the \textit{Change}
       
  3281   bit is set: Now the master tries to get the reason for this by
       
  3282   querying the \textit{AL Status Code} parameter.
       
  3283   $\rightarrow$~\textit{CODE}
       
  3284 
       
  3285 \item[END] If the state machine ends in this state, the slaves's state
       
  3286   change has been successful.
       
  3287 
       
  3288 \item[CODE] The status code query has been sent. Reading the
       
  3289   \textit{AL Status Code} might fail, because not all slaves support
       
  3290   this parameter. Anyway, the master has to acknowledge the state
       
  3291   change error by writing the current slave state to the ``AL Control
       
  3292   Request'' attribute with the \textit{Acknowledge} bit set.
       
  3293   $\rightarrow$~\textit{ACK}
       
  3294 
       
  3295 \item[ACK] After that, the ``AL Control Response'' attribute is
       
  3296   queried for the state of the acknowledgement.
       
  3297   $\rightarrow$~\textit{CHECK ACK}
       
  3298 
       
  3299 \item[CHECK ACK] If the acknowledgement has been accepted by the
       
  3300   slave, the old state is kept. Still, the state change was
       
  3301   unsuccessful. $\rightarrow$~\textit{ERROR}
       
  3302 
       
  3303   If the acknowledgement is ignored by the slave, a timeout happens.
       
  3304   In any case, the overall state change was unsuccessful.
       
  3305   $\rightarrow$~\textit{ERROR}
       
  3306 
       
  3307   If there is still now response from the slave, but the timer did not
       
  3308   run out yet, the slave's ``AL Control Response'' attribute is
       
  3309   queried again.  $\rightarrow$~\textit{CHECK ACK}
       
  3310 
       
  3311 \item[ERROR] If the state machine ends in this state, the slave's
       
  3312   state change was unsuccessful.
       
  3313 
       
  3314 \end{description}
       
  3315 
       
  3316 %------------------------------------------------------------------------------
       
  3317 
       
  3318 \subsection{The SII State Machine}
       
  3319 \label{sec:fsm-sii}
       
  3320 \index{FSM!SII}
       
  3321 
       
  3322 The SII\index{SII} state machine (shown in figure~\ref{fig:fsm-sii})
       
  3323 implements the process of reading or writing E$^2$PROM data via the
       
  3324 Slave Information Interface described in \cite[section~5.4]{alspec}.
       
  3325 
       
  3326 \begin{figure}[htbp]
       
  3327   \centering
       
  3328   \includegraphics[width=.9\textwidth]{images/fsm-sii}
       
  3329   \caption{Transition diagram of the SII state machine}
       
  3330   \label{fig:fsm-sii}
       
  3331 \end{figure}
       
  3332 
       
  3333 \begin{description}
       
  3334 \item[READ\_START] The beginning state for reading access, where the
       
  3335   read request and the requested address are written to the SII
       
  3336   attribute. Nothing can fail up to now.
       
  3337   $\rightarrow$~\textit{READ\_CHECK}
       
  3338 
       
  3339 \item[READ\_CHECK] When the SII read request has been sent
       
  3340   successfully, a timer is started. A check/fetch datagram is issued,
       
  3341   that reads out the SII attribute for state and data.
       
  3342   $\rightarrow$~\textit{READ\_FETCH}
       
  3343 
       
  3344 \item[READ\_FETCH] Upon reception of the check/fetch datagram, the
       
  3345   \textit{Read Operation} and \textit{Busy} parameters are checked:
       
  3346   \begin{itemize}
       
  3347   \item If the slave is still busy with fetching E$^2$PROM data into
       
  3348     the interface, the timer is checked. If it timed out, the reading
       
  3349     is aborted ($\rightarrow$~\textit{ERROR}), if not, the check/fetch
       
  3350     datagram is issued again. $\rightarrow$~\textit{READ\_FETCH}
       
  3351 
       
  3352   \item If the slave is ready with reading data, these are copied from
       
  3353     the datagram and the read cycle is completed.
       
  3354     $\rightarrow$~\textit{END}
       
  3355   \end{itemize}
       
  3356 \end{description}
       
  3357 
       
  3358 The write access states behave nearly the same:
       
  3359 
       
  3360 \begin{description}
       
  3361 \item[WRITE\_START] The beginning state for writing access,
       
  3362   respectively. A write request, the target address and the data word
       
  3363   are written to the SII attribute. Nothing can fail.
       
  3364   $\rightarrow$~\textit{WRITE\_CHECK}
       
  3365 
       
  3366 \item[WRITE\_CHECK] When the SII write request has been sent
       
  3367   successfully, the timer is started. A check datagram is issued, that
       
  3368   reads out the SII attribute for the state of the write operation.
       
  3369   $\rightarrow$~\textit{WRITE\_CHECK2}
       
  3370 
       
  3371 \item[WRITE\_CHECK2] Upon reception of the check datagram, the
       
  3372   \textit{Write Operation} and \textit{Busy} parameters are checked:
       
  3373   \begin{itemize}
       
  3374   \item If the slave is still busy with writing E$^2$PROM data, the
       
  3375     timer is checked. If it timed out, the operation is aborted
       
  3376     ($\rightarrow$~\textit{ERROR}), if not, the check datagram is
       
  3377     issued again. $\rightarrow$~\textit{WRITE\_CHECK2}
       
  3378   \item If the slave is ready with writing data, the write cycle is
       
  3379     completed. $\rightarrow$~\textit{END}
       
  3380   \end{itemize}
       
  3381 \end{description}
       
  3382 
       
  3383 %------------------------------------------------------------------------------
       
  3384 
       
  3385 \section{Mailbox Protocol Implementations}
       
  3386 \index{Mailbox}
       
  3387 
       
  3388 The EtherCAT master implements the EoE and the CoE mailbox
       
  3389 protocols. See the below section for details.
       
  3390 
       
  3391 %------------------------------------------------------------------------------
       
  3392 
       
  3393 \subsection{Ethernet-over-EtherCAT (EoE)}
       
  3394 \label{sec:eoeimp}
       
  3395 \index{EoE}
       
  3396 
       
  3397 The EtherCAT master implements the Ethernet-over-EtherCAT mailbox
       
  3398 protocol to enable the tunneling of Ethernet frames to special slaves,
       
  3399 that can either have physical Ethernet ports to forward the frames to,
       
  3400 or have an own IP stack to receive the frames.
       
  3401 
       
  3402 \paragraph{Virtual Network Interfaces}
       
  3403 
       
  3404 The master creates a virtual EoE network interface for every
       
  3405 EoE-capable slave. These interfaces are called \textit{eoeX}, where X
       
  3406 is a number provided by the kernel on interface registration. Frames
       
  3407 sent to these interfaces are forwarded to the associated slaves by the
       
  3408 master. Frames, that are received by the slaves, are fetched by the
       
  3409 master and forwarded to the virtual interfaces.
       
  3410 
       
  3411 This bears the following advantages:
       
  3412 
       
  3413 \begin{itemize}
       
  3414 \item Flexibility: The user can decide, how the EoE-capable slaves are
       
  3415   interconnected with the rest of the world.
       
  3416 \item Standard tools can be used to monitor the EoE activity and to
       
  3417   configure the EoE interfaces.
       
  3418 \item The Linux kernel's layer-2-bridging implementation (according to
       
  3419   the IEEE 802.1D MAC Bridging standard) can be used natively to
       
  3420   bridge Ethernet traffic between EoE-capable slaves.
       
  3421 \item The Linux kernel's network stack can be used to route packets
       
  3422   between EoE-capable slaves and to track security issues, just like
       
  3423   having physical network interfaces.
       
  3424 \end{itemize}
       
  3425 
       
  3426 \paragraph{EoE Handlers}
       
  3427 
       
  3428 The virtual EoE interfaces and the related functionality is encapsuled
       
  3429 in the \textit{ec\_eoe\_t} class (see section~\ref{sec:class-eoe}).
       
  3430 So the master does not create the network interfaces directly: This is
       
  3431 done inside the constructor of the \textit{ec\_eoe\_t} class. An
       
  3432 object of this class is called ``EoE handler'' below. An EoE handler
       
  3433 additionaly contains a frame queue. Each time, the kernel passes a new
       
  3434 socket buffer for sending via the interface's
       
  3435 \textit{hard\_start\_xmit()} callback, the socket buffer is queued for
       
  3436 transmittion by the EoE state machine (see below). If the queue gets
       
  3437 filled up, the passing of new socket buffers is suspended with a call
       
  3438 to \textit{netif\_stop\_queue()}.
       
  3439 
       
  3440 \paragraph{Static Handler Creation}
       
  3441 
       
  3442 The master creates a pool of EoE handlers at startup, that are coupled
       
  3443 to EoE-capable slaves on demand. The lifetime of the corresponding
       
  3444 network interfaces is equal to the lifetime of the master module.
       
  3445 This approach is opposed to creating the virtual network interfaces on
       
  3446 demand (i.~e. on running across a new EoE-capable slave). The latter
       
  3447 approach was considered as difficult, because of serveral reasons:
       
  3448 
       
  3449 \begin{itemize}
       
  3450 \item The \textit{alloc\_netdev()} function can sleep and must be
       
  3451   called from a non-interrupt context. This reduces the flexibility of
       
  3452   choosing an appropriate method for cyclic EoE processing.
       
  3453 \item Unregistering network interfaces requires them to be ``down'',
       
  3454   which can not be guaranteed upon sudden disappearing of an
       
  3455   EoE-capable slave.
       
  3456 \item The connection to the EoE-capable slaves must be as continuous
       
  3457   as possible. Especially the transition from idle to operation mode
       
  3458   (and vice versa) causes the rebuilding of the internal data
       
  3459   structures. These transitions must be as transparent as possible for
       
  3460   the instances using the network interfaces.
       
  3461 \end{itemize}
       
  3462 
       
  3463 \paragraph{Number of Handlers}
       
  3464 
       
  3465 The master module has a parameter \textit{ec\_eoeif\_count} to specify
       
  3466 the number of EoE interfaces (and handlers) per master to create. This
       
  3467 parameter can either be specified when manually loading the master
       
  3468 module, or (when using the init script) by setting the
       
  3469 \textit{\$EOE\_INTERFACES} variable in the sysconfig file (see
       
  3470 section~\ref{sec:sysconfig}). Upon loading of the master module, the
       
  3471 virtual interfaces become available:
       
  3472 
       
  3473 \begin{lstlisting}
       
  3474   host# `\textbf{ifconfig -a}`
       
  3475   eoe0      Link encap:Ethernet  HWaddr 00:11:22:33:44:06
       
  3476             BROADCAST MULTICAST  MTU:1500  Metric:1
       
  3477             RX packets:0 errors:0 dropped:0 overruns:0 frame:0
       
  3478             TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
       
  3479             collisions:0 txqueuelen:1000
       
  3480             RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)
       
  3481 
       
  3482   eoe1      Link encap:Ethernet  HWaddr 00:11:22:33:44:07
       
  3483             BROADCAST MULTICAST  MTU:1500  Metric:1
       
  3484             RX packets:0 errors:0 dropped:0 overruns:0 frame:0
       
  3485             TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
       
  3486             collisions:0 txqueuelen:1000
       
  3487             RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)
       
  3488   ...
       
  3489 \end{lstlisting}
       
  3490 
       
  3491 \paragraph{Coupling of EoE Slaves}
       
  3492 
       
  3493 During execution of the slave scan state machine (see
       
  3494 section~\ref{sec:fsm-scan}), the master determines the supported
       
  3495 mailbox protocols. This is done by examining the ``Supported Mailbox
       
  3496 Protocols'' mask field at word address 0x001C of the SII\index{SII}.
       
  3497 If bit 1 is set, the slave supports the EoE protocol. After slave
       
  3498 scanning, the master runs through all slaves again and couples each
       
  3499 EoE-capable slave to a free EoE handler. It can happen, that there are
       
  3500 not enough EoE handlers to cover all EoE-capable slaves. In this case,
       
  3501 the number of EoE handlers must be increased accordingly.
       
  3502 
       
  3503 \paragraph{EoE State Machine}
       
  3504 \index{FSM!EoE}
       
  3505 
       
  3506 Every EoE handler owns an EoE state machine, that is used to send
       
  3507 frames to the coupled slave and receive frames from the it via the EoE
       
  3508 communication primitives. This state machine is showed in
       
  3509 figure~\ref{fig:fsm-eoe}.
       
  3510 
       
  3511 \begin{figure}[htbp]
       
  3512   \centering
       
  3513   \includegraphics[width=.7\textwidth]{images/fsm-eoe}
       
  3514   \caption{Transition diagram of the EoE state machine}
       
  3515   \label{fig:fsm-eoe}
       
  3516 \end{figure}
       
  3517 
       
  3518 \begin{description}
       
  3519 \item[RX\_START] The beginning state of the EoE state machine. A
       
  3520   mailbox check datagram is sent, to query the slave's mailbox for new
       
  3521   frames. $\rightarrow$~\textit{RX\_CHECK}
       
  3522 
       
  3523 \item[RX\_CHECK] The mailbox check datagram is received. If the
       
  3524   slave's mailbox did not contain data, a transmit cycle is started.
       
  3525   $\rightarrow$~\textit{TX\_START}
       
  3526 
       
  3527   If there are new data in the mailbox, a datagram is sent to fetch
       
  3528   the new data. $\rightarrow$~\textit{RX\_FETCH}
       
  3529 
       
  3530 \item[RX\_FETCH] The fetch datagram is received. If the mailbox data
       
  3531   do not contain a ``EoE Fragment request'' command, the data are
       
  3532   dropped and a transmit sequence is started.
       
  3533   $\rightarrow$~\textit{TX\_START}
       
  3534 
       
  3535   If the received Ethernet frame fragment is the first fragment, a new
       
  3536   socket buffer is allocated. In either case, the data are copied into
       
  3537   the correct position of the socket buffer.
       
  3538 
       
  3539   If the fragment is the last fragment, the socket buffer is forwarded
       
  3540   to the network stack and a transmit sequence is started.
       
  3541   $\rightarrow$~\textit{TX\_START}
       
  3542 
       
  3543   Otherwise, a new receive sequence is started to fetch the next
       
  3544   fragment. $\rightarrow$~\textit{RX\_\-START}
       
  3545 
       
  3546 \item[TX\_START] The beginning state of a transmit sequence. It is
       
  3547   checked, if the transmittion queue contains a frame to send. If not,
       
  3548   a receive sequence is started. $\rightarrow$~\textit{RX\_START}
       
  3549 
       
  3550   If there is a frame to send, it is dequeued. If the queue was
       
  3551   inactive before (because it was full), the queue is woken up with a
       
  3552   call to \textit{netif\_wake\_queue()}. The first fragment of the
       
  3553   frame is sent. $\rightarrow$~\textit{TX\_SENT}
       
  3554 
       
  3555 \item[TX\_SENT] It is checked, if the first fragment was sent
       
  3556   successfully. If the current frame consists of further fragments,
       
  3557   the next one is sent. $\rightarrow$~\textit{TX\_SENT}
       
  3558 
       
  3559   If the last fragment was sent, a new receive sequence is started.
       
  3560   $\rightarrow$~\textit{RX\_START}
       
  3561 \end{description}
       
  3562 
       
  3563 \paragraph{EoE Processing}
       
  3564 
       
  3565 To execute the EoE state machine of every active EoE handler, there
       
  3566 must be a cyclic process. The easiest thing would be to execute the
       
  3567 EoE state machines synchronously to the operation state machine (see
       
  3568 section~\ref{sec:fsm-op}) with every realtime cycle. This approach has
       
  3569 the following disadvantages:
       
  3570 
       
  3571 \begin{itemize}
       
  3572 \item Only one EoE fragment can be sent or received every few cycles.
       
  3573   This causes the data rate to be very low, because the EoE state
       
  3574   machines are not executed in the time between the realtime
       
  3575   cycles. Moreover, the data rate would be dependent on the frequency
       
  3576   of the realtime process.
       
  3577 \item The receiving and forwarding of frames to the kernel requires
       
  3578   the dynamic allocation of frames. Some realtime extensions do not
       
  3579   support calling memory allocation functions in realtime context, so
       
  3580   the EoE state machine may not be executed with each realtime cycle.
       
  3581 \end{itemize}
       
  3582 
       
  3583 To overcome these problems, an own cyclic process is needed to
       
  3584 asynchronously execute the EoE state machines. For that, the master
       
  3585 owns a kernel timer, that is executed each timer interrupt. This
       
  3586 guarantees a constant bandwidth, but poses the new problem of
       
  3587 concurrent access to the master. The locking mechanisms needed for
       
  3588 this are introduced in section~\ref{sec:concurr}.
       
  3589 Section~\ref{sec:concurrency} gives practical implementation examples.
       
  3590 
       
  3591 \paragraph{Idle Mode}
       
  3592 
       
  3593 EoE data must also be exchanged idle mode, to guarantee the continuous
       
  3594 availability of the connection to the EoE-capable slaves. Although
       
  3595 there is no realtime module connected in this case, the master is
       
  3596 still accessed by the idle state machine (see
       
  3597 section~\ref{sec:fsm-idle}), that is executed by the master's
       
  3598 workqueue. With the EoE timer running in addition, there is still
       
  3599 concurrency, that has to be protected by a lock. Therefore the master
       
  3600 owns an internal spinlock that is used protect master access during
       
  3601 idle mode.
       
  3602 
       
  3603 \paragraph{Automatic Configuration}
       
  3604 
       
  3605 By default, slaves are left in \textit{INIT} state during idle mode.
       
  3606 If an EoE interface is set to running state (i.~e. with the
       
  3607 \textit{ifconfig up} command), the requested slave state of the
       
  3608 related slave is automatically set to \textit{OP}, whereupon the idle
       
  3609 state machine will attempt to configure the slave and put it into
       
  3610 operation.
       
  3611 
       
  3612 %------------------------------------------------------------------------------
       
  3613 
       
  3614 \subsection{CANopen-over-EtherCAT (CoE)}
       
  3615 \label{sec:coeimp}
       
  3616 \index{CoE}
       
  3617 
       
  3618 The CANopen-over-EtherCAT protocol \cite[section~5.6]{alspec} is used
       
  3619 to configure slaves on application level. Each CoE-capable slave
       
  3620 provides a list of SDOs for this reason.
       
  3621 
       
  3622 \paragraph{SDO Configuration}
       
  3623 
       
  3624 The SDO configurations have to be provided by the realtime module.
       
  3625 This is done via the \textit{ecrt\_slave\_conf\_sdo*()} methods (see
       
  3626 section~\ref{sec:ecrt-slave}), that are part of the realtime
       
  3627 interface. The slave stores the SDO configurations in a linked list,
       
  3628 but does not apply them at once.
       
  3629 
       
  3630 \paragraph{SDO Download State Machine}
       
  3631 
       
  3632 The best time to apply SDO configurations is during the slave's
       
  3633 \textit{PREOP} state, because mailbox communication is already
       
  3634 possible and slave's application will start with updating input data
       
  3635 in the succeeding \textit{SAVEOP} state. Therefore the SDO
       
  3636 configuration has to be part of the slave configuration state machine
       
  3637 (see section~\ref{sec:fsm-conf}): It is implemented via an SDO
       
  3638 download state machine, that is executed just before entering the
       
  3639 slave's \textit{SAVEOP} state. In this way, it is guaranteed that the
       
  3640 SDO configurations are applied each time, the slave is reconfigured.
       
  3641 
       
  3642 The transition diagram of the SDO Download state machine can be seen
       
  3643 in figure~\ref{fig:fsm-coedown}.
       
  3644 
       
  3645 \begin{figure}[htbp]
       
  3646   \centering
       
  3647   \includegraphics[width=.9\textwidth]{images/fsm-coedown}
       
  3648   \caption{Transition diagram of the CoE download state machine}
       
  3649   \label{fig:fsm-coedown}
       
  3650 \end{figure}
       
  3651 
       
  3652 \begin{description}
       
  3653 \item[START] The beginning state of the CoE download state
       
  3654   machine. The ``SDO Download Normal Request'' mailbox command is
       
  3655   sent. $\rightarrow$~\textit{REQUEST}
       
  3656 
       
  3657 \item[REQUEST] It is checked, if the CoE download request has been
       
  3658   received by the slave. After that, a mailbox check command is issued
       
  3659   and a timer is started. $\rightarrow$~\textit{CHECK}
       
  3660 
       
  3661 \item[CHECK] If no mailbox data is available, the timer is checked.
       
  3662   \begin{itemize}
       
  3663   \item If it timed out, the SDO download is aborted.
       
  3664     $\rightarrow$~\textit{ERROR}
       
  3665   \item Otherwise, the mailbox is queried again.
       
  3666     $\rightarrow$~\textit{CHECK}
       
  3667   \end{itemize}
       
  3668 
       
  3669   If the mailbox contains new data, the response is fetched.
       
  3670   $\rightarrow$~\textit{RESPONSE}
       
  3671 
       
  3672 \item[RESPONSE] If the mailbox response could not be fetched, the data
       
  3673   is invalid, the wrong protocol was received, or a ``Abort SDO
       
  3674   Transfer Request'' was received, the SDO download is aborted.
       
  3675   $\rightarrow$~\textit{ERROR}
       
  3676 
       
  3677   If a ``SDO Download Normal Response'' acknowledgement was received,
       
  3678   the SDO download was successful. $\rightarrow$~\textit{END}
       
  3679 
       
  3680 \item[END] The SDO download was successful.
       
  3681 
       
  3682 \item[ERROR] The SDO download was aborted due to an error.
       
  3683 
       
  3684 \end{description}
       
  3685 
       
  3686 %------------------------------------------------------------------------------
       
  3687 
       
  3688 \section{User Space}
       
  3689 \label{sec:user}
       
  3690 \index{User space}
       
  3691 
       
  3692 For the master runs as a kernel module, accessing it is natively
       
  3693 limited to analyzing syslog messages and controlling using modutils.
       
  3694 
       
  3695 It is necessary to implement further interfaces, that make it easier
       
  3696 to access the master from user space and allow a finer influence. It
       
  3697 should be possible to view and to change special parameters at runtime.
       
  3698 
       
  3699 Bus visualization is a second point: For development and debugging
       
  3700 purposes it would be nice, if one could show the connected slaves with
       
  3701 a single command.
       
  3702 
       
  3703 Another aspect is automatic startup and configuration. If the master
       
  3704 is to be integrated into a running system, it must be able to
       
  3705 automatically start with a persistent configuration.
       
  3706 
       
  3707 A last thing is monitoring EtherCAT communication. For debugging
       
  3708 purposes, there had to be a way to analyze EtherCAT datagrams. The
       
  3709 best way would be with a popular network analyzer, like Wireshark
       
  3710 \cite{wireshark} (the former Ethereal) or others.
       
  3711 
       
  3712 This section covers all those points and introduces the interfaces and
       
  3713 tools to make all that possible.
       
  3714 
       
  3715 %------------------------------------------------------------------------------
       
  3716 
       
  3717 \subsection{The Sysfs Interface}
       
  3718 \label{sec:sysfs}
       
  3719 
       
  3720 The system filesystem (Sysfs\index{Sysfs}) was introduced with Linux
       
  3721 kernel 2.5 and is a well-defined interface for drivers to export
       
  3722 information to user space. It serves also as an relief for the process
       
  3723 filesystem (Procfs), where over the years much non-process information
       
  3724 was concentrated.
       
  3725 
       
  3726 Sysfs exports information about devices, classes and busses via a
       
  3727 virtual filesystem, usually mounted to \textit{/sys}. The EtherCAT
       
  3728 master slightly differs from this concept, because the only physical
       
  3729 device is the network adapter it uses for bus communication, which is
       
  3730 already represented in Sysfs. For the EtherCAT bus is no system bus
       
  3731 like PCI (with device and driver structures), it would not make any
       
  3732 sense to represent it as bus structure in Sysfs.
       
  3733 
       
  3734 Therefore, the EtherCAT master is represented as a new directory
       
  3735 directly unter the Sysfs root. Every master gets its own Sysfs entry
       
  3736 named \textit{ethercatX}, where X is the index of the master. Two
       
  3737 masters would result in the directories \textit{/sys/ethercat0} and
       
  3738 \textit{/sys/ethercat1}, respectively.
       
  3739 
       
  3740 The Sysfs base class in the kernel code is the \textit{kobject}
       
  3741 structure. Each object structure, that is to be represented in Sysfs,
       
  3742 has to contain such a structure, because due to the concurrent access
       
  3743 (through ``normal'' kernel code and Sysfs code) the object deletion
       
  3744 gets a little more complicated: The object may not be freed until no
       
  3745 instance uses it any more. Therefore, each kobject maintains a
       
  3746 reference counter. If the reference counter gets zero, the object is
       
  3747 finally freed. A kobject can be registered to appear as a directory in
       
  3748 Sysfs with a call to \textit{kobject\_add()}. Each kobject type can
       
  3749 define attributes, that appear as files in the kobject's
       
  3750 directory. Callback functions have to be provided for reading (and
       
  3751 perhaps writing) access.
       
  3752 
       
  3753 \subsubsection{Master Attributes}
       
  3754 \label{sec:sysfs-master}
       
  3755 
       
  3756 Below is a typical listing of the masters Sysfs directory (that is a
       
  3757 file system representation of the master's kobject):
       
  3758 
       
  3759 \begin{lstlisting}
       
  3760   host> `\textbf{ls /sys/ethercat0}`
       
  3761   debug_level          slave000  slave003  slave006
       
  3762   eeprom_write_enable  slave001  slave004  slave007
       
  3763   info                 slave002  slave005  slave008
       
  3764 \end{lstlisting}
       
  3765 
       
  3766 The following attributes exist in the master directory:
       
  3767 
       
  3768 \begin{description}
       
  3769 \item[debug\_level] (read/write) This attribute contains the master's
       
  3770   debug level, which controls, how much information is printed into
       
  3771   syslog. The values 0 (no additional debug messages), 1 (a few
       
  3772   additional debug messages) and 2 (all additional debug messages) are
       
  3773   defined. Writing is done with command like
       
  3774 
       
  3775   \begin{lstlisting}[gobble=4]
       
  3776     host# `\textbf{echo 1 > /sys/ethercat0/debug\_level}`
       
  3777   \end{lstlisting}
       
  3778 
       
  3779   and is receipted with a syslog message by the master:
       
  3780 
       
  3781   \begin{lstlisting}[gobble=4]
       
  3782     EtherCAT: Master debug level set to 1.
       
  3783   \end{lstlisting}
       
  3784 
       
  3785 \item[enable\_eeprom\_writing] (read/write) See
       
  3786   section~\ref{sec:eepromaccess} for how to use this attribute.
       
  3787 
       
  3788 \item[info] (read only) This attribute contains information about the
       
  3789   master. Example contents are below:
       
  3790 
       
  3791   \begin{lstlisting}[gobble=4]
       
  3792     host> `\textbf{cat /sys/ethercat0/info}`
       
  3793 
       
  3794     Mode: IDLE
       
  3795     Slaves: 9
       
  3796 
       
  3797     Timing (min/avg/max) [us]:
       
  3798       Idle cycle: 4 / 4.38 / 34
       
  3799       EoE cycle: 9 / 11.91 / 23
       
  3800 
       
  3801     EoE statistics (RX/TX) [bps]:
       
  3802       eoe0: 0 / 3184
       
  3803   \end{lstlisting}
       
  3804 
       
  3805   The mode can be \textit{ORPHANED}, \textit{IDLE} or
       
  3806   \textit{OPERATION}. The other parameters are self-explanatory.
       
  3807 
       
  3808 \end{description}
       
  3809 
       
  3810 \subsubsection{Domain Attributes}
       
  3811 \label{sec:sysfs-domain}
       
  3812 
       
  3813 In operation mode, each created domain is represented as a directory
       
  3814 \textit{domainX}, where X is the domain index. Below is a listing of
       
  3815 the domain directory contents:
       
  3816 
       
  3817 \begin{lstlisting}
       
  3818   host> `\textbf{ls /sys/ethercat0/domain0}`
       
  3819   image_size
       
  3820 \end{lstlisting}
       
  3821 
       
  3822 The domain directories currently only export the domain's image size.
       
  3823 It is planned to export the whole process data mapping for debugging
       
  3824 purposes.
       
  3825 
       
  3826 \subsubsection{Slave Attributes}
       
  3827 \label{sec:sysfs-slave}
       
  3828 
       
  3829 Each slave on the bus is represented in its own directory
       
  3830 \textit{slaveXXX}, where XXX is the slave's 3-digit ring position in
       
  3831 the EtherCAT bus. Below is a listing of a slave directory:
       
  3832 
       
  3833 \begin{lstlisting}
       
  3834   host> `\textbf{ls /sys/ethercat0/slave003}`
       
  3835   eeprom  info  state
       
  3836 \end{lstlisting}
       
  3837 
       
  3838 \begin{description}
       
  3839 \item[eeprom] (read/write) See section~\ref{sec:eepromaccess} for how
       
  3840   to use this attribute.
       
  3841 
       
  3842 \item[info] (read only) This attribute contains a bunch of information
       
  3843   about the slave. Below is an example output:
       
  3844 
       
  3845   \begin{lstlisting}[gobble=4]
       
  3846     host> `\textbf{cat /sys/ethercat0/slave003/info}`
       
  3847 
       
  3848     Name: EL4132 2K. Ana. Ausgang +/-10V
       
  3849     Vendor ID: 0x00000002
       
  3850     Product code: 0x10243052
       
  3851 
       
  3852     State: INIT
       
  3853     Ring position: 3
       
  3854     Advanced position: 1:3
       
  3855 
       
  3856     Data link status:
       
  3857       Port 0 (EBUS) Link down, Loop open, Signal detected
       
  3858       Port 1 (EBUS) Link down, Loop open, Signal detected
       
  3859       Port 2 (EBUS) Link down, Loop closed, No signal
       
  3860       Port 3 (EBUS) Link down, Loop closed, No signal
       
  3861 
       
  3862     Mailboxes:
       
  3863       RX mailbox: 0x1800/246, TX mailbox: 0x18F6/246
       
  3864       Supported protocols: CoE, FoE
       
  3865 
       
  3866     SII data:
       
  3867       Group: AnaOut
       
  3868       Image: TERM_AO
       
  3869       Order#: EL4132
       
  3870 
       
  3871     Sync-Managers:
       
  3872       0: 0x1800, length 246, control 0x26, enable
       
  3873       1: 0x18F6, length 246, control 0x22, enable
       
  3874       2: 0x1000, length 0, control 0x24, enable
       
  3875       3: 0x1100, length 0, control 0x20, enable
       
  3876 
       
  3877     PDOs:
       
  3878       RXPDO "Channel 1" (0x1600), Sync-Manager 2
       
  3879         "Output" 0x6411:1, 16 bit
       
  3880       RXPDO "Channel 2" (0x1601), Sync-Manager 2
       
  3881         "Output" 0x6411:2, 16 bit
       
  3882   \end{lstlisting}
       
  3883 
       
  3884   This is nearly all of the SII category information needed to
       
  3885   configure the slave, supplemented with state and addressing
       
  3886   information.
       
  3887 
       
  3888 \item[state] (read/write) This attribute contains the slave's state.
       
  3889   It can be read or written:
       
  3890 
       
  3891   \begin{lstlisting}[gobble=4]
       
  3892     host# `\textbf{cat /sys/ethercat0/slave003/state}`
       
  3893     OP
       
  3894     host# `\textbf{echo SAVEOP > /sys/ethercat0/slave003/state}`
       
  3895   \end{lstlisting}
       
  3896 
       
  3897   This command should also be receipted with a syslog message:
       
  3898 
       
  3899   \begin{lstlisting}[gobble=4]
       
  3900     EtherCAT: Accepted new state SAVEOP for slave 3.
       
  3901     EtherCAT: Changing state of slave 3 from OP to SAVEOP.
       
  3902     EtherCAT: Slave states: INIT, SAVEOP, OP.
       
  3903   \end{lstlisting}
       
  3904 
       
  3905   After the new requested state was accepted from user space, the
       
  3906   operation state machine (see section~\ref{sec:fsm-op}) or the idle
       
  3907   state machine (section~\ref{sec:fsm-idle}) notices, that the
       
  3908   requested slave state differs from the current one, and therefore
       
  3909   executes the slave configuration state machine, until the slave has
       
  3910   reached the requested state.
       
  3911 \end{description}
       
  3912 
       
  3913 %------------------------------------------------------------------------------
       
  3914 
       
  3915 \subsubsection{E$^2$PROM Access}
       
  3916 \label{sec:eepromaccess}
       
  3917 \index{E$^2$PROM!Access}
       
  3918 
       
  3919 It is possible to directly read or write the complete E$^2$PROM
       
  3920 contents of the slaves. This was introduced for the reasons below:
       
  3921 
       
  3922 \begin{itemize}
       
  3923 \item The format of the E$^2$PROM data is still in development and
       
  3924   categories can be added in the future. With read and write access,
       
  3925   the complete memory contents can be easily backed up and restored.
       
  3926 \item Some E$^2$PROM data fields have to be altered (like the alias
       
  3927   address). A quick writing must be possible for that.
       
  3928 \item Through read access, analyzing category data is possible from
       
  3929   user space.
       
  3930 \end{itemize}
       
  3931 
       
  3932 Reading out E$^2$PROM data is as easy as reading other
       
  3933 attributes. Though the data are in binary format, analyzation is
       
  3934 easier with a tool like \textit{hexdump}:
       
  3935 
       
  3936 \begin{lstlisting}
       
  3937   host> `\textbf{cat /sys/ethercat0/slave003/eeprom | hexdump}`
       
  3938   0000000 0103 0000 0000 0000 0000 0000 0000 008c
       
  3939   0000010 0002 0000 3052 07f0 0000 0000 0000 0000
       
  3940   0000020 0000 0000 0000 0000 0000 0000 0000 0000
       
  3941   ...
       
  3942 \end{lstlisting}
       
  3943 
       
  3944 Backing up E$^2$PROM contents gets as easy as copying a file:
       
  3945 
       
  3946 \begin{lstlisting}
       
  3947   host> `\textbf{cp /sys/ethercat0/slave003/eeprom slave003.eep}`
       
  3948 \end{lstlisting}
       
  3949 
       
  3950 Writing access is only possible as \textit{root}. Moreover writing has
       
  3951 to be explicitly enabled and is only allowed in idle mode. This is a
       
  3952 safety measure, because without the correct memory contents, a slave
       
  3953 is unusable. Writing E$^2$PROM contents in operation mode is not
       
  3954 provided yet.
       
  3955 
       
  3956 E$^2$PROM writing is enabled with the command below:
       
  3957 
       
  3958 \begin{lstlisting}
       
  3959   host# `\textbf{echo 1 > /sys/ethercat0/eeprom\_write\_enable}`
       
  3960 \end{lstlisting}
       
  3961 
       
  3962 The success can be seen in the syslog messages again:
       
  3963 
       
  3964 \begin{lstlisting}
       
  3965   EtherCAT: Slave EEPROM writing enabled.
       
  3966 \end{lstlisting}
       
  3967 
       
  3968 Now, it is possible to write E$^2$PROM contents to a slave. The master
       
  3969 will accept data through the \textit{eeprom} file and will perform a
       
  3970 short validation of the contents, before starting the write operation.
       
  3971 This validation checks the complete size and the category headers.
       
  3972 
       
  3973 \begin{lstlisting}
       
  3974   host# `\textbf{cat slave003.eep > /sys/ethercat0/slave003/eeprom}`
       
  3975 \end{lstlisting}
       
  3976 
       
  3977 The write operation can take a few seconds.
       
  3978 
       
  3979 \begin{lstlisting}
       
  3980   EtherCAT: EEPROM writing scheduled for slave 3, 88 words.
       
  3981   EtherCAT: Writing EEPROM of slave 3...
       
  3982   EtherCAT: Finished writing EEPROM of slave 3.
       
  3983 \end{lstlisting}
       
  3984 
       
  3985 %------------------------------------------------------------------------------
       
  3986 
       
  3987 \subsection{User Space Tools}
       
  3988 \index{User space!Tools}
       
  3989 
       
  3990 There is a user space tool called \textit{lsec}\index{lsec} (``List
       
  3991 EtherCAT'') to visualize the EtherCAT bus. Running it usually results
       
  3992 in an output like this:
       
  3993 
       
  3994 \begin{lstlisting}
       
  3995   host> `\textbf{lsec}`
       
  3996   EtherCAT bus listing for master 0:
       
  3997      0  1:0  OP      EK1100 Ethernet Kopplerklemme (2A E-Bus)
       
  3998      1  1:1  INIT    EL4132 2K. Ana. Ausgang +/-10V
       
  3999      2  1:2  INIT    EL4132 2K. Ana. Ausgang +/-10V
       
  4000      3  1:3  SAVEOP  EL4132 2K. Ana. Ausgang +/-10V
       
  4001      4  1:4  INIT    EL5101 Incremental Encoder Interface
       
  4002      5  1:5  INIT    EL1014 4K. Dig. Eingang 24V, 10s
       
  4003      6  1:6  OP      EL6601 1 Port Switch (Ethernet, CoE)
       
  4004      7  1:7  INIT    EL5101 Incremental Encoder Interface
       
  4005      8  1:8  INIT    EL5001 1K. SSI Encoder
       
  4006 \end{lstlisting}
       
  4007 
       
  4008 Every slave is displayed as one text row. The first column shows its
       
  4009 ring position, the second displays the ``advanced position address''
       
  4010 (see section~\ref{sec:addr}) and the third column displays the current
       
  4011 slave state. The last column is the slave's name, as it appears in the
       
  4012 ``general'' E$^2$PROM category.
       
  4013 
       
  4014 The lsec program is a Perl script, that evaluates the Sysfs
       
  4015 \textit{info} attributes of the slaves (see
       
  4016 section~\ref{sec:sysfs-slave}). This is done for master $0$ by
       
  4017 default, but the master index can be specified via command line:
       
  4018 
       
  4019 \begin{lstlisting}
       
  4020   host> `\textbf{lsec -h}`
       
  4021   Usage: ec_list [OPTIONS]
       
  4022           -m <IDX>    Query master <IDX>.
       
  4023           -h          Show this help.
       
  4024 \end{lstlisting}
       
  4025 
       
  4026 This script has proved as useful for troubleshooting: If it displays
       
  4027 slaves, the master is up and running, and the bus connection is
       
  4028 present, too. It is also useful when building up a bus: It can verify
       
  4029 the list of slaves and help to create a process data image (see
       
  4030 chapter~\ref{chapter:usage}).
       
  4031 
       
  4032 %------------------------------------------------------------------------------
       
  4033 
       
  4034 \subsection{System Integration}
       
  4035 \label{sec:system}
       
  4036 
       
  4037 To integrate the EtherCAT master into a running system, it has to be
       
  4038 guaranteed, that it is started on system startup. In addition, there has
       
  4039 to be a persistent configuration, that is also applied on startup.
       
  4040 
       
  4041 \subsubsection{The EtherCAT Init Script}
       
  4042 \label{sec:init}
       
  4043 \index{Init script}
       
  4044 
       
  4045 The EtherCAT master provides an ``init script'', that conforms to the
       
  4046 requirements of the ``Linux Standard Base'' (LSB\index{LSB},
       
  4047 \cite{lsb}). The script is installed to \textit{/etc/init.d/ethercat},
       
  4048 so that the master can be easily inserted as a service. The different
       
  4049 Linux distributions offer different ways to mark the service for
       
  4050 starting and stopping in certain runlevels (for example, SUSE provides
       
  4051 the \textit{insserv} command).
       
  4052 
       
  4053 To provide service dependencies (i.~e. which services have to be
       
  4054 started before) right inside the init script code, LSB defines a
       
  4055 special comment block. System tools can extract this information to
       
  4056 insert the EtherCAT init script at the correct place in the startup
       
  4057 sequence:
       
  4058 
       
  4059 \begin{lstlisting}
       
  4060   ### BEGIN INIT INFO
       
  4061   # Provides:          ethercat
       
  4062   # Required-Start:    $local_fs $syslog $network
       
  4063   # Should-Start:      $time
       
  4064   # Required-Stop:     $local_fs $syslog $network
       
  4065   # Should-Stop:       $time
       
  4066   # Default-Start:     3 5
       
  4067   # Default-Stop:      0 1 2 6
       
  4068   # Short-Description: EtherCAT master modules
       
  4069   # Description:
       
  4070   ### END INIT INFO
       
  4071 \end{lstlisting}
       
  4072 
       
  4073 The init script can also be used for manually starting and stopping
       
  4074 the EtherCAT master. It has to be executed with one of the parameters
       
  4075 \textit{start}, \textit{stop}, \textit{restart} or \textit{status}.
       
  4076 Besides, a link to the script is placed at
       
  4077 \textit{/usr/sbin/rcethercat} for easier access.
       
  4078 
       
  4079 \begin{lstlisting}
       
  4080   host# `\textbf{/etc/init.d/ethercat restart}`
       
  4081   Shutting down EtherCAT master                done
       
  4082   Starting EtherCAT master                     done
       
  4083 \end{lstlisting}
       
  4084 
       
  4085 \subsubsection{The EtherCAT Sysconfig File}
       
  4086 \label{sec:sysconfig}
       
  4087 \index{Sysconfig file}
       
  4088 
       
  4089 For persistent configuration, the init script uses a sysconfig file
       
  4090 installed to \textit{/etc/sys\-config/ethercat}, that is mandatory for
       
  4091 the init script. The sysconfig file contains all configuration
       
  4092 variables needed to operate a master:
       
  4093 
       
  4094 \begin{description}
       
  4095 \item[DEVICE\_INDEX] This variable must contain the PCI index of the
       
  4096   EtherCAT device.  Setting this is mandatory for the EtherCAT init
       
  4097   script. Default: $-1$
       
  4098 \item[EOE\_INTERFACES] The number of virtual Ethernet-over-EtherCAT
       
  4099   interfaces, every master creates on startup. See
       
  4100   section~\ref{sec:eoeimp}. Default: $0$
       
  4101 \item[EOE\_BRIDGE] If this variable is set, all EoE interfaces will be
       
  4102   added to a network bridge according to IEEE 802.1D after master
       
  4103   startup. The variable must contain the name of the bridge. To use
       
  4104   this functionality, the kernel must be configured with the
       
  4105   \textit{CONFIG\_BRIDGE} option and the \textit{bridge-utils} package
       
  4106   must be installed (i.~e. the \textit{brctl} command is needed).
       
  4107 \item[EOE\_IP\_ADDRESS] The IP address of the EoE bridge. Setting this
       
  4108   together with \textit{EOE\_IP\_NETMASK} will let the local host
       
  4109   communicate with devices on the EoE bridge.
       
  4110 \item[EOE\_IP\_NETMASK] IP netmask of the EoE bridge.
       
  4111 \item[EOE\_EXTRA\_INTERFACES] The list of extra interfaces to include
       
  4112   in the EoE brid\-ge. Set this to interconnect the EoE bridge with
       
  4113   other local interfaces. If \textit{EOE\_\-BRIDGE} is empty or
       
  4114   undefined, setting this variable has no effect. Important: The IP
       
  4115   address of the listed interfaces will be cleared. Setting
       
  4116   \textit{EOE\_\-IP\_\-ADDRESS} and \textit{EOE\_IP\_NETMASK} will
       
  4117   re-enable them for IP traffic.
       
  4118 \item[EOE\_GATEWAY] The IP address of the default gateway. If this
       
  4119   variable is set, the gateway will be renewed after bridge
       
  4120   installation. This is necessary, if the default gateway's interface
       
  4121   is one of the \textit{EOE\_EXTRA\_INTERFACES}.
       
  4122 \end{description}
       
  4123 
       
  4124 %------------------------------------------------------------------------------
       
  4125 
       
  4126 \subsection{Monitoring and Debugging}
       
  4127 \label{sec:debug}
       
  4128 \index{Monitoring}
       
  4129 
       
  4130 For debugging purposes, every EtherCAT master registeres a read-only
       
  4131 network interface \textit{ecX}, where X is a number, provided by the
       
  4132 kernel on device registration. While it is ``up'', the master forwards
       
  4133 every frame sent and received to this interface.
       
  4134 
       
  4135 This makes it possible to connect an network monitor (like Wireshark
       
  4136 or tcpdump) to the debug interface and monitor the EtherCAT frames.
       
  4137 
       
  4138 It has to be considered, that can be frame rate can be very high. The
       
  4139 idle state machine usually runs every kernel timer interrupt (up to
       
  4140 $1$~kHz) and with a connected realtime module, the rate can be even
       
  4141 higher.
       
  4142 
       
  4143 \paragraph{Attention:} The socket buffers needed for the operation of
       
  4144 the debugging interface have to be allocated dynamically. Some Linux
       
  4145 realtime extensions do not allow this in realtime context!
       
  4146 
       
  4147 %------------------------------------------------------------------------------
       
  4148 
       
  4149 \section{Timing Aspects}
       
  4150 \label{sec:timing}
       
  4151 
       
  4152 Although EtherCAT's timing is highly deterministic and therefore
       
  4153 timing issues are rare, there are a few aspects that can (and should
       
  4154 be) dealt with.
       
  4155 
       
  4156 %------------------------------------------------------------------------------
       
  4157 
       
  4158 \subsection{Realtime Interface Profiling}
       
  4159 \label{sec:timing-profile}
       
  4160 \index{Realtime!Profiling}
       
  4161 
       
  4162 One of the most important timing aspects are the runtimes of the
       
  4163 realtime interface functions, that are called in cyclic context. These
       
  4164 functions make up an important part of the overall timing of the
       
  4165 realtime module. To measure the timing of the functions, the following
       
  4166 code was used:
       
  4167 
       
  4168 \begin{lstlisting}[gobble=2,language=C]
       
  4169   c0 = get_cycles();
       
  4170   ecrt_master_receive(master);
       
  4171   c1 = get_cycles();
       
  4172   ecrt_domain_process(domain1);
       
  4173   c2 = get_cycles();
       
  4174   ecrt_master_run(master);
       
  4175   c3 = get_cycles();
       
  4176   ecrt_master_send(master);
       
  4177   c4 = get_cycles();
       
  4178 \end{lstlisting}
       
  4179 
       
  4180 Between each call of an interface function, the CPU timestamp counter
       
  4181 is read. The counter differences are converted to microseconds with
       
  4182 help of the \textit{cpu\_khz} variable, that contains the number of
       
  4183 increments per millisecond.
       
  4184 
       
  4185 For the actual measuring, a system with a $2.0$~GHz CPU was used, that
       
  4186 ran the above code in an RTAI thread with a cycle time of $100$
       
  4187 \textmu s.  The measuring was repeated $n = 100$ times and the results
       
  4188 were averaged. These can be seen in table~\ref{tab:profile}.
       
  4189 
       
  4190 \begin{table}[htpb]
       
  4191   \centering
       
  4192   \caption{Profiling of a Realtime Cycle on a $2.0$~GHz Processor}
       
  4193   \label{tab:profile}
       
  4194   \vspace{2mm}
       
  4195   \begin{tabular}{l|r|r}
       
  4196     Element & Mean Duration [\textmu s] & Standard Deviancy [\textmu s] \\
       
  4197     \hline
       
  4198     \textit{ecrt\_master\_receive()} & 8.04 & 0.48\\
       
  4199     \textit{ecrt\_domain\_process()} & 0.14 & 0.03\\
       
  4200     \textit{ecrt\_master\_run()} & 0.29 & 0.12\\
       
  4201     \textit{ecrt\_master\_send()} & 2.18 & 0.17\\ \hline
       
  4202     Complete Cycle & 10.65 & 0.69\\ \hline
       
  4203   \end{tabular}
       
  4204 \end{table}
       
  4205 
       
  4206 It is obvious, that the the functions accessing hardware make up the
       
  4207 lion's share. The \textit{ec\_master\_receive()} executes the ISR of
       
  4208 the Ethernet device, analyzes datagrams and copies their contents into
       
  4209 the memory of the datagram objects. The \textit{ec\_master\_send()}
       
  4210 assembles a frame out of different datagrams and copies it to the
       
  4211 hardware buffers. Interestingly, this makes up only a quarter of the
       
  4212 receiving time.
       
  4213 
       
  4214 The functions that only operate on the masters internal data
       
  4215 structures are very fast ($\Delta t < 1$~\textmu s). Interestingly the
       
  4216 runtime of \textit{ec\_domain\_process()} has a small standard
       
  4217 deviancy relative to the mean value, while this ratio is about twice
       
  4218 as big for \textit{ec\_master\_run()}: This probably results from the
       
  4219 latter function having to execute code depending on the current state
       
  4220 and the different state functions are more or less complex.
       
  4221 
       
  4222 For a realtime cycle makes up about $10$~\textmu s, the theoretical
       
  4223 frequency can be up to $100$~kHz. For two reasons, this frequency
       
  4224 keeps being theoretical:
       
  4225 
       
  4226 \begin{enumerate}
       
  4227 \item The processor must still be able to run the operating system
       
  4228   between the realtime cycles.
       
  4229 \item The EtherCAT frame must be sent and received, before the next
       
  4230   realtime cycle begins. The determination of the bus cycle time is
       
  4231   difficult and covered in section~\ref{sec:timing-bus}.
       
  4232 \end{enumerate}
       
  4233 
       
  4234 %------------------------------------------------------------------------------
       
  4235 
       
  4236 \subsection{Bus Cycle Measuring}
       
  4237 \label{sec:timing-bus}
       
  4238 \index{Bus cycle}
       
  4239 
       
  4240 For measuring the time, a frame is ``on the wire'', two timestamps
       
  4241 must be be taken:
       
  4242 
       
  4243 \begin{enumerate}
       
  4244 \item The time, the Ethernet hardware begins with physically sending
       
  4245   the frame.
       
  4246 \item The time, the frame is completely received by the Ethernet
       
  4247   hardware.
       
  4248 \end{enumerate}
       
  4249 
       
  4250 Both times are difficult to determine. The first reason is, that the
       
  4251 interrupts are disabled and the master is not notified, when a frame
       
  4252 is sent or received (polling would distort the results). The second
       
  4253 reason is, that even with interrupts enabled, the time from the event
       
  4254 to the notification is unknown. Therefore the only way to confidently
       
  4255 determine the bus cycle time is an electrical measuring.
       
  4256 
       
  4257 Anyway, the bus cycle time is an important factor when designing
       
  4258 realtime code, because it limits the maximum frequency for the cyclic
       
  4259 part of the realtime module. In practice, these timing parameters are
       
  4260 highly dependent on the hardware and often a trial and error method
       
  4261 must be used to determine the limits of the system.
       
  4262 
       
  4263 The central question is: What happens, if the cycle frequency is too
       
  4264 high? The answer is, that the EtherCAT frames that have been sent at
       
  4265 the end of the cycle are not yet received, when the next cycle starts.
       
  4266 First this is noticed by \textit{ecrt\_domain\_process()}, because the
       
  4267 working counter of the process data datagrams were not increased. The
       
  4268 function will notify the user via syslog\footnote{To limit syslog
       
  4269   output, a mechanism has been implementet, that outputs a summarized
       
  4270   notification at maximum once a second.}. In this case, the process
       
  4271 data keeps being the same as in the last cycle, because it is not
       
  4272 erased by the domain. When the domain datagrams are queued again, the
       
  4273 master notices, that they are already queued (and marked as sent). The
       
  4274 master will mark them as unsent again and output a warning, that
       
  4275 datagrams were ``skipped''.
       
  4276 
       
  4277 On the mentioned $2.0$~GHz system, the possible cycle frequency can be
       
  4278 up to $25$~kHz without skipped frames. This value can surely be
       
  4279 increased by choosing faster hardware. Especially the RealTek network
       
  4280 hardware could be replaced by a faster one. Besides, implementing a
       
  4281 dedicated ISR for EtherCAT devices would also contribute to increasing
       
  4282 the latency. These are two points on the author's to-do list.
       
  4283 
       
  4284 %------------------------------------------------------------------------------
       
  4285 
       
  4286 \chapter{Using the EtherCAT Master}
       
  4287 \label{chapter:usage}
       
  4288 \index{Master!Usage}
       
  4289 
       
  4290 This chapter will give practical examples of how to use the EtherCAT
       
  4291 master via the realtime interface by writing a realtime module.
       
  4292 
       
  4293 Section~\ref{sec:make} shows how to compile and install the master,
       
  4294 while the sections~\ref{sec:mini} to~\ref{sec:concurrency} give
       
  4295 examples for different realtime modules.
       
  4296 
       
  4297 %------------------------------------------------------------------------------
       
  4298 
       
  4299 \section{Compiling and Installing}
       
  4300 \label{sec:make}
       
  4301 \index{Master!Compilation}
       
  4302 
       
  4303 The current EtherCAT master code is available at~\cite{etherlab}.
       
  4304 After downloading the \textit{tar.bz2} file, it has to be unpacked
       
  4305 with the command below (or similar):
       
  4306 
       
  4307 \begin{lstlisting}
       
  4308   host> `\textbf{tar xjf ethercat-stable-1.1-r513-src.tar.bz2}`
       
  4309   host> `\textbf{cd ethercat-stable-1.1-r513-src}`
       
  4310 \end{lstlisting}
       
  4311 
       
  4312 For compilation, the kernel sources are needed. Basically any kernel
       
  4313 sources are appropriate\footnote{If a realtime extension is to be
       
  4314   used, the kernel has to be patched before that.}, that are
       
  4315 configured with networking. If the host kernel is not the running
       
  4316 kernel, a copy of the configuration template has to be made:
       
  4317 
       
  4318 \begin{lstlisting}
       
  4319   host> `\textbf{cp ethercat.conf.tmpl ethercat.conf}`
       
  4320 \end{lstlisting}
       
  4321 
       
  4322 Now the \textit{\$KERNEL} variable inside the \textit{ethercat.conf}
       
  4323 file can be adjusted to reflect the appropriate kernel version. If
       
  4324 everything is correct now, the sucessive call to
       
  4325 
       
  4326 \begin{lstlisting}
       
  4327   host> `\textbf{make}`
       
  4328 \end{lstlisting}
       
  4329 
       
  4330 will result in no errors.
       
  4331 
       
  4332 The following commands have to be entered as \textit{root}: To install
       
  4333 the kernel modules, the init script, the sysconfig file and the user
       
  4334 space tools, the below command has to be executed:
       
  4335 
       
  4336 \begin{lstlisting}
       
  4337   host# `\textbf{make install}`
       
  4338 \end{lstlisting}
       
  4339 
       
  4340 If the sysconfig file did not exist yet, the user is notified to edit
       
  4341 it, before running the master. For the contents of the file, see
       
  4342 section~\ref{sec:sysconfig}. To give a short summary: The most
       
  4343 important thing is to adjust the \textit{\$DEVICE\_INDEX} variable. It
       
  4344 has to be set to the index of the compatible network device to use
       
  4345 with EtherCAT, where the order of devices is dependent on their
       
  4346 position in the PCI bus. If this is not known, the index can be
       
  4347 determinded with trial and error, but it has to be considered that a
       
  4348 wrong value can cause a loss of network connection.
       
  4349 
       
  4350 After the basic configuration is done, the master can be started with
       
  4351 the below command:
       
  4352 
       
  4353 \begin{lstlisting}
       
  4354   host# `\textbf{/etc/init.d/ethercat start}`
       
  4355 \end{lstlisting}
       
  4356 
       
  4357 The operation of the master can be observed by looking at the
       
  4358 syslog\index{syslog} messages, which should look like the ones below:
       
  4359 
       
  4360 \begin{lstlisting}[numbers=left]
       
  4361   EtherCAT: Master driver, 1.1 (stable) - rev. 513,
       
  4362       compiled by fp at Aug 09 2006 10:23:20
       
  4363   EtherCAT: Initializing 1 EtherCAT master(s)...
       
  4364   EtherCAT: Initializing master 0.
       
  4365   EtherCAT: Master driver initialized.
       
  4366   ec_8139too Fast Ethernet driver 0.9.27 Revision 513,
       
  4367       compiled by fp at Aug 09 2006 10:23:20
       
  4368   ec_device_index is 0
       
  4369   ACPI: PCI Interrupt 0000:01:00.0[A] -> Link [LNKC]
       
  4370       -> GSI 11 (level, low) -> IRQ 11
       
  4371   ec0: RealTek RTL8139 at 0xd047c000, 00:c0:26:00:c6:aa, IRQ 11
       
  4372   ec0:  Identified 8139 chip type 'RTL-8100B/8139D'
       
  4373   Registering EtherCAT device...
       
  4374   Starting EtherCAT device...
       
  4375   EtherCAT: Link state changed to UP.
       
  4376   EtherCAT: Starting Idle mode.
       
  4377   EtherCAT: 11 slaves responding.
       
  4378   EtherCAT: Slave states: INIT, OP.
       
  4379   EtherCAT: Scanning bus.
       
  4380   EtherCAT: Bus scanning completed.
       
  4381   EtherCAT: No EoE handlers coupled.
       
  4382 \end{lstlisting}
       
  4383 
       
  4384 \begin{description}
       
  4385 \item[\normalfont\textcircled{\tiny 1}] The master module is loaded,
       
  4386   and one master is initialized.
       
  4387 \item[\normalfont\textcircled{\tiny 6}] The EtherCAT-capable RTL8139
       
  4388   device driver is loaded. It connects its first network device to the
       
  4389   master.
       
  4390 \item[\normalfont\textcircled{\tiny 16}] The master starts idle mode
       
  4391   and begins scanning the bus for slaves.
       
  4392 \end{description}
       
  4393 
       
  4394 %------------------------------------------------------------------------------
       
  4395 
       
  4396 \section{A Minimal Example Module}
       
  4397 \label{sec:mini}
       
  4398 \index{Examples!Minimal}
       
  4399 
       
  4400 This section will explain the usage of the EtherCAT master from a
       
  4401 minimal kernel module. The complete module code is obtainable as a
       
  4402 part of the EtherCAT master code release (see~\cite{etherlab}, file
       
  4403 \textit{examples/mini/mini.c}).
       
  4404 
       
  4405 The minimal example uses a kernel timer (software interrupt) to handle
       
  4406 cyclic code. After the timer function is executed, it re-adds itself
       
  4407 with a delay of one \textit{jiffy}\index{jiffies}, which results in a
       
  4408 timer frequency of \textit{HZ}\nomenclature{HZ}{Kernel macro
       
  4409   containing the timer interrupt frequency}
       
  4410 
       
  4411 The module-global variables, needed to operate the master can be seen
       
  4412 in listing~\ref{lst:minivar}.
       
  4413 
       
  4414 \begin{lstlisting}[language=C,numbers=left,caption={Minimal
       
  4415     variables},label=lst:minivar]
       
  4416   struct timer_list timer;
       
  4417 
       
  4418   ec_master_t *master = NULL;
       
  4419   ec_domain_t *domain1 = NULL;
       
  4420 
       
  4421   void *r_dig_in, *r_ana_out;
       
  4422 
       
  4423   ec_pdo_reg_t domain1_pdos[] = {
       
  4424           {"1", Beckhoff_EL1014_Inputs, &r_dig_in},
       
  4425           {"2", Beckhoff_EL4132_Ouput1, &r_ana_out},
       
  4426           {}
       
  4427   };
       
  4428 \end{lstlisting}
       
  4429 
       
  4430 \begin{description}
       
  4431 \item[\normalfont\textcircled{\tiny 1}] There is a timer object
       
  4432   declared, that is needed to tell the kernel to install a timer and
       
  4433   execute a certain function, if it runs out. This is done by a
       
  4434   variable of the \textit{timer\_list} structure.
       
  4435 \item[\normalfont\textcircled{\tiny 3} -- \textcircled{\tiny 4}] There
       
  4436   is a pointer declared, that will later point to a requested EtherCAT
       
  4437   master.  Additionally there is a pointer to a domain object needed,
       
  4438   that will manage process data IO.
       
  4439 \item[\normalfont\textcircled{\tiny 6}] The pointers \textit{r\_*}
       
  4440   will later point to the \underline{r}aw process data values inside
       
  4441   the domain memory. The addresses they point to will be set during a
       
  4442   call to \textit{ec\_\-master\_\-activate()}, that will create the
       
  4443   domain memory and configure the mapped process data image.
       
  4444 \item[\normalfont\textcircled{\tiny 8} -- \textcircled{\tiny 12}] The
       
  4445   configuration of the mapping of certain PDOs in a domain can easily
       
  4446   be done with the help of an initialization array of the
       
  4447   \textit{ec\_pdo\_reg\_t} type, defined as part of the realtime
       
  4448   interface. Each record must contain the ASCII bus-address of the
       
  4449   slave (see section~\ref{sec:addr}), the slave's vendor ID and
       
  4450   product code, and the index and subindex of the PDO to map (these
       
  4451   four fields can be specified in junction, by using one of the
       
  4452   defines out of the \textit{include/ecdb.h} header). The last field
       
  4453   has to be the address of the process data pointer, so it can later
       
  4454   be redirected appropriately. Attention: The initialization array
       
  4455   must end with an empty record (\textit{\{\}})!
       
  4456 \end{description}
       
  4457 
       
  4458 The initialization of the minimal realtime module is done by the
       
  4459 ``Minimal init function'' in listing~\ref{lst:miniinit}.
       
  4460 
       
  4461 \begin{lstlisting}[language=C,numbers=left,caption={Minimal init
       
  4462     function},label={lst:miniinit}]
       
  4463   int __init init_mini_module(void)
       
  4464   {
       
  4465           if (!(master = ecrt_request_master(0))) {
       
  4466                   goto out_return;
       
  4467           }
       
  4468 
       
  4469           if (!(domain1 = ecrt_master_create_domain(master))) {
       
  4470                   goto out_release_master;
       
  4471           }
       
  4472 
       
  4473           if (ecrt_domain_register_pdo_list(domain1,
       
  4474                                             domain1_pdos)) {
       
  4475                   goto out_release_master;
       
  4476           }
       
  4477 
       
  4478           if (ecrt_master_activate(master)) {
       
  4479                   goto out_release_master;
       
  4480           }
       
  4481 
       
  4482           ecrt_master_prepare(master);
       
  4483 
       
  4484           init_timer(&timer);
       
  4485           timer.function = run;
       
  4486           timer.expires = jiffies + 10;
       
  4487           add_timer(&timer);
       
  4488 
       
  4489           return 0;
       
  4490 
       
  4491         out_release_master:
       
  4492           ecrt_release_master(master);
       
  4493         out_return:
       
  4494           return -1;
       
  4495   }
       
  4496 \end{lstlisting}
       
  4497 
       
  4498 \begin{description}
       
  4499 \item[\normalfont\textcircled{\tiny 3}] It is tried to request the
       
  4500   first EtherCAT master (index 0). On success, the
       
  4501   \textit{ecrt\_\-request\_\-master()} function returns a pointer to
       
  4502   the reserved master, that can be used as an object to following
       
  4503   functions calls. On failure, the function returns \textit{NULL}.
       
  4504 \item[\normalfont\textcircled{\tiny 7}] In order to exchange process
       
  4505   data, a domain object has to be created. The
       
  4506   \textit{ecrt\_\-master\_\-create\_domain()} function also returns a
       
  4507   pointer to the created domain, or \textit{NULL} in error case.
       
  4508 \item[\normalfont\textcircled{\tiny 11}] The registration of domain
       
  4509   PDOs with an initialization array results in a single function call.
       
  4510   Alternatively the data fields could be registered with individual
       
  4511   calls of \textit{ecrt\_domain\_register\_pdo()}.
       
  4512 \item[\normalfont\textcircled{\tiny 16}] After the configuration of
       
  4513   process data mapping, the master can be activated for cyclic
       
  4514   operation. This will configure all slaves and bring them into
       
  4515   \textit{OP} state.
       
  4516 \item[\normalfont\textcircled{\tiny 20}] This call is needed to avoid
       
  4517   a case differentiation in cyclic operation: The first operation in
       
  4518   cyclic mode is a receive call. Due to the fact, that there is
       
  4519   nothing to receive during the first cycle, there had to be an
       
  4520   \textit{if}-statement to avoid a warning. A call to
       
  4521   \textit{ec\_master\_prepare()} sends a first datagram containing a
       
  4522   process data exchange datagram, so that the first receive call will
       
  4523   not fail.
       
  4524 \item[\normalfont\textcircled{\tiny 22} -- \textcircled{\tiny 25}] The
       
  4525   master is now ready for cyclic operation. The kernel timer that
       
  4526   cyclically executes the \textit{run()} function is initialized and
       
  4527   started.
       
  4528 \end{description}
       
  4529 
       
  4530 The coding of a cleanup function fo the minimal module can be seen in
       
  4531 listing~\ref{lst:miniclean}.
       
  4532 
       
  4533 \begin{lstlisting}[language=C,numbers=left,caption={Minimal cleanup
       
  4534     function},label={lst:miniclean}]
       
  4535   void __exit cleanup_mini_module(void)
       
  4536   {
       
  4537           del_timer_sync(&timer);
       
  4538           ecrt_master_deactivate(master);
       
  4539           ecrt_release_master(master);
       
  4540   }
       
  4541 \end{lstlisting}
       
  4542 
       
  4543 \begin{description}
       
  4544 \item[\normalfont\textcircled{\tiny 3}] To cleanup the module, it it
       
  4545   necessary to stop the cyclic processing. This is done by a call to
       
  4546   \textit{del\_timer\_sync()} which safely removes a queued timer
       
  4547   object. It is assured, that no cyclic work will be done after this
       
  4548   call returns.
       
  4549 \item[\normalfont\textcircled{\tiny 4}] This call deactivates the
       
  4550   master, which results in all slaves being brought to their
       
  4551   \textit{INIT} state again.
       
  4552 \item[\normalfont\textcircled{\tiny 5}] This call releases the master,
       
  4553   removes any existing configuration and silently starts the idle
       
  4554   mode. The value of the master pointer is invalid after this call and
       
  4555   the module can be safely unloaded.
       
  4556 \end{description}
       
  4557 
       
  4558 The final part of the minimal module is that for the cyclic work. Its
       
  4559 coding can be seen in listing~\ref{lst:minirun}.
       
  4560 
       
  4561 \begin{lstlisting}[language=C,numbers=left,caption={Minimal cyclic
       
  4562     function},label={lst:minirun}]
       
  4563   void run(unsigned long data)
       
  4564   {
       
  4565           static uint8_t dig_in_0;
       
  4566 
       
  4567           ecrt_master_receive(master);
       
  4568           ecrt_domain_process(domain1);
       
  4569 
       
  4570           dig_in_0 = EC_READ_BIT(r_dig_in, 0);
       
  4571           EC_WRITE_S16(r_ana_out, dig_in_0 * 0x3FFF);
       
  4572 
       
  4573           ecrt_master_run(master);
       
  4574           ecrt_master_send(master);
       
  4575 
       
  4576           timer.expires += 1; // frequency = HZ
       
  4577           add_timer(&timer);
       
  4578   }
       
  4579 \end{lstlisting}
       
  4580 
       
  4581 \begin{description}
       
  4582 \item[\normalfont\textcircled{\tiny 5}] The cyclic processing starts
       
  4583   with receiving datagrams, that were sent in the last cycle. The
       
  4584   frames containing these datagrams have to be received by the network
       
  4585   interface card prior to this call.
       
  4586 \item[\normalfont\textcircled{\tiny 6}] The process data of domain 1
       
  4587   has been automatically copied into domain memory while datagram
       
  4588   reception. This call checks the working counter for changes and
       
  4589   re-queues the domain's datagram for sending.
       
  4590 \item[\normalfont\textcircled{\tiny 8}] This is an example for reading
       
  4591   out a bit-oriented process data value (i.~e. bit 0) via the
       
  4592   \textit{EC\_READ\_BIT()} macro. See section~\ref{sec:macros} for
       
  4593   more information about those macros.
       
  4594 \item[\normalfont\textcircled{\tiny 9}] This line shows how to write a
       
  4595   signed, 16-bit process data value. In this case, the slave is able
       
  4596   to output voltages of $-10$~V to $+10$~V with a resolution of 16
       
  4597   bit.  This write command outputs either $0$~V or $+5$~V, depending
       
  4598   of the value of \textit{dig\_in\_0}.
       
  4599 \item[\normalfont\textcircled{\tiny 11}] This call runs the master's
       
  4600   operation state machine (see section~\ref{sec:fsm-op}). A single
       
  4601   state is processed, and datagrams are queued. Mainly bus observation
       
  4602   is done: The bus state is determined and in case of slaves that lost
       
  4603   their configuration, reconfiguration is tried.
       
  4604 \item[\normalfont\textcircled{\tiny 12}] This method sends all queued
       
  4605   datagrams, in this case the domain's datagram and one of the master
       
  4606   state machine. In best case, all datagrams fit into one frame.
       
  4607 \item[\normalfont\textcircled{\tiny 14} -- \textcircled{\tiny 15}]
       
  4608   Kernel timers are implemented as ``one-shot'' timers, so they have
       
  4609   to be re-added after each execution. The time of the next execution
       
  4610   is specified in \textit{jiffies} and will happen at the time of the
       
  4611   next system timer interrupt. This results in the \textit{run()}
       
  4612   function being executed with a frequency of \textit{HZ}.
       
  4613 \end{description}
       
  4614 
       
  4615 %------------------------------------------------------------------------------
       
  4616 
       
  4617 \section{An RTAI Example Module}
       
  4618 \label{sec:rtai}
       
  4619 \index{Examples!RTAI}
       
  4620 
       
  4621 The whole code can be seen in the EtherCAT master code release
       
  4622 (see~\cite{etherlab}, file \textit{examples/rtai/rtai\_sample.c}).
       
  4623 
       
  4624 Listing~\ref{lst:rtaivar} shows the defines and global variables
       
  4625 needed for a minimal RTAI module with EtherCAT processing.
       
  4626 
       
  4627 \begin{lstlisting}[language=C,numbers=left,caption={RTAI task
       
  4628     declaration},label={lst:rtaivar}]
       
  4629   #define FREQUENCY 10000
       
  4630   #define TIMERTICKS (1000000000 / FREQUENCY)
       
  4631 
       
  4632   RT_TASK task;
       
  4633 \end{lstlisting}
       
  4634 
       
  4635 \begin{description}
       
  4636 \item[\normalfont\textcircled{\tiny 1} -- \textcircled{\tiny 2}] RTAI
       
  4637   takes the cycle period as nanoseconds, so the easiest way is to
       
  4638   define a frequency and convert it to a cycle time in nanoseconds.
       
  4639 \item[\normalfont\textcircled{\tiny 4}] The \textit{task} variable
       
  4640   later contains information about the running RTAI task.
       
  4641 \end{description}
       
  4642 
       
  4643 Listing~\ref{lst:rtaiinit} shows the module init function for the RTAI
       
  4644 module. Most lines are the same as in listing~\ref{lst:miniinit},
       
  4645 differences come up when starting the cyclic code.
       
  4646 
       
  4647 \begin{lstlisting}[language=C,numbers=left,caption={RTAI module init
       
  4648     function},label={lst:rtaiinit}]
       
  4649   int __init init_mod(void)
       
  4650   {
       
  4651           RTIME requested_ticks, tick_period, now;
       
  4652 
       
  4653           if (!(master = ecrt_request_master(0))) {
       
  4654                   goto out_return;
       
  4655           }
       
  4656 
       
  4657           if (!(domain1 = ecrt_master_create_domain(master))) {
       
  4658                   goto out_release_master;
       
  4659           }
       
  4660 
       
  4661           if (ecrt_domain_register_pdo_list(domain1,
       
  4662                                             domain1_pdos)) {
       
  4663                   goto out_release_master;
       
  4664           }
       
  4665 
       
  4666           if (ecrt_master_activate(master)) {
       
  4667                   goto out_release_master;
       
  4668           }
       
  4669 
       
  4670           ecrt_master_prepare(master);
       
  4671 
       
  4672           requested_ticks = nano2count(TIMERTICKS);
       
  4673           tick_period = start_rt_timer(requested_ticks);
       
  4674 
       
  4675           if (rt_task_init(&task, run, 0, 2000, 0, 1, NULL)) {
       
  4676                   goto out_stop_timer;
       
  4677           }
       
  4678 
       
  4679           now = rt_get_time();
       
  4680           if (rt_task_make_periodic(&task, now + tick_period,
       
  4681                                     tick_period)) {
       
  4682                   goto out_stop_task;
       
  4683           }
       
  4684 
       
  4685           return 0;
       
  4686 
       
  4687       out_stop_task:
       
  4688           rt_task_delete(&task);
       
  4689       out_stop_timer:
       
  4690           stop_rt_timer();
       
  4691       out_deactivate:
       
  4692           ecrt_master_deactivate(master);
       
  4693       out_release_master:
       
  4694           ecrt_release_master(master);
       
  4695       out_return:
       
  4696           return -1;
       
  4697   }
       
  4698 \end{lstlisting}
       
  4699 
       
  4700 \begin{description}
       
  4701 \item[\normalfont\textcircled{\tiny 24} -- \textcircled{\tiny 25}] The
       
  4702   nanoseconds are converted to RTAI timer ticks and an RTAI timer is
       
  4703   started.  \textit{tick\_period} will be the ``real'' number of ticks
       
  4704   used for the timer period (which can be different to the requested
       
  4705   one).
       
  4706 \item[\normalfont\textcircled{\tiny 27}] The RTAI task is initialized
       
  4707   by specifying the cyclic function, the parameter to hand over, the
       
  4708   stack size, priority, a flag that tells, if the function will use
       
  4709   floating point operations and a signal handler.
       
  4710 \item[\normalfont\textcircled{\tiny 32}] The task is made periodic by
       
  4711   specifying a start time and a period.
       
  4712 \end{description}
       
  4713 
       
  4714 The cleanup function of the RTAI module in listing~\ref{lst:rtaiclean}
       
  4715 is nearly as simple as that of the minimal module.
       
  4716 
       
  4717 \begin{lstlisting}[language=C,numbers=left,caption={RTAI module
       
  4718     cleanup function},label={lst:rtaiclean}]
       
  4719   void __exit cleanup_mod(void)
       
  4720   {
       
  4721           rt_task_delete(&task);
       
  4722           stop_rt_timer();
       
  4723           ecrt_master_deactivate(master);
       
  4724           ecrt_release_master(master);
       
  4725           rt_sem_delete(&master_sem);
       
  4726   }
       
  4727 \end{lstlisting}
       
  4728 
       
  4729 \begin{description}
       
  4730 \item[\normalfont\textcircled{\tiny 2}] The RTAI task will be stopped
       
  4731   and deleted.
       
  4732 \item[\normalfont\textcircled{\tiny 3}] After that, the RTAI timer can
       
  4733   be stopped.
       
  4734 \end{description}
       
  4735 
       
  4736 The rest is the same as for the minimal module.
       
  4737 
       
  4738 Worth to mention is, that the cyclic function of the RTAI module
       
  4739 (listing~\ref{lst:rtairun}) has a slightly different architecture. The
       
  4740 function is not executed until returning for every cycle, but has an
       
  4741 infinite loop in it, that is placed in a waiting state for the rest of
       
  4742 each cycle.
       
  4743 
       
  4744 \begin{lstlisting}[language=C,numbers=left,caption={RTAI module cyclic
       
  4745     function},label={lst:rtairun}]
       
  4746   void run(long data)
       
  4747   {
       
  4748           while (1) {
       
  4749                   ecrt_master_receive(master);
       
  4750                   ecrt_domain_process(domain1);
       
  4751 
       
  4752                   k_pos = EC_READ_U32(r_ssi_input);
       
  4753 
       
  4754                   ecrt_master_run(master);
       
  4755                   ecrt_master_send(master);
       
  4756 
       
  4757                   rt_task_wait_period();
       
  4758           }
       
  4759   }
       
  4760 \end{lstlisting}
       
  4761 
       
  4762 \begin{description}
       
  4763 \item[\normalfont\textcircled{\tiny 3}] The \textit{while (1)} loop
       
  4764   executes for the lifetime of the RTAI task.
       
  4765 \item[\normalfont\textcircled{\tiny 12}] The
       
  4766   \textit{rt\_task\_wait\_period()} function sets the process into a
       
  4767   sleeping state until the beginning of the next cycle. It also
       
  4768   checks, if the cyclic function has to be terminated.
       
  4769 \end{description}
       
  4770 
       
  4771 %------------------------------------------------------------------------------
       
  4772 
       
  4773 \section{Concurrency Example}
       
  4774 \label{sec:concurrency}
       
  4775 \index{Examples!Concurrency}
       
  4776 
       
  4777 As mentioned before, there can be concurrent access to the EtherCAT
       
  4778 master. The realtime module and a EoE\index{EoE} process can compete
       
  4779 for master access, for example. In this case, the module has to
       
  4780 provide the locking mechanism, because it depends on the module's
       
  4781 architecture which lock has to be used. The module makes this locking
       
  4782 mechanism available to the master through the master's locking
       
  4783 callbacks.
       
  4784 
       
  4785 In case of RTAI, the lock can be an RTAI semaphore, as shown in
       
  4786 listing~\ref{lst:convar}. A normal linux semaphore would not be
       
  4787 appropriate, because it could not block the RTAI task due to RTAI
       
  4788 running in a higher domain than the linux kernel (see~\cite{rtai}).
       
  4789 
       
  4790 \begin{lstlisting}[language=C,numbers=left,caption={RTAI semaphore for
       
  4791     concurrent access},label={lst:convar}]
       
  4792   SEM master_sem;
       
  4793 \end{lstlisting}
       
  4794 
       
  4795 The module has to implement the two callbacks for requesting and
       
  4796 releasing the master lock. An exemplary coding can be seen in
       
  4797 listing~\ref{lst:conlock}.
       
  4798 
       
  4799 \begin{lstlisting}[language=C,numbers=left,caption={RTAI locking
       
  4800     callbacks for concurrent access},label={lst:conlock}]
       
  4801   int request_lock(void *data)
       
  4802   {
       
  4803           rt_sem_wait(&master_sem);
       
  4804           return 0;
       
  4805   }
       
  4806 
       
  4807   void release_lock(void *data)
       
  4808   {
       
  4809           rt_sem_signal(&master_sem);
       
  4810   }
       
  4811 \end{lstlisting}
       
  4812 
       
  4813 \begin{description}
       
  4814 \item[\normalfont\textcircled{\tiny 1}] The \textit{request\_lock()}
       
  4815   function has a data parameter. The master always passes the value,
       
  4816   that was specified when registering the callback function. This can
       
  4817   be used for handing the master pointer. Notice, that it has an
       
  4818   integer return value (see line 4).
       
  4819 \item[\normalfont\textcircled{\tiny 3}] The call to
       
  4820   \textit{rt\_sem\_wait()} either returns at once, when the semaphore
       
  4821   was free, or blocks until the semaphore is freed again. In any case,
       
  4822   the semaphore finally is reserved for the process calling the
       
  4823   request function.
       
  4824 \item[\normalfont\textcircled{\tiny 4}] When the lock was requested
       
  4825   successfully, the function should return 0. The module can prohibit
       
  4826   requesting the lock by returning non-zero (see paragraph ``Tuning
       
  4827   the jitter'' below).
       
  4828 \item[\normalfont\textcircled{\tiny 7}] The \textit{release\_lock()}
       
  4829   function gets the same argument passed, but has a void return value,
       
  4830   because is always succeeds.
       
  4831 \item[\normalfont\textcircled{\tiny 9}] The \textit{rt\_sem\_signal()}
       
  4832   function frees the semaphore, that was prior reserved with
       
  4833   \textit{rt\_sem\_wait()}.
       
  4834 \end{description}
       
  4835 
       
  4836 In the module's init function, the semaphore must be initialized, and
       
  4837 the callbacks must be passed to the EtherCAT master:
       
  4838 
       
  4839 \begin{lstlisting}[language=C,numbers=left,caption={Module init
       
  4840     function for concurrent access},label={lst:coninit}]
       
  4841   int __init init_mod(void)
       
  4842   {
       
  4843           RTIME tick_period, requested_ticks, now;
       
  4844 
       
  4845           rt_sem_init(&master_sem, 1);
       
  4846 
       
  4847           if (!(master = ecrt_request_master(0))) {
       
  4848                   goto out_return;
       
  4849           }
       
  4850 
       
  4851           ecrt_master_callbacks(master, request_lock,
       
  4852                                 release_lock, NULL);
       
  4853           // ...
       
  4854 \end{lstlisting}
       
  4855 
       
  4856 \begin{description}
       
  4857 \item[\normalfont\textcircled{\tiny 5}] The call to
       
  4858   \textit{rt\_sem\_init()} initializes the semaphore and sets its
       
  4859   value to 1, meaning that only one process can reserve the semaphore
       
  4860   without blocking.
       
  4861 \item[\normalfont\textcircled{\tiny 11}] The callbacks are passed to
       
  4862   the master with a call to \textit{ecrt\_master\_callbacks()}. The
       
  4863   last parameter is the argument, that the master should pass with
       
  4864   each call to a callback function. Here it is not used and set to
       
  4865   \textit{NULL}.
       
  4866 \end{description}
       
  4867 
       
  4868 For the cyclic function being only one competitor for master access,
       
  4869 it has to request the lock like any other process. There is no need to
       
  4870 use the callbacks (which are meant for processes of lower priority),
       
  4871 so it can access the semaphore directly:
       
  4872 
       
  4873 \begin{lstlisting}[language=C,numbers=left,caption={RTAI cyclic
       
  4874     function for concurrent access},label={lst:conrun}]
       
  4875   void run(long data)
       
  4876   {
       
  4877           while (1) {
       
  4878                   rt_sem_wait(&master_sem);
       
  4879 
       
  4880                   ecrt_master_receive(master);
       
  4881                   ecrt_domain_process(domain1);
       
  4882 
       
  4883                   k_pos = EC_READ_U32(r_ssi_input);
       
  4884 
       
  4885                   ecrt_master_run(master);
       
  4886                   ecrt_master_send(master);
       
  4887 
       
  4888                   rt_sem_signal(&master_sem);
       
  4889                   rt_task_wait_period();
       
  4890           }
       
  4891   }
       
  4892 \end{lstlisting}
       
  4893 
       
  4894 \begin{description}
       
  4895 \item[\normalfont\textcircled{\tiny 4}] Every access to the master has
       
  4896   to be preceeded by a call to \textit{rt\_sem\_wait()}, because
       
  4897   another instance might currently access the master.
       
  4898 \item[\normalfont\textcircled{\tiny 14}] When cyclic processing
       
  4899   finished, the semaphore has to be freed again, so that other
       
  4900   processes have the possibility to access the master.
       
  4901 \end{description}
       
  4902 
       
  4903 A little change has to be made to the cleanup function in case of
       
  4904 concurrent master access.
       
  4905 
       
  4906 \begin{lstlisting}[language=C,numbers=left,caption={RTAI module
       
  4907     cleanup function for concurrent access},label={lst:conclean}]
       
  4908   void __exit cleanup_mod(void)
       
  4909   {
       
  4910           rt_task_delete(&task);
       
  4911           stop_rt_timer();
       
  4912           ecrt_master_deactivate(master);
       
  4913           ecrt_release_master(master);
       
  4914           rt_sem_delete(&master_sem);
       
  4915   }
       
  4916 \end{lstlisting}
       
  4917 
       
  4918 \begin{description}
       
  4919 \item[\normalfont\textcircled{\tiny 7}] Upon module cleanup, the
       
  4920   semaphore has to be deleted, so that memory can be freed.
       
  4921 \end{description}
       
  4922 
       
  4923 \paragraph{Tuning the Jitter}
       
  4924 \index{Jitter}
       
  4925 
       
  4926 Concurrent access leads to higher jitter of the realtime process,
       
  4927 because there are situations, in which the realtime process has to
       
  4928 wait for a process of lower priority to finish accessing the master.
       
  4929 In most cases this is acceptable, because a master access cycle
       
  4930 (receive/process/send) only takes $10$~\textmu s to $20$~\textmu s on
       
  4931 recent systems, what would be the maximum additional jitter. However
       
  4932 some applications demand a minimum jitter. For this reason the master
       
  4933 access can be prohibited by the realtime module: If the time, another
       
  4934 process wants to access the master, is to close to the beginning of
       
  4935 the next realtime cycle, the module can disallow, that the lock is
       
  4936 taken. In this case, the request callback has to return $1$, meaning
       
  4937 that the lock has not been taken. The foreign process must abort its
       
  4938 master access and try again next time.
       
  4939 
       
  4940 This measure helps to significantly reducing the jitter produced by
       
  4941 concurrent master access. Below are exerpts of an example coding:
       
  4942 
       
  4943 \begin{lstlisting}[language=C,numbers=left,caption={Variables for
       
  4944     jitter reduction},label={lst:redvar}]
       
  4945   #define FREQUENCY 10000 // RTAI task frequency in Hz
       
  4946   // ...
       
  4947   cycles_t t_last_cycle = 0;
       
  4948   const cycles_t t_critical = cpu_khz * 1000 / FREQUENCY
       
  4949                               - cpu_khz * 30 / 1000;
       
  4950 \end{lstlisting}
       
  4951 
       
  4952 \begin{description}
       
  4953 \item[\normalfont\textcircled{\tiny 3}] The variable
       
  4954   \textit{t\_last\_cycle} holds the timer ticks at the beginning of
       
  4955   the last realtime cycle.
       
  4956 \item[\normalfont\textcircled{\tiny 4}] \textit{t\_critical} contains
       
  4957   the number of ticks, that may have passed since the beginning of the
       
  4958   last cycle, until there is no more foreign access possible. It is
       
  4959   calculated by substracting the ticks for $30$~\textmu s from the
       
  4960   ticks for a complete cycle.
       
  4961 \end{description}
       
  4962 
       
  4963 \begin{lstlisting}[language=C,numbers=left,caption={Cyclic function
       
  4964     with reduced jitter},label={lst:redrun}]
       
  4965   void run(long data)
       
  4966   {
       
  4967           while (1) {
       
  4968                   t_last_cycle = get_cycles();
       
  4969                   rt_sem_wait(&master_sem);
       
  4970                   // ...
       
  4971 \end{lstlisting}
       
  4972 
       
  4973 \begin{description}
       
  4974 \item[\normalfont\textcircled{\tiny 4}] The ticks of the beginning of
       
  4975   the current realtime cycle are taken before reserving the semaphore.
       
  4976 \end{description}
       
  4977 
       
  4978 \begin{lstlisting}[language=C,numbers=left,caption={Request callback
       
  4979     for reduced jitter},label={lst:redreq}]
       
  4980   int request_lock(void *data)
       
  4981   {
       
  4982           // too close to the next RT cycle: deny access.
       
  4983           if (get_cycles() - t_last_cycle > t_critical)
       
  4984                   return -1;
       
  4985 
       
  4986           // allow access
       
  4987           rt_sem_wait(&master_sem);
       
  4988           return 0;
       
  4989   }
       
  4990 \end{lstlisting}
       
  4991 
       
  4992 \begin{description}
       
  4993 \item[\normalfont\textcircled{\tiny 4}] If the time of request is too
       
  4994   close to the next realtime cycle (here: \textless~$30$~\textmu s
       
  4995   before the estimated beginning), the locking is denied. The
       
  4996   requesting process must abort its cycle.
       
  4997 \end{description}
       
  4998 
       
  4999 %------------------------------------------------------------------------------
       
  5000 
       
  5001 \begin{thebibliography}{99}
       
  5002 \bibitem{etherlab} Ingenieurgemeinschaft IgH: EtherLab -- Open Source
       
  5003   Toolkit for rapid realtime code generation under Linux with
       
  5004   Simulink/RTW and EtherCAT technology. URL: http://etherlab.org,
       
  5005   July~31, 2006.
       
  5006 \bibitem{dlspec} IEC 61158-4-12: Data-link Protocol Specification.
       
  5007   International Electrotechnical Comission (IEC), 2005.
       
  5008 \bibitem{alspec} IEC 61158-6-12: Application Layer Protocol
       
  5009   Specification. International Electrotechnical Comission (IEC), 2005.
       
  5010 \bibitem{gpl} GNU General Public License, Version 2. URL:
       
  5011   http://www.gnu.org/licenses/gpl.txt. August~9, 2006.
       
  5012 \bibitem{lsb} Linux Standard Base. URL:
       
  5013   http://www.freestandards.org/en/LSB. August~9, 2006.
       
  5014 \bibitem{wireshark} Wireshark. URL: http://www.wireshark.org.
       
  5015   August~9, 2006.
       
  5016 \bibitem{automata} {\it Hopcroft, J.~E. / Ullman, J.~D.}: Introduction
       
  5017   to Automata Theory, Languages and Computation. Adison-Wesley,
       
  5018   Reading, Mass.~1979.
       
  5019 \bibitem{fsmmis} {\it Wagner, F. / Wolstenholme, P.}: State machine
       
  5020   misunderstandings. In: IEE journal ``Computing and Control
       
  5021   Engineering'', 2004.
       
  5022 \bibitem{rtai} RTAI. The RealTime Application Interface for Linux from
       
  5023   DIAPM. URL: http://www.rtai.org, 2006.
       
  5024 \end{thebibliography}
       
  5025 
       
  5026 \printglossary
       
  5027 \addcontentsline{toc}{chapter}{\nomname}
       
  5028 \markleft{\nomname}
       
  5029 
       
  5030 \printindex
       
  5031 \markleft{Index}
       
  5032 
       
  5033 %------------------------------------------------------------------------------
       
  5034 
       
  5035 \end{document}
       
  5036 
       
  5037 %------------------------------------------------------------------------------