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