documentation/ethercat_doc.tex
branchstable-1.4
changeset 1630 ffa89570d84f
parent 1140 cc779f7d2496
child 1641 e260d76b9c70
equal deleted inserted replaced
1629:70040a399528 1630:ffa89570d84f
     2 %
     2 %
     3 %  IgH EtherCAT Master Documentation
     3 %  IgH EtherCAT Master Documentation
     4 %
     4 %
     5 %  $Id$
     5 %  $Id$
     6 %
     6 %
     7 %  vi: spell spelllang=en
     7 %  vi: spell spelllang=en tw=78
     8 % 
     8 % 
     9 %------------------------------------------------------------------------------
     9 %------------------------------------------------------------------------------
    10 
       
    11 %
       
    12 %   Conventions
       
    13 % The IgH EtherCAT Master
       
    14 %   Feature Summary
       
    15 %   License
       
    16 % Architecture
       
    17 %   Phases
       
    18 %   Behavior (Scanning) TODO
       
    19 % Application Interface
       
    20 %   Interface version
       
    21 %   Master Requesting and Releasing
       
    22 %   Master Locking
       
    23 %   Slave configuration
       
    24 %   Configuring Pdo assignment and mapping
       
    25 %   Domains (memory)
       
    26 %   Pdo entry registration
       
    27 %   Sdo configuration
       
    28 %   Sdo access
       
    29 %   Cyclic operation
       
    30 % Ethernet Devices
       
    31 %   Device Interface
       
    32 %   Device Modules
       
    33 %   Network Driver Basics
       
    34 %   EtherCAT Network Drivers
       
    35 %   Device Selection
       
    36 %   The Device Interface
       
    37 %   Patching Network Drivers
       
    38 % The Master's State Machines
       
    39 %   Master
       
    40 %   Slave scanning
       
    41 %     SII
       
    42 %     Pdo assign/mapping
       
    43 %   Slave configuration
       
    44 %     State change
       
    45 %     Pdo assign/mapping
       
    46 %   CoE upload/download/information
       
    47 % Mailbox Protocol Implementations
       
    48 %     Ethernet-over-EtherCAT (EoE)
       
    49 %     CANopen-over-EtherCAT (CoE)
       
    50 % User Space
       
    51 %     The ethercat command
       
    52 %     System Integration
       
    53 %         The EtherCAT Init Script
       
    54 %         The EtherCAT Sysconfig File
       
    55 %     Monitoring and Debugging
       
    56 % Installation
       
    57 % Example applications
       
    58 % Bibliography
       
    59 % Glossary
       
    60 %
       
    61 
    10 
    62 \documentclass[a4paper,12pt,BCOR6mm,bibtotoc,idxtotoc]{scrbook}
    11 \documentclass[a4paper,12pt,BCOR6mm,bibtotoc,idxtotoc]{scrbook}
    63 
    12 
    64 \usepackage[latin1]{inputenc}
    13 \usepackage[latin1]{inputenc}
    65 \usepackage[automark,headsepline]{scrpage2}
    14 \usepackage[automark,headsepline]{scrpage2}
   131   \begin{center}
    80   \begin{center}
   132     \rule{\textwidth}{1.5mm}
    81     \rule{\textwidth}{1.5mm}
   133 
    82 
   134     {\Huge\bf IgH \includegraphics[height=2.4ex]{images/ethercat}
    83     {\Huge\bf IgH \includegraphics[height=2.4ex]{images/ethercat}
   135       Master \masterversion\\[1ex]
    84       Master \masterversion\\[1ex]
   136       Documentation}
    85       Preliminary Documentation}
   137 
    86 
   138     \vspace{1ex}
    87     \vspace{1ex}
   139     \rule{\textwidth}{1.5mm}
    88     \rule{\textwidth}{1.5mm}
   140 
    89 
   141     \vspace{\fill}
    90     \vspace{\fill} {\Large Dipl.-Ing. (FH) Florian Pose,
   142     {\Large Florian Pose, \url{fp@igh-essen.com}\\[1ex]
    91     \url{fp@igh-essen.com}\\[1ex] Ingenieurgemeinschaft \IgH}
   143       Ingenieurgemeinschaft \IgH}
       
   144 
    92 
   145     \vspace{\fill}
    93     \vspace{\fill}
   146     {\Large Essen, \SVNDate\\[1ex]
    94     {\Large Essen, \SVNDate\\[1ex]
   147       Revision \SVNRevision}
    95       Revision \SVNRevision}
   148   \end{center}
    96   \end{center}
   151 %------------------------------------------------------------------------------
    99 %------------------------------------------------------------------------------
   152 
   100 
   153 \tableofcontents
   101 \tableofcontents
   154 \listoftables
   102 \listoftables
   155 \listoffigures
   103 \listoffigures
   156 \lstlistoflistings
   104 %\lstlistoflistings
   157 
   105 
   158 %------------------------------------------------------------------------------
   106 %------------------------------------------------------------------------------
   159 
   107 
   160 \newpage
   108 \newpage
   161 \pagestyle{scrheadings}
   109 \pagestyle{scrheadings}
   248 
   196 
   249   \item It runs well even without realtime extensions.
   197   \item It runs well even without realtime extensions.
   250 
   198 
   251   \end{itemize}
   199   \end{itemize}
   252 
   200 
   253 \item Common ``realtime interface'' for applications, that want to use
   201 \item Common ``Application Interface'' for applications, that want to use
   254 EtherCAT functionality (see section~\ref{sec:ecrt}).
   202 EtherCAT functionality (see section~\ref{sec:ecrt}).
   255 
   203 
   256 \item \textit{Domains} are introduced, to allow grouping of process
   204 \item \textit{Domains} are introduced, to allow grouping of process
   257   data transfers with different slave groups and task periods.
   205   data transfers with different slave groups and task periods.
   258 
   206 
   381 \paragraph{Master Module}
   329 \paragraph{Master Module}
   382 \index{Master module}
   330 \index{Master module}
   383 
   331 
   384 Kernel module containing one or more EtherCAT master instances (see
   332 Kernel module containing one or more EtherCAT master instances (see
   385 section~\ref{sec:mastermod}), the ``Device Interface'' (see
   333 section~\ref{sec:mastermod}), the ``Device Interface'' (see
   386 section~\ref{sec:ecdev}) and the ``Realtime Interface'' (see
   334 section~\ref{sec:ecdev}) and the ``Application Interface'' (see
   387 section~\ref{sec:ecrt}).
   335 section~\ref{sec:ecrt}).
   388 
   336 
   389 \paragraph{Device Modules}
   337 \paragraph{Device Modules}
   390 \index{Device modules}
   338 \index{Device modules}
   391 
   339 
   401 \index{Application module}
   349 \index{Application module}
   402 
   350 
   403 Kernel modules, that use the EtherCAT master (usually for cyclic exchange of
   351 Kernel modules, that use the EtherCAT master (usually for cyclic exchange of
   404 process data with EtherCAT slaves). These modules are not part of the EtherCAT
   352 process data with EtherCAT slaves). These modules are not part of the EtherCAT
   405 master code\footnote{Although there are some examples provided in the
   353 master code\footnote{Although there are some examples provided in the
   406 \textit{examples} directory, see chapter~\ref{chapter:examples}}, but have to
   354 \textit{examples/} directory.}, but have to be generated or written by the
   407 be generated or written by the user. An application module can ``request'' a
   355 user. An application module can ``request'' a master through the application
   408 master through the realtime interface (see section~\ref{sec:ecrt}). If this
   356 interface (see section~\ref{sec:ecrt}). If this succeeds, the module has the
   409 succeeds, the module has the control over the master: It can provide a bus
   357 control over the master: It can provide a bus configuration and exchange
   410 configuration and exchange process data.
   358 process data.
   411 
   359 
   412 %------------------------------------------------------------------------------
   360 %------------------------------------------------------------------------------
   413 
   361 
   414 \section{Phases}
   362 \section{Phases}
   415 \index{Master phases}
   363 \index{Master phases}
   441 
   389 
   442 \end{description}
   390 \end{description}
   443 
   391 
   444 %------------------------------------------------------------------------------
   392 %------------------------------------------------------------------------------
   445 
   393 
   446 \section{General behavior} % FIXME
   394 \section{General Behavior} % FIXME
   447 \index{Master behavior}
   395 \index{Master behavior}
   448 
   396 
   449 \ldots
   397 \ldots
   450 
   398 
       
   399 %   Behavior (Scanning) TODO
       
   400 
   451 %------------------------------------------------------------------------------
   401 %------------------------------------------------------------------------------
   452 
   402 
   453 \section{Master Module}
   403 \section{Master Module}
   454 \label{sec:mastermodule}
   404 \label{sec:mastermod}
   455 \index{Master module}
   405 \index{Master module}
   456 
   406 
   457 The EtherCAT master kernel module \textit{ec\_master} can contain multiple
   407 The EtherCAT master kernel module \textit{ec\_master} can contain multiple
   458 master instances. Each master waits for a certain Ethernet device identified
   408 master instances. Each master waits for a certain Ethernet device identified
   459 by its MAC address\index{MAC address}. These addresses have to be specified on
   409 by its MAC address\index{MAC address}. These addresses have to be specified on
   475 # `\textbf{modprobe ec\_master main\_devices=00:0E:0C:DA:A2:20,00:e0:81:71:d5:1c}`
   425 # `\textbf{modprobe ec\_master main\_devices=00:0E:0C:DA:A2:20,00:e0:81:71:d5:1c}`
   476 \end{lstlisting}
   426 \end{lstlisting}
   477 
   427 
   478 The two masters can be addressed by their indices 0 and 1 respectively (see
   428 The two masters can be addressed by their indices 0 and 1 respectively (see
   479 figure~\ref{fig:masters}). The master index is needed for the
   429 figure~\ref{fig:masters}). The master index is needed for the
   480 \lstinline+ecrt_master_request()+ function of the realtime interface (see
   430 \lstinline+ecrt_master_request()+ function of the application interface (see
   481 section~\ref{sec:ecrt}) and the \lstinline+--master+ option of the
   431 section~\ref{sec:ecrt}) and the \lstinline+--master+ option of the
   482 \textit{ethercat} command-line tool (see section~\ref{sec:ethercat}), which
   432 \textit{ethercat} command-line tool (see section~\ref{sec:ethercat}), which
   483 defaults to $0$.
   433 defaults to $0$.
   484 
   434 
   485 \begin{figure}[htbp]
   435 \begin{figure}[htbp]
   607 
   557 
   608 \chapter{Application Interface}
   558 \chapter{Application Interface}
   609 \label{sec:ecrt}
   559 \label{sec:ecrt}
   610 \index{Application interface}
   560 \index{Application interface}
   611 
   561 
       
   562 %   Interface version
       
   563 %   Master Requesting and Releasing
       
   564 %   Master Locking
       
   565 %   Slave configuration
       
   566 %   Configuring Pdo assignment and mapping
       
   567 %   Domains (memory)
       
   568 %   Pdo entry registration
       
   569 %   Sdo configuration
       
   570 %   Sdo access
       
   571 %   Cyclic operation
       
   572 
   612 The application interface provides functions and data structures for
   573 The application interface provides functions and data structures for
   613 applications to access and use an EtherCAT master. The complete documentation
   574 applications to access and use an EtherCAT master. The complete documentation
   614 of the interface is included as Doxygen~\cite{doxygen} comments in the header
   575 of the interface is included as Doxygen~\cite{doxygen} comments in the header
   615 file \textit{include/ecrt.h}. You can either directly view the file comments
   576 file \textit{include/ecrt.h}. You can either directly view the file comments
   616 or generate an HTML documentation as described in section~\ref{sec:gendoc}.
   577 or generate an HTML documentation as described in section~\ref{sec:gendoc}.
   629 \item[Operation] Cyclic code is run, process data is exchanged (see
   590 \item[Operation] Cyclic code is run, process data is exchanged (see
   630 section~\ref{sec:cyclic}).
   591 section~\ref{sec:cyclic}).
   631 
   592 
   632 \end{description}
   593 \end{description}
   633 
   594 
       
   595 \paragraph{Example Applications} \index{Example Applications} There are a few
       
   596 example applications in the \textit{examples/} subdirectory of the master
       
   597 code. They are documented in the source code.
       
   598 
   634 %------------------------------------------------------------------------------
   599 %------------------------------------------------------------------------------
   635 
   600 
   636 \section{Master Configuration}
   601 \section{Master Configuration}
   637 \label{sec:masterconfig}
   602 \label{sec:masterconfig}
   638 
   603 
   639 \ldots
   604 \ldots
       
   605 % FIXME Attaching
   640 
   606 
   641 \begin{figure}[htbp]
   607 \begin{figure}[htbp]
   642   \centering
   608   \centering
   643   \includegraphics[width=.8\textwidth]{images/app-config}
   609   \includegraphics[width=.8\textwidth]{images/app-config}
   644   \caption{Master configuration structures}
   610   \caption{Master Configuration}
   645   \label{fig:app-config}
   611   \label{fig:app-config}
   646 \end{figure}
   612 \end{figure}
   647 
   613 
   648 %------------------------------------------------------------------------------
   614 %------------------------------------------------------------------------------
   649 
   615 
   666 section~\ref{sec:eoeimp}). For this reason, the master is a shared resource,
   632 section~\ref{sec:eoeimp}). For this reason, the master is a shared resource,
   667 and access to it has to be sequentialized. This is usually done by locking with
   633 and access to it has to be sequentialized. This is usually done by locking with
   668 semaphores, or other methods to protect critical sections.
   634 semaphores, or other methods to protect critical sections.
   669 
   635 
   670 The master itself can not provide locking mechanisms, because it has no chance
   636 The master itself can not provide locking mechanisms, because it has no chance
   671 to know the appropriate kind of lock. Imagine, the application uses RTAI
   637 to know the appropriate kind of lock. For example if the application uses RTAI
   672 functionality, then ordinary kernel semaphores would not be sufficient. For
   638 functionality, ordinary kernel semaphores would not be sufficient. For that, an
   673 that, an important design decision was made: The application that reserved a
   639 important design decision was made: The application that reserved a master must
   674 master must have the total control, therefore it has to take responsibility for
   640 have the total control, therefore it has to take responsibility for providing
   675 providing the appropriate locking mechanisms. If another instance wants to
   641 the appropriate locking mechanisms. If another instance wants to access the
   676 access the master, it has to request the master lock by callbacks, that have to
   642 master, it has to request the master lock by callbacks, that have to be set by
   677 be set by the application. Moreover the application can deny access to the
   643 the application. Moreover the application can deny access to the master if it
   678 master if it considers it to be awkward at the moment.
   644 considers it to be awkward at the moment.
   679 
   645 
   680 \begin{figure}[htbp]
   646 \begin{figure}[htbp]
   681   \centering
   647   \centering
   682   \includegraphics[width=.6\textwidth]{images/master-locks}
   648   \includegraphics[width=.6\textwidth]{images/master-locks}
   683   \caption{Concurrent master access}
   649   \caption{Concurrent master access}
   684   \label{fig:locks}
   650   \label{fig:locks}
   685 \end{figure}
   651 \end{figure}
   686 
   652 
   687 Figure~\ref{fig:locks} exemplary shows, how two processes share one master: The
   653 Figure~\ref{fig:locks} exemplary shows, how two processes share one master:
   688 application's cyclic task uses the master for process data exchange, while the
   654 The application's cyclic task uses the master for process data exchange, while
   689 master-internal EoE process uses it to communicate with EoE-capable slaves.
   655 the master-internal EoE process uses it to communicate with EoE-capable
   690 Both have to acquire the master lock before access: The application task can
   656 slaves.  Both have to acquire the master lock before access: The application
   691 access the lock natively, while the EoE process has to use the callbacks.
   657 task can access the lock natively, while the EoE process has to use the
   692 Section~\ref{sec:concurrency} gives an example, of how to implement this.
   658 callbacks.  See the application interface documentation
   693 
   659 (section~\ref{sec:ecrt} of how to use the locking callbacks.
   694 %------------------------------------------------------------------------------
   660 
   695 
   661 %------------------------------------------------------------------------------
   696 \chapter{Ethernet devices}
   662 
       
   663 \chapter{Ethernet Devices}
   697 \label{sec:devices}
   664 \label{sec:devices}
   698 
   665 
   699 The EtherCAT protocol is based on the Ethernet standard. That's why the master
   666 The EtherCAT protocol is based on the Ethernet standard, so a master relies on
   700 relies on standard Ethernet hardware to communicate with the bus.
   667 standard Ethernet hardware to communicate with the bus.
   701 
   668 
   702 The term \textit{device} is used as a synonym for Ethernet network interface
   669 The term \textit{device} is used as a synonym for Ethernet network interface
   703 hardware. There are device driver modules that handle Ethernet hardware, which
   670 hardware. There are device driver modules that handle Ethernet hardware, which
   704 the master can use to connect to an EtherCAT bus.
   671 a master can use to connect to an EtherCAT bus.
   705 
       
   706 Section~\ref{sec:networkdrivers} offers an overview of general Linux
       
   707 network driver modules, while section~\ref{sec:requirements} will show
       
   708 the requirements to an EtherCAT-enabled network driver. Finally,
       
   709 sections~\ref{sec:seldev} to~\ref{sec:patching} show how to fulfill
       
   710 these requirements and implement such a driver module.
       
   711 
   672 
   712 %------------------------------------------------------------------------------
   673 %------------------------------------------------------------------------------
   713 
   674 
   714 \section{Network Driver Basics}
   675 \section{Network Driver Basics}
   715 \label{sec:networkdrivers}
   676 \label{sec:networkdrivers}
   753 hardware interrupt), the reason for the interrupt has to be determined
   714 hardware interrupt), the reason for the interrupt has to be determined
   754 by reading the device's interrupt register. For example, if the flag
   715 by reading the device's interrupt register. For example, if the flag
   755 for received frames is set, frame data has to be copied from hardware
   716 for received frames is set, frame data has to be copied from hardware
   756 to kernel memory and passed to the network stack.
   717 to kernel memory and passed to the network stack.
   757 
   718 
   758 \paragraph{The net\_device structure}
   719 \paragraph{The \lstinline+net_device+ Structure}
   759 \index{net\_device}
   720 \index{net\_device}
   760 
   721 
   761 The driver registers a \textit{net\_device} structure for each device
   722 The driver registers a \lstinline+net_device+ structure for each device to
   762 to communicate with the network stack and to create a ``network
   723 communicate with the network stack and to create a ``network interface''. In
   763 interface''. In case of an Ethernet driver, this interface appears as
   724 case of an Ethernet driver, this interface appears as \textit{ethX}, where X is
   764 \textit{ethX}, where X is a number assigned by the kernel on
   725 a number assigned by the kernel on registration. The \lstinline+net_device+
   765 registration. The \textit{net\_device} structure receives events
   726 structure receives events (either from user space or from the network stack)
   766 (either from user space or from the network stack) via several
   727 via several callbacks, which have to be set before registration. Not every
   767 callbacks, which have to be set before registration. Not every
   728 callback is mandatory, but for reasonable operation the ones below are needed
   768 callback is mandatory, but for reasonable operation the ones below are
   729 in any case:
   769 needed in any case:
   730 
       
   731 \newsavebox\boxopen
       
   732 \sbox\boxopen{\lstinline+open()+}
       
   733 \newsavebox\boxstop
       
   734 \sbox\boxstop{\lstinline+stop()+}
       
   735 \newsavebox\boxxmit
       
   736 \sbox\boxxmit{\lstinline+hard_start_xmit()+}
       
   737 \newsavebox\boxstats
       
   738 \sbox\boxstats{\lstinline+get_stats()+}
   770 
   739 
   771 \begin{description}
   740 \begin{description}
   772 
   741 
   773 \item[open()] This function is called when network communication has to be
   742 \item[\usebox\boxopen] This function is called when network communication has
   774 started, for example after a command \textit{ifconfig ethX up} from user
   743 to be started, for example after a command \lstinline+ip link set ethX up+ from
   775 space. Frame reception has to be enabled by the driver.
   744 user space. Frame reception has to be enabled by the driver.
   776 
   745 
   777 \item[stop()] The purpose of this callback is to ``close'' the device, i.~e.
   746 \item[\usebox\boxstop] The purpose of this callback is to ``close'' the device,
   778 make the hardware stop receiving frames.
   747 i.~e.  make the hardware stop receiving frames.
   779 
   748 
   780 \item[hard\_start\_xmit()] This function is cal\-led for each frame that has
   749 \item[\usebox\boxxmit] This function is called for each frame that has to be
   781 to be transmitted. The network stack passes the frame as a pointer to an
   750 transmitted. The network stack passes the frame as a pointer to an
   782 \textit{sk\_buff} structure (``socket buffer''\index{Socket buffer}, see
   751 \lstinline+sk_buff+ structure (``socket buffer''\index{Socket buffer}, see
   783 below), which has to be freed after sending.
   752 below), which has to be freed after sending.
   784 
   753 
   785 \item[get\_stats()] This call has to return a pointer to the device's
   754 \item[\usebox\boxstats] This call has to return a pointer to the device's
   786 \textit{net\_device\_stats} structure, which permanently has to be filled with
   755 \lstinline+net_device_stats+ structure, which permanently has to be filled with
   787 frame statistics. This means, that every time a frame is received, sent, or an
   756 frame statistics. This means, that every time a frame is received, sent, or an
   788 error happened, the appropriate counter in this structure has to be increased.
   757 error happened, the appropriate counter in this structure has to be increased.
   789 
   758 
   790 \end{description}
   759 \end{description}
   791 
   760 
   792 The actual registration is done with the \lstinline+register_netdev()+ call,
   761 The actual registration is done with the \lstinline+register_netdev()+ call,
   793 unregistering is done with \lstinline+unregister_netdev()+.
   762 unregistering is done with \lstinline+unregister_netdev()+.
   794 
   763 
   795 \paragraph{The netif Interface}
   764 \paragraph{The \lstinline+netif+ Interface}
   796 \index{netif}
   765 \index{netif}
   797 
   766 
   798 All other communication in the direction interface $\to$ network stack is done
   767 All other communication in the direction interface $\to$ network stack is done
   799 via the \lstinline+netif_*()+ calls. For example, on successful device
   768 via the \lstinline+netif_*()+ calls. For example, on successful device opening,
   800 opening, the network stack has to be notified, that it can now pass frames to
   769 the network stack has to be notified, that it can now pass frames to the
   801 the interface.  This is done by calling \lstinline+netif_start_queue()+. After
   770 interface. This is done by calling \lstinline+netif_start_queue()+. After this
   802 this call, the \lstinline+hard_start_xmit()+ callback can be called by the
   771 call, the \lstinline+hard_start_xmit()+ callback can be called by the network
   803 network stack.  Furthermore a network driver usually manages a frame
   772 stack. Furthermore a network driver usually manages a frame transmission queue.
   804 transmission queue. If this gets filled up, the network stack has to be told
   773 If this gets filled up, the network stack has to be told to stop passing
   805 to stop passing further frames for a while. This happens with a call to
   774 further frames for a while. This happens with a call to
   806 \lstinline+netif_stop_queue()+.  If some frames have been sent, and there is
   775 \lstinline+netif_stop_queue()+. If some frames have been sent, and there is
   807 enough space again to queue new frames, this can be notified with
   776 enough space again to queue new frames, this can be notified with
   808 \lstinline+netif_wake_queue()+. Another important call is
   777 \lstinline+netif_wake_queue()+. Another important call is
   809 \lstinline+netif_receive_skb()+\footnote{This function is part of the NAPI
   778 \lstinline+netif_receive_skb()+\footnote{This function is part of the NAPI
   810 (``New API''), that replaces the kernel 2.4 technique for interfacing to the
   779 (``New API''), that replaces the kernel 2.4 technique for interfacing to the
   811 network stack (with \lstinline+netif_rx()+). NAPI is a technique to improve
   780 network stack (with \lstinline+netif_rx()+). NAPI is a technique to improve
   812 network performance on Linux. Read more in
   781 network performance on Linux. Read more in
   813 \url{http://www.cyberus.ca/~hadi/usenix-paper.tgz}.}: It passes a frame to the
   782 \url{http://www.cyberus.ca/~hadi/usenix-paper.tgz}.}: It passes a frame to the
   814 network stack, that was just received by the device. Frame data has to be
   783 network stack, that was just received by the device. Frame data has to be
   815 packed into a so-called ``socket buffer'' for that (see below).
   784 included in a so-called ``socket buffer'' for that (see below).
   816 
   785 
   817 \paragraph{Socket Buffers}
   786 \paragraph{Socket Buffers}
   818 \index{Socket buffer}
   787 \index{Socket buffer}
   819 
   788 
   820 Socket buffers are the basic data type for the whole network stack.  They
   789 Socket buffers are the basic data type for the whole network stack. They serve
   821 serve as containers for network data and are able to quickly add data headers
   790 as containers for network data and are able to quickly add data headers and
   822 and footers, or strip them off again. Therefore a socket buffer consists of an
   791 footers, or strip them off again. Therefore a socket buffer consists of an
   823 allocated buffer and several pointers that mark beginning of the buffer
   792 allocated buffer and several pointers that mark beginning of the buffer
   824 (\textit{head}), beginning of data (\textit{data}), end of data
   793 (\lstinline+head+), beginning of data (\lstinline+data+), end of data
   825 (\textit{tail}) and end of buffer (\textit{end}). In addition, a socket buffer
   794 (\lstinline+tail+) and end of buffer (\lstinline+end+). In addition, a socket
   826 holds network header information and (in case of received data) a pointer to
   795 buffer holds network header information and (in case of received data) a
   827 the \textit{net\_device}, it was received on. There exist functions that
   796 pointer to the \lstinline+net_device+, it was received on. There exist
   828 create a socket buffer (\lstinline+dev_alloc_skb()+), add data either from
   797 functions that create a socket buffer (\lstinline+dev_alloc_skb()+), add data
   829 front (\lstinline+skb_push()+) or back (\lstinline+skb_put()+), remove data
   798 either from front (\lstinline+skb_push()+) or back (\lstinline+skb_put()+),
   830 from front (\lstinline+skb_pull()+) or back (\lstinline+skb_trim()+), or
   799 remove data from front (\lstinline+skb_pull()+) or back
   831 delete the buffer (\lstinline+kfree_skb()+).  A socket buffer is passed from
   800 (\lstinline+skb_trim()+), or delete the buffer (\lstinline+kfree_skb()+).  A
   832 layer to layer, and is freed by the layer that uses it the last time. In case
   801 socket buffer is passed from layer to layer, and is freed by the layer that
   833 of sending, freeing has to be done by the network driver.
   802 uses it the last time. In case of sending, freeing has to be done by the
       
   803 network driver.
   834 
   804 
   835 %------------------------------------------------------------------------------
   805 %------------------------------------------------------------------------------
   836 
   806 
   837 \section{EtherCAT Device Drivers}
   807 \section{EtherCAT Device Drivers}
   838 \label{sec:requirements}
   808 \label{sec:ethercatdrivers}
   839 
   809 
   840 There are a few requirements for Ethernet network devices to function as
   810 There are a few requirements for Ethernet network devices to function as
   841 EtherCAT devices, when connected to an EtherCAT bus.
   811 EtherCAT devices, when connected to an EtherCAT bus.
   842 
   812 
   843 \paragraph{Dedicated Interfaces}
   813 \paragraph{Dedicated Interfaces}
   844 
   814 
   845 For performance and realtime purposes, the EtherCAT master needs direct and
   815 For performance and realtime purposes, the EtherCAT master needs direct and
   846 exclusive access to the Ethernet hardware. This implies that the network
   816 exclusive access to the Ethernet hardware. This implies that the network device
   847 device must not be connected to the kernel's network stack as usual, because
   817 must not be connected to the kernel's network stack as usual, because the
   848 the kernel would try to use it as an ordinary Ethernet device.
   818 kernel would try to use it as an ordinary Ethernet device.
   849 
   819 
   850 \paragraph{Interrupt-less Operation}
   820 \paragraph{Interrupt-less Operation}
   851 \index{Interrupt}
   821 \index{Interrupt}
   852 
   822 
   853 EtherCAT frames travel through the logical EtherCAT ring and are then sent
   823 EtherCAT frames travel through the logical EtherCAT ring and are then sent back
   854 back to the master. Communication is highly deterministic: A frame is sent and
   824 to the master. Communication is highly deterministic: A frame is sent and will
   855 will be received again after a constant time.  Therefore, there is no need to
   825 be received again after a constant time, so there is no need to notify the
   856 notify the driver about frame reception: The master can instead query the
   826 driver about frame reception: The master can instead query the hardware for
   857 hardware for received frames.
   827 received frames, if it expects them to be already received.
   858 
   828 
   859 Figure~\ref{fig:interrupt} shows two workflows for cyclic frame transmission
   829 Figure~\ref{fig:interrupt} shows two workflows for cyclic frame transmission
   860 and reception with and without interrupts.
   830 and reception with and without interrupts.
   861 
   831 
   862 \begin{figure}[htbp]
   832 \begin{figure}[htbp]
   863   \centering
   833   \centering
   864   \includegraphics[width=.8\textwidth]{images/interrupt}
   834   \includegraphics[width=.9\textwidth]{images/interrupt}
   865   \caption{Interrupt Operation versus Interrupt-less Operation}
   835   \caption{Interrupt Operation versus Interrupt-less Operation}
   866   \label{fig:interrupt}
   836   \label{fig:interrupt}
   867 \end{figure}
   837 \end{figure}
   868 
   838 
   869 In the left workflow ``Interrupt Operation'', the data from the last cycle is
   839 In the left workflow ``Interrupt Operation'', the data from the last cycle is
   879 executing the ISR. If the frame has been received in the meantime, it will be
   849 executing the ISR. If the frame has been received in the meantime, it will be
   880 dissected. The situation is now the same as at the beginning of the left
   850 dissected. The situation is now the same as at the beginning of the left
   881 workflow: The received data is processed and a new frame is assembled and
   851 workflow: The received data is processed and a new frame is assembled and
   882 sent. There is nothing to do for the rest of the cycle.
   852 sent. There is nothing to do for the rest of the cycle.
   883 
   853 
   884 The interrupt-less operation is desirable, because there is simply no need for
   854 The interrupt-less operation is desirable, because hardware interrupts are not
   885 an interrupt. Moreover hardware interrupts are not conducive in improving the
   855 conducive in improving the driver's realtime behaviour: Their indeterministic
   886 driver's realtime behaviour: Their indeterministic incidences contribute to
   856 incidences contribute to increasing the jitter. Besides, if a realtime
   887 increasing the jitter. Besides, if a realtime extension (like RTAI) is used,
   857 extension (like RTAI) is used, some additional effort would have to be made to
   888 some additional effort would have to be made to prioritize interrupts.
   858 prioritize interrupts.
   889 
   859 
   890 \paragraph{Ethernet and EtherCAT Devices}
   860 \paragraph{Ethernet and EtherCAT Devices}
   891 
   861 
   892 Another issue lies in the way Linux handles devices of the same type.  For
   862 Another issue lies in the way Linux handles devices of the same type.  For
   893 example, a PCI\nomenclature{PCI}{Peripheral Component Interconnect, Computer
   863 example, a PCI\nomenclature{PCI}{Peripheral Component Interconnect, Computer
   925 %------------------------------------------------------------------------------
   895 %------------------------------------------------------------------------------
   926 
   896 
   927 \section{Device Selection}
   897 \section{Device Selection}
   928 \label{sec:deviceselection}
   898 \label{sec:deviceselection}
   929 
   899 
   930 After loading the master module, at least one EtherCAT-capable network
   900 After loading the master module, at least one EtherCAT-capable network driver
   931 driver module has to be loaded, that connects one of its devices to
   901 module has to be loaded, that offers its devices to the master (see
   932 the master. To specify an EtherCAT device and the master to connect
   902 section~\ref{sec:ecdev}. The master module knows the devices to choose from the
   933 to, all EtherCAT-capable network driver modules should provide two
   903 module parameters (see section~\ref{sec:mastermod}). If the init script is used
   934 module parameters:
   904 to start the master, the drivers and devices to use can be specified in the
   935 
   905 sysconfig file (see section~\ref{sec:sysconfig}).
   936 \begin{description}
   906 
   937 \item[ec\_device\_index] PCI device index of the device that is
   907 %------------------------------------------------------------------------------
   938   connected to the EtherCAT bus. If this parameter is left away, all
   908 
   939   devices found are treated as ordinary Ethernet devices. Default:
   909 \section{EtherCAT Device Interface}
   940   $-1$
       
   941 \item[ec\_master\_index] Index of the master to connect to. Default:
       
   942   $0$
       
   943 \end{description}
       
   944 
       
   945 The following command loads the EtherCAT-capable RTL8139 device
       
   946 driver, telling it to handle the second device as an EtherCAT device
       
   947 and connecting it to the first master:
       
   948 
       
   949 \begin{lstlisting}[gobble=2]
       
   950   # `\textbf{modprobe ec\_8139too ec\_device\_index=1}`
       
   951 \end{lstlisting}
       
   952 
       
   953 Usually, this command does not have to be entered manually, but is
       
   954 called by the EtherCAT init script. See section~\ref{sec:init} for
       
   955 more information.
       
   956 
       
   957 %------------------------------------------------------------------------------
       
   958 
       
   959 \section{The Device Interface}
       
   960 \label{sec:ecdev}
   910 \label{sec:ecdev}
   961 \index{Device interface}
   911 \index{Device interface}
   962 
   912 
   963 An anticipation to the section about the master module
   913 An anticipation to the section about the master module
   964 (section~\ref{sec:mastermod}) has to be made in order to understand
   914 (section~\ref{sec:mastermod}) has to be made in order to understand
   965 the way, a network device driver module can connect a device to a
   915 the way, a network device driver module can connect a device to a
   966 specific EtherCAT master.
   916 specific EtherCAT master.
   967 
   917 
   968 The master module provides a ``device interface'' for network device
   918 The master module provides a ``device interface'' for network device drivers.
   969 drivers. To use this interface, a network device driver module must
   919 To use this interface, a network device driver module must include the header
   970 include the header
   920 \textit{devices/ecdev.h}\nomenclature{ecdev}{EtherCAT Device}, coming with the
   971 \textit{devices/ecdev.h}\nomenclature{ecdev}{EtherCAT Device}, coming
   921 EtherCAT master code. This header offers a function interface for EtherCAT
   972 with the EtherCAT master code. This header offers a function interface
   922 devices. All functions of the device interface are named with the prefix
   973 for EtherCAT devices which is explained below. All functions of the
   923 \lstinline+ecdev+.
   974 device interface are named with the prefix \textit{ecdev}.
   924 
   975 
   925 The documentation of the device interface can be found in the header file or in
   976 \paragraph{Device Registration}
   926 the appropriate module of the interface documentation (see
   977 
   927 section~\ref{sec:gendoc} for generation instructions).
   978 A network device driver can connect a physical device to an EtherCAT
   928 
   979 master with the \textit{ecdev\_register()} function.
   929 \ldots % FIXME general description of the device interface
   980 
       
   981 \begin{lstlisting}[gobble=2,language=C]
       
   982   ec_device_t *ecdev_register(unsigned int master_index,
       
   983                               struct net_device *net_dev,
       
   984                               ec_isr_t isr,
       
   985                               struct module *module);
       
   986 \end{lstlisting}
       
   987 
       
   988 The first parameter \textit{master\_index} must be the index of the
       
   989 EtherCAT master to connect to (see section~\ref{sec:mastermod}),
       
   990 followed by \textit{net\_dev}, the pointer to the corresponding
       
   991 net\_device structure, which represents the network device to connect.
       
   992 The third parameter \textit{isr} must be a pointer to the interrupt
       
   993 service routine (ISR\index{ISR}) handling the device. The master will
       
   994 later execute the ISR in order to receive frames and to update the
       
   995 device status. The last parameter \textit{module} must be the pointer
       
   996 to the device driver module, which is usually accessible via the macro
       
   997 \textit{THIS\_MODULE} (see next paragraph). On success, the function
       
   998 returns a pointer to an \textit{ec\_device\_t} object, which has to be
       
   999 specified when calling further functions of the device interface.
       
  1000 Therefore the device module has to store this pointer for future use.
       
  1001 In error case, the \textit{ecdev\_register()} returns \textit{NULL},
       
  1002 which means that the device could not be registered.  The reason for
       
  1003 this is printed to \textit{Syslog}\index{Syslog}. In this case, the
       
  1004 device module is supposed to abort the module initialisation and let
       
  1005 the \textit{insmod} command fail.
       
  1006 
       
  1007 \paragraph{Implicit Dependencies}
       
  1008 
       
  1009 The reason for the module pointer has to be specified at device registration is
       
  1010 a non-trivial one: The master has to know about the module, because there will
       
  1011 be an implicit dependency between the device module and a later connected
       
  1012 application module: When an application module connects to the master, the use
       
  1013 count of the master module will be increased, so that the master module can not
       
  1014 be unloaded for the time of the connection. This is reasonable, and so
       
  1015 automatically done by the kernel. The kernel knows about this dependency,
       
  1016 because the application module uses kernel symbols provided by the master
       
  1017 module.  Moreover it is mandatory, that the device module can be unloaded
       
  1018 neither, because it is implicitly used by the application module, too.
       
  1019 Unloading it would lead to a fatal situation, because the master would have no
       
  1020 device to send and receive frames for the application. This dependency can not
       
  1021 be detected automatically, because the application module does not use any
       
  1022 symbols of the device module. Therefore the master explicitly increments the
       
  1023 use counter of the connected device module upon connection of an application
       
  1024 and decrements it, if it disconnects again. In this manner, it is impossible to
       
  1025 unload a device module while the master is in use. This is done with the kernel
       
  1026 function pair \textit{try\_module\_get()}
       
  1027 \index{try\_module\_get@\textit{try\_module\_get()}} and \textit{module\_put()}
       
  1028 \index{module\_put@\textit{module\_put()}}. The first one increases the use
       
  1029 count of a module and only fails, if the module is currently being unloaded.
       
  1030 The last one decreases the use count again and never fails. Both functions take
       
  1031 a pointer to the module as their argument, which the device module therefore
       
  1032 has to specify upon device registration.
       
  1033 
       
  1034 \paragraph{Device Unregistering}
       
  1035 
       
  1036 The deregistration of a device is usually done in the device module's cleanup
       
  1037 function, by calling the \textit{ecdev\_unregister()} function and specifying
       
  1038 the master index and a pointer to the device object again.
       
  1039 
       
  1040 \begin{lstlisting}[gobble=2,language=C]
       
  1041   void ecdev_unregister(unsigned int master_index,
       
  1042                         ec_device_t *device);
       
  1043 \end{lstlisting}
       
  1044 
       
  1045 This function can fail too (if the master index is invalid, or the
       
  1046 given device was not registered), but due to the fact, that this
       
  1047 failure can not be dealt with appropriately, because the device module
       
  1048 is unloading anyway, the failure code would not be of any interest. So
       
  1049 the function has a void return value.
       
  1050 
       
  1051 \paragraph{Starting the Master}
       
  1052 
       
  1053 When a device has been initialized completely and is ready to send and
       
  1054 receive frames, the master has to be notified about this by calling
       
  1055 the \textit{ecdev\_start()} function.
       
  1056 
       
  1057 \begin{lstlisting}[gobble=2,language=C]
       
  1058   int ecdev_start(unsigned int master_index);
       
  1059 \end{lstlisting}
       
  1060 
       
  1061 The master will then enter ``Idle Mode'' and start scanning the bus
       
  1062 (and possibly handling EoE slaves). Moreover it will make the bus
       
  1063 accessible via Sysfs interface and react to user interactions. The
       
  1064 function takes one parameter \textit{master\_index}, which has to be
       
  1065 the same as at the call to \textit{ecdev\_register()}. The return
       
  1066 value will be non-zero if the starting process failed. In this case
       
  1067 the device module is supposed to abort the init sequence and make the
       
  1068 init function return an error code.
       
  1069 
       
  1070 \paragraph{Stopping the Master}
       
  1071 
       
  1072 Before a device can be unregistered, the master has to be stopped by
       
  1073 calling the \textit{ecdev\_stop()} function. It will stop processing
       
  1074 messages of EoE slaves and leave ``Idle Mode''. The only parameter is
       
  1075 \textit{master\_index}. This function can not fail.
       
  1076 
       
  1077 \begin{lstlisting}[gobble=2,language=C]
       
  1078   void ecdev_stop(unsigned int master_index);
       
  1079 \end{lstlisting}
       
  1080 
       
  1081 A subsequent call to \textit{ecdev\_unregister()} will now unregister
       
  1082 the device savely.
       
  1083 
       
  1084 \paragraph{Receiving Frames}
       
  1085 
       
  1086 The interrupt service routine handling device events usually has a
       
  1087 section where new frames are fetched from the hardware and forwarded
       
  1088 to the kernel network stack via \textit{netif\_receive\_skb()}. For an
       
  1089 EtherCAT-capable device, this has to be replaced by calling the
       
  1090 \textit{ecdev\_receive()} function to forward the received data to the
       
  1091 connected EtherCAT master instead.
       
  1092 
       
  1093 \begin{lstlisting}[gobble=2,language=C]
       
  1094   void ecdev_receive(ec_device_t *device,
       
  1095                      const void *data,
       
  1096                      size_t size);
       
  1097 \end{lstlisting}
       
  1098 
       
  1099 This function takes 3 arguments, a pointer to the device object
       
  1100 (\textit{device}), a pointer to the received data, and the size of the
       
  1101 received data. The data range has to include the Ethernet headers
       
  1102 starting with the destination address and reach up to the last octet
       
  1103 of EtherCAT data, excluding the FCS. Most network devices handle the
       
  1104 FCS in hardware, so it is not seen by the driver code and therefore
       
  1105 doesn't have to be cut off manually.
       
  1106 
       
  1107 \paragraph{Handling the Link Status}
       
  1108 
       
  1109 Information about the link status (i.~e. if there is a carrier signal detected
       
  1110 on the physical port) is also important to the master. This information is
       
  1111 usually gathered by the ISR and should be forwarded to the master by calling
       
  1112 the \textit{ecdev\_link\_state()} function. The master then can react on this
       
  1113 and warn the application of a lost link.
       
  1114 
       
  1115 \begin{lstlisting}[gobble=2,language=C]
       
  1116   void ecdev_link_state(ec_device_t *device,
       
  1117                         uint8_t new_state);
       
  1118 \end{lstlisting}
       
  1119 
       
  1120 The parameter \textit{device} has to be a pointer to the device object
       
  1121 returned by \textit{ecdev\_\-register()}. With the second parameter
       
  1122 \textit{new\_state}, the new link state is passed: 1, if the link went
       
  1123 up, and 0, if it went down.
       
  1124 
   930 
  1125 %------------------------------------------------------------------------------
   931 %------------------------------------------------------------------------------
  1126 
   932 
  1127 \section{Patching Network Drivers}
   933 \section{Patching Network Drivers}
  1128 \label{sec:patching}
   934 \label{sec:patching}
  1129 \index{Network drivers}
   935 \index{Network drivers}
  1130 
   936 
  1131 This section will demonstrate, how to make a standard Ethernet driver
   937 This section will describe, how to make a standard Ethernet driver
  1132 EtherCAT-capable. The below code examples are taken out of the
   938 EtherCAT-capable. Unfortunately, there is no standard procedure to enable an
  1133 modified RealTek RTL8139 driver coming with the EtherCAT master
   939 Ethernet driver for use with the EtherCAT master, but there are a few common
  1134 (\textit{devices/8139too.c}). The driver was originally developed by
   940 techniques.
  1135 Donald Becker, and is currently maintained by Jeff Garzik.
       
  1136 
       
  1137 Unfortunately, there is no standard procedure to enable an Ethernet
       
  1138 driver for use with the EtherCAT master, but there are a few common
       
  1139 techniques, that are described in this section.
       
  1140 
   941 
  1141 \begin{enumerate}
   942 \begin{enumerate}
  1142 \item A first simple rule is, that \textit{netif\_*()}-calls must be
   943 
  1143   strictly avoided for all EtherCAT devices. As mentioned before,
   944 \item A first simple rule is, that \lstinline+netif_*()+ calls must be avoided
  1144   EtherCAT devices have no connection to the network stack, and
   945 for all EtherCAT devices. As mentioned before, EtherCAT devices have no
  1145   therefore must not call its interface functions.
   946 connection to the network stack, and therefore must not call its interface
  1146 \item Another important thing is, that EtherCAT devices should be
   947 functions.
  1147   operated without interrupts. So any calls of registering interrupt
   948 
  1148   handlers and enabling interrupts at hardware level must be avoided,
   949 \item Another important thing is, that EtherCAT devices should be operated
  1149   too.
   950 without interrupts. So any calls of registering interrupt handlers and enabling
  1150 \item The master does not use a new socket buffer for each send
   951 interrupts at hardware level must be avoided, too.
  1151   operation: Instead there is a fix one allocated on master
   952 
  1152   initialization. This socket buffer is filled with an EtherCAT frame
   953 \item The master does not use a new socket buffer for each send operation:
  1153   with every send operation and passed to the
   954 Instead there is a fix one allocated on master initialization. This socket
  1154   \textit{hard\_start\_xmit()} callback. For that it is necessary,
   955 buffer is filled with an EtherCAT frame with every send operation and passed to
  1155   that the socket buffer is not be freed by the network driver as
   956 the \lstinline+hard_start_xmit()+ callback. For that it is necessary, that the
  1156   usual.
   957 socket buffer is not be freed by the network driver as usual.
       
   958 
  1157 \end{enumerate}
   959 \end{enumerate}
  1158 
   960 
  1159 As mentioned before, the driver will handle both EtherCAT and ordinary
   961 An Ethernet driver usually handles several Ethernet devices, each described by
  1160 Ethernet devices. This implies, that for each device-dependent
   962 a \lstinline+net_device+ structure with a \lstinline+priv_data+ field to
  1161 operation, it has to be checked if an EtherCAT device is involved, or
   963 attach driver-dependent data to the structure. To distinguish between normal
  1162 just an Ethernet device. For means of simplicity, this example driver
   964 Ethernet devices and the ones used by EtherCAT masters, the private data
  1163 will only handle one EtherCAT device. This makes the case
   965 structure used by the driver could be extended by a pointer, that points to an
  1164 differentiations easier.
   966 \lstinline+ec_device_t+ object returned by \lstinline+ecdev_offer()+ (see
  1165 
   967 section~\ref{sec:ecdev}) if the device is used by a master and otherwise is
  1166 \paragraph{Global Variables}
   968 zero.
  1167 
   969 
  1168 First of all, there have to be additional global variables declared,
   970 The RealTek RTL-8139 Fast Ethernet driver is a ``simple'' Ethernet driver and
  1169 as shown in the listing:
   971 can be taken as an example to patch new drivers. The interesting sections can
  1170 
   972 be found by searching the string ``ecdev" in the file
  1171 \begin{lstlisting}[gobble=2,language=C,numbers=left]
   973 \textit{devices/8139too-2.6.24-ethercat.c}.
  1172   static int ec_device_index = -1;
       
  1173   static int ec_device_master_index = 0;
       
  1174   static ec_device_t *rtl_ec_dev;
       
  1175   struct net_device *rtl_ec_net_dev = NULL;
       
  1176 \end{lstlisting}
       
  1177 
       
  1178 \begin{description}
       
  1179 \item[\linenum{1} -- \linenum{2}] To
       
  1180   comply to the requirements for parameters of EtherCAT device modules
       
  1181   described in section~\ref{sec:seldev}, there have to be additional
       
  1182   parameter variables: \textit{ec\_\-device\_\-index} holds the index
       
  1183   of the EtherCAT device and defaults to $-1$ (no EtherCAT device),
       
  1184   while \textit{ec\_device\_master\_index} stores index of the master,
       
  1185   the single device will be connected to. Default: $0$
       
  1186 \item[\linenum{3}] \textit{rtl\_ec\_dev} will be
       
  1187   the pointer to the later registered RealTek EtherCAT device, which
       
  1188   can be used as a parameter for device methods.
       
  1189 \item[\linenum{4}] \textit{rtl\_ec\_net\_dev} is
       
  1190   a pointer to the \textit{net\_device} structure of the dedicated
       
  1191   device and is set while scanning the PCI bus and finding the device
       
  1192   with the specified index. This is done inside the
       
  1193   \textit{pci\_module\_init()} function executed as the first thing on
       
  1194   module loading.
       
  1195 \end{description}
       
  1196 
       
  1197 \paragraph{Module Initialization}
       
  1198 
       
  1199 Below is the (shortened) coding of the device driver's module init
       
  1200 function:
       
  1201 
       
  1202 \begin{lstlisting}[gobble=2,language=C,numbers=left]
       
  1203   static int __init rtl8139_init_module(void)
       
  1204   {
       
  1205           if (pci_module_init(&rtl8139_pci_driver) < 0) {
       
  1206                   printk(KERN_ERR "Failed to init PCI mod.\n");
       
  1207                   goto out_return;
       
  1208           }
       
  1209 
       
  1210           if (rtl_ec_net_dev) {
       
  1211                   printk(KERN_INFO "Registering"
       
  1212                          " EtherCAT device...\n");
       
  1213                   if (!(rtl_ec_dev =
       
  1214                           ecdev_register(ec_device_master_index,
       
  1215                                          rtl_ec_net_dev,
       
  1216                                          rtl8139_interrupt,
       
  1217                                          THIS_MODULE))) {
       
  1218                           printk(KERN_ERR "Failed to reg."
       
  1219                                           " EtherCAT device!\n");
       
  1220                           goto out_unreg_pci;
       
  1221                   }
       
  1222 
       
  1223                   printk(KERN_INFO "Starting EtherCAT"
       
  1224                          " device...\n");
       
  1225                   if (ecdev_start(ec_device_master_index)) {
       
  1226                           printk(KERN_ERR "Failed to start"
       
  1227                                  " EtherCAT device!\n");
       
  1228                           goto out_unreg_ec;
       
  1229                   }
       
  1230           } else {
       
  1231                   printk(KERN_WARNING "No EtherCAT device"
       
  1232                          " registered!\n");
       
  1233           }
       
  1234 
       
  1235           return 0;
       
  1236 
       
  1237       out_unreg_ec:
       
  1238           ecdev_unregister(ec_device_master_index, rtl_ec_dev);
       
  1239       out_unreg_pci:
       
  1240           pci_unregister_driver(&rtl8139_pci_driver);
       
  1241       out_return:
       
  1242           return -1;
       
  1243   }
       
  1244 \end{lstlisting}
       
  1245 
       
  1246 \begin{description}
       
  1247 \item[\linenum{3}] This call initializes all
       
  1248   RTL8139-compatible devices found on the pci bus. If a device with
       
  1249   index \textit{ec\_device\_index} is found, a pointer to its
       
  1250   \textit{net\_device} structure is stored in
       
  1251   \textit{rtl\_ec\_net\_dev} for later use (see next listings).
       
  1252 \item[\linenum{8}] If the specified device was
       
  1253   found, \textit{rtl\_ec\_net\_dev} is non-zero.
       
  1254 \item[\linenum{11}] The device is connected to
       
  1255   the specified master with a call to \textit{ecdev\_register()}. If
       
  1256   this fails, module loading is aborted.
       
  1257 \item[\linenum{23}] The device registration was
       
  1258   successful and the master is started. This can fail, which aborts
       
  1259   module loading.
       
  1260 \item[\linenum{29}] If no EtherCAT device was
       
  1261   found, a warning is output.
       
  1262 \end{description}
       
  1263 
       
  1264 \paragraph{Device Searching}
       
  1265 
       
  1266 During the PCI initialization phase, a variable \textit{board\_idx} is
       
  1267 increased for each RTL8139-compatible device found. The code below is
       
  1268 executed for each device:
       
  1269 
       
  1270 \begin{lstlisting}[gobble=2,language=C,numbers=left]
       
  1271   if (board_idx == ec_device_index) {
       
  1272           rtl_ec_net_dev = dev;
       
  1273           strcpy(dev->name, "ec0");
       
  1274   }
       
  1275 \end{lstlisting}
       
  1276 
       
  1277 \begin{description}
       
  1278 \item[\linenum{1}] The device with the specified
       
  1279   index will be the EtherCAT device.
       
  1280 \end{description}
       
  1281 
       
  1282 \paragraph{Avoiding Device Registration}
       
  1283 
       
  1284 Later in the PCI initialization phase, the net\_devices get
       
  1285 registered. This has to be avoided for EtherCAT devices and so this is
       
  1286 a typical example for an EtherCAT case differentiation:
       
  1287 
       
  1288 \begin{lstlisting}[gobble=2,language=C,numbers=left]
       
  1289   if (dev != rtl_ec_net_dev) {
       
  1290           i = register_netdev(dev);
       
  1291           if (i) goto err_out;
       
  1292   }
       
  1293 \end{lstlisting}
       
  1294 
       
  1295 \begin{description}
       
  1296 \item[\linenum{1}] If the current net\_device is
       
  1297   not the EtherCAT device, it is registered at the network stack.
       
  1298 \end{description}
       
  1299 
       
  1300 \paragraph{Avoiding Interrupt Registration}
       
  1301 
       
  1302 In the next two listings, there is an interrupt requested and the
       
  1303 device's interrupts are enabled. This also has to be encapsulated by
       
  1304 if-clauses, because interrupt operation is not wanted for EtherCAT
       
  1305 devices.
       
  1306 
       
  1307 \begin{lstlisting}[gobble=2,language=C,numbers=left]
       
  1308   if (dev != rtl_ec_net_dev) {
       
  1309           retval = request_irq(dev->irq, rtl8139_interrupt,
       
  1310                                SA_SHIRQ, dev->name, dev);
       
  1311           if (retval) return retval;
       
  1312   }
       
  1313 \end{lstlisting}
       
  1314 
       
  1315 \begin{lstlisting}[gobble=2,language=C,numbers=left]
       
  1316   if (dev != rtl_ec_net_dev) {
       
  1317           /* Enable all known interrupts by setting
       
  1318              the interrupt mask. */
       
  1319           RTL_W16(IntrMask, rtl8139_intr_mask);
       
  1320   }
       
  1321 \end{lstlisting}
       
  1322 
       
  1323 \paragraph{Frame Sending}
       
  1324 
       
  1325 The listing below shows an excerpt of the function representing the
       
  1326 \textit{hard\_start\_xmit()} callback of the net\_device.
       
  1327 
       
  1328 \begin{lstlisting}[gobble=2,language=C,numbers=left]
       
  1329   /* Note: the chip doesn't have auto-pad! */
       
  1330   if (likely(len < TX_BUF_SIZE)) {
       
  1331           if (len < ETH_ZLEN)
       
  1332                   memset(tp->tx_buf[entry], 0, ETH_ZLEN);
       
  1333           skb_copy_and_csum_dev(skb, tp->tx_buf[entry]);
       
  1334           if (dev != rtl_ec_net_dev) {
       
  1335                   dev_kfree_skb(skb);
       
  1336           }
       
  1337   } else {
       
  1338           if (dev != rtl_ec_net_dev) {
       
  1339                   dev_kfree_skb(skb);
       
  1340           }
       
  1341           tp->stats.tx_dropped++;
       
  1342           return 0;
       
  1343   }
       
  1344 \end{lstlisting}
       
  1345 
       
  1346 \begin{description}
       
  1347 \item[\linenum{6} + \linenum{10}] The
       
  1348   master uses a fixed socket buffer for transmission, which is reused
       
  1349   and may not be freed.
       
  1350 \end{description}
       
  1351 
       
  1352 \paragraph{Frame Receiving}
       
  1353 
       
  1354 During ordinary frame reception, a socket buffer is created and filled
       
  1355 with the received data. This is not necessary for an EtherCAT device:
       
  1356 
       
  1357 \begin{lstlisting}[gobble=2,language=C,numbers=left]
       
  1358   if (dev != rtl_ec_net_dev) {
       
  1359           /* Malloc up new buffer, compatible with net-2e. */
       
  1360           /* Omit the four octet CRC from the length. */
       
  1361 
       
  1362           skb = dev_alloc_skb (pkt_size + 2);
       
  1363           if (likely(skb)) {
       
  1364                   skb->dev = dev;
       
  1365                   skb_reserve(skb, 2); /* 16 byte align
       
  1366                                           the IP fields. */
       
  1367                   eth_copy_and_sum(skb, &rx_ring[ring_off + 4],
       
  1368                                    pkt_size, 0);
       
  1369                   skb_put(skb, pkt_size);
       
  1370                   skb->protocol = eth_type_trans(skb, dev);
       
  1371 
       
  1372                   dev->last_rx = jiffies;
       
  1373                   tp->stats.rx_bytes += pkt_size;
       
  1374                   tp->stats.rx_packets++;
       
  1375 
       
  1376                   netif_receive_skb (skb);
       
  1377           } else {
       
  1378                   if (net_ratelimit())
       
  1379                           printk(KERN_WARNING
       
  1380                                  "%s: Memory squeeze, dropping"
       
  1381                                  " packet.\n", dev->name);
       
  1382                   tp->stats.rx_dropped++;
       
  1383           }
       
  1384   } else {
       
  1385           ecdev_receive(rtl_ec_dev,
       
  1386                         &rx_ring[ring_offset + 4], pkt_size);
       
  1387           dev->last_rx = jiffies;
       
  1388           tp->stats.rx_bytes += pkt_size;
       
  1389           tp->stats.rx_packets++;
       
  1390   }
       
  1391 \end{lstlisting}
       
  1392 
       
  1393 \begin{description}
       
  1394 \item[\linenum{28}] If the device is an EtherCAT
       
  1395   device, no socket buffer is allocated. Instead a pointer to the data
       
  1396   (which is still in the device's receive ring) is passed to the
       
  1397   EtherCAT master. Unnecessary copy operations are avoided.
       
  1398 \item[\linenum{30} -- \linenum{32}] The
       
  1399   device's statistics are updated as usual.
       
  1400 \end{description}
       
  1401 
       
  1402 \paragraph{Link State}
       
  1403 
       
  1404 The link state (i.~e. if there is a carrier signal detected on the
       
  1405 receive port) is determined during execution of the ISR. The listing
       
  1406 below shows the different processing for Ethernet and EtherCAT
       
  1407 devices:
       
  1408 
       
  1409 \begin{lstlisting}[gobble=2,language=C,numbers=left]
       
  1410   if (dev != rtl_ec_net_dev) {
       
  1411           if (tp->phys[0] >= 0) {
       
  1412                   mii_check_media(&tp->mii, netif_msg_link(tp),
       
  1413                                   init_media);
       
  1414           }
       
  1415   } else {
       
  1416           void __iomem *ioaddr = tp->mmio_addr;
       
  1417           uint16_t link = RTL_R16(BasicModeStatus)
       
  1418                           & BMSR_LSTATUS;
       
  1419           ecdev_link_state(rtl_ec_dev, link ? 1 : 0);
       
  1420   }
       
  1421 \end{lstlisting}
       
  1422 
       
  1423 \begin{description}
       
  1424 \item[\linenum{3}] The ``media check'' is done
       
  1425   via the media independent interface (MII\nomenclature{MII}{Media
       
  1426     Independent Interface}), a standard interface for Fast Ethernet
       
  1427   devices.
       
  1428 \item[\linenum{7} -- \linenum{10}] For
       
  1429   EtherCAT devices, the link state is fetched manually from the
       
  1430   appropriate device register, and passed to the EtherCAT master by
       
  1431   calling \textit{ecdev\_\-link\_\-state()}.
       
  1432 \end{description}
       
  1433 
       
  1434 \paragraph{Module Cleanup}
       
  1435 
       
  1436 Below is the module's cleanup function:
       
  1437 
       
  1438 \begin{lstlisting}[gobble=2,language=C,numbers=left]
       
  1439   static void __exit rtl8139_cleanup_module (void)
       
  1440   {
       
  1441           printk(KERN_INFO "Cleaning up RTL8139-EtherCAT"
       
  1442                  " module...\n");
       
  1443 
       
  1444           if (rtl_ec_net_dev) {
       
  1445                   printk(KERN_INFO "Stopping device...\n");
       
  1446                   ecdev_stop(ec_device_master_index);
       
  1447                   printk(KERN_INFO "Unregistering device...\n");
       
  1448                   ecdev_unregister(ec_device_master_index,
       
  1449                                    rtl_ec_dev);
       
  1450                   rtl_ec_dev = NULL;
       
  1451           }
       
  1452 
       
  1453           pci_unregister_driver(&rtl8139_pci_driver);
       
  1454 
       
  1455           printk(KERN_INFO "RTL8139-EtherCAT module"
       
  1456                  " cleaned up.\n");
       
  1457   }
       
  1458 \end{lstlisting}
       
  1459 
       
  1460 \begin{description}
       
  1461 
       
  1462 \item[\linenum{6}] Stopping and deregistration is only done, if a device was
       
  1463 registered before.
       
  1464 
       
  1465 \item[\linenum{8}] The master is first stopped, so it does not access the
       
  1466 device any more.
       
  1467 
       
  1468 \item[\linenum{10}] After this, the device is unregistered. The master is now
       
  1469 ``orphaned''.
       
  1470 
       
  1471 \end{description}
       
  1472 
   974 
  1473 %------------------------------------------------------------------------------
   975 %------------------------------------------------------------------------------
  1474 
   976 
  1475 \chapter{State Machines}
   977 \chapter{State Machines}
  1476 \label{sec:fsm}
   978 \label{sec:fsm}
  1720 \end{lstlisting}
  1222 \end{lstlisting}
  1721 
  1223 
  1722 In the master code, state pointers of all state machines\footnote{All except
  1224 In the master code, state pointers of all state machines\footnote{All except
  1723 for the EoE state machine, because multiple EoE slaves have to be handled in
  1225 for the EoE state machine, because multiple EoE slaves have to be handled in
  1724 parallel. For this reason each EoE handler object has its own state pointer.}
  1226 parallel. For this reason each EoE handler object has its own state pointer.}
  1725 are gathered in a single object of the \textit{ec\_fsm\_t} class. This is
  1227 are gathered in a single object of the \lstinline+ec_fsm_master_t+ class. This
  1726 advantageous, because there is always one instance of every state machine
  1228 is advantageous, because there is always one instance of every state machine
  1727 available and can be started on demand.
  1229 available and can be started on demand.
  1728 
  1230 
  1729 \paragraph{Mealy and Moore}
  1231 \paragraph{Mealy and Moore}
  1730 
  1232 
  1731 If a closer look is taken to the above listing, it can be seen that
  1233 If a closer look is taken to the above listing, it can be seen that the
  1732 the actions executed (the ``outputs'' of the state machine) only
  1234 actions executed (the ``outputs'' of the state machine) only depend on the
  1733 depend on the current state. This accords to the ``Moore'' model
  1235 current state. This accords to the ``Moore'' model introduced in
  1734 introduced in section~\ref{sec:fsmtheory}. As mentioned, the ``Mealy''
  1236 section~\ref{sec:fsmtheory}. As mentioned, the ``Mealy'' model offers a higher
  1735 model offers a higher flexibility, which can be seen in the listing
  1237 flexibility, which can be seen in the listing below:
  1736 below:
       
  1737 
  1238 
  1738 \begin{lstlisting}[gobble=2,language=C,numbers=left]
  1239 \begin{lstlisting}[gobble=2,language=C,numbers=left]
  1739   void state7(void *priv_data) {
  1240   void state7(void *priv_data) {
  1740           if (some_condition) {
  1241           if (some_condition) {
  1741                   action_7a();
  1242                   action_7a();
  1747           }
  1248           }
  1748   }
  1249   }
  1749 \end{lstlisting}
  1250 \end{lstlisting}
  1750 
  1251 
  1751 \begin{description}
  1252 \begin{description}
  1752 \item[\linenum{3} + \linenum{7}] The
  1253 
  1753   state function executes the actions depending on the state
  1254 \item[\linenum{3} + \linenum{7}] The state function executes the actions
  1754   transition, that is about to be done.
  1255 depending on the state transition, that is about to be done.
       
  1256 
  1755 \end{description}
  1257 \end{description}
  1756 
  1258 
  1757 The most flexible alternative is to execute certain actions depending
  1259 The most flexible alternative is to execute certain actions depending
  1758 on the state, followed by some actions dependent on the state
  1260 on the state, followed by some actions dependent on the state
  1759 transition:
  1261 transition:
  1770                   state = state10;
  1272                   state = state10;
  1771           }
  1273           }
  1772   }
  1274   }
  1773 \end{lstlisting}
  1275 \end{lstlisting}
  1774 
  1276 
  1775 This model is oftenly used in the master. It combines the best aspects
  1277 This model is often used in the master. It combines the best aspects of both
  1776 of both approaches.
  1278 approaches.
  1777 
  1279 
  1778 \paragraph{Using Sub State Machines}
  1280 \paragraph{Using Sub State Machines}
  1779 
  1281 
  1780 To avoid having too much states, certain functions of the EtherCAT master state
  1282 To avoid having too much states, certain functions of the EtherCAT master
  1781 machine have been sourced out into sub state machines.  This helps to
  1283 state machine have been sourced out into sub state machines.  This helps to
  1782 encapsulate the related workflows and moreover avoids the ``state explosion''
  1284 encapsulate the related workflows and moreover avoids the ``state explosion''
  1783 phenomenon described in section~\ref{sec:fsmtheory}. If the master would
  1285 phenomenon described in section~\ref{sec:fsmtheory}. If the master would
  1784 instead use one big state machine, the number of states would be a multiple of
  1286 instead use one big state machine, the number of states would be a multiple of
  1785 the actual number. This would increase the level of complexity to a
  1287 the actual number. This would increase the level of complexity to a
  1786 non-manageable grade.
  1288 non-manageable grade.
  1808           // continue state processing
  1310           // continue state processing
  1809           ...
  1311           ...
  1810 \end{lstlisting}
  1312 \end{lstlisting}
  1811 
  1313 
  1812 \begin{description}
  1314 \begin{description}
  1813 \item[\linenum{3}] \textit{change\_state} is the
  1315 
  1814   state pointer of the state change state machine. The state function,
  1316 \item[\linenum{3}] \lstinline+change_state+ is the state pointer of the state
  1815   the pointer points on, is executed\ldots
  1317 change state machine. The state function, the pointer points on, is
  1816 \item[\linenum{6}] \ldots either until the state
  1318 executed\ldots
  1817   machine terminates with the error state \ldots
  1319 
  1818 \item[\linenum{11}] \ldots or until the state
  1320 \item[\linenum{6}] \ldots either until the state machine terminates with the
  1819   machine terminates in the end state. Until then, the ``higher''
  1321 error state \ldots
  1820   state machine remains in the current state and executes the sub
  1322 
  1821   state machine again in the next cycle.
  1323 \item[\linenum{11}] \ldots or until the state machine terminates in the end
       
  1324 state. Until then, the ``higher'' state machine remains in the current state
       
  1325 and executes the sub state machine again in the next cycle.
       
  1326 
  1822 \end{description}
  1327 \end{description}
  1823 
  1328 
  1824 \paragraph{State Machine Descriptions}
  1329 \paragraph{State Machine Descriptions}
  1825 
  1330 
  1826 The below sections describe every state machine used in the EtherCAT
  1331 The below sections describe every state machine used in the EtherCAT master.
  1827 master. The textual descriptions of the state machines contain
  1332 The textual descriptions of the state machines contain references to the
  1828 references to the transitions in the corresponding state transition
  1333 transitions in the corresponding state transition diagrams, that are marked
  1829 diagrams, that are marked with an arrow followed by the name of the
  1334 with an arrow followed by the name of the successive state. Transitions caused
  1830 successive state.  Transitions caused by trivial error cases (i.~e. no
  1335 by trivial error cases (i.~e. no response from slave) are not described
  1831 response from slave) are not described explicitly. These transitions
  1336 explicitly. These transitions are drawn as dashed arrows in the diagrams.
  1832 are drawn as dashed arrows in the diagrams.
  1337 
  1833 
  1338 %------------------------------------------------------------------------------
  1834 %------------------------------------------------------------------------------
  1339 
  1835 
  1340 \section{The Master State Machine}
  1836 \section{The Operation State Machine}
  1341 \label{sec:fsm-master}
  1837 \label{sec:fsm-op}
  1342 \index{FSM!Master}
  1838 \index{FSM!Operation}
  1343 
  1839 
  1344 The master state machine is executed in the context of the master thread.
  1840 The Operation state machine is executed by calling the
  1345 Figure~\ref{fig:fsm-master} shows its transition diagram. Its purposes are:
  1841 \textit{ecrt\_master\_run()} method in cyclic realtime code. Its
       
  1842 purpose is to monitor the bus and to reconfigure slaves after a bus
       
  1843 failure or power failure. Figure~\ref{fig:fsm-op} shows its transition
       
  1844 diagram.
       
  1845 
  1346 
  1846 \begin{figure}[htbp]
  1347 \begin{figure}[htbp]
  1847   \centering
  1348   \centering
  1848   \includegraphics[width=.8\textwidth]{images/fsm-op}
  1349   \includegraphics[width=\textwidth]{graphs/fsm_master}
  1849   \caption{Transition diagram of the operation state machine}
  1350   \caption{Transition diagram of the master state machine}
  1850   \label{fig:fsm-op}
  1351   \label{fig:fsm-master}
  1851 \end{figure}
  1352 \end{figure}
  1852 
  1353 
  1853 \begin{description}
  1354 \begin{description}
  1854 \item[START] This is the beginning state of the operation state
  1355 
  1855   machine. There is a datagram issued, that queries the ``AL Control
  1356 \item[Bus monitoring] The bus topology is monitored. If it changes, the bus is
  1856   Response'' attribute \cite[section~5.3.2]{alspec} of all slaves via
  1357 (re-)scanned.
  1857   broadcast. In this way, all slave states and the number of slaves
  1358 
  1858   responding can be determined.  $\rightarrow$~BROADCAST
  1359 \item[Slave configuration] The application-layer states of the slaves are
  1859 
  1360 monitored. If a slave is not in the state it supposed to be, the slave is
  1860 \item[BROADCAST] The broadcast datagram is evaluated. A change in the number of
  1361 (re-)configured.
  1861 responding slaves is treated as a topology change. If the number of slaves is
  1362 
  1862 not as expected, the bus is marked as ``tainted''. In this state, no slave
  1363 \item[Request handling] Requests (either originating from the application or
  1863 reconfiguration is possible, because the assignment of known slaves and those
  1364 from external sources) are handled. A request is a job that the master shall
  1864 present on the bus is ambiguous. If the number of slaves is considered as
  1365 process asynchronously, for example an SII access, Sdo access, or similar.
  1865 right, the bus is marked for validation, because it turned from tainted to
       
  1866 normal state and it has to be checked, if all slaves are valid. Now, the state
       
  1867 of every single slave has to be determined. For that, a (unicast) datagram is
       
  1868 issued, that queries the first slave's ``AL Control Response'' attribute.
       
  1869 $\rightarrow$~READ STATES
       
  1870 
       
  1871 \item[READ STATES] If the current slave did not respond to its configured
       
  1872 station address, it is marked as offline, and the next slave is queried.
       
  1873 $\rightarrow$~READ STATES
       
  1874 
       
  1875   If the slave responded, it is marked as online and its current state
       
  1876   is stored. The next slave is queried. $\rightarrow$~READ STATES
       
  1877 
       
  1878   If all slaves have been queried, and the bus is marked for
       
  1879   validation, the validation is started by checking the first slaves
       
  1880   vendor ID. $\rightarrow$~VALIDATE VENDOR
       
  1881 
       
  1882   If no validation has to be done, it is checked, if all slaves are in
       
  1883   the state they are supposed to be. If not, the first of slave with
       
  1884   the wrong state is reconfigured and brought in the required state.
       
  1885   $\rightarrow$~CONFIGURE SLAVES
       
  1886 
       
  1887   If all slaves are in the correct state, the state machine is
       
  1888   restarted. $\rightarrow$~START
       
  1889 
       
  1890 \item[CONFIGURE SLAVES] The slave configuration state machine is
       
  1891   executed until termination. $\rightarrow$~CONFIGURE SLAVES
       
  1892 
       
  1893   If there are still slaves in the wrong state after another check,
       
  1894   the first of these slaves is configured and brought into the correct
       
  1895   state again. $\rightarrow$~CONFIGURE SLAVES
       
  1896 
       
  1897   If all slaves are in the correct state, the state machine is
       
  1898   restarted. $\rightarrow$~START
       
  1899 
       
  1900 \item[VALIDATE VENDOR] The SII state machine is executed until
       
  1901   termination. If the slave has the wrong vendor ID, the state machine
       
  1902   is restarted. $\rightarrow$~START
       
  1903 
       
  1904   If the slave has the correct vendor ID, its product ID is queried.
       
  1905   $\rightarrow$~VALIDATE PRODUCT
       
  1906 
       
  1907 \item[VALIDATE PRODUCT] The SII state machine is executed until
       
  1908   termination. If the slave has the wrong product ID, the state
       
  1909   machine is restarted. $\rightarrow$~START
       
  1910 
       
  1911   If the slave has the correct product ID, the next slave's vendor ID
       
  1912   is queried. $\rightarrow$~VALIDATE VENDOR
       
  1913 
       
  1914   If all slaves have the correct vendor IDs and product codes, the
       
  1915   configured station addresses can be safely rewritten. This is done
       
  1916   for the first slave marked as offline.
       
  1917   $\rightarrow$~REWRITE ADDRESSES
       
  1918 
       
  1919 \item[REWRITE ADDRESSES] If the station address was successfully written, it is
       
  1920 searched for the next slave marked as offline. If there is one, its address is
       
  1921 reconfigured, too.  $\rightarrow$~REWRITE ADDRESSES
       
  1922 
       
  1923   If there are no more slaves marked as offline, the state machine is
       
  1924   restarted. $\rightarrow$~START
       
  1925 \end{description}
       
  1926 
       
  1927 %------------------------------------------------------------------------------
       
  1928 
       
  1929 \section{The Idle State Machine}
       
  1930 \label{sec:fsm-idle}
       
  1931 \index{FSM!Idle}
       
  1932 
       
  1933 The Idle state machine is executed by a kernel thread, if no application is
       
  1934 connected. Its purpose is to make slave information available to user space,
       
  1935 operate EoE-capable slaves, read and write SII contents and test slave
       
  1936 functionality.  Figure~\ref{fig:fsm-idle} shows its transition diagram.
       
  1937 
       
  1938 \begin{figure}[htbp]
       
  1939   \centering
       
  1940   \includegraphics[width=.8\textwidth]{images/fsm-idle}
       
  1941   \caption{Transition diagram of the idle state machine}
       
  1942   \label{fig:fsm-idle}
       
  1943 \end{figure}
       
  1944 
       
  1945 \begin{description}
       
  1946 \item[START] The beginning state of the idle state machine. Similar to
       
  1947   the operation state machine, a broadcast datagram is issued, to
       
  1948   query all slave states and the number of slaves.
       
  1949   $\rightarrow$~BROADCAST
       
  1950 
       
  1951 \item[BROADCAST] The number of responding slaves is evaluated. If it
       
  1952   has changed since the last time, this is treated as a topology
       
  1953   change and the internal list of slaves is cleared and rebuild
       
  1954   completely. The slave scan state machine is started for the first
       
  1955   slave. $\rightarrow$~SCAN FOR SLAVES
       
  1956 
       
  1957   If no topology change happened, every single slave state is fetched.
       
  1958   $\rightarrow$~READ STATES
       
  1959 
       
  1960 \item[SCAN FOR SLAVES] The slave scan state machine is executed until
       
  1961   termination. $\rightarrow$~SCAN FOR SLAVES
       
  1962 
       
  1963   If there is another slave to scan, the slave scan state machine is
       
  1964   started again. $\rightarrow$~SCAN FOR SLAVES
       
  1965 
       
  1966   If all slave information has been fetched, slave addresses are
       
  1967   calculated and EoE processing is started. Then, the state machine is
       
  1968   restarted. $\rightarrow$~START
       
  1969 
       
  1970 \item[READ STATES] If the slave did not respond to the query, it is
       
  1971   marked as offline. The next slave is queried.
       
  1972   $\rightarrow$~READ STATES
       
  1973 
       
  1974   If the slave responded, it is marked as online. And the next slave
       
  1975   is queried. $\rightarrow$~READ STATES
       
  1976 
       
  1977   If all slave states have been determined, it is checked, if any
       
  1978   slaves are not in the state they supposed to be. If this is true,
       
  1979   the slave configuration state machine is started for the first of
       
  1980   them. $\rightarrow$~CONFIGURE SLAVES
       
  1981 
       
  1982   If all slaves are in the correct state, it is checked, if any
       
  1983   E$^2$PROM write operations are pending. If this is true, the first
       
  1984   pending operation is executed by starting the SII state machine for
       
  1985   writing access. $\rightarrow$~WRITE EEPROM
       
  1986 
       
  1987   If all these conditions are false, there is nothing to do and the
       
  1988   state machine is restarted. $\rightarrow$~START
       
  1989 
       
  1990 \item[CONFIGURE SLAVES] The slave configuration state machine is
       
  1991   executed until termination. $\rightarrow$~CONFIGURE SLAVES
       
  1992 
       
  1993   After this, it is checked, if another slave needs a state change. If
       
  1994   this is true, the slave state change state machine is started for
       
  1995   this slave. $\rightarrow$~CONFIGURE SLAVES
       
  1996 
       
  1997   If all slaves are in the correct state, it is determined, if any
       
  1998   E$^2$PROM write operations are pending. If this is true, the first
       
  1999   pending operation is executed by starting the SII state machine for
       
  2000   writing access. $\rightarrow$~WRITE EEPROM
       
  2001 
       
  2002   If all prior conditions are false, the state machine is restarted.
       
  2003   $\rightarrow$~START
       
  2004 
       
  2005 \item[WRITE EEPROM] The SII state machine is executed until
       
  2006   termination. $\rightarrow$~WRITE EEPROM
       
  2007 
       
  2008   If the current word has been written successfully, and there are
       
  2009   still word to write, the SII state machine is started for the next
       
  2010   word. $\rightarrow$~WRITE EEPROM
       
  2011 
       
  2012   If all words have been written successfully, the new E$^2$PROM
       
  2013   contents are evaluated and the state machine is restarted.
       
  2014   $\rightarrow$~START
       
  2015 
  1366 
  2016 \end{description}
  1367 \end{description}
  2017 
  1368 
  2018 %------------------------------------------------------------------------------
  1369 %------------------------------------------------------------------------------
  2019 
  1370 
  2020 \section{The Slave Scan State Machine}
  1371 \section{The Slave Scan State Machine}
  2021 \label{sec:fsm-scan}
  1372 \label{sec:fsm-scan}
  2022 \index{FSM!Slave Scan}
  1373 \index{FSM!Slave Scan}
  2023 
  1374 
  2024 The slave scan state machine, which can be seen in
  1375 The slave scan state machine, which can be seen in
  2025 figure~\ref{fig:fsm-slavescan}, leads through the process of fetching
  1376 figure~\ref{fig:fsm-slavescan}, leads through the process of reading desired
  2026 all slave information.
  1377 slave information.
  2027 
  1378 
  2028 \begin{figure}[htbp]
  1379 \begin{figure}[htbp]
  2029   \centering
  1380   \centering
  2030   \includegraphics[width=.6\textwidth]{images/fsm-slavescan}
  1381   \includegraphics[height=.8\textheight]{graphs/fsm_slave_scan}
  2031   \caption{Transition diagram of the slave scan state machine}
  1382   \caption{Transition diagram of the slave scan state machine}
  2032   \label{fig:fsm-slavescan}
  1383   \label{fig:fsm-slavescan}
  2033 \end{figure}
  1384 \end{figure}
  2034 
  1385 
       
  1386 The scan process includes the following steps:
       
  1387 
  2035 \begin{description}
  1388 \begin{description}
  2036 \item[START] In the beginning state of the slave scan state machine,
  1389 
  2037   the station address is written to the slave, which is always the
  1390 \item[Node Address] The node address is set for the slave, so that it can be
  2038   ring position~+~$1$. In this way, the address 0x0000 (default
  1391 node-addressed for all following operations.
  2039   address) is not used, which makes it easy to detect unconfigured
  1392 
  2040   slaves.  $\rightarrow$~ADDRESS
  1393 \item[AL State] The initial application-layer state is read.
  2041 
  1394 
  2042 \item[ADDRESS] The writing of the station address is verified. After
  1395 \item[Base Information] Base information (like the number of supported FMMUs)
  2043   that, the slave's ``AL Control Response'' attribute is queried.
  1396 is read from the lower physical memory.
  2044   $\rightarrow$~STATE
  1397 
  2045 
  1398 \item[Data Link] Information about the physical ports is read.
  2046 \item[STATE] The AL state is evaluated. A warning is output, if the
  1399 
  2047   slave has still the \textit{Change} bit set. After that, the slave's
  1400 \item[SII Size] The size of the SII contents is determined to allocate SII
  2048   ``DL Information'' attribute is queried.
  1401 image memory.
  2049   $\rightarrow$~BASE
  1402 
  2050 
  1403 \item[SII Data] The SII contents are read into the master's image.
  2051 \item[BASE] The queried base data are evaluated: Slave type, revision
  1404 
  2052   and build number, and even more important, the number of supported
  1405 \item[PREOP] If the slave supports CoE, it is set to PREOP state using the
  2053   sync managers and FMMUs are stored. After that, the slave's data
  1406 State change FSM (see section~\ref{sec:fsm-change}) to enable mailbox
  2054   link layer information is read from the ``DL Status'' attribute at
  1407 communication and read the Pdo configuration via CoE.
  2055   address 0x0110. $\rightarrow$~DATALINK
  1408 
  2056 
  1409 \item[Pdos] The Pdos are read via CoE (if supported) using the Pdo Reading FSM
  2057 \item[DATALINK] In this state, the DL information is evaluated: This
  1410 (see section~\ref{sec:fsm-pdo}). If this is successful, the Pdo information
  2058   information about the communication ports contains, if the link is
  1411 from the SII (if any) is overwritten.
  2059   up, if the loop has been closed and if there is a carrier detected
       
  2060   on the RX side of each port.
       
  2061 
       
  2062   Then, the state machine starts measuring the size of the slave's
       
  2063   E$^2$PROM contents. This is done by subsequently reading out each
       
  2064   category header, until the last category is reached (type 0xFFFF).
       
  2065   This procedure is started by querying the first category header at
       
  2066   word address 0x0040 via the SII state machine.
       
  2067   $\rightarrow$~EEPROM SIZE
       
  2068 
       
  2069 \item[EEPROM SIZE] The SII state machine is executed until
       
  2070   termination. $\rightarrow$~EEPROM SIZE
       
  2071 
       
  2072   If the category type does not mark the end of the categories, the
       
  2073   position of the next category header is determined via the length of
       
  2074   the current category, and the SII state machine is started again.
       
  2075   $\rightarrow$~EEPROM SIZE
       
  2076 
       
  2077   If the size of the E$^2$PROM contents has been determined, memory is
       
  2078   allocated, to read all the contents. The SII state machine is
       
  2079   started to read the first word. $\rightarrow$~EEPROM DATA
       
  2080 
       
  2081 \item[EEPROM DATA] The SII state machine is executed until
       
  2082   termination. $\rightarrow$~EEPROM DATA
       
  2083 
       
  2084   Two words have been read. If more than one word is needed, the two
       
  2085   words are written in the allocated memory. Otherwise only one word
       
  2086   (the last word) is copied. If more words are to read, the SII state
       
  2087   machine is started again to read the next two words.
       
  2088   $\rightarrow$~EEPROM DATA
       
  2089 
       
  2090   The complete E$^2$PROM contents have been read. The slave's identity
       
  2091   object and mailbox information are evaluated. Moreover the category
       
  2092   types STRINGS, GENERAL, SYNC and PDO are evaluated. The slave
       
  2093   scanning has been completed. $\rightarrow$~END
       
  2094 
       
  2095 \item[END] Slave scanning has been finished.
       
  2096 
  1412 
  2097 \end{description}
  1413 \end{description}
  2098 
  1414 
  2099 %------------------------------------------------------------------------------
  1415 %------------------------------------------------------------------------------
  2100 
  1416 
  2101 \section{The Slave Configuration State Machine}
  1417 \section{The Slave Configuration State Machine}
  2102 \label{sec:fsm-conf}
  1418 \label{sec:fsm-conf}
  2103 \index{FSM!Slave Configuration}
  1419 \index{FSM!Slave Configuration}
  2104 
  1420 
  2105 The slave configuration state machine, which can be seen in
  1421 The slave configuration state machine, which can be seen in
  2106 figure~\ref{fig:fsm-slaveconf}, leads through the process of
  1422 figure~\ref{fig:fsm-slaveconf}, leads through the process of configuring a
  2107 configuring a slave and bringing it to a certain state.
  1423 slave and bringing it to a certain application-layer state.
  2108 
  1424 
  2109 \begin{figure}[htbp]
  1425 \begin{figure}[htbp]
  2110   \centering
  1426   \centering
  2111   \includegraphics[width=.6\textwidth]{images/fsm-slaveconf}
  1427   \includegraphics[height=.9\textheight]{graphs/fsm_slave_conf}
  2112   \caption{Transition diagram of the slave configuration state
  1428   \caption{Transition diagram of the slave configuration state
  2113     machine}
  1429     machine}
  2114   \label{fig:fsm-slaveconf}
  1430   \label{fig:fsm-slaveconf}
  2115 \end{figure}
  1431 \end{figure}
  2116 
  1432 
  2117 \begin{description}
  1433 \begin{description}
  2118 \item[INIT] The state change state machine has been initialized to
  1434 
  2119   bring the slave into the INIT state. Now, the slave state change
  1435 \item[INIT] The state change FSM is used to bring the slave to the INIT state.
  2120   state machine is executed until termination. $\rightarrow$~INIT
  1436 
  2121 
  1437 \item[FMMU Clearing] To avoid that the slave reacts on any process data, the
  2122   If the slave state change failed, the configuration has to be
  1438 FMMU configuration are cleared. If the slave does not support FMMUs, this
  2123   aborted. $\rightarrow$~END
  1439 state is skipped. If INIT is the requested state, the state machine is
  2124 
  1440 finished.
  2125   The slave state change succeeded and the slave is now in INIT state.
  1441 
  2126   If this is the target state, the configuration is finished.
  1442 \item[Mailbox Sync Manager Configuration] If the slaves support mailbox
  2127   $\rightarrow$~END
  1443 communication, the mailbox sync managers are configured. Otherwise this state
  2128 
  1444 is skipped.
  2129   If the slave does not support any sync managers, the sync manager
  1445 
  2130   configuration can be skipped. The state change state machine is
  1446 \item[PREOP] The state change FSM is used to bring the slave to PREOP state.
  2131   started to bring the slave into PREOP state.
  1447 If this is the requested state, the state machine is finished.
  2132   $\rightarrow$~PREOP
  1448 
  2133 
  1449 \item[Sdo Configuration] If there is a slave configuration attached (see
  2134   Sync managers are configured conforming to the sync manager category
  1450 section~\ref{sec:masterconfig}), and there are any Sdo configurations are
  2135   information provided in the slave's E$^2$PROM. The corresponding
  1451 provided by the application, these are sent to the slave.
  2136   datagram is issued. $\rightarrow$~SYNC
  1452 
  2137 
  1453 \item[Pdo Configuration] The Pdo configuration state machine is executed to
  2138 \item[SYNC] If the sync manager configuration datagram is accepted,
  1454 apply all necessary Pdo configurations.
  2139   the sync manager configuration was successful. The slave may now
  1455 
  2140   enter the PREOP state, and the state change state machine is
  1456 \item[Pdo Sync Manager Configuration] If any Pdo sync managers exist, they are
  2141   started. $\rightarrow$~PREOP
  1457 configured.
  2142 
  1458 
  2143 \item[PREOP] The state change state machine is executed until
  1459 \item[FMMU Configuration] If there are FMMUs configurations supplied by the
  2144   termination. $\rightarrow$~PREOP
  1460 application (i.~e. if the application registered Pdo entries), they are
  2145 
  1461 applied. 
  2146   If the state change failed, the configuration has to be aborted.
  1462 
  2147   $\rightarrow$~END
  1463 \item[SAFEOP] The state change FSM is used to bring the slave to SAFEOP state.
  2148 
  1464 If this is the requested state, the state machine is finished.
  2149   If the PREOP state was the target state, the configuration is
  1465 
  2150   finished. $\rightarrow$~END
  1466 \item[OP] The state change FSM is used to bring the slave to OP state.
  2151 
  1467 If this is the requested state, the state machine is finished.
  2152   If the slave supports no FMMUs, the FMMU configuration can be
       
  2153   skipped. If the slave has Sdos to configure, it is begun with
       
  2154   sending the first Sdo. $\rightarrow$~SDO\_CONF
       
  2155 
       
  2156   If no Sdo configurations are provided, the slave can now directly be
       
  2157   brought into the SAFEOP state and the state change state machine is
       
  2158   started again. $\rightarrow$~SAFEOP
       
  2159 
       
  2160   Otherwise, all supported FMMUs are configured according to the Pdos
       
  2161   requested via the master's realtime interface. The appropriate
       
  2162   datagram is issued. $\rightarrow$~FMMU
       
  2163 
       
  2164 \item[FMMU] The FMMU configuration datagram was accepted. If the slave
       
  2165   has Sdos to configure, it is begun with sending the first Sdo.
       
  2166   $\rightarrow$~SDO\_CONF
       
  2167 
       
  2168   Otherwise, the slave can now be brought into the SAFEOP state. The
       
  2169   state change state machine is started.
       
  2170   $\rightarrow$~SAFEOP
       
  2171 
       
  2172 \item[SDO\_CONF] The CoE state machine is executed until termination.
       
  2173   $\rightarrow$~SDO\_CONF
       
  2174 
       
  2175   If another Sdo has to be configured, a new Sdo download sequence is
       
  2176   begun. $\rightarrow$~SDO\_CONF
       
  2177 
       
  2178   Otherwise, the slave can now be brought into the SAFEOP state. The
       
  2179   state change state machine is started.
       
  2180   $\rightarrow$~SAFEOP
       
  2181 
       
  2182 \item[SAFEOP] The state change state machine is executed until
       
  2183   termination. $\rightarrow$~SAFEOP
       
  2184 
       
  2185   If the state change failed, the configuration has to be aborted.
       
  2186   $\rightarrow$~END
       
  2187 
       
  2188   If the SAFEOP state was the target state, the configuration is
       
  2189   finished. $\rightarrow$~END
       
  2190 
       
  2191   The slave can now directly be brought into the OP state and the
       
  2192   state change state machine is started a last time.
       
  2193   $\rightarrow$~OP
       
  2194 
       
  2195 \item[OP] The state change state machine is executed until
       
  2196   termination. $\rightarrow$~OP
       
  2197 
       
  2198   If the state change state machine terminates, the slave
       
  2199   configuration is finished, regardless of its success.
       
  2200   $\rightarrow$~END
       
  2201 
       
  2202 \item[END] The termination state.
       
  2203 
  1468 
  2204 \end{description}
  1469 \end{description}
  2205 
  1470 
  2206 %------------------------------------------------------------------------------
  1471 %------------------------------------------------------------------------------
  2207 
  1472 
  2208 \section{The State Change State Machine}
  1473 \section{The State Change State Machine}
  2209 \label{sec:fsm-change}
  1474 \label{sec:fsm-change}
  2210 \index{FSM!State Change}
  1475 \index{FSM!State Change}
  2211 
  1476 
  2212 The state change state machine, which can be seen in
  1477 The state change state machine, which can be seen in
  2213 figure~\ref{fig:fsm-change}, leads through the process of changing a
  1478 figure~\ref{fig:fsm-change}, leads through the process of changing a slave's
  2214 slave's state. This implements the states and transitions described in
  1479 application-layer state. This implements the states and transitions described
  2215 \cite[section~6.4.1]{alspec}.
  1480 in \cite[section~6.4.1]{alspec}.
  2216 
  1481 
  2217 \begin{figure}[htbp]
  1482 \begin{figure}[htbp]
  2218   \centering
  1483   \centering
  2219   \includegraphics[width=.9\textwidth]{images/fsm-change}
  1484   \includegraphics[width=.6\textwidth]{graphs/fsm_change}
  2220   \caption{Transition diagram of the state change state machine}
  1485   \caption{Transition Diagram of the State Change State Machine}
  2221   \label{fig:fsm-change}
  1486   \label{fig:fsm-change}
  2222 \end{figure}
  1487 \end{figure}
  2223 
  1488 
  2224 \begin{description}
  1489 \begin{description}
  2225 \item[START] The beginning state, where a datagram with the state
  1490 
  2226   change command is written to the slave's ``AL Control Request''
  1491 \item[Start] The new application-layer state is requested via the ``AL Control
  2227   attribute. Nothing can fail. $\rightarrow$~CHECK
  1492 Request'' register (see ~\cite[section 5.3.1]{alspec}).
  2228 
  1493 
  2229 \item[CHECK] After the state change datagram has been sent, the ``AL
  1494 \item[Check for Response] Some slave need some time to respond to an AL state
  2230   Control Response'' attribute is queried with a second datagram.
  1495 change command, and do not respond for some time. For this case, the command
  2231   $\rightarrow$~STATUS
  1496 is issued again, until it is acknowledged.
  2232 
  1497 
  2233 \item[STATUS] The read memory contents are evaluated: While the
  1498 \item[Check AL Status] If the AL State change datagram was acknowledged, the
  2234   parameter \textit{State} still contains the old slave state, the
  1499 ``AL Control Response'' register (see~\cite[section 5.3.2]{alspec}) must be
  2235   slave is busy with reacting on the state change command. In this
  1500 read out until the slave changes the AL state.
  2236   case, the attribute has to be queried again.
  1501 
  2237   $\rightarrow$~STATUS
  1502 \item[AL Status Code] If the slave refused the state change command, the
  2238 
  1503 reason can be read from the ``AL Status Code'' field in the ``AL State
  2239   In case of success, the \textit{State} parameter contains the new
  1504 Changed'' registers (see~\cite[section 5.3.3]{alspec}).
  2240   state and the \textit{Change} bit is cleared. The slave is in the
  1505 
  2241   requested state.  $\rightarrow$~END
  1506 \item[Acknowledge State] If the state change was not successful, the master
  2242 
  1507 has to acknowledge the old state by writing to the ``AL Control request''
  2243   If the slave can not process the state change, the \textit{Change}
  1508 register again.
  2244   bit is set: Now the master tries to get the reason for this by
  1509 
  2245   querying the \textit{AL Status Code} parameter.
  1510 \item[Check Acknowledge] After sending the acknowledge command, it has to read
  2246   $\rightarrow$~CODE
  1511 out the ``AL Control Response'' register again.
  2247 
       
  2248 \item[END] If the state machine ends in this state, the slave's state
       
  2249   change has been successful.
       
  2250 
       
  2251 \item[CODE] The status code query has been sent. Reading the
       
  2252   \textit{AL Status Code} might fail, because not all slaves support
       
  2253   this parameter. Anyway, the master has to acknowledge the state
       
  2254   change error by writing the current slave state to the ``AL Control
       
  2255   Request'' attribute with the \textit{Acknowledge} bit set.
       
  2256   $\rightarrow$~ACK
       
  2257 
       
  2258 \item[ACK] After that, the ``AL Control Response'' attribute is
       
  2259   queried for the state of the acknowledgement.
       
  2260   $\rightarrow$~CHECK ACK
       
  2261 
       
  2262 \item[CHECK ACK] If the acknowledgement has been accepted by the
       
  2263   slave, the old state is kept. Still, the state change was
       
  2264   unsuccessful. $\rightarrow$~ERROR
       
  2265 
       
  2266   If the acknowledgement is ignored by the slave, a timeout happens.
       
  2267   In any case, the overall state change was unsuccessful.
       
  2268   $\rightarrow$~ERROR
       
  2269 
       
  2270   If there is still now response from the slave, but the timer did not
       
  2271   run out yet, the slave's ``AL Control Response'' attribute is
       
  2272   queried again.  $\rightarrow$~CHECK ACK
       
  2273 
       
  2274 \item[ERROR] If the state machine ends in this state, the slave's
       
  2275   state change was unsuccessful.
       
  2276 
  1512 
  2277 \end{description}
  1513 \end{description}
       
  1514 
       
  1515 The ``start\_ack'' state is a shortcut in the state machine for the case, that
       
  1516 the master wants to acknowledge a spontaneous AL state change, that was not
       
  1517 requested.
  2278 
  1518 
  2279 %------------------------------------------------------------------------------
  1519 %------------------------------------------------------------------------------
  2280 
  1520 
  2281 \section{The SII State Machine}
  1521 \section{The SII State Machine}
  2282 \label{sec:fsm-sii}
  1522 \label{sec:fsm-sii}
  2283 \index{FSM!SII}
  1523 \index{FSM!SII}
  2284 
  1524 
  2285 The SII\index{SII} state machine (shown in figure~\ref{fig:fsm-sii})
  1525 The SII\index{SII} state machine (shown in figure~\ref{fig:fsm-sii})
  2286 implements the process of reading or writing E$^2$PROM data via the
  1526 implements the process of reading or writing SII data via the
  2287 Slave Information Interface described in \cite[section~5.4]{alspec}.
  1527 Slave Information Interface described in \cite[section~6.4]{dlspec}.
  2288 
  1528 
  2289 \begin{figure}[htbp]
  1529 \begin{figure}[htbp]
  2290   \centering
  1530   \centering
  2291   \includegraphics[width=.9\textwidth]{images/fsm-sii}
  1531   \includegraphics[width=.5\textwidth]{graphs/fsm_sii}
  2292   \caption{Transition diagram of the SII state machine}
  1532   \caption{Transition Diagram of the SII State Machine}
  2293   \label{fig:fsm-sii}
  1533   \label{fig:fsm-sii}
  2294 \end{figure}
  1534 \end{figure}
  2295 
  1535 
       
  1536 This is how the reading part of the state machine works:
       
  1537 
  2296 \begin{description}
  1538 \begin{description}
  2297 \item[READ\_START] The beginning state for reading access, where the
  1539 
  2298   read request and the requested address are written to the SII
  1540 \item[Start Reading] The read request and the requested word address are
  2299   attribute. Nothing can fail up to now.
  1541 written to the SII attribute.
  2300   $\rightarrow$~READ\_CHECK
  1542 
  2301 
  1543 \item[Check Read Command] If the SII read request command has been
  2302 \item[READ\_CHECK] When the SII read request has been sent
  1544 acknowledged, a timer is started. A datagram is issued, that reads out the SII
  2303   successfully, a timer is started. A check/fetch datagram is issued,
  1545 attribute for state and data.
  2304   that reads out the SII attribute for state and data.
  1546 
  2305   $\rightarrow$~READ\_FETCH
  1547 \item[Fetch Data] If the read operation is still busy (the SII is usually
  2306 
  1548 implemented as an E$^2$PROM), the state is read again. Otherwise the data are
  2307 \item[READ\_FETCH] Upon reception of the check/fetch datagram, the
  1549 copied from the datagram.
  2308   \textit{Read Operation} and \textit{Busy} parameters are checked:
  1550 
  2309   \begin{itemize}
       
  2310   \item If the slave is still busy with fetching E$^2$PROM data into
       
  2311     the interface, the timer is checked. If it timed out, the reading
       
  2312     is aborted ($\rightarrow$~ERROR), if not, the check/fetch datagram
       
  2313     is issued again. $\rightarrow$~READ\_FETCH
       
  2314 
       
  2315   \item If the slave is ready with reading data, these are copied from
       
  2316     the datagram and the read cycle is completed.
       
  2317     $\rightarrow$~END
       
  2318   \end{itemize}
       
  2319 \end{description}
  1551 \end{description}
  2320 
  1552 
  2321 The write access states behave nearly the same:
  1553 The writing part works nearly similar:
  2322 
  1554 
  2323 \begin{description}
  1555 \begin{description}
  2324 \item[WRITE\_START] The beginning state for writing access,
  1556 
  2325   respectively. A write request, the target address and the data word
  1557 \item[Start Writing] A write request, the target address and the data word are
  2326   are written to the SII attribute. Nothing can fail.
  1558 written to the SII attribute.
  2327   $\rightarrow$~WRITE\_CHECK
  1559 
  2328 
  1560 \item[Check Write Command] If the SII write request command has been
  2329 \item[WRITE\_CHECK] When the SII write request has been sent
  1561 acknowledged, a timer is started. A datagram is issued, that reads out the SII
  2330   successfully, the timer is started. A check datagram is issued, that
  1562 attribute for the state of the write operation.
  2331   reads out the SII attribute for the state of the write operation.
  1563 
  2332   $\rightarrow$~WRITE\_CHECK2
  1564 \item[Wait while Busy] If the write operation is still busy (determined by a
  2333 
  1565 minimum wait time and the state of the busy flag), the state machine remains in
  2334 \item[WRITE\_CHECK2] Upon reception of the check datagram, the
  1566 this state to avoid that another write operation is issued too early.
  2335   \textit{Write Operation} and \textit{Busy} parameters are checked:
  1567 
  2336   \begin{itemize}
       
  2337   \item If the slave is still busy with writing E$^2$PROM data, the
       
  2338     timer is checked. If it timed out, the operation is aborted
       
  2339     ($\rightarrow$~ERROR), if not, the check datagram is issued again.
       
  2340     $\rightarrow$~WRITE\_CHECK2
       
  2341   \item If the slave is ready with writing data, the write cycle is
       
  2342     completed. $\rightarrow$~END
       
  2343   \end{itemize}
       
  2344 \end{description}
  1568 \end{description}
       
  1569 
       
  1570 %------------------------------------------------------------------------------
       
  1571 
       
  1572 \section{The Pdo State Machines}
       
  1573 \label{sec:fsm-pdo}
       
  1574 \index{FSM!Pdo}
       
  1575 
       
  1576 The Pdo state machines are a set of state machines that read or write the Pdo
       
  1577 assignment and the Pdo mapping via the ``CoE Communication Area'' described in
       
  1578 \cite[section 5.6.7.4]{alspec}. For the object access, the
       
  1579 CANopen-over-EtherCAT access primitives are used (see
       
  1580 section~\ref{sec:coeimp}), so the slave must support the CoE mailbox protocol.
       
  1581 
       
  1582 \paragraph{Pdo Reading FSM} This state machine (fig.~\ref{fig:fsm-pdo-read})
       
  1583 has the purpose to read the complete Pdo configuration of a slave. It reads
       
  1584 the Pdo assignment for each Sync Manager and uses the Pdo Entry Reading FSM
       
  1585 (fig.~\ref{fig:fsm-pdo-entry-read}) to read the mapping for each assigned Pdo.
       
  1586 
       
  1587 \begin{figure}[htbp]
       
  1588   \centering
       
  1589   \includegraphics[width=.4\textwidth]{graphs/fsm_pdo_read}
       
  1590   \caption{Transition Diagram of the Pdo Reading State Machine}
       
  1591   \label{fig:fsm-pdo-read}
       
  1592 \end{figure}
       
  1593 
       
  1594 Basically it reads the every Sync manager's Pdo assignment Sdo's
       
  1595 (\lstinline+0x1C1x+) number of elements to determine the number of assigned
       
  1596 Pdos for this sync manager and then reads out the subindices of the Sdo to get
       
  1597 the assigned Pdo's indices. When a Pdo index is read, the Pdo Entry Reading
       
  1598 FSM is executed to read the Pdo's mapped Pdo entries.
       
  1599 
       
  1600 \paragraph{Pdo Entry Reading FSM} This state machine
       
  1601 (fig.~\ref{fig:fsm-pdo-entry-read}) reads the Pdo mapping (the Pdo entries) of
       
  1602 a Pdo. It reads the respective mapping Sdo (\lstinline+0x1600+ -
       
  1603 \lstinline+0x17ff+, or \lstinline+0x1a00+ - \lstinline+0x1bff+) for the given
       
  1604 Pdo by reading first the subindex zero (number of elements) to determine the
       
  1605 number of mapped Pdo entries. After that, each subindex is read to get the
       
  1606 mapped Pdo entry index, subindex and bit size.
       
  1607 
       
  1608 \begin{figure}[htbp]
       
  1609   \centering
       
  1610   \includegraphics[width=.4\textwidth]{graphs/fsm_pdo_entry_read}
       
  1611   \caption{Transition Diagram of the Pdo Entry Reading State Machine}
       
  1612   \label{fig:fsm-pdo-entry-read}
       
  1613 \end{figure}
       
  1614 
       
  1615 \begin{figure}[htbp]
       
  1616   \centering
       
  1617   \includegraphics[width=.9\textwidth]{graphs/fsm_pdo_conf}
       
  1618   \caption{Transition Diagram of the Pdo Configuration State Machine}
       
  1619   \label{fig:fsm-pdo-conf}
       
  1620 \end{figure}
       
  1621 
       
  1622 \begin{figure}[htbp]
       
  1623   \centering
       
  1624   \includegraphics[width=.4\textwidth]{graphs/fsm_pdo_entry_conf}
       
  1625   \caption{Transition Diagram of the Pdo Entry Configuration State Machine}
       
  1626   \label{fig:fsm-pdo-entry-conf}
       
  1627 \end{figure}
  2345 
  1628 
  2346 %------------------------------------------------------------------------------
  1629 %------------------------------------------------------------------------------
  2347 
  1630 
  2348 \chapter{Mailbox Protocol Implementations}
  1631 \chapter{Mailbox Protocol Implementations}
  2349 \index{Mailbox}
  1632 \index{Mailbox}
  2355 
  1638 
  2356 \section{Ethernet-over-EtherCAT (EoE)}
  1639 \section{Ethernet-over-EtherCAT (EoE)}
  2357 \label{sec:eoeimp}
  1640 \label{sec:eoeimp}
  2358 \index{EoE}
  1641 \index{EoE}
  2359 
  1642 
  2360 The EtherCAT master implements the Ethernet-over-EtherCAT mailbox
  1643 The EtherCAT master implements the Ethernet-over-EtherCAT mailbox protocol to
  2361 protocol to enable the tunneling of Ethernet frames to special slaves,
  1644 enable the tunneling of Ethernet frames to special slaves, that can either
  2362 that can either have physical Ethernet ports to forward the frames to,
  1645 have physical Ethernet ports to forward the frames to, or have an own IP stack
  2363 or have an own IP stack to receive the frames.
  1646 to receive the frames.
  2364 
  1647 
  2365 \paragraph{Virtual Network Interfaces}
  1648 \paragraph{Virtual Network Interfaces}
  2366 
  1649 
  2367 The master creates a virtual EoE network interface for every
  1650 The master creates a virtual EoE network interface for every EoE-capable
  2368 EoE-capable slave. These interfaces are called \textit{eoeX}, where X
  1651 slave. These interfaces are called either
  2369 is a number provided by the kernel on interface registration. Frames
  1652 
  2370 sent to these interfaces are forwarded to the associated slaves by the
  1653 \begin{description}
  2371 master. Frames, that are received by the slaves, are fetched by the
  1654 
  2372 master and forwarded to the virtual interfaces.
  1655 \item[eoeXsY] for a slave without an alias address (see
       
  1656 section~\ref{sec:alias}), where X is the master index and Y is the slave's
       
  1657 ring position, or
       
  1658 
       
  1659 \item[eoeXaY] for a slave with a non-zero alias address, where X is the master
       
  1660 index and Y is the decimal alias address.
       
  1661 
       
  1662 \end{description}
       
  1663 
       
  1664 Frames sent to these interfaces are forwarded to the associated slaves by the
       
  1665 master. Frames, that are received by the slaves, are fetched by the master and
       
  1666 forwarded to the virtual interfaces.
  2373 
  1667 
  2374 This bears the following advantages:
  1668 This bears the following advantages:
  2375 
  1669 
  2376 \begin{itemize}
  1670 \begin{itemize}
       
  1671 
  2377 \item Flexibility: The user can decide, how the EoE-capable slaves are
  1672 \item Flexibility: The user can decide, how the EoE-capable slaves are
  2378   interconnected with the rest of the world.
  1673 interconnected with the rest of the world.
  2379 \item Standard tools can be used to monitor the EoE activity and to
  1674 
  2380   configure the EoE interfaces.
  1675 \item Standard tools can be used to monitor the EoE activity and to configure
  2381 \item The Linux kernel's layer-2-bridging implementation (according to
  1676 the EoE interfaces.
  2382   the IEEE 802.1D MAC Bridging standard) can be used natively to
  1677 
  2383   bridge Ethernet traffic between EoE-capable slaves.
  1678 \item The Linux kernel's layer-2-bridging implementation (according to the
  2384 \item The Linux kernel's network stack can be used to route packets
  1679 IEEE 802.1D MAC Bridging standard) can be used natively to bridge Ethernet
  2385   between EoE-capable slaves and to track security issues, just like
  1680 traffic between EoE-capable slaves.
  2386   having physical network interfaces.
  1681 
       
  1682 \item The Linux kernel's network stack can be used to route packets between
       
  1683 EoE-capable slaves and to track security issues, just like having physical
       
  1684 network interfaces.
       
  1685 
  2387 \end{itemize}
  1686 \end{itemize}
  2388 
  1687 
  2389 \paragraph{EoE Handlers}
  1688 \paragraph{EoE Handlers}
  2390 
  1689 
  2391 The virtual EoE interfaces and the related functionality is encapsulated in the
  1690 The virtual EoE interfaces and the related functionality is encapsulated in
  2392 \textit{ec\_eoe\_t} class (see section~\ref{sec:class-eoe}).  So the master
  1691 the \lstinline+ec_eoe_t+ class. An object of this class is called ``EoE
  2393 does not create the network interfaces directly: This is done inside the
  1692 handler''. For example the master does not create the network interfaces
  2394 constructor of the \textit{ec\_eoe\_t} class. An object of this class is called
  1693 directly: This is done inside the constructor of an EoE handler. An EoE
  2395 ``EoE handler'' below. An EoE handler additionally contains a frame queue. Each
  1694 handler additionally contains a frame queue. Each time, the kernel passes a
  2396 time, the kernel passes a new socket buffer for sending via the interface's
  1695 new socket buffer for sending via the interface's
  2397 \textit{hard\_start\_xmit()} callback, the socket buffer is queued for
  1696 \lstinline+hard_start_xmit()+ callback, the socket buffer is queued for
  2398 transmission by the EoE state machine (see below). If the queue gets filled up,
  1697 transmission by the EoE state machine (see below). If the queue gets filled
  2399 the passing of new socket buffers is suspended with a call to
  1698 up, the passing of new socket buffers is suspended with a call to
  2400 \textit{netif\_stop\_queue()}.
  1699 \lstinline+netif_stop_queue()+.
  2401 
  1700 
  2402 \paragraph{Static Handler Creation}
  1701 \paragraph{Creation of EoE Handlers}
  2403 
  1702 
  2404 The master creates a pool of EoE handlers at startup, that are coupled
  1703 During bus scanning (see section~\ref{sec:fsm-scan}), the master determines
  2405 to EoE-capable slaves on demand. The lifetime of the corresponding
  1704 the supported mailbox protocols foe each slave. This is done by examining the
  2406 network interfaces is equal to the lifetime of the master module.
  1705 ``Supported Mailbox Protocols'' mask field at word address 0x001C of the
  2407 This approach is opposed to creating the virtual network interfaces on
  1706 SII\index{SII}. If bit 1 is set, the slave supports the EoE protocol. In this
  2408 demand (i.~e. on running across a new EoE-capable slave). The latter
  1707 case, an EoE handler is created for that slave.
  2409 approach was considered as difficult, because of several reasons:
       
  2410 
       
  2411 \begin{itemize}
       
  2412 \item The \textit{alloc\_netdev()} function can sleep and must be
       
  2413   called from a non-interrupt context. This reduces the flexibility of
       
  2414   choosing an appropriate method for cyclic EoE processing.
       
  2415 \item Unregistering network interfaces requires them to be ``down'',
       
  2416   which can not be guaranteed upon sudden disappearing of an
       
  2417   EoE-capable slave.
       
  2418 \item The connection to the EoE-capable slaves must be as continuous
       
  2419   as possible. Especially the transition from idle to operation mode
       
  2420   (and vice versa) causes the rebuilding of the internal data
       
  2421   structures. These transitions must be as transparent as possible for
       
  2422   the instances using the network interfaces.
       
  2423 \end{itemize}
       
  2424 
       
  2425 \paragraph{Number of Handlers} % FIXME
       
  2426 
       
  2427 The master module has a parameter \textit{ec\_eoeif\_count} to specify
       
  2428 the number of EoE interfaces (and handlers) per master to create. This
       
  2429 parameter can either be specified when manually loading the master
       
  2430 module, or (when using the init script) by setting the
       
  2431 \$EOE\_INTERFACES variable in the sysconfig file (see
       
  2432 section~\ref{sec:sysconfig}). Upon loading of the master module, the
       
  2433 virtual interfaces become available:
       
  2434 
       
  2435 \begin{lstlisting}[gobble=2]
       
  2436   # `\textbf{ifconfig -a}`
       
  2437   eoe0      Link encap:Ethernet  HWaddr 00:11:22:33:44:06
       
  2438             BROADCAST MULTICAST  MTU:1500  Metric:1
       
  2439             RX packets:0 errors:0 dropped:0 overruns:0 frame:0
       
  2440             TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
       
  2441             collisions:0 txqueuelen:1000
       
  2442             RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)
       
  2443 
       
  2444   eoe1      Link encap:Ethernet  HWaddr 00:11:22:33:44:07
       
  2445             BROADCAST MULTICAST  MTU:1500  Metric:1
       
  2446             RX packets:0 errors:0 dropped:0 overruns:0 frame:0
       
  2447             TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
       
  2448             collisions:0 txqueuelen:1000
       
  2449             RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)
       
  2450   ...
       
  2451 \end{lstlisting}
       
  2452 
       
  2453 \paragraph{Coupling of EoE Slaves}
       
  2454 
       
  2455 During execution of the slave scan state machine (see
       
  2456 section~\ref{sec:fsm-scan}), the master determines the supported
       
  2457 mailbox protocols. This is done by examining the ``Supported Mailbox
       
  2458 Protocols'' mask field at word address 0x001C of the SII\index{SII}.
       
  2459 If bit 1 is set, the slave supports the EoE protocol. After slave
       
  2460 scanning, the master runs through all slaves again and couples each
       
  2461 EoE-capable slave to a free EoE handler. It can happen, that there are
       
  2462 not enough EoE handlers to cover all EoE-capable slaves. In this case,
       
  2463 the number of EoE handlers must be increased accordingly.
       
  2464 
  1708 
  2465 \paragraph{EoE State Machine}
  1709 \paragraph{EoE State Machine}
  2466 \index{FSM!EoE}
  1710 \index{FSM!EoE}
  2467 
  1711 
  2468 Every EoE handler owns an EoE state machine, that is used to send
  1712 Every EoE handler owns an EoE state machine, that is used to send frames to
  2469 frames to the coupled slave and receive frames from the it via the EoE
  1713 the corresponding slave and receive frames from the it via the EoE
  2470 communication primitives. This state machine is showed in
  1714 communication primitives. This state machine is showed in
  2471 figure~\ref{fig:fsm-eoe}.
  1715 figure~\ref{fig:fsm-eoe}.
  2472 
  1716 
  2473 \begin{figure}[htbp]
  1717 \begin{figure}[htbp]
  2474   \centering
  1718   \centering
  2475   \includegraphics[width=.7\textwidth]{images/fsm-eoe}
  1719   \includegraphics[width=.7\textwidth]{images/fsm-eoe} % FIXME
  2476   \caption{Transition diagram of the EoE state machine}
  1720   \caption{Transition Diagram of the EoE State Machine}
  2477   \label{fig:fsm-eoe}
  1721   \label{fig:fsm-eoe}
  2478 \end{figure}
  1722 \end{figure}
       
  1723 
       
  1724 % FIXME
  2479 
  1725 
  2480 \begin{description}
  1726 \begin{description}
  2481 \item[RX\_START] The beginning state of the EoE state machine. A
  1727 \item[RX\_START] The beginning state of the EoE state machine. A
  2482   mailbox check datagram is sent, to query the slave's mailbox for new
  1728   mailbox check datagram is sent, to query the slave's mailbox for new
  2483   frames. $\rightarrow$~RX\_CHECK
  1729   frames. $\rightarrow$~RX\_CHECK
  2522   $\rightarrow$~RX\_START
  1768   $\rightarrow$~RX\_START
  2523 \end{description}
  1769 \end{description}
  2524 
  1770 
  2525 \paragraph{EoE Processing}
  1771 \paragraph{EoE Processing}
  2526 
  1772 
  2527 To execute the EoE state machine of every active EoE handler, there
  1773 To execute the EoE state machine of every active EoE handler, there must be a
  2528 must be a cyclic process. The easiest thing would be to execute the
  1774 cyclic process. The easiest solution would be to execute the EoE state
  2529 EoE state machines synchronously to the operation state machine (see
  1775 machines synchronously with the master state machine (see
  2530 section~\ref{sec:fsm-op}) with every realtime cycle. This approach has
  1776 section~\ref{sec:fsm-master}). This approach has the following disadvantage:
  2531 the following disadvantages:
  1777 
  2532 
  1778 Only one EoE fragment could be sent or received every few cycles. This
  2533 \begin{itemize}
       
  2534 
       
  2535 \item Only one EoE fragment can be sent or received every few cycles.  This
       
  2536 causes the data rate to be very low, because the EoE state machines are not
  1779 causes the data rate to be very low, because the EoE state machines are not
  2537 executed in the time between the application cycles. Moreover, the data rate
  1780 executed in the time between the application cycles. Moreover, the data rate
  2538 would be dependent on the period of the application task.
  1781 would be dependent on the period of the application task.
  2539 
  1782 
  2540 \item The receiving and forwarding of frames to the kernel requires the dynamic
  1783 To overcome this problem, an own cyclic process is needed to asynchronously
  2541 allocation of frames. Some realtime extensions do not support calling memory
  1784 execute the EoE state machines. For that, the master owns a kernel timer, that
  2542 allocation functions in realtime context, so the EoE state machine may not be
  1785 is executed each timer interrupt. This guarantees a constant bandwidth, but
  2543 executed with each application cycle.
  1786 poses the new problem of concurrent access to the master. The locking
  2544 
  1787 mechanisms needed for this are introduced in section~\ref{sec:concurr}.
  2545 \end{itemize}
       
  2546 
       
  2547 To overcome these problems, an own cyclic process is needed to
       
  2548 asynchronously execute the EoE state machines. For that, the master
       
  2549 owns a kernel timer, that is executed each timer interrupt. This
       
  2550 guarantees a constant bandwidth, but poses the new problem of
       
  2551 concurrent access to the master. The locking mechanisms needed for
       
  2552 this are introduced in section~\ref{sec:concurr}.
       
  2553 Section~\ref{sec:concurrency} gives practical implementation examples.
       
  2554 
       
  2555 \paragraph{Idle phase}
       
  2556 
       
  2557 EoE data must also be exchanged in idle phase, to guarantee the continuous
       
  2558 availability of the connection to the EoE-capable slaves. Although there is no
       
  2559 application connected in this case, the master is still accessed by the master
       
  2560 state machine (see section~\ref{sec:fsm-master}). With the EoE timer running in
       
  2561 addition, there is still concurrency, that has to be protected by a lock.
       
  2562 Therefore the master owns an internal spinlock that is used protect master
       
  2563 access during idle phase.
       
  2564 
  1788 
  2565 \paragraph{Automatic Configuration}
  1789 \paragraph{Automatic Configuration}
  2566 
  1790 
  2567 By default, slaves are left in INIT state during idle mode. If an EoE
  1791 By default, slaves are left in PREOP state, if no configuration is applied. If
  2568 interface is set to running state (i.~e. with the \textit{ifconfig up}
  1792 an EoE interface link is set to ``up'', the requested slave's
  2569 command), the requested slave state of the related slave is
  1793 application-layer state is automatically set to OP.
  2570 automatically set to OP, whereupon the idle state machine will attempt
       
  2571 to configure the slave and put it into operation.
       
  2572 
  1794 
  2573 %------------------------------------------------------------------------------
  1795 %------------------------------------------------------------------------------
  2574 
  1796 
  2575 \section{CANopen-over-EtherCAT (CoE)}
  1797 \section{CANopen-over-EtherCAT (CoE)}
  2576 \label{sec:coeimp}
  1798 \label{sec:coeimp}
  2577 \index{CoE}
  1799 \index{CoE}
  2578 
  1800 
  2579 The CANopen-over-EtherCAT protocol \cite[section~5.6]{alspec} is used
  1801 The CANopen-over-EtherCAT protocol \cite[section~5.6]{alspec} is used to
  2580 to configure slaves on application level. Each CoE-capable slave
  1802 configure slaves and exchange data objects on application level.
  2581 provides a list of Sdos for this reason.
  1803 
  2582 
  1804 % FIXME
  2583 \paragraph{Sdo Configuration}
  1805 %
  2584 
  1806 % Download / Upload
  2585 The Sdo configurations have to be provided by the application.  This is done
  1807 % Expedited / Normal
  2586 via the \textit{ecrt\_slave\_conf\_sdo*()} methods (see
  1808 % Segmenting
  2587 section~\ref{sec:ecrt-slave}), that are part of the realtime interface. The
  1809 % Sdo Info Services
  2588 slave stores the Sdo configurations in a linked list, but does not apply them
  1810 %
  2589 at once.
  1811 
       
  1812 \ldots
  2590 
  1813 
  2591 \paragraph{Sdo Download State Machine}
  1814 \paragraph{Sdo Download State Machine}
  2592 
  1815 
  2593 The best time to apply Sdo configurations is during the slave's PREOP
  1816 The best time to apply Sdo configurations is during the slave's PREOP
  2594 state, because mailbox communication is already possible and slave's
  1817 state, because mailbox communication is already possible and slave's
  2603 The transition diagram of the Sdo Download state machine can be seen
  1826 The transition diagram of the Sdo Download state machine can be seen
  2604 in figure~\ref{fig:fsm-coedown}.
  1827 in figure~\ref{fig:fsm-coedown}.
  2605 
  1828 
  2606 \begin{figure}[htbp]
  1829 \begin{figure}[htbp]
  2607   \centering
  1830   \centering
  2608   \includegraphics[width=.9\textwidth]{images/fsm-coedown}
  1831   \includegraphics[width=.9\textwidth]{images/fsm-coedown} % FIXME
  2609   \caption{Transition diagram of the CoE download state machine}
  1832   \caption{Transition diagram of the CoE download state machine}
  2610   \label{fig:fsm-coedown}
  1833   \label{fig:fsm-coedown}
  2611 \end{figure}
  1834 \end{figure}
       
  1835 
       
  1836 % FIXME
  2612 
  1837 
  2613 \begin{description}
  1838 \begin{description}
  2614 \item[START] The beginning state of the CoE download state
  1839 \item[START] The beginning state of the CoE download state
  2615   machine. The ``Sdo Download Normal Request'' mailbox command is
  1840   machine. The ``Sdo Download Normal Request'' mailbox command is
  2616   sent. $\rightarrow$~REQUEST
  1841   sent. $\rightarrow$~REQUEST
  2648 
  1873 
  2649 \chapter{User Space}
  1874 \chapter{User Space}
  2650 \label{sec:user}
  1875 \label{sec:user}
  2651 \index{User space}
  1876 \index{User space}
  2652 
  1877 
  2653 For the master runs as a kernel module, accessing it is natively
  1878 % FIXME
  2654 limited to analyzing Syslog messages and controlling using modutils.
  1879 
  2655 
  1880 For the master runs as a kernel module, accessing it is natively limited to
  2656 It is necessary to implement further interfaces, that make it easier
  1881 analyzing Syslog messages and controlling using modutils.
  2657 to access the master from user space and allow a finer influence. It
  1882 
  2658 should be possible to view and to change special parameters at runtime.
  1883 It is necessary to implement further interfaces, that make it easier to access
  2659 
  1884 the master from user space and allow a finer influence. It should be possible
  2660 Bus visualization is a second point: For development and debugging
  1885 to view and to change special parameters at runtime.
  2661 purposes it would be nice, if one could show the connected slaves with
  1886 
  2662 a single command.
  1887 Bus visualization is a second point: For development and debugging purposes it
  2663 
  1888 would be nice, if one could show the connected slaves with a single command.
  2664 Another aspect is automatic startup and configuration. If the master
  1889 
  2665 is to be integrated into a running system, it must be able to
  1890 Another aspect is automatic startup and configuration. If the master is to be
  2666 automatically start with a persistent configuration.
  1891 integrated into a running system, it must be able to automatically start with
  2667 
  1892 a persistent configuration.
  2668 A last thing is monitoring EtherCAT communication. For debugging
  1893 
  2669 purposes, there had to be a way to analyze EtherCAT datagrams. The
  1894 A last thing is monitoring EtherCAT communication. For debugging purposes,
  2670 best way would be with a popular network analyzer, like Wireshark
  1895 there had to be a way to analyze EtherCAT datagrams. The best way would be
  2671 \cite{wireshark} (the former Ethereal) or others.
  1896 with a popular network analyzer, like Wireshark \cite{wireshark} (the former
  2672 
  1897 Ethereal) or others.
  2673 This section covers all those points and introduces the interfaces and
  1898 
  2674 tools to make all that possible.
  1899 This section covers all those points and introduces the interfaces and tools
       
  1900 to make all that possible.
  2675 
  1901 
  2676 %------------------------------------------------------------------------------
  1902 %------------------------------------------------------------------------------
  2677 
  1903 
  2678 \section{Command-line Tool}
  1904 \section{Command-line Tool}
  2679 \label{sec:ethercat}
  1905 \label{sec:ethercat}
  2680 
  1906 
  2681 % --master
  1907 % --master
  2682 
  1908 
  2683 \subsection{Character devices}
  1909 \subsection{Character Devices}
  2684 \label{sec:cdev}
  1910 \label{sec:cdev}
  2685 
  1911 
  2686 Each master instance will get a character device as a user-space interface.
  1912 Each master instance will get a character device as a user-space interface.
  2687 The devices are named \textit{/dev/EtherCATX}, where $X$ is the index of the
  1913 The devices are named \textit{/dev/EtherCATX}, where $X$ is the index of the
  2688 master.
  1914 master.
  2691 % udev
  1917 % udev
  2692 % rights
  1918 % rights
  2693 
  1919 
  2694 %------------------------------------------------------------------------------
  1920 %------------------------------------------------------------------------------
  2695 
  1921 
  2696 \subsection{Setting alias addresses}
  1922 \subsection{Setting Alias Addresses}
       
  1923 \label{sec:alias} % FIXME
  2697 
  1924 
  2698 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_alias}
  1925 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_alias}
  2699 
  1926 
  2700 %------------------------------------------------------------------------------
  1927 %------------------------------------------------------------------------------
  2701 
  1928 
  2702 \subsection{Displaying the bus configuration}
  1929 \subsection{Displaying the Bus Configuration}
  2703 
  1930 
  2704 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_config}
  1931 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_config}
  2705 
  1932 
  2706 %------------------------------------------------------------------------------
  1933 %------------------------------------------------------------------------------
  2707 
  1934 
  2708 \subsection{Displaying process data}
  1935 \subsection{Displaying Process Data}
  2709 
  1936 
  2710 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_data}
  1937 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_data}
  2711 
  1938 
  2712 %------------------------------------------------------------------------------
  1939 %------------------------------------------------------------------------------
  2713 
  1940 
  2714 \subsection{Setting a master's debug level}
  1941 \subsection{Setting a Master's Debug Level}
  2715 
  1942 
  2716 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_debug}
  1943 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_debug}
  2717 
  1944 
  2718 %------------------------------------------------------------------------------
  1945 %------------------------------------------------------------------------------
  2719 
  1946 
  2720 \subsection{Configured domains}
  1947 \subsection{Configured Domains}
  2721 
  1948 
  2722 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_domains}
  1949 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_domains}
  2723 
  1950 
  2724 %------------------------------------------------------------------------------
  1951 %------------------------------------------------------------------------------
  2725 
  1952 
  2726 \subsection{Master and Ethernet device information}
  1953 \subsection{Master and Ethernet Devices}
  2727 
  1954 
  2728 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_master}
  1955 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_master}
  2729 
  1956 
  2730 %------------------------------------------------------------------------------
  1957 %------------------------------------------------------------------------------
  2731 
  1958 
  2732 \subsection{Showing slaves' sync managers, Pdos and Pdo entries}
  1959 \subsection{Sync Managers, Pdos and Pdo Entries}
  2733 
  1960 
  2734 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_pdos}
  1961 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_pdos}
  2735 
  1962 
  2736 %------------------------------------------------------------------------------
  1963 %------------------------------------------------------------------------------
  2737 
  1964 
  2738 \subsection{Displaying the Sdo dictionary}
  1965 \subsection{Sdo Dictionary}
  2739 
  1966 
  2740 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_sdos}
  1967 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_sdos}
  2741 
  1968 
  2742 %------------------------------------------------------------------------------
  1969 %------------------------------------------------------------------------------
  2743 
  1970 
  2744 \subsection{Sdo access}
  1971 \subsection{Sdo Access}
  2745 
  1972 
  2746 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_download}
  1973 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_download}
  2747 
  1974 
  2748 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_upload}
  1975 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_upload}
  2749 
  1976 
  2750 %------------------------------------------------------------------------------
  1977 %------------------------------------------------------------------------------
  2751 
  1978 
  2752 \subsection{Displaying slaves on the bus}
  1979 \subsection{Slaves on the Bus}
  2753 
  1980 
  2754 Slave information can be gathered with the subcommand \lstinline+slaves+:
  1981 Slave information can be gathered with the subcommand \lstinline+slaves+:
  2755 
  1982 
  2756 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_slaves}
  1983 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_slaves}
  2757 
  1984 
  2792 
  2019 
  2793 Reading out SII data is as easy as other commands. Though the data are in
  2020 Reading out SII data is as easy as other commands. Though the data are in
  2794 binary format, analysis is easier with a tool like \textit{hexdump}:
  2021 binary format, analysis is easier with a tool like \textit{hexdump}:
  2795 
  2022 
  2796 \begin{lstlisting}
  2023 \begin{lstlisting}
  2797 $ `\textbf{ethercat sii\_read --slave 3 | hexdump}`
  2024 $ `\textbf{ethercat sii\_read --position 3 | hexdump}`
  2798 0000000 0103 0000 0000 0000 0000 0000 0000 008c
  2025 0000000 0103 0000 0000 0000 0000 0000 0000 008c
  2799 0000010 0002 0000 3052 07f0 0000 0000 0000 0000
  2026 0000010 0002 0000 3052 07f0 0000 0000 0000 0000
  2800 0000020 0000 0000 0000 0000 0000 0000 0000 0000
  2027 0000020 0000 0000 0000 0000 0000 0000 0000 0000
  2801 ...
  2028 ...
  2802 \end{lstlisting}
  2029 \end{lstlisting}
  2803 
  2030 
  2804 Backing up SII contents can easily done with a redirection:
  2031 Backing up SII contents can easily done with a redirection:
  2805 
  2032 
  2806 \begin{lstlisting}
  2033 \begin{lstlisting}
  2807 $ `\textbf{ethercat sii\_read --slave 3 > sii-of-slave3.bin}`
  2034 $ `\textbf{ethercat sii\_read --position 3 > sii-of-slave3.bin}`
  2808 \end{lstlisting}
  2035 \end{lstlisting}
  2809 
  2036 
  2810 To download SII contents to a slave, writing access to the master's character
  2037 To download SII contents to a slave, writing access to the master's character
  2811 device is necessary (see section~\ref{sec:cdev}).
  2038 device is necessary (see section~\ref{sec:cdev}).
  2812 
  2039 
  2813 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_sii_write}
  2040 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_sii_write}
  2814 
  2041 
  2815 \begin{lstlisting}
  2042 \begin{lstlisting}
  2816 # `\textbf{ethercat sii\_write --slave 3 sii-of-slave3.bin}`
  2043 # `\textbf{ethercat sii\_write --position 3 sii-of-slave3.bin}`
  2817 \end{lstlisting}
  2044 \end{lstlisting}
  2818 
  2045 
  2819 The SII contents will be checked for validity and then sent to the slave. The
  2046 The SII contents will be checked for validity and then sent to the slave. The
  2820 write operation may take a few seconds.
  2047 write operation may take a few seconds.
  2821 
  2048 
  2822 %------------------------------------------------------------------------------
  2049 %------------------------------------------------------------------------------
  2823 
  2050 
  2824 \subsection{Requesting application-layer states}
  2051 \subsection{Requesting Application-Layer States}
  2825 
  2052 
  2826 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_states}
  2053 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_states}
  2827 
  2054 
  2828 %------------------------------------------------------------------------------
  2055 %------------------------------------------------------------------------------
  2829 
  2056 
  2830 \subsection{Generating slave description XML}
  2057 \subsection{Generating Slave Description XML}
  2831 
  2058 
  2832 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_xml}
  2059 \lstinputlisting[basicstyle=\ttfamily\footnotesize]{external/ethercat_xml}
  2833 
  2060 
  2834 %------------------------------------------------------------------------------
  2061 %------------------------------------------------------------------------------
  2835 
  2062 
  2843 \label{sec:init}
  2070 \label{sec:init}
  2844 \index{Init script}
  2071 \index{Init script}
  2845 
  2072 
  2846 The EtherCAT master init script conforms to the requirements of the ``Linux
  2073 The EtherCAT master init script conforms to the requirements of the ``Linux
  2847 Standard Base'' (LSB\index{LSB}, \cite{lsb}). The script is installed to
  2074 Standard Base'' (LSB\index{LSB}, \cite{lsb}). The script is installed to
  2848 \textit{etc/init.d/ethercat} below the installation prefix and has to be copied
  2075 \textit{etc/init.d/ethercat} below the installation prefix and has to be
  2849 (or better: linked) to the appropriate location (see
  2076 copied (or better: linked) to the appropriate location (see
  2850 section~\ref{sec:install}), before the master can be inserted as a service.
  2077 section~\ref{sec:installation}), before the master can be inserted as a
  2851 Please note, that the init script depends on the sysconfig file described
  2078 service.  Please note, that the init script depends on the sysconfig file
  2852 below.
  2079 described below.
  2853 
  2080 
  2854 To provide service dependencies (i.~e. which services have to be started before
  2081 To provide service dependencies (i.~e. which services have to be started before
  2855 others) inside the init script code, LSB defines a special comment block.
  2082 others) inside the init script code, LSB defines a special comment block.
  2856 System tools can extract this information to insert the EtherCAT init script at
  2083 System tools can extract this information to insert the EtherCAT init script at
  2857 the correct place in the startup sequence:
  2084 the correct place in the startup sequence:
  2858 
  2085 
  2859 \lstinputlisting[firstline=38,lastline=48]
  2086 \lstinputlisting[firstline=38,lastline=48]
  2860     {../script/init.d/ethercat}
  2087     {../script/init.d/ethercat}
  2861 
  2088 
  2862 \subsection{Sysconfig}
  2089 \subsection{Sysconfig File}
  2863 \label{sec:sysconfig}
  2090 \label{sec:sysconfig}
  2864 \index{Sysconfig file}
  2091 \index{Sysconfig file}
  2865 
  2092 
  2866 For persistent configuration, the init script uses a sysconfig file installed
  2093 For persistent configuration, the init script uses a sysconfig file installed
  2867 to \textit{etc/sysconfig/ethercat} (below the installation prefix), that is
  2094 to \textit{etc/sysconfig/ethercat} (below the installation prefix), that is
  2870 the file and included below:
  2097 the file and included below:
  2871 
  2098 
  2872 \lstinputlisting[numbers=left,firstline=9,basicstyle=\ttfamily\scriptsize]
  2099 \lstinputlisting[numbers=left,firstline=9,basicstyle=\ttfamily\scriptsize]
  2873     {../script/sysconfig/ethercat}
  2100     {../script/sysconfig/ethercat}
  2874 
  2101 
  2875 \subsection{Service}
  2102 \subsection{Starting the Master as a Service}
  2876 \label{sec:service}
  2103 \label{sec:service}
  2877 \index{Service}
  2104 \index{Service}
  2878 
  2105 
  2879 After the init script and the sysconfig file are placed into the right
  2106 After the init script and the sysconfig file are placed into the right
  2880 location, the EtherCAT master can be inserted as a service. The different Linux
  2107 location, the EtherCAT master can be inserted as a service. The different Linux
  2900 
  2127 
  2901 \section{Monitoring and Debugging}
  2128 \section{Monitoring and Debugging}
  2902 \label{sec:debug}
  2129 \label{sec:debug}
  2903 \index{Monitoring}
  2130 \index{Monitoring}
  2904 
  2131 
       
  2132 % FIXME
       
  2133 
  2905 For debugging purposes, every EtherCAT master registers a read-only network
  2134 For debugging purposes, every EtherCAT master registers a read-only network
  2906 interface \textit{ecX}, where X is a number, provided by the kernel on device
  2135 interface \textit{ecX}, where X is a number, provided by the kernel on device
  2907 registration. While it is ``up'', the master forwards every frame sent and
  2136 registration. While it is ``up'', the master forwards every frame sent and
  2908 received to this interface.
  2137 received to this interface.
  2909 
  2138 
  2928 Although EtherCAT's timing is highly deterministic and therefore timing issues
  2157 Although EtherCAT's timing is highly deterministic and therefore timing issues
  2929 are rare, there are a few aspects that can (and should be) dealt with.
  2158 are rare, there are a few aspects that can (and should be) dealt with.
  2930 
  2159 
  2931 %------------------------------------------------------------------------------
  2160 %------------------------------------------------------------------------------
  2932 
  2161 
  2933 \subsection{Realtime Interface Profiling}
  2162 \subsection{Application Interface Profiling}
  2934 \label{sec:timing-profile}
  2163 \label{sec:timing-profile}
  2935 \index{Realtime!Profiling}
  2164 \index{Profiling}
       
  2165 % FIXME
  2936 
  2166 
  2937 One of the most important timing aspects are the execution times of the
  2167 One of the most important timing aspects are the execution times of the
  2938 realtime interface functions, that are called in cyclic context. These
  2168 application interface functions, that are called in cyclic context. These
  2939 functions make up an important part of the overall timing of the application.
  2169 functions make up an important part of the overall timing of the application.
  2940 To measure the timing of the functions, the following code was used:
  2170 To measure the timing of the functions, the following code was used:
  2941 
  2171 
  2942 \begin{lstlisting}[gobble=2,language=C]
  2172 \begin{lstlisting}[gobble=2,language=C]
  2943   c0 = get_cycles();
  2173   c0 = get_cycles();
  2961 \unit{100}{\micro\second}. The measuring was repeated $n = 100$ times and the
  2191 \unit{100}{\micro\second}. The measuring was repeated $n = 100$ times and the
  2962 results were averaged. These can be seen in table~\ref{tab:profile}.
  2192 results were averaged. These can be seen in table~\ref{tab:profile}.
  2963 
  2193 
  2964 \begin{table}[htpb]
  2194 \begin{table}[htpb]
  2965   \centering
  2195   \centering
  2966   \caption{Profiling of a Realtime Cycle on a \unit{2.0}{\giga\hertz}
  2196   \caption{Profiling of an Application Cycle on a \unit{2.0}{\giga\hertz}
  2967   Processor}
  2197   Processor}
  2968   \label{tab:profile}
  2198   \label{tab:profile}
  2969   \vspace{2mm}
  2199   \vspace{2mm}
  2970   \begin{tabular}{l|r|r}
  2200   \begin{tabular}{l|r|r}
  2971     Element & Mean Duration [\second] & Standard Deviancy [\micro\second] \\
  2201     Element & Mean Duration [\second] & Standard Deviancy [\micro\second] \\
  3030 is sent or received (polling would distort the results). The second
  2260 is sent or received (polling would distort the results). The second
  3031 reason is, that even with interrupts enabled, the time from the event
  2261 reason is, that even with interrupts enabled, the time from the event
  3032 to the notification is unknown. Therefore the only way to confidently
  2262 to the notification is unknown. Therefore the only way to confidently
  3033 determine the bus cycle time is an electrical measuring.
  2263 determine the bus cycle time is an electrical measuring.
  3034 
  2264 
  3035 Anyway, the bus cycle time is an important factor when designing realtime code,
  2265 Anyway, the bus cycle time is an important factor when designing realtime
  3036 because it limits the maximum frequency for the cyclic task of the application.
  2266 code, because it limits the maximum frequency for the cyclic task of the
  3037 In practice, these timing parameters are highly dependent on the hardware and
  2267 application.  In practice, these timing parameters are highly dependent on the
  3038 often a trial and error method must be used to determine the limits of the
  2268 hardware and often a trial and error method must be used to determine the
  3039 system.
  2269 limits of the system.
  3040 
  2270 
  3041 The central question is: What happens, if the cycle frequency is too high? The
  2271 The central question is: What happens, if the cycle frequency is too high? The
  3042 answer is, that the EtherCAT frames that have been sent at the end of the cycle
  2272 answer is, that the EtherCAT frames that have been sent at the end of the cycle
  3043 are not yet received, when the next cycle starts.  First this is noticed by
  2273 are not yet received, when the next cycle starts.  First this is noticed by
  3044 \textit{ecrt\_domain\_process()}, because the working counter of the process
  2274 \textit{ecrt\_domain\_process()}, because the working counter of the process
  3062 
  2292 
  3063 \chapter{Installation}
  2293 \chapter{Installation}
  3064 \label{sec:installation}
  2294 \label{sec:installation}
  3065 \index{Master!Installation}
  2295 \index{Master!Installation}
  3066 
  2296 
  3067 \section{Building the software}
  2297 \section{Building the Software}
  3068 
  2298 
  3069 The current EtherCAT master code is available at~\cite{etherlab} or can be
  2299 The current EtherCAT master code is available at~\cite{etherlab} or can be
  3070 obtained from the EtherLab CD. The \textit{tar.bz2} file has to be unpacked
  2300 obtained from the EtherLab CD. The \textit{tar.bz2} file has to be unpacked
  3071 with the commands below (or similar):
  2301 with the commands below (or similar):
  3072 
  2302 
  3073 \begin{lstlisting}[gobble=2]
  2303 \begin{lstlisting}[gobble=2]
  3074   `\$` `\textbf{tar xjf ethercat-\masterversion.tar.bz2}`
  2304   $ `\textbf{tar xjf ethercat-\masterversion.tar.bz2}`
  3075   `\$` `\textbf{cd ethercat-\masterversion/}`
  2305   $ `\textbf{cd ethercat-\masterversion/}`
  3076 \end{lstlisting}
  2306 \end{lstlisting}
  3077 
  2307 
  3078 The tarball was created with GNU Autotools, so the build process
  2308 The tarball was created with GNU Autotools, so the build process
  3079 follows the below commands:
  2309 follows the below commands:
  3080 
  2310 
  3081 \begin{lstlisting}[gobble=2]
  2311 \begin{lstlisting}[gobble=2]
  3082   `\$` `\textbf{./configure}`
  2312   $ `\textbf{./configure}`
  3083   `\$` `\textbf{make}`
  2313   $ `\textbf{make}`
  3084   `\$` `\textbf{make modules}`
  2314   $ `\textbf{make modules}`
  3085 \end{lstlisting}
  2315 \end{lstlisting}
  3086 
  2316 
  3087 Table~\ref{tab:config} lists important configuration switches and options.
  2317 Table~\ref{tab:config} lists important configuration switches and options.
  3088 
  2318 
  3089 \begin{table}
  2319 \begin{table}
  3143 
  2373 
  3144 \end{description}
  2374 \end{description}
  3145 
  2375 
  3146 \end{table}
  2376 \end{table}
  3147 
  2377 
  3148 \section{Building the documentation}
  2378 \section{Building the Interface Documentation}
  3149 \label{sec:gendoc}
  2379 \label{sec:gendoc}
  3150 
  2380 
  3151 The source code is documented using Doxygen~\cite{doxygen}. To build the HTML
  2381 The source code is documented using Doxygen~\cite{doxygen}. To build the HTML
  3152 documentation, you must have the Doxygen software installed. The below command
  2382 documentation, the Doxygen software has to be installed. The below command
  3153 will generate the documents in the subdirectory \textit{doxygen-output}:
  2383 will generate the documents in the subdirectory \textit{doxygen-output}:
  3154 
  2384 
  3155 \begin{lstlisting}
  2385 \begin{lstlisting}
  3156 $ `\textbf{make doc}`
  2386 $ `\textbf{make doc}`
  3157 \end{lstlisting}
  2387 \end{lstlisting}
  3158 
  2388 
  3159 To view them, point your browser to \textit{doxygen-output/html/index.html}.
  2389 The interface documentation can be viewed by pointing a browser to the file
  3160 
  2390 \textit{doxygen-output/html/index.html}.
  3161 \section{Installation}
  2391 
       
  2392 \section{Installing the Software}
  3162 
  2393 
  3163 The below commands have to be entered as \textit{root}: The first one will
  2394 The below commands have to be entered as \textit{root}: The first one will
  3164 install the EtherCAT header, init script, sysconfig file and the user space
  2395 install the EtherCAT header, init script, sysconfig file and the user space
  3165 tools to the prefix path. The second one will install the kernel modules to the
  2396 tool to the prefix path. The second one will install the kernel modules to the
  3166 kernel's modules directory. The following \lstinline+depmod+ call is necessary
  2397 kernel's modules directory. The final \lstinline+depmod+ call is necessary to
  3167 to include the kernel modules into the \textit{modules.dep} file to make it
  2398 include the kernel modules into the \textit{modules.dep} file to make it
  3168 available to the \lstinline+modprobe+ command, used in the init script. 
  2399 available to the \lstinline+modprobe+ command, used in the init script. 
  3169 
  2400 
  3170 \begin{lstlisting}
  2401 \begin{lstlisting}
  3171 # `\textbf{make install}`
  2402 # `\textbf{make install}`
  3172 # `\textbf{make modules\_install}`
  2403 # `\textbf{make modules\_install}`
  3211 
  2442 
  3212 \begin{lstlisting}
  2443 \begin{lstlisting}
  3213 # `\textbf{/etc/init.d/ethercat start}`
  2444 # `\textbf{/etc/init.d/ethercat start}`
  3214 \end{lstlisting}
  2445 \end{lstlisting}
  3215 
  2446 
  3216 The operation of the master can be observed by looking at the
  2447 The operation of the master can be observed with the command
  3217 Syslog\index{Syslog} messages, which should look like the ones below.  If
  2448 \lstinline+ethercat master+ or by viewing the Syslog\index{Syslog}
  3218 EtherCAT slaves are connected to the master's EtherCAT device, the activity
  2449 messages, which should look like the ones below. If EtherCAT slaves are
  3219 indicators should begin to flash.
  2450 connected to the master's EtherCAT device, the activity indicators should
       
  2451 begin to flash.
  3220 
  2452 
  3221 \begin{lstlisting}[numbers=left]
  2453 \begin{lstlisting}[numbers=left]
  3222 EtherCAT: Master driver `\masterversion`
  2454 EtherCAT: Master driver `\masterversion`
  3223 EtherCAT: 1 master waiting for devices.
  2455 EtherCAT: 1 master waiting for devices.
  3224 EtherCAT Intel(R) PRO/1000 Network Driver - version 6.0.60-k2
  2456 EtherCAT Intel(R) PRO/1000 Network Driver - version 6.0.60-k2
  3253 
  2485 
  3254 \end{description}
  2486 \end{description}
  3255 
  2487 
  3256 %------------------------------------------------------------------------------
  2488 %------------------------------------------------------------------------------
  3257 
  2489 
  3258 \chapter{Application examples}
       
  3259 \label{chapter:examples}
       
  3260 
       
  3261 This chapter will give practical examples of how to use the EtherCAT master via
       
  3262 the realtime interface by writing an application module.
       
  3263 
       
  3264 %------------------------------------------------------------------------------
       
  3265 
       
  3266 \section{Minimal Example}
       
  3267 \label{sec:mini}
       
  3268 \index{Examples!Minimal}
       
  3269 
       
  3270 This section will explain the use of the EtherCAT master from a minimal kernel
       
  3271 module. The complete module code is obtainable as a part of the EtherCAT master
       
  3272 code release (see~\cite{etherlab}, file \textit{examples/mini/mini.c}).
       
  3273 
       
  3274 The minimal example uses a kernel timer (software interrupt) to generate a
       
  3275 cyclic task. After the timer function is executed, it re-adds itself with a
       
  3276 delay of one \textit{jiffy}\index{jiffies}, which results in a timer frequency
       
  3277 of \textit{HZ}\nomenclature{HZ}{Kernel macro containing the timer interrupt
       
  3278 frequency}
       
  3279 
       
  3280 The module-global variables, needed to operate the master can be seen
       
  3281 in listing~\ref{lst:minivar}.
       
  3282 
       
  3283 \begin{lstlisting}[gobble=2,language=C,numbers=left,caption={Minimal
       
  3284     variables},label=lst:minivar]
       
  3285   struct timer_list timer;
       
  3286 
       
  3287   ec_master_t *master = NULL;
       
  3288   ec_domain_t *domain1 = NULL;
       
  3289 
       
  3290   void *r_dig_in, *r_ana_out;
       
  3291 
       
  3292   ec_pdo_reg_t domain1_pdos[] = {
       
  3293           {"1", Beckhoff_EL1014_Inputs, &r_dig_in},
       
  3294           {"2", Beckhoff_EL4132_Ouput1, &r_ana_out},
       
  3295           {}
       
  3296   };
       
  3297 \end{lstlisting}
       
  3298 
       
  3299 \begin{description}
       
  3300 \item[\linenum{1}] There is a timer object
       
  3301   declared, that is needed to tell the kernel to install a timer and
       
  3302   execute a certain function, if it runs out. This is done by a
       
  3303   variable of the \textit{timer\_list} structure.
       
  3304 \item[\linenum{3} -- \linenum{4}] There
       
  3305   is a pointer declared, that will later point to a requested EtherCAT
       
  3306   master.  Additionally there is a pointer to a domain object needed,
       
  3307   that will manage process data IO.
       
  3308 \item[\linenum{6}] The pointers \textit{r\_*}
       
  3309   will later point to the \underline{r}aw process data values inside
       
  3310   the domain memory. The addresses they point to will be set during a
       
  3311   call to \textit{ec\_\-master\_\-activate()}, that will create the
       
  3312   domain memory and configure the mapped process data image.
       
  3313 \item[\linenum{8} -- \linenum{12}] The
       
  3314   configuration of the mapping of certain Pdos in a domain can easily
       
  3315   be done with the help of an initialization array of the
       
  3316   \textit{ec\_pdo\_reg\_t} type, defined as part of the realtime
       
  3317   interface. Each record must contain the ASCII bus-address of the
       
  3318   slave (see section~\ref{sec:addr}), the slave's vendor ID and
       
  3319   product code, and the index and subindex of the Pdo to map (these
       
  3320   four fields can be specified in junction, by using one of the
       
  3321   defines out of the \textit{include/ecdb.h} header). The last field
       
  3322   has to be the address of the process data pointer, so it can later
       
  3323   be redirected appropriately. Attention: The initialization array
       
  3324   must end with an empty record (\textit{\{\}})!
       
  3325 \end{description}
       
  3326 
       
  3327 The initialization of the minimal application is done by the ``Minimal init
       
  3328 function'' in listing~\ref{lst:miniinit}.
       
  3329 
       
  3330 \begin{lstlisting}[gobble=2,language=C,numbers=left,caption={Minimal init
       
  3331     function},label={lst:miniinit}]
       
  3332   int __init init_mini_module(void)
       
  3333   {
       
  3334           if (!(master = ecrt_request_master(0))) {
       
  3335                   goto out_return;
       
  3336           }
       
  3337 
       
  3338           if (!(domain1 = ecrt_master_create_domain(master))) {
       
  3339                   goto out_release_master;
       
  3340           }
       
  3341 
       
  3342           if (ecrt_domain_register_pdo_list(domain1,
       
  3343                                             domain1_pdos)) {
       
  3344                   goto out_release_master;
       
  3345           }
       
  3346 
       
  3347           if (ecrt_master_activate(master)) {
       
  3348                   goto out_release_master;
       
  3349           }
       
  3350 
       
  3351           ecrt_master_prepare(master);
       
  3352 
       
  3353           init_timer(&timer);
       
  3354           timer.function = run;
       
  3355           timer.expires = jiffies + 10;
       
  3356           add_timer(&timer);
       
  3357 
       
  3358           return 0;
       
  3359 
       
  3360         out_release_master:
       
  3361           ecrt_release_master(master);
       
  3362         out_return:
       
  3363           return -1;
       
  3364   }
       
  3365 \end{lstlisting}
       
  3366 
       
  3367 \begin{description}
       
  3368 \item[\linenum{3}] It is tried to request the
       
  3369   first EtherCAT master (index 0). On success, the
       
  3370   \textit{ecrt\_\-request\_\-master()} function returns a pointer to
       
  3371   the reserved master, that can be used as an object to following
       
  3372   functions calls. On failure, the function returns \textit{NULL}.
       
  3373 \item[\linenum{7}] In order to exchange process
       
  3374   data, a domain object has to be created. The
       
  3375   \textit{ecrt\_\-master\_\-create\_domain()} function also returns a
       
  3376   pointer to the created domain, or \textit{NULL} in error case.
       
  3377 \item[\linenum{11}] The registration of domain
       
  3378   Pdos with an initialization array results in a single function call.
       
  3379   Alternatively the data fields could be registered with individual
       
  3380   calls of \textit{ecrt\_domain\_register\_pdo()}.
       
  3381 \item[\linenum{16}] After the configuration of
       
  3382   process data mapping, the master can be activated for cyclic
       
  3383   operation. This will configure all slaves and bring them into
       
  3384   OP state.
       
  3385 \item[\linenum{20}] This call is needed to avoid
       
  3386   a case differentiation in cyclic operation: The first operation in
       
  3387   cyclic mode is a receive call. Due to the fact, that there is
       
  3388   nothing to receive during the first cycle, there had to be an
       
  3389   \textit{if}-statement to avoid a warning. A call to
       
  3390   \textit{ec\_master\_prepare()} sends a first datagram containing a
       
  3391   process data exchange datagram, so that the first receive call will
       
  3392   not fail.
       
  3393 \item[\linenum{22} -- \linenum{25}] The
       
  3394   master is now ready for cyclic operation. The kernel timer that
       
  3395   cyclically executes the \textit{run()} function is initialized and
       
  3396   started.
       
  3397 \end{description}
       
  3398 
       
  3399 The coding of a cleanup function fo the minimal module can be seen in
       
  3400 listing~\ref{lst:miniclean}.
       
  3401 
       
  3402 \begin{lstlisting}[gobble=2,language=C,numbers=left,caption={Minimal cleanup
       
  3403     function},label={lst:miniclean}]
       
  3404   void __exit cleanup_mini_module(void)
       
  3405   {
       
  3406           del_timer_sync(&timer);
       
  3407           ecrt_master_deactivate(master);
       
  3408           ecrt_release_master(master);
       
  3409   }
       
  3410 \end{lstlisting}
       
  3411 
       
  3412 \begin{description}
       
  3413 \item[\linenum{3}] To cleanup the module, it it
       
  3414   necessary to stop the cyclic processing. This is done by a call to
       
  3415   \textit{del\_timer\_sync()} which safely removes a queued timer
       
  3416   object. It is assured, that no cyclic work will be done after this
       
  3417   call returns.
       
  3418 \item[\linenum{4}] This call deactivates the
       
  3419   master, which results in all slaves being brought to their INIT
       
  3420   state again.
       
  3421 \item[\linenum{5}] This call releases the master,
       
  3422   removes any existing configuration and silently starts the idle
       
  3423   mode. The value of the master pointer is invalid after this call and
       
  3424   the module can be safely unloaded.
       
  3425 \end{description}
       
  3426 
       
  3427 The final part of the minimal module is that for the cyclic work. Its
       
  3428 coding can be seen in listing~\ref{lst:minirun}.
       
  3429 
       
  3430 \begin{lstlisting}[gobble=2,language=C,numbers=left,caption={Minimal cyclic
       
  3431     function},label={lst:minirun}]
       
  3432   void run(unsigned long data)
       
  3433   {
       
  3434           static uint8_t dig_in_0;
       
  3435 
       
  3436           ecrt_master_receive(master);
       
  3437           ecrt_domain_process(domain1);
       
  3438 
       
  3439           dig_in_0 = EC_READ_BIT(r_dig_in, 0);
       
  3440           EC_WRITE_S16(r_ana_out, dig_in_0 * 0x3FFF);
       
  3441 
       
  3442           ecrt_master_run(master);
       
  3443           ecrt_master_send(master);
       
  3444 
       
  3445           timer.expires += 1; // frequency = HZ
       
  3446           add_timer(&timer);
       
  3447   }
       
  3448 \end{lstlisting}
       
  3449 
       
  3450 \begin{description}
       
  3451 
       
  3452 \item[\linenum{5}] The cyclic processing starts with receiving datagrams, that
       
  3453 were sent in the last cycle. The frames containing these datagrams have to be
       
  3454 received by the network interface card prior to this call.
       
  3455 
       
  3456 \item[\linenum{6}] The process data of domain 1 has been automatically copied
       
  3457 into domain memory while datagram reception. This call checks the working
       
  3458 counter for changes and re-queues the domain's datagram for sending.
       
  3459 
       
  3460 \item[\linenum{8}] This is an example for reading out a bit-oriented process
       
  3461 data value (i.~e. bit 0) via the \textit{EC\_READ\_BIT()} macro. See
       
  3462 section~\ref{sec:macros} for more information about those macros.
       
  3463 
       
  3464 \item[\linenum{9}] This line shows how to write a signed, 16-bit process data
       
  3465 value. In this case, the slave is able to output voltages of
       
  3466 \unit{-10--+10}{\volt} with a resolution of \unit{16}{bit}.  This write command
       
  3467 outputs either \unit{0}{\volt} or \unit{+5}{\volt}, depending of the value of
       
  3468 \textit{dig\_in\_0}.
       
  3469 
       
  3470 \item[\linenum{11}] This call runs the master's operation state machine (see
       
  3471 section~\ref{sec:fsm-op}). A single state is processed, and datagrams are
       
  3472 queued. Mainly bus observation is done: The bus state is determined and in case
       
  3473 of slaves that lost their configuration, reconfiguration is tried.
       
  3474 
       
  3475 \item[\linenum{12}] This method sends all queued datagrams, in this case the
       
  3476 domain's datagram and one of the master state machine. In best case, all
       
  3477 datagrams fit into one frame.
       
  3478 
       
  3479 \item[\linenum{14} -- \linenum{15}] Kernel timers are implemented as
       
  3480 ``one-shot'' timers, so they have to be re-added after each execution. The time
       
  3481 of the next execution is specified in \textit{jiffies} and will happen at the
       
  3482 time of the next system timer interrupt. This results in the \textit{run()}
       
  3483 function being executed with a frequency of \textit{HZ}.
       
  3484 
       
  3485 \end{description}
       
  3486 
       
  3487 %------------------------------------------------------------------------------
       
  3488 
       
  3489 \section{RTAI Example}
       
  3490 \label{sec:rtai}
       
  3491 \index{Examples!RTAI}
       
  3492 
       
  3493 The whole code can be seen in the EtherCAT master code release
       
  3494 (see~\cite{etherlab}, file \textit{examples/rtai/rtai\_sample.c}).
       
  3495 
       
  3496 Listing~\ref{lst:rtaivar} shows the defines and global variables
       
  3497 needed for a minimal RTAI module with EtherCAT processing.
       
  3498 
       
  3499 \begin{lstlisting}[gobble=2,language=C,numbers=left,caption={RTAI task
       
  3500     declaration},label={lst:rtaivar}]
       
  3501   #define FREQUENCY 10000
       
  3502   #define TIMERTICKS (1000000000 / FREQUENCY)
       
  3503 
       
  3504   RT_TASK task;
       
  3505 \end{lstlisting}
       
  3506 
       
  3507 \begin{description}
       
  3508 \item[\linenum{1} -- \linenum{2}] RTAI
       
  3509   takes the cycle period as nanoseconds, so the easiest way is to
       
  3510   define a frequency and convert it to a cycle time in nanoseconds.
       
  3511 \item[\linenum{4}] The \textit{task} variable
       
  3512   later contains information about the running RTAI task.
       
  3513 \end{description}
       
  3514 
       
  3515 Listing~\ref{lst:rtaiinit} shows the module init function for the RTAI
       
  3516 module. Most lines are the same as in listing~\ref{lst:miniinit},
       
  3517 differences come up when starting the cyclic code.
       
  3518 
       
  3519 \begin{lstlisting}[gobble=2,language=C,numbers=left,caption={RTAI module init
       
  3520     function},label={lst:rtaiinit}]
       
  3521   int __init init_mod(void)
       
  3522   {
       
  3523           RTIME requested_ticks, tick_period, now;
       
  3524 
       
  3525           if (!(master = ecrt_request_master(0))) {
       
  3526                   goto out_return;
       
  3527           }
       
  3528 
       
  3529           if (!(domain1 = ecrt_master_create_domain(master))) {
       
  3530                   goto out_release_master;
       
  3531           }
       
  3532 
       
  3533           if (ecrt_domain_register_pdo_list(domain1,
       
  3534                                             domain1_pdos)) {
       
  3535                   goto out_release_master;
       
  3536           }
       
  3537 
       
  3538           if (ecrt_master_activate(master)) {
       
  3539                   goto out_release_master;
       
  3540           }
       
  3541 
       
  3542           ecrt_master_prepare(master);
       
  3543 
       
  3544           requested_ticks = nano2count(TIMERTICKS);
       
  3545           tick_period = start_rt_timer(requested_ticks);
       
  3546 
       
  3547           if (rt_task_init(&task, run, 0, 2000, 0, 1, NULL)) {
       
  3548                   goto out_stop_timer;
       
  3549           }
       
  3550 
       
  3551           now = rt_get_time();
       
  3552           if (rt_task_make_periodic(&task, now + tick_period,
       
  3553                                     tick_period)) {
       
  3554                   goto out_stop_task;
       
  3555           }
       
  3556 
       
  3557           return 0;
       
  3558 
       
  3559       out_stop_task:
       
  3560           rt_task_delete(&task);
       
  3561       out_stop_timer:
       
  3562           stop_rt_timer();
       
  3563       out_deactivate:
       
  3564           ecrt_master_deactivate(master);
       
  3565       out_release_master:
       
  3566           ecrt_release_master(master);
       
  3567       out_return:
       
  3568           return -1;
       
  3569   }
       
  3570 \end{lstlisting}
       
  3571 
       
  3572 \begin{description}
       
  3573 \item[\linenum{24} -- \linenum{25}] The
       
  3574   nanoseconds are converted to RTAI timer ticks and an RTAI timer is
       
  3575   started.  \textit{tick\_period} will be the ``real'' number of ticks
       
  3576   used for the timer period (which can be different to the requested
       
  3577   one).
       
  3578 \item[\linenum{27}] The RTAI task is initialized
       
  3579   by specifying the cyclic function, the parameter to hand over, the
       
  3580   stack size, priority, a flag that tells, if the function will use
       
  3581   floating point operations and a signal handler.
       
  3582 \item[\linenum{32}] The task is made periodic by
       
  3583   specifying a start time and a period.
       
  3584 \end{description}
       
  3585 
       
  3586 The cleanup function of the RTAI module in listing~\ref{lst:rtaiclean}
       
  3587 is nearly as simple as that of the minimal module.
       
  3588 
       
  3589 \begin{lstlisting}[gobble=2,language=C,numbers=left,caption={RTAI module
       
  3590     cleanup function},label={lst:rtaiclean}]
       
  3591   void __exit cleanup_mod(void)
       
  3592   {
       
  3593           rt_task_delete(&task);
       
  3594           stop_rt_timer();
       
  3595           ecrt_master_deactivate(master);
       
  3596           ecrt_release_master(master);
       
  3597           rt_sem_delete(&master_sem);
       
  3598   }
       
  3599 \end{lstlisting}
       
  3600 
       
  3601 \begin{description}
       
  3602 \item[\linenum{2}] The RTAI task will be stopped
       
  3603   and deleted.
       
  3604 \item[\linenum{3}] After that, the RTAI timer can
       
  3605   be stopped.
       
  3606 \end{description}
       
  3607 
       
  3608 The rest is the same as for the minimal module.
       
  3609 
       
  3610 Worth to mention is, that the cyclic function of the RTAI module
       
  3611 (listing~\ref{lst:rtairun}) has a slightly different architecture. The
       
  3612 function is not executed until returning for every cycle, but has an
       
  3613 infinite loop in it, that is placed in a waiting state for the rest of
       
  3614 each cycle.
       
  3615 
       
  3616 \begin{lstlisting}[gobble=2,language=C,numbers=left,caption={RTAI module cyclic
       
  3617     function},label={lst:rtairun}]
       
  3618   void run(long data)
       
  3619   {
       
  3620           while (1) {
       
  3621                   ecrt_master_receive(master);
       
  3622                   ecrt_domain_process(domain1);
       
  3623 
       
  3624                   k_pos = EC_READ_U32(r_ssi_input);
       
  3625 
       
  3626                   ecrt_master_run(master);
       
  3627                   ecrt_master_send(master);
       
  3628 
       
  3629                   rt_task_wait_period();
       
  3630           }
       
  3631   }
       
  3632 \end{lstlisting}
       
  3633 
       
  3634 \begin{description}
       
  3635 \item[\linenum{3}] The \textit{while (1)} loop
       
  3636   executes for the lifetime of the RTAI task.
       
  3637 \item[\linenum{12}] The
       
  3638   \textit{rt\_task\_wait\_period()} function sets the process into a
       
  3639   sleeping state until the beginning of the next cycle. It also
       
  3640   checks, if the cyclic function has to be terminated.
       
  3641 \end{description}
       
  3642 
       
  3643 %------------------------------------------------------------------------------
       
  3644 
       
  3645 \section{Concurrency Example}
       
  3646 \label{sec:concurrency}
       
  3647 \index{Examples!Concurrency}
       
  3648 
       
  3649 As mentioned before, there can be concurrent access to the EtherCAT master. The
       
  3650 application and a EoE\index{EoE} process can compete for master access, for
       
  3651 example. In this case, the module has to provide the locking mechanism, because
       
  3652 it depends on the module's architecture which lock has to be used. The module
       
  3653 makes this locking mechanism available to the master through the master's
       
  3654 locking callbacks.
       
  3655 
       
  3656 In case of RTAI, the lock can be an RTAI semaphore, as shown in
       
  3657 listing~\ref{lst:convar}. A normal Linux semaphore would not be appropriate,
       
  3658 because it could not block the RTAI task due to RTAI running in a higher domain
       
  3659 than the Linux kernel (see~\cite{rtai}).
       
  3660 
       
  3661 \begin{lstlisting}[gobble=2,language=C,numbers=left,caption={RTAI semaphore for
       
  3662     concurrent access},label={lst:convar}]
       
  3663   SEM master_sem;
       
  3664 \end{lstlisting}
       
  3665 
       
  3666 The module has to implement the two callbacks for requesting and
       
  3667 releasing the master lock. An exemplary coding can be seen in
       
  3668 listing~\ref{lst:conlock}.
       
  3669 
       
  3670 \begin{lstlisting}[gobble=2,language=C,numbers=left,caption={RTAI locking
       
  3671     callbacks for concurrent access},label={lst:conlock}]
       
  3672   int request_lock(void *data)
       
  3673   {
       
  3674           rt_sem_wait(&master_sem);
       
  3675           return 0;
       
  3676   }
       
  3677 
       
  3678   void release_lock(void *data)
       
  3679   {
       
  3680           rt_sem_signal(&master_sem);
       
  3681   }
       
  3682 \end{lstlisting}
       
  3683 
       
  3684 \begin{description}
       
  3685 \item[\linenum{1}] The \textit{request\_lock()}
       
  3686   function has a data parameter. The master always passes the value,
       
  3687   that was specified when registering the callback function. This can
       
  3688   be used for handing the master pointer. Notice, that it has an
       
  3689   integer return value (see line 4).
       
  3690 \item[\linenum{3}] The call to
       
  3691   \textit{rt\_sem\_wait()} either returns at once, when the semaphore
       
  3692   was free, or blocks until the semaphore is freed again. In any case,
       
  3693   the semaphore finally is reserved for the process calling the
       
  3694   request function.
       
  3695 \item[\linenum{4}] When the lock was requested
       
  3696   successfully, the function should return 0. The module can prohibit
       
  3697   requesting the lock by returning non-zero (see paragraph ``Tuning
       
  3698   the jitter'' below).
       
  3699 \item[\linenum{7}] The \textit{release\_lock()}
       
  3700   function gets the same argument passed, but has a void return value,
       
  3701   because is always succeeds.
       
  3702 \item[\linenum{9}] The \textit{rt\_sem\_signal()}
       
  3703   function frees the semaphore, that was prior reserved with
       
  3704   \textit{rt\_sem\_wait()}.
       
  3705 \end{description}
       
  3706 
       
  3707 In the module's init function, the semaphore must be initialized, and
       
  3708 the callbacks must be passed to the EtherCAT master:
       
  3709 
       
  3710 \begin{lstlisting}[gobble=2,language=C,numbers=left,caption={Module init
       
  3711     function for concurrent access},label={lst:coninit}]
       
  3712   int __init init_mod(void)
       
  3713   {
       
  3714           RTIME tick_period, requested_ticks, now;
       
  3715 
       
  3716           rt_sem_init(&master_sem, 1);
       
  3717 
       
  3718           if (!(master = ecrt_request_master(0))) {
       
  3719                   goto out_return;
       
  3720           }
       
  3721 
       
  3722           ecrt_master_callbacks(master, request_lock,
       
  3723                                 release_lock, NULL);
       
  3724           // ...
       
  3725 \end{lstlisting}
       
  3726 
       
  3727 \begin{description}
       
  3728 \item[\linenum{5}] The call to
       
  3729   \textit{rt\_sem\_init()} initializes the semaphore and sets its
       
  3730   value to 1, meaning that only one process can reserve the semaphore
       
  3731   without blocking.
       
  3732 \item[\linenum{11}] The callbacks are passed to
       
  3733   the master with a call to \textit{ecrt\_master\_callbacks()}. The
       
  3734   last parameter is the argument, that the master should pass with
       
  3735   each call to a callback function. Here it is not used and set to
       
  3736   \textit{NULL}.
       
  3737 \end{description}
       
  3738 
       
  3739 For the cyclic function being only one competitor for master access,
       
  3740 it has to request the lock like any other process. There is no need to
       
  3741 use the callbacks (which are meant for processes of lower priority),
       
  3742 so it can access the semaphore directly:
       
  3743 
       
  3744 \begin{lstlisting}[gobble=2,language=C,numbers=left,caption={RTAI cyclic
       
  3745     function for concurrent access},label={lst:conrun}]
       
  3746   void run(long data)
       
  3747   {
       
  3748           while (1) {
       
  3749                   rt_sem_wait(&master_sem);
       
  3750 
       
  3751                   ecrt_master_receive(master);
       
  3752                   ecrt_domain_process(domain1);
       
  3753 
       
  3754                   k_pos = EC_READ_U32(r_ssi_input);
       
  3755 
       
  3756                   ecrt_master_run(master);
       
  3757                   ecrt_master_send(master);
       
  3758 
       
  3759                   rt_sem_signal(&master_sem);
       
  3760                   rt_task_wait_period();
       
  3761           }
       
  3762   }
       
  3763 \end{lstlisting}
       
  3764 
       
  3765 \begin{description}
       
  3766 
       
  3767 \item[\linenum{4}] Every access to the master has to be preceded by a call to
       
  3768 \textit{rt\_sem\_wait()}, because another instance might currently access the
       
  3769 master.
       
  3770 
       
  3771 \item[\linenum{14}] When cyclic processing finished, the semaphore has to be
       
  3772 freed again, so that other processes have the possibility to access the master.
       
  3773 
       
  3774 \end{description}
       
  3775 
       
  3776 A little change has to be made to the cleanup function in case of
       
  3777 concurrent master access.
       
  3778 
       
  3779 \begin{lstlisting}[gobble=2,language=C,numbers=left,caption={RTAI module
       
  3780     cleanup function for concurrent access},label={lst:conclean}]
       
  3781   void __exit cleanup_mod(void)
       
  3782   {
       
  3783           rt_task_delete(&task);
       
  3784           stop_rt_timer();
       
  3785           ecrt_master_deactivate(master);
       
  3786           ecrt_release_master(master);
       
  3787           rt_sem_delete(&master_sem);
       
  3788   }
       
  3789 \end{lstlisting}
       
  3790 
       
  3791 \begin{description}
       
  3792 \item[\linenum{7}] Upon module cleanup, the
       
  3793   semaphore has to be deleted, so that memory can be freed.
       
  3794 \end{description}
       
  3795 
       
  3796 \paragraph{Tuning the Jitter}
       
  3797 \index{Jitter}
       
  3798 
       
  3799 Concurrent access leads to higher jitter for the application task, because
       
  3800 there are situations, in which the task has to wait for a process of lower
       
  3801 priority to finish accessing the master.  In most cases this is acceptable,
       
  3802 because a master access cycle (receive/process/send) only takes
       
  3803 \unit{10-20}{\micro\second} on recent systems, what would be the maximum
       
  3804 additional jitter. However some applications demand a minimum jitter. For this
       
  3805 reason the master access can be prohibited by the application: If the time,
       
  3806 another process wants to access the master, is to close to the beginning of the
       
  3807 next application cycle, the module can disallow, that the lock is taken. In
       
  3808 this case, the request callback has to return $1$, meaning that the lock has
       
  3809 not been taken. The foreign process must abort its master access and try again
       
  3810 next time.
       
  3811 
       
  3812 This measure helps to significantly reducing the jitter produced by concurrent
       
  3813 master access. Below are excerpts of an example coding:
       
  3814 
       
  3815 \begin{lstlisting}[gobble=2,language=C,numbers=left,caption={Variables for
       
  3816     jitter reduction},label={lst:redvar}]
       
  3817   #define FREQUENCY 10000 // RTAI task frequency in Hz
       
  3818   // ...
       
  3819   cycles_t t_last_cycle = 0;
       
  3820   const cycles_t t_critical = cpu_khz * 1000 / FREQUENCY
       
  3821                               - cpu_khz * 30 / 1000;
       
  3822 \end{lstlisting}
       
  3823 
       
  3824 \begin{description}
       
  3825 
       
  3826 \item[\linenum{3}] The variable \textit{t\_last\_cycle} holds the timer ticks
       
  3827 at the beginning of the last realtime cycle.
       
  3828 
       
  3829 \item[\linenum{4}] \textit{t\_critical} contains the number of ticks, that may
       
  3830 have passed since the beginning of the last cycle, until there is no more
       
  3831 foreign access possible. It is calculated by subtracting the ticks for
       
  3832 \unit{30}{\micro\second} from the ticks for a complete cycle.
       
  3833 
       
  3834 \end{description}
       
  3835 
       
  3836 \begin{lstlisting}[gobble=2,language=C,numbers=left,caption={Cyclic function
       
  3837     with reduced jitter},label={lst:redrun}]
       
  3838   void run(long data)
       
  3839   {
       
  3840           while (1) {
       
  3841                   t_last_cycle = get_cycles();
       
  3842                   rt_sem_wait(&master_sem);
       
  3843                   // ...
       
  3844 \end{lstlisting}
       
  3845 
       
  3846 \begin{description}
       
  3847 \item[\linenum{4}] The ticks of the beginning of
       
  3848   the current realtime cycle are taken before reserving the semaphore.
       
  3849 \end{description}
       
  3850 
       
  3851 \begin{lstlisting}[gobble=2,language=C,numbers=left,caption={Request callback
       
  3852     for reduced jitter},label={lst:redreq}]
       
  3853   int request_lock(void *data)
       
  3854   {
       
  3855           // too close to the next RT cycle: deny access.
       
  3856           if (get_cycles() - t_last_cycle > t_critical)
       
  3857                   return -1;
       
  3858 
       
  3859           // allow access
       
  3860           rt_sem_wait(&master_sem);
       
  3861           return 0;
       
  3862   }
       
  3863 \end{lstlisting}
       
  3864 
       
  3865 \begin{description}
       
  3866 
       
  3867 \item[\linenum{4}] If the time of request is too close to the next realtime
       
  3868 cycle (here: \unit{<30}{\micro\second} before the estimated beginning), the
       
  3869 locking is denied. The requesting process must abort its cycle.
       
  3870 
       
  3871 \end{description}
       
  3872 
       
  3873 %------------------------------------------------------------------------------
       
  3874 
       
  3875 \begin{thebibliography}{99}
  2490 \begin{thebibliography}{99}
  3876 
  2491 
  3877 \bibitem{etherlab} Ingenieurgemeinschaft IgH: EtherLab -- Open Source Toolkit
  2492 \bibitem{etherlab} Ingenieurgemeinschaft IgH: EtherLab -- Open Source Toolkit
  3878 for rapid realtime code generation under Linux with Simulink/RTW and EtherCAT
  2493 for rapid realtime code generation under Linux with Simulink/RTW and EtherCAT
  3879 technology. \url{http://etherlab.org/en}, 2008.
  2494 technology. \url{http://etherlab.org/en}, 2008.