diff options
Diffstat (limited to 'daemons/gptp/linux/src')
-rw-r--r-- | daemons/gptp/linux/src/daemon_cl.cpp | 557 | ||||
-rw-r--r-- | daemons/gptp/linux/src/linux_hal_common.cpp | 1117 | ||||
-rw-r--r-- | daemons/gptp/linux/src/linux_hal_common.hpp | 723 | ||||
-rw-r--r-- | daemons/gptp/linux/src/linux_hal_generic.cpp | 588 | ||||
-rw-r--r-- | daemons/gptp/linux/src/linux_hal_generic.hpp | 217 | ||||
-rw-r--r-- | daemons/gptp/linux/src/linux_hal_generic_adj.cpp | 102 | ||||
-rw-r--r-- | daemons/gptp/linux/src/linux_hal_generic_tsprivate.hpp | 61 | ||||
-rw-r--r-- | daemons/gptp/linux/src/linux_hal_i210.cpp | 162 | ||||
-rw-r--r-- | daemons/gptp/linux/src/linux_hal_intelce.cpp | 243 | ||||
-rw-r--r-- | daemons/gptp/linux/src/linux_hal_intelce.hpp | 127 | ||||
-rw-r--r-- | daemons/gptp/linux/src/linux_hal_persist_file.cpp | 155 | ||||
-rw-r--r-- | daemons/gptp/linux/src/linux_hal_persist_file.hpp | 42 | ||||
-rw-r--r-- | daemons/gptp/linux/src/linux_ipc.hpp | 43 | ||||
-rw-r--r-- | daemons/gptp/linux/src/platform.cpp | 65 | ||||
-rw-r--r-- | daemons/gptp/linux/src/platform.hpp | 108 | ||||
-rw-r--r-- | daemons/gptp/linux/src/watchdog.cpp | 46 | ||||
-rw-r--r-- | daemons/gptp/linux/src/watchdog.hpp | 21 |
17 files changed, 0 insertions, 4377 deletions
diff --git a/daemons/gptp/linux/src/daemon_cl.cpp b/daemons/gptp/linux/src/daemon_cl.cpp deleted file mode 100644 index 53a8f9a4..00000000 --- a/daemons/gptp/linux/src/daemon_cl.cpp +++ /dev/null @@ -1,557 +0,0 @@ -/****************************************************************************** - - Copyright (c) 2012 Intel Corporation - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. Neither the name of the Intel Corporation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - ******************************************************************************/ - -#include "ieee1588.hpp" -#include "avbts_clock.hpp" -#include "avbts_osnet.hpp" -#include "avbts_oslock.hpp" -#include "avbts_persist.hpp" -#include "gptp_cfg.hpp" -#include "ether_port.hpp" - -#ifdef ARCH_INTELCE -#include "linux_hal_intelce.hpp" -#else -#include "linux_hal_generic.hpp" -#endif - -#include "linux_hal_persist_file.hpp" -#include <ctype.h> -#include <inttypes.h> -#include <signal.h> -#include <fcntl.h> -#include <sys/mman.h> -#include <stdlib.h> -#include <errno.h> -#include <sys/stat.h> -#include <unistd.h> -#include <string.h> - -#ifdef SYSTEMD_WATCHDOG -#include <watchdog.hpp> -#endif - -#define PHY_DELAY_GB_TX_I20 184 //1G delay -#define PHY_DELAY_GB_RX_I20 382 //1G delay -#define PHY_DELAY_MB_TX_I20 1044//100M delay -#define PHY_DELAY_MB_RX_I20 2133//100M delay - -void gPTPPersistWriteCB(char *bufPtr, uint32_t bufSize); - -void print_usage( char *arg0 ) { - fprintf( stderr, - "%s <network interface> [-S] [-P] [-M <filename>] " - "[-G <group>] [-R <priority 1>] " - "[-D <gb_tx_delay,gb_rx_delay,mb_tx_delay,mb_rx_delay>] " - "[-T] [-L] [-E] [-GM] [-INITSYNC <value>] [-OPERSYNC <value>] " - "[-INITPDELAY <value>] [-OPERPDELAY <value>] " - "[-F <path to gptp_cfg.ini file>] " - "\n", - arg0 ); - fprintf - ( stderr, - "\t-S start syntonization\n" - "\t-P pulse per second\n" - "\t-M <filename> save/restore state\n" - "\t-G <group> group id for shared memory\n" - "\t-R <priority 1> priority 1 value\n" - "\t-D Phy Delay <gb_tx_delay,gb_rx_delay,mb_tx_delay,mb_rx_delay>\n" - "\t-T force master (ignored when Automotive Profile set)\n" - "\t-L force slave (ignored when Automotive Profile set)\n" - "\t-E enable test mode (as defined in AVnu automotive profile)\n" - "\t-V enable AVnu Automotive Profile\n" - "\t-GM set grandmaster for Automotive Profile\n" - "\t-INITSYNC <value> initial sync interval (Log base 2. 0 = 1 second)\n" - "\t-OPERSYNC <value> operational sync interval (Log base 2. 0 = 1 second)\n" - "\t-INITPDELAY <value> initial pdelay interval (Log base 2. 0 = 1 second)\n" - "\t-OPERPDELAY <value> operational pdelay interval (Log base 2. 0 = 1 sec)\n" - "\t-F <path-to-ini-file>\n" - ); -} - -int watchdog_setup(OSThreadFactory *thread_factory) -{ -#ifdef SYSTEMD_WATCHDOG - SystemdWatchdogHandler *watchdog = new SystemdWatchdogHandler(); - OSThread *watchdog_thread = thread_factory->createThread(); - int watchdog_result; - long unsigned int watchdog_interval; - watchdog_interval = watchdog->getSystemdWatchdogInterval(&watchdog_result); - if (watchdog_result) { - GPTP_LOG_INFO("Watchtog interval read from service file: %lu us", watchdog_interval); - watchdog->update_interval = watchdog_interval / 2; - GPTP_LOG_STATUS("Starting watchdog handler (Update every: %lu us)", watchdog->update_interval); - watchdog_thread->start(watchdogUpdateThreadFunction, watchdog); - return 0; - } else if (watchdog_result < 0) { - GPTP_LOG_ERROR("Watchdog settings read error."); - return -1; - } else { - GPTP_LOG_STATUS("Watchdog disabled"); - return 0; - } -#else - return 0; -#endif -} - -static IEEE1588Clock *pClock = NULL; -static EtherPort *pPort = NULL; - -int main(int argc, char **argv) -{ - PortInit_t portInit; - - sigset_t set; - InterfaceName *ifname; - int sig; - - bool syntonize = false; - int i; - bool pps = false; - uint8_t priority1 = 248; - bool override_portstate = false; - PortState port_state = PTP_SLAVE; - char *restoredata = NULL; - char *restoredataptr = NULL; - off_t restoredatalength = 0; - off_t restoredatacount = 0; - bool restorefailed = false; - LinuxIPCArg *ipc_arg = NULL; - bool use_config_file = false; - char config_file_path[512]; - const char *systemClockDesc = NULL; - memset(config_file_path, 0, 512); - - GPTPPersist *pGPTPPersist = NULL; - LinuxThreadFactory *thread_factory = new LinuxThreadFactory(); - - // Block SIGUSR1 - { - sigset_t block; - sigemptyset( &block ); - sigaddset( &block, SIGUSR1 ); - if( pthread_sigmask( SIG_BLOCK, &block, NULL ) != 0 ) { - GPTP_LOG_ERROR("Failed to block SIGUSR1"); - return -1; - } - } - - GPTP_LOG_REGISTER(); - GPTP_LOG_INFO("gPTP starting"); - if (watchdog_setup(thread_factory) != 0) { - GPTP_LOG_ERROR("Watchdog handler setup error"); - return -1; - } - phy_delay_map_t ether_phy_delay; - bool input_delay=false; - - portInit.clock = NULL; - portInit.index = 0; - portInit.timestamper = NULL; - portInit.net_label = NULL; - portInit.automotive_profile = false; - portInit.isGM = false; - portInit.testMode = false; - portInit.linkUp = false; - portInit.initialLogSyncInterval = LOG2_INTERVAL_INVALID; - portInit.initialLogPdelayReqInterval = LOG2_INTERVAL_INVALID; - portInit.operLogPdelayReqInterval = LOG2_INTERVAL_INVALID; - portInit.operLogSyncInterval = LOG2_INTERVAL_INVALID; - portInit.condition_factory = NULL; - portInit.thread_factory = NULL; - portInit.timer_factory = NULL; - portInit.lock_factory = NULL; - portInit.syncReceiptThreshold = - CommonPort::DEFAULT_SYNC_RECEIPT_THRESH; - portInit.neighborPropDelayThreshold = - CommonPort::NEIGHBOR_PROP_DELAY_THRESH; - - LinuxNetworkInterfaceFactory *default_factory = - new LinuxNetworkInterfaceFactory; - OSNetworkInterfaceFactory::registerFactory - (factory_name_t("default"), default_factory); - LinuxTimerQueueFactory *timerq_factory = new LinuxTimerQueueFactory(); - LinuxLockFactory *lock_factory = new LinuxLockFactory(); - LinuxTimerFactory *timer_factory = new LinuxTimerFactory(); - LinuxConditionFactory *condition_factory = new LinuxConditionFactory(); - LinuxSharedMemoryIPC *ipc = new LinuxSharedMemoryIPC(); - /* Create Low level network interface object */ - if( argc < 2 ) { - printf( "Interface name required\n" ); - print_usage( argv[0] ); - return -1; - } - ifname = new InterfaceName( argv[1], strlen(argv[1]) ); - - /* Process optional arguments */ - for( i = 2; i < argc; ++i ) { - - if( argv[i][0] == '-' ) { - if( strcmp(argv[i] + 1, "S") == 0 ) { - // Get syntonize directive from command line - syntonize = true; - } - else if( strcmp(argv[i] + 1, "T" ) == 0 ) { - override_portstate = true; - port_state = PTP_MASTER; - } - else if( strcmp(argv[i] + 1, "L" ) == 0 ) { - override_portstate = true; - port_state = PTP_SLAVE; - } - else if( strcmp(argv[i] + 1, "M" ) == 0 ) { - // Open file - if( i+1 < argc ) { - pGPTPPersist = makeLinuxGPTPPersistFile(); - if (pGPTPPersist) { - pGPTPPersist->initStorage(argv[i + 1]); - } - } - else { - printf( "Restore file must be specified on " - "command line\n" ); - } - } - else if( strcmp(argv[i] + 1, "G") == 0 ) { - if( i+1 < argc ) { - ipc_arg = new LinuxIPCArg(argv[++i]); - } else { - printf( "Must specify group name on the command line\n" ); - } - } - else if( strcmp(argv[i] + 1, "P") == 0 ) { - pps = true; - } - else if( strcmp(argv[i] + 1, "H") == 0 ) { - print_usage( argv[0] ); - GPTP_LOG_UNREGISTER(); - return 0; - } - else if( strcmp(argv[i] + 1, "R") == 0 ) { - if( i+1 >= argc ) { - printf( "Priority 1 value must be specified on " - "command line, using default value\n" ); - } else { - unsigned long tmp = strtoul( argv[i+1], NULL, 0 ); ++i; - if( tmp == 0 ) { - printf( "Invalid priority 1 value, using " - "default value\n" ); - } else { - priority1 = (uint8_t) tmp; - } - } - } - else if (strcmp(argv[i] + 1, "D") == 0) { - int phy_delay[4]; - input_delay=true; - int delay_count=0; - char *cli_inp_delay = strtok(argv[i+1],","); - while (cli_inp_delay != NULL) - { - if(delay_count>3) - { - printf("Too many values\n"); - print_usage( argv[0] ); - GPTP_LOG_UNREGISTER(); - return 0; - } - phy_delay[delay_count]=atoi(cli_inp_delay); - delay_count++; - cli_inp_delay = strtok(NULL,","); - } - if (delay_count != 4) - { - printf("All four delay values must be specified\n"); - print_usage( argv[0] ); - GPTP_LOG_UNREGISTER(); - return 0; - } - ether_phy_delay[LINKSPEED_1G].set_delay - ( phy_delay[0], phy_delay[1] ); - ether_phy_delay[LINKSPEED_100MB].set_delay - ( phy_delay[2], phy_delay[3] ); - } - else if (strcmp(argv[i] + 1, "V") == 0) { - portInit.automotive_profile = true; - } - else if (strcmp(argv[i] + 1, "GM") == 0) { - portInit.isGM = true; - } - else if (strcmp(argv[i] + 1, "E") == 0) { - portInit.testMode = true; - } - else if (strcmp(argv[i] + 1, "INITSYNC") == 0) { - portInit.initialLogSyncInterval = atoi(argv[++i]); - } - else if (strcmp(argv[i] + 1, "OPERSYNC") == 0) { - portInit.operLogSyncInterval = atoi(argv[++i]); - } - else if (strcmp(argv[i] + 1, "INITPDELAY") == 0) { - portInit.initialLogPdelayReqInterval = atoi(argv[++i]); - } - else if (strcmp(argv[i] + 1, "OPERPDELAY") == 0) { - portInit.operLogPdelayReqInterval = atoi(argv[++i]); - } - else if (strcmp(argv[i] + 1, "F") == 0) - { - if( i+1 < argc ) { - use_config_file = true; - strcpy(config_file_path, argv[i+1]); - } else { - fprintf(stderr, "config file must be specified.\n"); - } - } - } - } - - if (!input_delay) - { - ether_phy_delay[LINKSPEED_1G].set_delay - ( PHY_DELAY_GB_TX_I20, PHY_DELAY_GB_RX_I20 ); - ether_phy_delay[LINKSPEED_100MB].set_delay - ( PHY_DELAY_MB_TX_I20, PHY_DELAY_MB_RX_I20 ); - } - portInit.phy_delay = ðer_phy_delay; - - if( !ipc->init( ipc_arg ) ) { - delete ipc; - ipc = NULL; - } - if( ipc_arg != NULL ) delete ipc_arg; - - if( pGPTPPersist ) { - uint32_t bufSize = 0; - if (!pGPTPPersist->readStorage(&restoredata, &bufSize)) - GPTP_LOG_ERROR("Failed to stat restore file"); - restoredatalength = bufSize; - restoredatacount = restoredatalength; - restoredataptr = (char *)restoredata; - } - -#ifdef ARCH_INTELCE - EtherTimestamper *timestamper = new LinuxTimestamperIntelCE(); -#else - EtherTimestamper *timestamper = new LinuxTimestamperGeneric(); -#endif - - sigemptyset(&set); - sigaddset(&set, SIGINT); - sigaddset( &set, SIGTERM ); - sigaddset(&set, SIGHUP); - sigaddset(&set, SIGUSR2); - if (pthread_sigmask(SIG_BLOCK, &set, NULL) != 0) { - perror("pthread_sigmask()"); - GPTP_LOG_UNREGISTER(); - return -1; - } - - pClock = new IEEE1588Clock - ( false, syntonize, priority1, timerq_factory, ipc, - lock_factory ); - - if( restoredataptr != NULL ) { - if( !restorefailed ) - restorefailed = - !pClock->restoreSerializedState( restoredataptr, &restoredatacount ); - restoredataptr = ((char *)restoredata) + (restoredatalength - restoredatacount); - } - - // TODO: The setting of values into temporary variables should be changed to - // just set directly into the portInit struct. - portInit.clock = pClock; - portInit.index = 1; - portInit.timestamper = timestamper; - portInit.net_label = ifname; - portInit.condition_factory = condition_factory; - portInit.thread_factory = thread_factory; - portInit.timer_factory = timer_factory; - portInit.lock_factory = lock_factory; - - if(use_config_file) - { - GptpIniParser iniParser(config_file_path); - - if (iniParser.parserError() < 0) { - GPTP_LOG_ERROR("Cant parse ini file. Aborting file reading."); - } - else - { - GPTP_LOG_INFO("priority1 = %d", iniParser.getPriority1()); - GPTP_LOG_INFO("announceReceiptTimeout: %d", iniParser.getAnnounceReceiptTimeout()); - GPTP_LOG_INFO("syncReceiptTimeout: %d", iniParser.getSyncReceiptTimeout()); - iniParser.print_phy_delay(); - GPTP_LOG_INFO("neighborPropDelayThresh: %ld", iniParser.getNeighborPropDelayThresh()); - GPTP_LOG_INFO("syncReceiptThreshold: %d", iniParser.getSyncReceiptThresh()); - - /* If using config file, set the neighborPropDelayThresh. - * Otherwise it will use its default value (800ns) */ - portInit.neighborPropDelayThreshold = - iniParser.getNeighborPropDelayThresh(); - - /* If using config file, set the syncReceiptThreshold, otherwise - * it will use the default value (SYNC_RECEIPT_THRESH) - */ - portInit.syncReceiptThreshold = - iniParser.getSyncReceiptThresh(); - - if( strnlen( iniParser.getSystemClockDesc(), - MAX_CLOCK_DESC_LEN ) != 0 ) - systemClockDesc = - iniParser.getSystemClockDesc(); - - /*Only overwrites phy_delay default values if not input_delay switch enabled*/ - if(!input_delay) - { - ether_phy_delay = iniParser.getPhyDelay(); - } - } - - } - - if( systemClockDesc != NULL ) - { - if( timestamper->HWTimestamper_setsystemclock - ( systemClockDesc )) - GPTP_LOG_INFO - ( "Using system Clock: %s", systemClockDesc ); - } - - pPort = new EtherPort(&portInit); - - if (!pPort->init_port()) { - GPTP_LOG_ERROR("failed to initialize port"); - GPTP_LOG_UNREGISTER(); - return -1; - } - - if( restoredataptr != NULL ) { - if( !restorefailed ) { - restorefailed = !pPort->restoreSerializedState( restoredataptr, &restoredatacount ); - GPTP_LOG_INFO("Persistent port data restored: asCapable:%d, port_state:%d, one_way_delay:%lld", - pPort->getAsCapable(), pPort->getPortState(), pPort->getLinkDelay()); - } - restoredataptr = ((char *)restoredata) + (restoredatalength - restoredatacount); - } - - if (portInit.automotive_profile) { - if (portInit.isGM) { - port_state = PTP_MASTER; - } - else { - port_state = PTP_SLAVE; - } - override_portstate = true; - } - - if( override_portstate ) { - pPort->setPortState( port_state ); - } - - // Start PPS if requested - if( pps ) { - if( !timestamper->HWTimestamper_PPS_start()) { - GPTP_LOG_ERROR("Failed to start pulse per second I/O"); - } - } - - // Configure persistent write - if (pGPTPPersist) { - off_t len = 0; - restoredatacount = 0; - pClock->serializeState(NULL, &len); - restoredatacount += len; - pPort->serializeState(NULL, &len); - restoredatacount += len; - pGPTPPersist->setWriteSize((uint32_t)restoredatacount); - pGPTPPersist->registerWriteCB(gPTPPersistWriteCB); - } - - pPort->processEvent(POWERUP); - - do { - sig = 0; - - if (sigwait(&set, &sig) != 0) { - perror("sigwait()"); - GPTP_LOG_UNREGISTER(); - return -1; - } - - if (sig == SIGHUP) { - if (pGPTPPersist) { - // If port is either master or slave, save clock and then port state - if (pPort->getPortState() == PTP_MASTER || pPort->getPortState() == PTP_SLAVE) { - pGPTPPersist->triggerWriteStorage(); - } - } - } - - if (sig == SIGUSR2) { - pPort->logIEEEPortCounters(); - } - } while (sig == SIGHUP || sig == SIGUSR2); - - GPTP_LOG_ERROR("Exiting on %d", sig); - - if (pGPTPPersist) { - pGPTPPersist->closeStorage(); - } - - // Stop PPS if previously started - if( pps ) { - if( !timestamper->HWTimestamper_PPS_stop()) { - GPTP_LOG_ERROR("Failed to stop pulse per second I/O"); - } - } - - if( ipc ) delete ipc; - - GPTP_LOG_UNREGISTER(); - return 0; -} - -void gPTPPersistWriteCB(char *bufPtr, uint32_t bufSize) -{ - off_t restoredatalength = bufSize; - off_t restoredatacount = restoredatalength; - char *restoredataptr = NULL; - - GPTP_LOG_INFO("Signal received to write restore data"); - - restoredataptr = (char *)bufPtr; - pClock->serializeState(restoredataptr, &restoredatacount); - restoredataptr = ((char *)bufPtr) + (restoredatalength - restoredatacount); - pPort->serializeState(restoredataptr, &restoredatacount); - restoredataptr = ((char *)bufPtr) + (restoredatalength - restoredatacount); -} diff --git a/daemons/gptp/linux/src/linux_hal_common.cpp b/daemons/gptp/linux/src/linux_hal_common.cpp deleted file mode 100644 index ab312c95..00000000 --- a/daemons/gptp/linux/src/linux_hal_common.cpp +++ /dev/null @@ -1,1117 +0,0 @@ -/****************************************************************************** - - Copyright (c) 2009-2012, Intel Corporation - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. Neither the name of the Intel Corporation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - -******************************************************************************/ - -#include <linux_hal_common.hpp> -#include <sys/types.h> -#include <avbts_clock.hpp> -#include <ether_port.hpp> - -#include <pthread.h> -#include <linux_ipc.hpp> - -#include <sys/mman.h> -#include <fcntl.h> -#include <grp.h> -#include <net/if.h> - -#include <unistd.h> -#include <errno.h> - -#include <signal.h> -#include <net/ethernet.h> /* the L2 protocols */ - -#include <netpacket/packet.h> -#include <sys/ioctl.h> -#include <sys/types.h> -#include <sys/stat.h> - -#include <sys/socket.h> -#include <netinet/in.h> -#include <linux/netlink.h> -#include <linux/rtnetlink.h> -#include <linux/sockios.h> -#include <gptp_cfg.hpp> - -Timestamp tsToTimestamp(struct timespec *ts) -{ - Timestamp ret; - int seclen = sizeof(ts->tv_sec) - sizeof(ret.seconds_ls); - if (seclen > 0) { - ret.seconds_ms = - ts->tv_sec >> (sizeof(ts->tv_sec) - seclen) * 8; - ret.seconds_ls = ts->tv_sec & 0xFFFFFFFF; - } else { - ret.seconds_ms = 0; - ret.seconds_ls = ts->tv_sec; - } - ret.nanoseconds = ts->tv_nsec; - return ret; -} - -LinuxNetworkInterface::~LinuxNetworkInterface() { - close( sd_event ); - close( sd_general ); -} - -net_result LinuxNetworkInterface::send -( LinkLayerAddress *addr, uint16_t etherType, uint8_t *payload, size_t length, bool timestamp ) { - sockaddr_ll *remote = NULL; - int err; - remote = new struct sockaddr_ll; - memset( remote, 0, sizeof( *remote )); - remote->sll_family = AF_PACKET; - remote->sll_protocol = PLAT_htons( etherType ); - remote->sll_ifindex = ifindex; - remote->sll_halen = ETH_ALEN; - addr->toOctetArray( remote->sll_addr ); - - if( timestamp ) { -#ifndef ARCH_INTELCE - net_lock.lock(); -#endif - err = sendto - ( sd_event, payload, length, 0, (sockaddr *) remote, - sizeof( *remote )); - } else { - err = sendto - ( sd_general, payload, length, 0, (sockaddr *) remote, - sizeof( *remote )); - } - delete remote; - if( err == -1 ) { - GPTP_LOG_ERROR( "Failed to send: %s(%d)", strerror(errno), errno ); - return net_fatal; - } - return net_succeed; -} - - -void LinuxNetworkInterface::disable_rx_queue() { - struct packet_mreq mr_8021as; - int err; - - if( !net_lock.lock() ) { - fprintf( stderr, "D rx lock failed\n" ); - _exit(0); - } - - memset( &mr_8021as, 0, sizeof( mr_8021as )); - mr_8021as.mr_ifindex = ifindex; - mr_8021as.mr_type = PACKET_MR_MULTICAST; - mr_8021as.mr_alen = 6; - memcpy( mr_8021as.mr_address, P8021AS_MULTICAST, mr_8021as.mr_alen ); - err = setsockopt - ( sd_event, SOL_PACKET, PACKET_DROP_MEMBERSHIP, &mr_8021as, - sizeof( mr_8021as )); - if( err == -1 ) { - GPTP_LOG_ERROR - ( "Unable to add PTP multicast addresses to port id: %u", - ifindex ); - return; - } - - return; -} - -void LinuxNetworkInterface::clear_reenable_rx_queue() { - struct packet_mreq mr_8021as; - char buf[256]; - int err; - - while( recvfrom( sd_event, buf, 256, MSG_DONTWAIT, NULL, 0 ) != -1 ); - - memset( &mr_8021as, 0, sizeof( mr_8021as )); - mr_8021as.mr_ifindex = ifindex; - mr_8021as.mr_type = PACKET_MR_MULTICAST; - mr_8021as.mr_alen = 6; - memcpy( mr_8021as.mr_address, P8021AS_MULTICAST, mr_8021as.mr_alen ); - err = setsockopt - ( sd_event, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mr_8021as, - sizeof( mr_8021as )); - if( err == -1 ) { - GPTP_LOG_ERROR - ( "Unable to add PTP multicast addresses to port id: %u", - ifindex ); - return; - } - - if( !net_lock.unlock() ) { - fprintf( stderr, "D failed unlock rx lock, %d\n", err ); - } -} - -static void x_readEvent -( int sockint, EtherPort *pPort, int ifindex ) -{ - int status; - char buf[4096]; - struct iovec iov = { buf, sizeof buf }; - struct sockaddr_nl snl; - struct msghdr msg = { (void *) &snl, sizeof snl, &iov, 1, NULL, 0, 0 }; - struct nlmsghdr *msgHdr; - struct ifinfomsg *ifi; - - status = recvmsg(sockint, &msg, 0); - - if (status < 0) { - GPTP_LOG_ERROR("read_netlink: Error recvmsg: %d", status); - return; - } - - if (status == 0) { - GPTP_LOG_ERROR("read_netlink: EOF"); - return; - } - - // Process the NETLINK messages - for (msgHdr = (struct nlmsghdr *)buf; NLMSG_OK(msgHdr, (unsigned int)status); msgHdr = NLMSG_NEXT(msgHdr, status)) - { - if (msgHdr->nlmsg_type == NLMSG_DONE) - return; - - if (msgHdr->nlmsg_type == NLMSG_ERROR) { - GPTP_LOG_ERROR("netlink message error"); - return; - } - - if (msgHdr->nlmsg_type == RTM_NEWLINK) { - ifi = (struct ifinfomsg *)NLMSG_DATA(msgHdr); - if (ifi->ifi_index == ifindex) { - bool linkUp = ifi->ifi_flags & IFF_RUNNING; - if (linkUp != pPort->getLinkUpState()) { - pPort->setLinkUpState(linkUp); - if (linkUp) { - pPort->processEvent(LINKUP); - } - else { - pPort->processEvent(LINKDOWN); - } - } - else { - GPTP_LOG_DEBUG("False (repeated) %s event for the interface", linkUp ? "LINKUP" : "LINKDOWN"); - } - } - } - } - return; -} - -static void x_initLinkUpStatus( EtherPort *pPort, int ifindex ) -{ - struct ifreq device; - memset(&device, 0, sizeof(device)); - device.ifr_ifindex = ifindex; - - int inetSocket = socket (AF_INET, SOCK_STREAM, 0); - if (inetSocket < 0) { - GPTP_LOG_ERROR("initLinkUpStatus error opening socket: %s", strerror(errno)); - return; - } - - int r = ioctl(inetSocket, SIOCGIFNAME, &device); - if (r < 0) { - GPTP_LOG_ERROR("initLinkUpStatus error reading interface name: %s", strerror(errno)); - close(inetSocket); - return; - } - r = ioctl(inetSocket, SIOCGIFFLAGS, &device); - if (r < 0) { - GPTP_LOG_ERROR("initLinkUpStatus error reading flags: %s", strerror(errno)); - close(inetSocket); - return; - } - if (device.ifr_flags & IFF_RUNNING) { - GPTP_LOG_DEBUG("Interface %s is up", device.ifr_name); - pPort->setLinkUpState(true); - } //linkUp == false by default - close(inetSocket); -} - - -bool LinuxNetworkInterface::getLinkSpeed( int sd, uint32_t *speed ) -{ - struct ifreq ifr; - struct ethtool_cmd edata; - - ifr.ifr_ifindex = ifindex; - if( ioctl( sd, SIOCGIFNAME, &ifr ) == -1 ) - { - GPTP_LOG_ERROR - ( "%s: SIOCGIFNAME failed: %s", __PRETTY_FUNCTION__, - strerror( errno )); - return false; - } - - ifr.ifr_data = (char *) &edata; - edata.cmd = ETHTOOL_GSET; - if( ioctl( sd, SIOCETHTOOL, &ifr ) == -1 ) - { - GPTP_LOG_ERROR - ( "%s: SIOCETHTOOL failed: %s", __PRETTY_FUNCTION__, - strerror( errno )); - return false; - } - - switch (ethtool_cmd_speed(&edata)) - { - default: - GPTP_LOG_ERROR( "%s: Unknown/Unsupported Speed!", - __PRETTY_FUNCTION__ ); - return false; - case SPEED_100: - *speed = LINKSPEED_100MB; - break; - case SPEED_1000: - *speed = LINKSPEED_1G; - break; - case SPEED_2500: - *speed = LINKSPEED_2_5G; - break; - case SPEED_10000: - *speed = LINKSPEED_10G; - break; - } - GPTP_LOG_STATUS( "Link Speed: %d kb/sec", *speed ); - - return true; -} - -void LinuxNetworkInterface::watchNetLink( CommonPort *iPort ) -{ - fd_set netLinkFD; - int netLinkSocket; - int inetSocket; - struct sockaddr_nl addr; - - EtherPort *pPort = - dynamic_cast<EtherPort *>(iPort); - if( pPort == NULL ) - { - GPTP_LOG_ERROR("NETLINK socket open error"); - return; - } - - netLinkSocket = socket (AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); - if (netLinkSocket < 0) { - GPTP_LOG_ERROR("NETLINK socket open error"); - return; - } - - memset((void *) &addr, 0, sizeof (addr)); - - addr.nl_family = AF_NETLINK; - addr.nl_pid = getpid (); - addr.nl_groups = RTMGRP_LINK; - - if (bind (netLinkSocket, (struct sockaddr *) &addr, sizeof (addr)) < 0) { - GPTP_LOG_ERROR("Socket bind failed"); - close (netLinkSocket); - return; - } - - /* - * Open an INET family socket to be passed to getLinkSpeed() which calls - * ioctl() because NETLINK sockets do not support ioctl(). Since we will - * enter an infinite loop, there are no apparent close() calls for the - * open sockets, but they will be closed on process termination. - */ - inetSocket = socket (AF_INET, SOCK_STREAM, 0); - if (inetSocket < 0) { - GPTP_LOG_ERROR("watchNetLink error opening socket: %s", strerror(errno)); - close (netLinkSocket); - return; - } - - x_initLinkUpStatus(pPort, ifindex); - if( pPort->getLinkUpState() ) - { - uint32_t link_speed; - getLinkSpeed( inetSocket, &link_speed ); - pPort->setLinkSpeed((int32_t) link_speed ); - } else - { - pPort->setLinkSpeed( INVALID_LINKSPEED ); - } - - while (1) { - FD_ZERO(&netLinkFD); - FD_CLR(netLinkSocket, &netLinkFD); - FD_SET(netLinkSocket, &netLinkFD); - - // Wait forever for a net link event - int retval = select(FD_SETSIZE, &netLinkFD, NULL, NULL, NULL); - if (retval == -1) - ; // Error on select. We will ignore and keep going - else if (retval) { - bool prev_link_up = pPort->getLinkUpState(); - x_readEvent(netLinkSocket, pPort, ifindex); - - // Don't do anything else if link state is the same - if( prev_link_up == pPort->getLinkUpState() ) - continue; - if( pPort->getLinkUpState() ) - { - uint32_t link_speed; - getLinkSpeed( inetSocket, &link_speed ); - pPort->setLinkSpeed((int32_t) link_speed ); - } else - { - pPort->setLinkSpeed( INVALID_LINKSPEED ); - } - } - else { - ; // Would be timeout but Won't happen because we wait forever - } - } -} - - -struct LinuxTimerQueuePrivate { - pthread_t signal_thread; -}; - -struct LinuxTimerQueueActionArg { - timer_t timer_handle; - struct sigevent sevp; - event_descriptor_t *inner_arg; - ostimerq_handler func; - int type; - bool rm; -}; - -LinuxTimerQueue::~LinuxTimerQueue() { - pthread_join(_private->signal_thread,NULL); - if( _private != NULL ) delete _private; -} - -bool LinuxTimerQueue::init() { - _private = new LinuxTimerQueuePrivate; - if( _private == NULL ) return false; - - return true; -} - -void *LinuxTimerQueueHandler( void *arg ) { - LinuxTimerQueue *timerq = (LinuxTimerQueue *) arg; - sigset_t waitfor; - struct timespec timeout; - timeout.tv_sec = 0; timeout.tv_nsec = 100000000; /* 100 ms */ - - sigemptyset( &waitfor ); - GPTP_LOG_DEBUG("Signal thread started"); - while( !timerq->stop ) { - siginfo_t info; - LinuxTimerQueueMap_t::iterator iter; - sigaddset( &waitfor, SIGUSR1 ); - if( sigtimedwait( &waitfor, &info, &timeout ) == -1 ) { - if( errno == EAGAIN ) { - continue; - } - else { - GPTP_LOG_ERROR("Signal thread sigtimedwait error: %d", errno); - break; - } - } - if( timerq->lock->lock() != oslock_ok ) { - break; - } - - iter = timerq->timerQueueMap.find(info.si_value.sival_int); - if( iter != timerq->timerQueueMap.end() ) { - struct LinuxTimerQueueActionArg *arg = iter->second; - timerq->timerQueueMap.erase(iter); - timerq->LinuxTimerQueueAction( arg ); - if( arg->rm ) { - delete arg->inner_arg; - } - timer_delete(arg->timer_handle); - delete arg; - } - if( timerq->lock->unlock() != oslock_ok ) { - break; - } - } - GPTP_LOG_DEBUG("Signal thread exit"); - return NULL; -} - -void LinuxTimerQueue::LinuxTimerQueueAction( LinuxTimerQueueActionArg *arg ) { - arg->func( arg->inner_arg ); - - return; -} - -OSTimerQueue *LinuxTimerQueueFactory::createOSTimerQueue - ( IEEE1588Clock *clock ) { - LinuxTimerQueue *ret = new LinuxTimerQueue(); - - if( !ret->init() ) { - return NULL; - } - - ret->key = 0; - ret->stop = false; - ret->lock = clock->timerQLock(); - if( pthread_create - ( &(ret->_private->signal_thread), - NULL, LinuxTimerQueueHandler, ret ) != 0 ) { - delete ret; - return NULL; - } - - return ret; -} - - - -bool LinuxTimerQueue::addEvent -( unsigned long micros, int type, ostimerq_handler func, - event_descriptor_t * arg, bool rm, unsigned *event) { - LinuxTimerQueueActionArg *outer_arg; - int err; - LinuxTimerQueueMap_t::iterator iter; - - - outer_arg = new LinuxTimerQueueActionArg; - outer_arg->inner_arg = arg; - outer_arg->rm = rm; - outer_arg->func = func; - outer_arg->type = type; - - // Find key that we can use - while( timerQueueMap.find( key ) != timerQueueMap.end() ) { - ++key; - } - - { - struct itimerspec its; - memset(&(outer_arg->sevp), 0, sizeof(outer_arg->sevp)); - outer_arg->sevp.sigev_notify = SIGEV_SIGNAL; - outer_arg->sevp.sigev_signo = SIGUSR1; - outer_arg->sevp.sigev_value.sival_int = key; - if ( timer_create - (CLOCK_MONOTONIC, &outer_arg->sevp, &outer_arg->timer_handle) - == -1) { - GPTP_LOG_ERROR("timer_create failed - %s", strerror(errno)); - return false; - } - timerQueueMap[key] = outer_arg; - - memset(&its, 0, sizeof(its)); - its.it_value.tv_sec = micros / 1000000; - its.it_value.tv_nsec = (micros % 1000000) * 1000; - err = timer_settime( outer_arg->timer_handle, 0, &its, NULL ); - if( err < 0 ) { - GPTP_LOG_ERROR("Failed to arm timer: %s", strerror(errno)); - return false; - } - } - - return true; -} - - -bool LinuxTimerQueue::cancelEvent( int type, unsigned *event ) { - LinuxTimerQueueMap_t::iterator iter; - for( iter = timerQueueMap.begin(); iter != timerQueueMap.end();) { - if( (iter->second)->type == type ) { - // Delete element - if( (iter->second)->rm ) { - delete (iter->second)->inner_arg; - } - timer_delete(iter->second->timer_handle); - delete iter->second; - timerQueueMap.erase(iter++); - } else { - ++iter; - } - } - - return true; -} - - -void* OSThreadCallback( void* input ) { - OSThreadArg *arg = (OSThreadArg*) input; - - arg->ret = arg->func( arg->arg ); - return 0; -} - -bool LinuxTimestamper::post_init( int ifindex, int sd, TicketingLock *lock ) { - return true; -} - -LinuxTimestamper::~LinuxTimestamper() {} - -unsigned long LinuxTimer::sleep(unsigned long micros) { - struct timespec req; - struct timespec rem; - req.tv_sec = micros / 1000000; - req.tv_nsec = micros % 1000000 * 1000; - int ret = nanosleep( &req, &rem ); - while( ret == -1 && errno == EINTR ) { - req = rem; - ret = nanosleep( &req, &rem ); - } - if( ret == -1 ) { - fprintf - ( stderr, "Error calling nanosleep: %s\n", strerror( errno )); - _exit(-1); - } - return micros; -} - -struct TicketingLockPrivate { - pthread_cond_t condition; - pthread_mutex_t cond_lock; -}; - -bool TicketingLock::lock( bool *got ) { - uint8_t ticket; - bool yield = false; - bool ret = true; - if( !init_flag ) return false; - - if( pthread_mutex_lock( &_private->cond_lock ) != 0 ) { - ret = false; - goto done; - } - // Take a ticket - ticket = cond_ticket_issue++; - while( ticket != cond_ticket_serving ) { - if( got != NULL ) { - *got = false; - --cond_ticket_issue; - yield = true; - goto unlock; - } - if( pthread_cond_wait( &_private->condition, &_private->cond_lock ) != 0 ) { - ret = false; - goto unlock; - } - } - - if( got != NULL ) *got = true; - - unlock: - if( pthread_mutex_unlock( &_private->cond_lock ) != 0 ) { - ret = false; - goto done; - } - - if( yield ) pthread_yield(); - - done: - return ret; -} - -bool TicketingLock::unlock() { - bool ret = true; - if( !init_flag ) return false; - - if( pthread_mutex_lock( &_private->cond_lock ) != 0 ) { - ret = false; - goto done; - } - ++cond_ticket_serving; - if( pthread_cond_broadcast( &_private->condition ) != 0 ) { - ret = false; - goto unlock; - } - - unlock: - if( pthread_mutex_unlock( &_private->cond_lock ) != 0 ) { - ret = false; - goto done; - } - - done: - return ret; -} - -bool TicketingLock::init() { - int err; - if( init_flag ) return false; // Don't do this more than once - _private = new TicketingLockPrivate; - if( _private == NULL ) return false; - - err = pthread_mutex_init( &_private->cond_lock, NULL ); - if( err != 0 ) return false; - err = pthread_cond_init( &_private->condition, NULL ); - if( err != 0 ) return false; - in_use = false; - cond_ticket_issue = 0; - cond_ticket_serving = 0; - init_flag = true; - - return true; -} - -TicketingLock::TicketingLock() { - init_flag = false; - _private = NULL; -} - -TicketingLock::~TicketingLock() { - if( _private != NULL ) delete _private; -} - -struct LinuxLockPrivate { - pthread_t thread_id; - pthread_mutexattr_t mta; - pthread_mutex_t mutex; - pthread_cond_t port_ready_signal; -}; - -bool LinuxLock::initialize( OSLockType type ) { - int lock_c; - - _private = new LinuxLockPrivate; - if( _private == NULL ) return false; - - pthread_mutexattr_init(&_private->mta); - if( type == oslock_recursive ) - pthread_mutexattr_settype(&_private->mta, PTHREAD_MUTEX_RECURSIVE); - lock_c = pthread_mutex_init(&_private->mutex,&_private->mta); - if(lock_c != 0) { - GPTP_LOG_ERROR("Mutex initialization failed - %s",strerror(errno)); - return false; - } - - return true; -} - -LinuxLock::~LinuxLock() { - int lock_c = pthread_mutex_lock(&_private->mutex); - if(lock_c == 0) { - pthread_mutex_destroy( &_private->mutex ); - } -} - -OSLockResult LinuxLock::lock() { - int lock_c; - lock_c = pthread_mutex_lock(&_private->mutex); - if(lock_c != 0) { - fprintf( stderr, "LinuxLock: lock failed %d\n", lock_c ); - return oslock_fail; - } - return oslock_ok; -} - -OSLockResult LinuxLock::trylock() { - int lock_c; - lock_c = pthread_mutex_trylock(&_private->mutex); - if(lock_c != 0) return oslock_fail; - return oslock_ok; -} - -OSLockResult LinuxLock::unlock() { - int lock_c; - lock_c = pthread_mutex_unlock(&_private->mutex); - if(lock_c != 0) { - fprintf( stderr, "LinuxLock: unlock failed %d\n", lock_c ); - return oslock_fail; - } - return oslock_ok; -} - -struct LinuxConditionPrivate { - pthread_cond_t port_ready_signal; - pthread_mutex_t port_lock; -}; - - -LinuxCondition::~LinuxCondition() { - if( _private != NULL ) delete _private; -} - -bool LinuxCondition::initialize() { - int lock_c; - - _private = new LinuxConditionPrivate; - if( _private == NULL ) return false; - - pthread_cond_init(&_private->port_ready_signal, NULL); - lock_c = pthread_mutex_init(&_private->port_lock, NULL); - if (lock_c != 0) - return false; - return true; -} - -bool LinuxCondition::wait_prelock() { - pthread_mutex_lock(&_private->port_lock); - up(); - return true; -} - -bool LinuxCondition::wait() { - pthread_cond_wait(&_private->port_ready_signal, &_private->port_lock); - down(); - pthread_mutex_unlock(&_private->port_lock); - return true; -} - -bool LinuxCondition::signal() { - pthread_mutex_lock(&_private->port_lock); - if (waiting()) - pthread_cond_broadcast(&_private->port_ready_signal); - pthread_mutex_unlock(&_private->port_lock); - return true; -} - -struct LinuxThreadPrivate { - pthread_t thread_id; -}; - -bool LinuxThread::start(OSThreadFunction function, void *arg) { - sigset_t set; - sigset_t oset; - int err; - - _private = new LinuxThreadPrivate; - if( _private == NULL ) return false; - - arg_inner = new OSThreadArg(); - arg_inner->func = function; - arg_inner->arg = arg; - sigemptyset(&set); - sigaddset(&set, SIGALRM); - err = pthread_sigmask(SIG_BLOCK, &set, &oset); - if (err != 0) { - GPTP_LOG_ERROR - ("Add timer pthread_sigmask( SIG_BLOCK ... )"); - return false; - } - err = pthread_create(&_private->thread_id, NULL, OSThreadCallback, - arg_inner); - if (err != 0) - return false; - sigdelset(&oset, SIGALRM); - err = pthread_sigmask(SIG_SETMASK, &oset, NULL); - if (err != 0) { - GPTP_LOG_ERROR - ("Add timer pthread_sigmask( SIG_SETMASK ... )"); - return false; - } - - return true; -} - -bool LinuxThread::join(OSThreadExitCode & exit_code) { - int err; - err = pthread_join(_private->thread_id, NULL); - if (err != 0) - return false; - exit_code = arg_inner->ret; - delete arg_inner; - return true; -} - -LinuxThread::LinuxThread() { - _private = NULL; -}; - -LinuxThread::~LinuxThread() { - if( _private != NULL ) delete _private; -} - -LinuxSharedMemoryIPC::~LinuxSharedMemoryIPC() { - munmap(master_offset_buffer, SHM_SIZE); - shm_unlink(SHM_NAME); -} - -bool LinuxSharedMemoryIPC::init( OS_IPC_ARG *barg ) { - LinuxIPCArg *arg; - struct group *grp; - const char *group_name; - pthread_mutexattr_t shared; - mode_t oldumask = umask(0); - - if( barg == NULL ) { - group_name = DEFAULT_GROUPNAME; - } else { - arg = dynamic_cast<LinuxIPCArg *> (barg); - if( arg == NULL ) { - GPTP_LOG_ERROR( "Wrong IPC init arg type" ); - goto exit_error; - } else { - group_name = arg->group_name; - } - } - grp = getgrnam( group_name ); - if( grp == NULL ) { - GPTP_LOG_ERROR( "Group %s not found, will try root (0) instead", group_name ); - } - - shm_fd = shm_open( SHM_NAME, O_RDWR | O_CREAT, 0660 ); - if( shm_fd == -1 ) { - GPTP_LOG_ERROR( "shm_open(): %s", strerror(errno) ); - goto exit_error; - } - (void) umask(oldumask); - if (fchown(shm_fd, -1, grp != NULL ? grp->gr_gid : 0) < 0) { - GPTP_LOG_ERROR("shm_open(): Failed to set ownership"); - } - if( ftruncate( shm_fd, SHM_SIZE ) == -1 ) { - GPTP_LOG_ERROR( "ftruncate()" ); - goto exit_unlink; - } - master_offset_buffer = (char *) mmap - ( NULL, SHM_SIZE, PROT_READ | PROT_WRITE, MAP_LOCKED | MAP_SHARED, - shm_fd, 0 ); - if( master_offset_buffer == (char *) -1 ) { - GPTP_LOG_ERROR( "mmap()" ); - goto exit_unlink; - } - /*create mutex attr */ - err = pthread_mutexattr_init(&shared); - if(err != 0) { - GPTP_LOG_ERROR - ("mutex attr initialization failed - %s", - strerror(errno)); - goto exit_unlink; - } - pthread_mutexattr_setpshared(&shared,1); - /*create a mutex */ - err = pthread_mutex_init((pthread_mutex_t *) master_offset_buffer, &shared); - if(err != 0) { - GPTP_LOG_ERROR - ("sharedmem - Mutex initialization failed - %s", - strerror(errno)); - goto exit_unlink; - } - return true; - exit_unlink: - shm_unlink( SHM_NAME ); - exit_error: - return false; -} - -bool LinuxSharedMemoryIPC::update( - int64_t ml_phoffset, - int64_t ls_phoffset, - FrequencyRatio ml_freqoffset, - FrequencyRatio ls_freqoffset, - uint64_t local_time, - uint32_t sync_count, - uint32_t pdelay_count, - PortState port_state, - bool asCapable ) -{ - int buf_offset = 0; - pid_t process_id = getpid(); - char *shm_buffer = master_offset_buffer; - gPtpTimeData *ptimedata; - if( shm_buffer != NULL ) { - /* lock */ - pthread_mutex_lock((pthread_mutex_t *) shm_buffer); - buf_offset += sizeof(pthread_mutex_t); - ptimedata = (gPtpTimeData *) (shm_buffer + buf_offset); - ptimedata->ml_phoffset = ml_phoffset; - ptimedata->ls_phoffset = ls_phoffset; - ptimedata->ml_freqoffset = ml_freqoffset; - ptimedata->ls_freqoffset = ls_freqoffset; - ptimedata->local_time = local_time; - ptimedata->sync_count = sync_count; - ptimedata->pdelay_count = pdelay_count; - ptimedata->asCapable = asCapable; - ptimedata->port_state = port_state; - ptimedata->process_id = process_id; - /* unlock */ - pthread_mutex_unlock((pthread_mutex_t *) shm_buffer); - } - return true; -} - -bool LinuxSharedMemoryIPC::update_grandmaster( - uint8_t gptp_grandmaster_id[], - uint8_t gptp_domain_number ) -{ - int buf_offset = 0; - char *shm_buffer = master_offset_buffer; - gPtpTimeData *ptimedata; - if( shm_buffer != NULL ) { - /* lock */ - pthread_mutex_lock((pthread_mutex_t *) shm_buffer); - buf_offset += sizeof(pthread_mutex_t); - ptimedata = (gPtpTimeData *) (shm_buffer + buf_offset); - memcpy(ptimedata->gptp_grandmaster_id, gptp_grandmaster_id, PTP_CLOCK_IDENTITY_LENGTH); - ptimedata->gptp_domain_number = gptp_domain_number; - /* unlock */ - pthread_mutex_unlock((pthread_mutex_t *) shm_buffer); - } - return true; -} - -bool LinuxSharedMemoryIPC::update_network_interface( - uint8_t clock_identity[], - uint8_t priority1, - uint8_t clock_class, - int16_t offset_scaled_log_variance, - uint8_t clock_accuracy, - uint8_t priority2, - uint8_t domain_number, - int8_t log_sync_interval, - int8_t log_announce_interval, - int8_t log_pdelay_interval, - uint16_t port_number ) -{ - int buf_offset = 0; - char *shm_buffer = master_offset_buffer; - gPtpTimeData *ptimedata; - if( shm_buffer != NULL ) { - /* lock */ - pthread_mutex_lock((pthread_mutex_t *) shm_buffer); - buf_offset += sizeof(pthread_mutex_t); - ptimedata = (gPtpTimeData *) (shm_buffer + buf_offset); - memcpy(ptimedata->clock_identity, clock_identity, PTP_CLOCK_IDENTITY_LENGTH); - ptimedata->priority1 = priority1; - ptimedata->clock_class = clock_class; - ptimedata->offset_scaled_log_variance = offset_scaled_log_variance; - ptimedata->clock_accuracy = clock_accuracy; - ptimedata->priority2 = priority2; - ptimedata->domain_number = domain_number; - ptimedata->log_sync_interval = log_sync_interval; - ptimedata->log_announce_interval = log_announce_interval; - ptimedata->log_pdelay_interval = log_pdelay_interval; - ptimedata->port_number = port_number; - /* unlock */ - pthread_mutex_unlock((pthread_mutex_t *) shm_buffer); - } - return true; -} - -void LinuxSharedMemoryIPC::stop() { - if( master_offset_buffer != NULL ) { - munmap( master_offset_buffer, SHM_SIZE ); - shm_unlink( SHM_NAME ); - } -} - -bool LinuxNetworkInterfaceFactory::createInterface -( OSNetworkInterface **net_iface, InterfaceLabel *label, - CommonTimestamper *timestamper ) { - struct ifreq device; - int err; - struct sockaddr_ll ifsock_addr; - struct packet_mreq mr_8021as; - LinkLayerAddress addr; - int ifindex; - - LinuxNetworkInterface *net_iface_l = new LinuxNetworkInterface(); - - if( !net_iface_l->net_lock.init()) { - GPTP_LOG_ERROR( "Failed to initialize network lock"); - return false; - } - - InterfaceName *ifname = dynamic_cast<InterfaceName *>(label); - if( ifname == NULL ){ - GPTP_LOG_ERROR( "ifname == NULL"); - return false; - } - - net_iface_l->sd_general = socket( PF_PACKET, SOCK_DGRAM, 0 ); - if( net_iface_l->sd_general == -1 ) { - GPTP_LOG_ERROR( "failed to open general socket: %s", strerror(errno)); - return false; - } - net_iface_l->sd_event = socket( PF_PACKET, SOCK_DGRAM, 0 ); - if( net_iface_l->sd_event == -1 ) { - GPTP_LOG_ERROR - ( "failed to open event socket: %s ", strerror(errno)); - return false; - } - - memset( &device, 0, sizeof(device)); - ifname->toString( device.ifr_name, IFNAMSIZ - 1 ); - err = ioctl( net_iface_l->sd_event, SIOCGIFHWADDR, &device ); - if( err == -1 ) { - GPTP_LOG_ERROR - ( "Failed to get interface address: %s", strerror( errno )); - return false; - } - - addr = LinkLayerAddress( (uint8_t *)&device.ifr_hwaddr.sa_data ); - net_iface_l->local_addr = addr; - err = ioctl( net_iface_l->sd_event, SIOCGIFINDEX, &device ); - if( err == -1 ) { - GPTP_LOG_ERROR - ( "Failed to get interface index: %s", strerror( errno )); - return false; - } - ifindex = device.ifr_ifindex; - net_iface_l->ifindex = ifindex; - memset( &mr_8021as, 0, sizeof( mr_8021as )); - mr_8021as.mr_ifindex = ifindex; - mr_8021as.mr_type = PACKET_MR_MULTICAST; - mr_8021as.mr_alen = 6; - memcpy( mr_8021as.mr_address, P8021AS_MULTICAST, mr_8021as.mr_alen ); - err = setsockopt - ( net_iface_l->sd_event, SOL_PACKET, PACKET_ADD_MEMBERSHIP, - &mr_8021as, sizeof( mr_8021as )); - if( err == -1 ) { - GPTP_LOG_ERROR - ( "Unable to add PTP multicast addresses to port id: %u", - ifindex ); - return false; - } - - memset( &ifsock_addr, 0, sizeof( ifsock_addr )); - ifsock_addr.sll_family = AF_PACKET; - ifsock_addr.sll_ifindex = ifindex; - ifsock_addr.sll_protocol = PLAT_htons( PTP_ETHERTYPE ); - err = bind - ( net_iface_l->sd_event, (sockaddr *) &ifsock_addr, - sizeof( ifsock_addr )); - if( err == -1 ) { - GPTP_LOG_ERROR( "Call to bind() failed: %s", strerror(errno) ); - return false; - } - - net_iface_l->timestamper = - dynamic_cast <LinuxTimestamper *>(timestamper); - if(net_iface_l->timestamper == NULL) { - GPTP_LOG_ERROR( "timestamper == NULL" ); - return false; - } - if( !net_iface_l->timestamper->post_init - ( ifindex, net_iface_l->sd_event, &net_iface_l->net_lock )) { - GPTP_LOG_ERROR( "post_init failed\n" ); - return false; - } - *net_iface = net_iface_l; - - return true; -} diff --git a/daemons/gptp/linux/src/linux_hal_common.hpp b/daemons/gptp/linux/src/linux_hal_common.hpp deleted file mode 100644 index 9eb3ddc9..00000000 --- a/daemons/gptp/linux/src/linux_hal_common.hpp +++ /dev/null @@ -1,723 +0,0 @@ -/****************************************************************************** - - Copyright (c) 2012, Intel Corporation - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. Neither the name of the Intel Corporation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - -******************************************************************************/ - -#ifndef LINUX_HAL_COMMON_HPP -#define LINUX_HAL_COMMON_HPP - -/**@file*/ - -#include "avbts_osnet.hpp" -#include "avbts_oslock.hpp" -#include "avbts_oscondition.hpp" -#include "avbts_ostimerq.hpp" -#include "avbts_ostimer.hpp" -#include "avbts_osthread.hpp" -#include "avbts_osipc.hpp" -#include "ieee1588.hpp" -#include <ether_tstamper.hpp> -#include <linux/ethtool.h> - -#include <list> - -#define ONE_WAY_PHY_DELAY 400 /*!< One way phy delay. TX or RX phy delay default value*/ -#define P8021AS_MULTICAST "\x01\x80\xC2\x00\x00\x0E" /*!< Default multicast address*/ -#define PTP_DEVICE "/dev/ptpXX" /*!< Default PTP device */ -#define PTP_DEVICE_IDX_OFFS 8 /*!< PTP device index offset*/ -#define CLOCKFD 3 /*!< Clock file descriptor */ -#define FD_TO_CLOCKID(fd) ((~(clockid_t) (fd) << 3) | CLOCKFD) /*!< Converts an FD to CLOCKID */ -struct timespec; - -/** - * @brief Converts timestamp in the struct timespec format to Timestamp - * @param ts Timestamp on struct timespec format - * @return timestamp on the Timestamp format - */ -extern Timestamp tsToTimestamp(struct timespec *ts); - -struct TicketingLockPrivate; - -/** - * @brief Provides the type for the TicketingLock private structure - */ -typedef struct TicketingLockPrivate * TicketingLockPrivate_t; - -/** - * @brief TicketingLock: Implements the ticket lock algorithm. - * A ticket lock consists of two counters, one containing the - * number of requests to acquire the lock, and the other the - * number of times the lock has been released. A processor acquires the lock - * by performing a fetch and increment operation on the request counter and - * waiting until the result its ticket is equal to the value of the release - * counter. It releases the lock by incrementing the release counter. - */ -class TicketingLock { -public: - /** - * @brief Lock mechanism. - * Gets a ticket and try locking the process. - * @param got [out] If non-null, it is set to TRUE when the lock is acquired. FALSE otherwise. - * @return TRUE when successfully got the lock, FALSE otherwise. - */ - bool lock( bool *got = NULL ); - - /** - * @brief Unlock mechanism. Increments the release counter and unblock other threads - * waiting for a condition flag. - * @return TRUE in case of success, FALSE otherwise. - */ - bool unlock(); - - /** - * @brief Initializes all flags and counters. Create private structures. - * @return TRUE in case of success, FALSE otherwise. - */ - bool init(); - - /** - * @brief Default constructor sets some flags to false that will be initialized on - * the init method. Protects against using lock/unlock without calling init. - */ - TicketingLock(); - - /** - * @brief Deletes the object and private structures. - */ - ~TicketingLock(); -private: - bool init_flag; - TicketingLockPrivate_t _private; - bool in_use; - uint8_t cond_ticket_issue; - uint8_t cond_ticket_serving; -}; - -/** - * @brief LinuxTimestamper: Provides a generic hardware - * timestamp interface for linux based systems. - */ -class LinuxTimestamper : public EtherTimestamper { -public: - /** - * @brief Destructor - */ - virtual ~LinuxTimestamper() = 0; - - /** - * @brief Provides a generic method for initializing timestamp interfaces - * @param ifindex Network device interface index - * @param sd Socket descriptor - * @param lock [in] Pointer to ticketing Lock object - * @return TRUE if success, FALSE in case of error - */ - virtual bool post_init( int ifindex, int sd, TicketingLock *lock ) = 0; -}; - -/** - * @brief Provides a Linux network generic interface - */ -class LinuxNetworkInterface : public OSNetworkInterface { - friend class LinuxNetworkInterfaceFactory; -private: - LinkLayerAddress local_addr; - int sd_event; - int sd_general; - LinuxTimestamper *timestamper; - int ifindex; - - TicketingLock net_lock; -public: - /** - * @brief Sends a packet to a remote address - * @param addr [in] Remote link layer address - * @param etherType [in] The EtherType of the message in host order - * @param payload [in] Data buffer - * @param length Size of data buffer - * @param timestamp TRUE if to use the event socket with the PTP multicast address. FALSE if to use - * a general socket. - * @return net_fatal if error, net_success if success - */ - virtual net_result send - ( LinkLayerAddress *addr, uint16_t etherType, uint8_t *payload, size_t length, - bool timestamp ); - - /** - * @brief Receives a packet from a remote address - * @param addr [in] Remote link layer address - * @param payload [out] Data buffer - * @param length [out] Size of received data buffer - * @return net_succeed in case of successful reception, net_trfail in case there is - * an error on the transmit side, net_fatal if error on reception - */ - virtual net_result nrecv - ( LinkLayerAddress *addr, uint8_t *payload, size_t &length ); - - /** - * @brief Disables rx socket descriptor rx queue - * @return void - */ - void disable_rx_queue();; - - /** - * @brief Clears and enables the rx socket descriptor - * @return void - */ - void clear_reenable_rx_queue(); - - /** - * @brief Gets the local link layer address - * @param addr [out] Pointer to the LinkLayerAddress object - * @return void - */ - virtual void getLinkLayerAddress( LinkLayerAddress *addr ) { - *addr = local_addr; - } - - /** - * @brief Get speed of network link - * - * @param [in] sd Open socket descriptor - * @param [out] speed Link speed in kb/sec - * @return false on error - */ - bool getLinkSpeed( int sd, uint32_t *speed ); - - /** - * @brief Watch for net link changes. - */ - virtual void watchNetLink( CommonPort *pPort ); - - /** - * @brief Gets the payload offset - * @return payload offset - */ - virtual unsigned getPayloadOffset() { - return 0; - } - /** - * @brief Destroys the network interface - */ - ~LinuxNetworkInterface(); -protected: - /** - * @brief Default constructor - */ - LinuxNetworkInterface() {}; -}; - -/** - * @brief Provides a list of LinuxNetworkInterface members - */ -typedef std::list<LinuxNetworkInterface *> LinuxNetworkInterfaceList; - -struct LinuxLockPrivate; -/** - * @brief Provides a type for the LinuxLock class - */ -typedef LinuxLockPrivate * LinuxLockPrivate_t; - -/** - * @brief Extends OSLock generic interface to Linux - */ -class LinuxLock : public OSLock { - friend class LinuxLockFactory; -private: - OSLockType type; - LinuxLockPrivate_t _private; -protected: - /** - * @brief Default constructor. - */ - LinuxLock() { - _private = NULL; - } - - /** - * @brief Initializes all mutexes and locks - * @param type OSLockType enumeration. If oslock_recursive then set pthreads - * attributes to PTHREAD_MUTEX_RECURSIVE - * @return If successful, returns oslock_ok. Returns oslock_fail otherwise - */ - bool initialize( OSLockType type ); - - /** - * @brief Destroys mutexes if lock is still valid - */ - ~LinuxLock(); - - /** - * @brief Provides a simple lock mechanism. - * @return oslock_fail if lock has failed, oslock_ok otherwise. - */ - OSLockResult lock(); - - /** - * @brief Provides a simple trylock mechanism. - * @return oslock_fail if lock has failed, oslock_ok otherwise. - */ - OSLockResult trylock(); - - /** - * @brief Provides a simple unlock mechanism. - * @return oslock_fail if unlock has failed, oslock_ok otherwise. - */ - OSLockResult unlock(); -}; - -/** - * @brief Provides a factory pattern for LinuxLock class - */ -class LinuxLockFactory:public OSLockFactory { -public: - /** - * @brief Creates the locking mechanism - * @param type OSLockType enumeration - * @return Pointer to OSLock object - */ - OSLock * createLock( OSLockType type ) const - { - LinuxLock *lock = new LinuxLock(); - if (!lock->initialize(type)) { - delete lock; - lock = NULL; - } - return lock; - } -}; - -struct LinuxConditionPrivate; -/** - * @brief Provides a private type for the LinuxCondition class - */ -typedef struct LinuxConditionPrivate * LinuxConditionPrivate_t; - -/** - * @brief Extends OSCondition class to Linux - */ -class LinuxCondition : public OSCondition { - friend class LinuxConditionFactory; -private: - LinuxConditionPrivate_t _private; -protected: - - /** - * @brief Initializes locks and mutex conditions - * @return TRUE if it is ok, FALSE in case of error - */ - bool initialize(); -public: - - /** - * @brief Counts up the amount of times we call the locking - * mechanism - * @return TRUE after incrementing the counter. - */ - bool wait_prelock(); - - /** - * @brief Waits until the ready signal condition is met and decrements - * the counter. - */ - bool wait(); - - /** - * @brief Unblock all threads that are busy waiting for a condition - * @return TRUE - */ - bool signal(); - - /* - * Default constructor - */ - ~LinuxCondition(); - - /* - * Destructor: Deletes internal variables - */ - LinuxCondition() { - _private = NULL; - } -}; - -/** - * @brief Implements factory design pattern for LinuxCondition class - */ -class LinuxConditionFactory : public OSConditionFactory { -public: - /** - * @brief Creates LinuxCondition objects - * @return Pointer to the OSCondition object in case of success. NULL otherwise - */ - OSCondition *createCondition() const - { - LinuxCondition *result = new LinuxCondition(); - return result->initialize() ? result : NULL; - } -}; - -struct LinuxTimerQueueActionArg; - -/** - * @brief Provides a map type for the LinuxTimerQueue class - */ -typedef std::map < int, struct LinuxTimerQueueActionArg *> LinuxTimerQueueMap_t; - -/** - * @brief Linux timer queue handler. Deals with linux queues - * @param arg [in] LinuxTimerQueue arguments - * @return void - */ -void *LinuxTimerQueueHandler( void *arg ); - -struct LinuxTimerQueuePrivate; -/** - * @brief Provides a private type for the LinuxTimerQueue class - */ -typedef struct LinuxTimerQueuePrivate * LinuxTimerQueuePrivate_t; - -/** - * @brief Extends OSTimerQueue to Linux - */ -class LinuxTimerQueue : public OSTimerQueue { - friend class LinuxTimerQueueFactory; - friend void *LinuxTimerQueueHandler( void * arg ); -private: - LinuxTimerQueueMap_t timerQueueMap; - int key; - bool stop; - LinuxTimerQueuePrivate_t _private; - OSLock *lock; - void LinuxTimerQueueAction( LinuxTimerQueueActionArg *arg ); -protected: - /** - * @brief Default constructor - */ - LinuxTimerQueue() { - _private = NULL; - } - - /** - * @brief Initializes internal variables - * @return TRUE if success, FALSE otherwise. - */ - virtual bool init(); -public: - /** - * @brief Deletes pre-allocated internal variables. - */ - ~LinuxTimerQueue(); - - /** - * @brief Add an event to the timer queue - * @param micros Time in microsseconds - * @param type Event type - * @param func Callback - * @param arg inner argument of type event_descriptor_t - * @param rm when true, allows elements to be deleted from the queue - * @param event [inout] Pointer to the event - * @return TRUE success, FALSE fail - */ - bool addEvent - ( unsigned long micros, int type, ostimerq_handler func, - event_descriptor_t * arg, bool rm, unsigned *event ); - - /** - * @brief Removes an event from the timer queue - * @param type Event type - * @param event [inout] Pointer to the event - * @return TRUE success, FALSE fail - */ - bool cancelEvent( int type, unsigned *event ); -}; - -/** - * @brief Implements factory design pattern for linux - */ -class LinuxTimerQueueFactory : public OSTimerQueueFactory { -public: - /** - * @brief Creates Linux timer queue - * @param clock [in] Pointer to IEEE15588Clock type - * @return Pointer to OSTimerQueue - */ - virtual OSTimerQueue *createOSTimerQueue( IEEE1588Clock *clock ); -}; - -/** - * @brief Extends the OSTimer generic class to Linux - */ -class LinuxTimer : public OSTimer { - friend class LinuxTimerFactory; - public: - /** - * @brief Sleeps for a given amount of time in microsseconds - * @param micros Time in micro-seconds - * @return -1 if error, micros (input argument) if success - */ - virtual unsigned long sleep(unsigned long micros); - protected: - /** - * @brief Destroys linux timer - */ - LinuxTimer() {}; -}; - -/** - * @brief Provides factory design pattern for LinuxTimer - */ -class LinuxTimerFactory : public OSTimerFactory { - public: - /** - * @brief Creates the linux timer - * @return Pointer to OSTimer object - */ - virtual OSTimer *createTimer() const - { - return new LinuxTimer(); - } -}; - -/** - * @brief Provides the default arguments for the OSThread class - */ -struct OSThreadArg { - OSThreadFunction func; /*!< Callback function */ - void *arg; /*!< Input arguments */ - OSThreadExitCode ret; /*!< Return code */ -}; - -/** - * @brief OSThread callback - * @param input OSThreadArg structure - * @return void - */ -void *OSThreadCallback(void *input); - -struct LinuxThreadPrivate; -/** - * @brief Provides a private type for the LinuxThread class - */ -typedef LinuxThreadPrivate * LinuxThreadPrivate_t; - -/** - * @brief Extends OSThread class to Linux - */ -class LinuxThread : public OSThread { - friend class LinuxThreadFactory; - private: - LinuxThreadPrivate_t _private; - OSThreadArg *arg_inner; - public: - /** - * @brief Starts a new thread - * @param function Callback to the thread to be started - * @param arg Function's parameters - * @return TRUE if no error during init, FALSE otherwise - */ - virtual bool start(OSThreadFunction function, void *arg); - - /** - * @brief Joins a new thread - * @param exit_code Callback's return code - * @return TRUE if ok, FALSE if error. - */ - virtual bool join(OSThreadExitCode & exit_code); - virtual ~LinuxThread(); - protected: - LinuxThread(); -}; - -/** - * @brief Provides factory design pattern for LinuxThread class - */ -class LinuxThreadFactory:public OSThreadFactory { - public: - /** - * @brief Creates a new LinuxThread - * @return Pointer to LinuxThread object - */ - OSThread *createThread() const { - return new LinuxThread(); - } -}; - -/** - * @brief Extends OSNetworkInterfaceFactory for LinuxNetworkInterface - */ -class LinuxNetworkInterfaceFactory : public OSNetworkInterfaceFactory { -public: - /** - * @brief Creates a new interface - * @param net_iface [out] Network interface. Created internally. - * @param label [in] Label to be cast to the interface's name internally - * @param timestamper [in] Pointer to a hardware timestamp object - * @return TRUE if no error during interface creation, FALSE otherwise - */ - virtual bool createInterface - ( OSNetworkInterface **net_iface, InterfaceLabel *label, - CommonTimestamper *timestamper ); -}; - -/** - * @brief Extends IPC ARG generic interface to linux - */ -class LinuxIPCArg : public OS_IPC_ARG { -private: - char *group_name; -public: - /** - * @brief Initializes IPCArg object - * @param group_name [in] Group's name - */ - LinuxIPCArg( char *group_name ) { - int len = strnlen(group_name,16); - this->group_name = new char[len+1]; - strncpy( this->group_name, group_name, len+1 ); - this->group_name[len] = '\0'; - } - /** - * @brief Destroys IPCArg internal variables - */ - virtual ~LinuxIPCArg() { - delete group_name; - } - friend class LinuxSharedMemoryIPC; -}; - -#define DEFAULT_GROUPNAME "ptp" /*!< Default groupname for the shared memory interface*/ - -/** - * @brief Linux shared memory interface - */ -class LinuxSharedMemoryIPC:public OS_IPC { -private: - int shm_fd; - char *master_offset_buffer; - int err; -public: - /** - * @brief Initializes the internal flags - */ - LinuxSharedMemoryIPC() { - shm_fd = 0; - err = 0; - master_offset_buffer = NULL; - }; - /** - * @brief Destroys and unlinks shared memory - */ - ~LinuxSharedMemoryIPC(); - - /** - * @brief Initializes shared memory with DEFAULT_GROUPNAME case arg is null - * @param barg Groupname of the shared memory - * @return TRUE if no error, FALSE otherwise - */ - virtual bool init( OS_IPC_ARG *barg = NULL ); - - /** - * @brief Updates IPC values - * - * @param ml_phoffset Master to local phase offset - * @param ls_phoffset Local to slave phase offset - * @param ml_freqoffset Master to local frequency offset - * @param ls_freqoffset Local to slave frequency offset - * @param local_time Local time - * @param sync_count Count of syncs - * @param pdelay_count Count of pdelays - * @param port_state Port's state - * @param asCapable asCapable flag - * - * @return TRUE - */ - virtual bool update( - int64_t ml_phoffset, - int64_t ls_phoffset, - FrequencyRatio ml_freqoffset, - FrequencyRatio ls_freqoffset, - uint64_t local_time, - uint32_t sync_count, - uint32_t pdelay_count, - PortState port_state, - bool asCapable ); - - /** - * @brief Updates grandmaster IPC values - * - * @param gptp_grandmaster_id Current grandmaster id (all 0's if no grandmaster selected) - * @param gptp_domain_number gPTP domain number - * - * @return TRUE - */ - virtual bool update_grandmaster( - uint8_t gptp_grandmaster_id[], - uint8_t gptp_domain_number ); - - /** - * @brief Updates network interface IPC values - * - * @param clock_identity The clock identity of the interface - * @param priority1 The priority1 field of the grandmaster functionality of the interface, or 0xFF if not supported - * @param clock_class The clockClass field of the grandmaster functionality of the interface, or 0xFF if not supported - * @param offset_scaled_log_variance The offsetScaledLogVariance field of the grandmaster functionality of the interface, or 0x0000 if not supported - * @param clock_accuracy The clockAccuracy field of the grandmaster functionality of the interface, or 0xFF if not supported - * @param priority2 The priority2 field of the grandmaster functionality of the interface, or 0xFF if not supported - * @param domain_number The domainNumber field of the grandmaster functionality of the interface, or 0 if not supported - * @param log_sync_interval The currentLogSyncInterval field of the grandmaster functionality of the interface, or 0 if not supported - * @param log_announce_interval The currentLogAnnounceInterval field of the grandmaster functionality of the interface, or 0 if not supported - * @param log_pdelay_interval The currentLogPDelayReqInterval field of the grandmaster functionality of the interface, or 0 if not supported - * @param port_number The portNumber field of the interface, or 0x0000 if not supported - * - * @return TRUE - */ - virtual bool update_network_interface( - uint8_t clock_identity[], - uint8_t priority1, - uint8_t clock_class, - int16_t offset_scaled_log_variance, - uint8_t clock_accuracy, - uint8_t priority2, - uint8_t domain_number, - int8_t log_sync_interval, - int8_t log_announce_interval, - int8_t log_pdelay_interval, - uint16_t port_number ); - - /** - * @brief unmaps and unlink shared memory - * @return void - */ - void stop(); -}; - - -#endif/*LINUX_HAL_COMMON_HPP*/ diff --git a/daemons/gptp/linux/src/linux_hal_generic.cpp b/daemons/gptp/linux/src/linux_hal_generic.cpp deleted file mode 100644 index 2a462696..00000000 --- a/daemons/gptp/linux/src/linux_hal_generic.cpp +++ /dev/null @@ -1,588 +0,0 @@ -/****************************************************************************** - - Copyright (c) 2009-2012, Intel Corporation - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. Neither the name of the Intel Corporation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - -******************************************************************************/ -#include <linux_hal_generic.hpp> -#include <linux_hal_generic_tsprivate.hpp> -#include <platform.hpp> -#include <avbts_message.hpp> -#include <gptp_cfg.hpp> - -#include <sys/select.h> -#include <sys/socket.h> -#include <netpacket/packet.h> -#include <errno.h> -#include <linux/ethtool.h> -#include <net/if.h> -#include <linux/sockios.h> -#include <sys/ioctl.h> -#include <unistd.h> -#include <fcntl.h> -#include <linux/net_tstamp.h> -#include <linux/ptp_clock.h> -#include <syscall.h> -#include <limits.h> - -#define TX_PHY_TIME 184 -#define RX_PHY_TIME 382 - -net_result LinuxNetworkInterface::nrecv -( LinkLayerAddress *addr, uint8_t *payload, size_t &length ) -{ - fd_set readfds; - int err; - struct msghdr msg; - struct cmsghdr *cmsg; - struct { - struct cmsghdr cm; - char control[256]; - } control; - struct sockaddr_ll remote; - struct iovec sgentry; - net_result ret = net_succeed; - bool got_net_lock; - - LinuxTimestamperGeneric *gtimestamper; - - struct timeval timeout = { 0, 16000 }; // 16 ms - - if( !net_lock.lock( &got_net_lock )) { - GPTP_LOG_ERROR("A Failed to lock mutex"); - return net_fatal; - } - if( !got_net_lock ) { - return net_trfail; - } - - FD_ZERO( &readfds ); - FD_SET( sd_event, &readfds ); - - err = select( sd_event+1, &readfds, NULL, NULL, &timeout ); - if( err == 0 ) { - ret = net_trfail; - goto done; - } else if( err == -1 ) { - if( err == EINTR ) { - // Caught signal - GPTP_LOG_ERROR("select() recv signal"); - ret = net_trfail; - goto done; - } else { - GPTP_LOG_ERROR("select() failed"); - ret = net_fatal; - goto done; - } - } else if( !FD_ISSET( sd_event, &readfds )) { - ret = net_trfail; - goto done; - } - - memset( &msg, 0, sizeof( msg )); - - msg.msg_iov = &sgentry; - msg.msg_iovlen = 1; - - sgentry.iov_base = payload; - sgentry.iov_len = length; - - memset( &remote, 0, sizeof(remote)); - msg.msg_name = (caddr_t) &remote; - msg.msg_namelen = sizeof( remote ); - msg.msg_control = &control; - msg.msg_controllen = sizeof(control); - - err = recvmsg( sd_event, &msg, 0 ); - if( err < 0 ) { - if( errno == ENOMSG ) { - GPTP_LOG_ERROR("Got ENOMSG: %s:%d", __FILE__, __LINE__); - ret = net_trfail; - goto done; - } - GPTP_LOG_ERROR("recvmsg() failed: %s", strerror(errno)); - ret = net_fatal; - goto done; - } - *addr = LinkLayerAddress( remote.sll_addr ); - - gtimestamper = dynamic_cast<LinuxTimestamperGeneric *>(timestamper); - if( err > 0 && !(payload[0] & 0x8) && gtimestamper != NULL ) { - /* Retrieve the timestamp */ - cmsg = CMSG_FIRSTHDR(&msg); - while( cmsg != NULL ) { - if - ( cmsg->cmsg_level == SOL_SOCKET && - cmsg->cmsg_type == SO_TIMESTAMPING ) { - struct timespec *ts_device, *ts_system; - Timestamp device, system; - ts_system = ((struct timespec *) CMSG_DATA(cmsg)) + 1; - system = tsToTimestamp( ts_system ); - ts_device = ts_system + 1; device = tsToTimestamp( ts_device ); - gtimestamper->pushRXTimestamp( &device ); - break; - } - cmsg = CMSG_NXTHDR(&msg,cmsg); - } - } - - length = err; - - done: - if( !net_lock.unlock()) { - GPTP_LOG_ERROR("A Failed to unlock, %d", err); - return net_fatal; - } - - return ret; -} - -int findPhcIndex( InterfaceLabel *iface_label ) { - int sd; - InterfaceName *ifname; - struct ethtool_ts_info info; - struct ifreq ifr; - - if(( ifname = dynamic_cast<InterfaceName *>(iface_label)) == NULL ) { - GPTP_LOG_ERROR("findPTPIndex requires InterfaceName"); - return -1; - } - - sd = socket( AF_UNIX, SOCK_DGRAM, 0 ); - if( sd < 0 ) { - GPTP_LOG_ERROR("findPTPIndex: failed to open socket"); - return -1; - } - - memset( &ifr, 0, sizeof(ifr)); - memset( &info, 0, sizeof(info)); - info.cmd = ETHTOOL_GET_TS_INFO; - ifname->toString( ifr.ifr_name, IFNAMSIZ-1 ); - ifr.ifr_data = (char *) &info; - - if( ioctl( sd, SIOCETHTOOL, &ifr ) < 0 ) { - GPTP_LOG_ERROR("findPTPIndex: ioctl(SIOETHTOOL) failed"); - return -1; - } - - close(sd); - - return info.phc_index; -} - -LinuxTimestamperGeneric::clock_map_t -LinuxTimestamperGeneric::system_clock_map[] = -{ - { CLOCK_REALTIME, "Realtime" }, - { CLOCK_MONOTONIC_RAW, "MonotonicRaw" } -}; - -LinuxTimestamperGeneric::~LinuxTimestamperGeneric() { - if( _private != NULL ) delete _private; -#ifdef WITH_IGBLIB - if( igb_private != NULL ) delete igb_private; -#endif -} - -LinuxTimestamperGeneric::LinuxTimestamperGeneric() { - _private = NULL; -#ifdef WITH_IGBLIB - igb_private = NULL; -#endif - sd = -1; - system_clockid = CLOCK_REALTIME; -} - -const char *LinuxTimestamperGeneric::getClockNameFromId( clockid_t clockid ) - const -{ - unsigned i; - - for( i = 0; i < sizeof(system_clock_map)/sizeof(system_clock_map[0]); - ++i ) - { - if( system_clock_map[i].clockid == clockid ) - return system_clock_map[i].clock_name; - } - - return NULL; -} - -bool LinuxTimestamperGeneric::Adjust( void *tmx ) const { - if( syscall(__NR_clock_adjtime, _private->clockid, tmx ) != 0 ) { - GPTP_LOG_ERROR("Failed to adjust PTP clock rate"); - return false; - } - return true; -} - -bool LinuxTimestamperGeneric::HWTimestamper_init -( InterfaceLabel *iface_label, OSNetworkInterface *iface ) { - cross_stamp_good = false; - int phc_index; - char ptp_device[] = PTP_DEVICE; -#ifdef PTP_HW_CROSSTSTAMP - struct ptp_clock_caps ptp_capability; -#endif - _private = new LinuxTimestamperGenericPrivate; - - pthread_mutex_init( &_private->cross_stamp_lock, NULL ); - - // Determine the correct PTP clock interface - phc_index = findPhcIndex( iface_label ); - if( phc_index < 0 ) { - GPTP_LOG_ERROR("Failed to find PTP device index"); - return false; - } - - snprintf - ( ptp_device+PTP_DEVICE_IDX_OFFS, - sizeof(ptp_device)-PTP_DEVICE_IDX_OFFS, "%d", phc_index ); - GPTP_LOG_ERROR("Using clock device: %s", ptp_device); - phc_fd = open( ptp_device, O_RDWR ); - if( phc_fd == -1 || (_private->clockid = FD_TO_CLOCKID(phc_fd)) == -1 ) { - GPTP_LOG_ERROR("Failed to open PTP clock device"); - return false; - } - -#ifdef PTP_HW_CROSSTSTAMP - // Query PTP stack for availability of HW cross-timestamp - if( ioctl( phc_fd, PTP_CLOCK_GETCAPS, &ptp_capability ) == -1 ) - { - GPTP_LOG_ERROR("Failed to query PTP clock capabilities"); - return false; - } - precise_timestamp_enabled = ptp_capability.cross_timestamping; -#endif - - if( !resetFrequencyAdjustment() ) { - GPTP_LOG_ERROR("Failed to reset (zero) frequency adjustment"); - return false; - } - - if( dynamic_cast<LinuxNetworkInterface *>(iface) != NULL ) { - iface_list.push_front - ( (dynamic_cast<LinuxNetworkInterface *>(iface)) ); - } - - return true; -} - -void LinuxTimestamperGeneric::HWTimestamper_reset() -{ - if( !resetFrequencyAdjustment() ) { - GPTP_LOG_ERROR("Failed to reset (zero) frequency adjustment"); - } -} - -bool LinuxTimestamperGeneric::HWTimestamper_setsystemclock -( const char *system_clock_desc ) -{ - unsigned i; - - if( system_clock_desc == NULL ) - return false; - - for( i = 0; i < sizeof(system_clock_map)/sizeof(system_clock_map[0]); - ++i ) - { - if( strncmp( system_clock_desc, system_clock_map[i].clock_name, - MAX_CLOCK_DESC_LEN ) == 0 ) - { - system_clockid = system_clock_map[i].clockid; - - return true; - } - } - - GPTP_LOG_ERROR - ( "Requested clock type: '%s' not found", system_clock_desc ); - - return false; -} - -int LinuxTimestamperGeneric::HWTimestamper_txtimestamp -( PortIdentity *identity, PTPMessageId messageId, Timestamp ×tamp, - unsigned &clock_value, bool last ) -{ - int err; - int ret = GPTP_EC_EAGAIN; - struct msghdr msg; - struct cmsghdr *cmsg; - struct sockaddr_ll remote; - struct iovec sgentry; - PTPMessageId reflectedMessageId; - uint8_t reflected_bytes[ETHER_HDR_LEN + PTP_COMMON_HDR_LENGTH]; - uint8_t *gptpCommonHeader; - uint16_t sequenceId; - struct { - struct cmsghdr cm; - char control[256]; - } control; - - if( sd == -1 ) return -1; - memset( &msg, 0, sizeof( msg )); - - msg.msg_iov = &sgentry; - msg.msg_iovlen = 1; - - sgentry.iov_base = reflected_bytes; - sgentry.iov_len = sizeof(reflected_bytes); - - gptpCommonHeader = reflected_bytes + ETHER_HDR_LEN; - - memset( &remote, 0, sizeof(remote)); - msg.msg_name = (caddr_t) &remote; - msg.msg_namelen = sizeof( remote ); - msg.msg_control = &control; - msg.msg_controllen = sizeof(control); - - err = recvmsg( sd, &msg, MSG_ERRQUEUE ); - if( err == -1 ) { - if( errno == EAGAIN ) { - ret = GPTP_EC_EAGAIN; - goto done; - } - else { - ret = GPTP_EC_FAILURE; - goto done; - } - } - sequenceId = PLAT_ntohs(*((uint16_t*)(PTP_COMMON_HDR_SEQUENCE_ID(gptpCommonHeader)))); - reflectedMessageId.setSequenceId(sequenceId); - reflectedMessageId.setMessageType((MessageType)(*PTP_COMMON_HDR_TRANSSPEC_MSGTYPE(gptpCommonHeader) & 0xF)); - if (messageId != reflectedMessageId) { - GPTP_LOG_WARNING("Timestamp discarded due to wrong message id"); - ret = GPTP_EC_EAGAIN; - goto done; - } - - // Retrieve the timestamp - cmsg = CMSG_FIRSTHDR(&msg); - while( cmsg != NULL ) { - if( cmsg->cmsg_level == SOL_SOCKET && - cmsg->cmsg_type == SO_TIMESTAMPING ) { - struct timespec *ts_device, *ts_system; - Timestamp device, system; - ts_system = ((struct timespec *) CMSG_DATA(cmsg)) + 1; - system = tsToTimestamp( ts_system ); - ts_device = ts_system + 1; device = tsToTimestamp( ts_device ); - system._version = version; - device._version = version; - timestamp = device; - ret = 0; - break; - } - cmsg = CMSG_NXTHDR(&msg,cmsg); - } - - if( ret != 0 ) { - GPTP_LOG_ERROR("Received a error message, but didn't find a valid timestamp"); - } - - done: - if( ret == 0 || last ) { - net_lock->unlock(); - } - - return ret; -} - -bool LinuxTimestamperGeneric::post_init( int ifindex, int sd, TicketingLock *lock ) { - int timestamp_flags = 0; - struct ifreq device; - struct hwtstamp_config hwconfig; - int err; - - this->sd = sd; - this->net_lock = lock; - - memset( &device, 0, sizeof(device)); - device.ifr_ifindex = ifindex; - err = ioctl( sd, SIOCGIFNAME, &device ); - if( err == -1 ) { - GPTP_LOG_ERROR - ("Failed to get interface name: %s", strerror(errno)); - return false; - } - - device.ifr_data = (char *) &hwconfig; - memset( &hwconfig, 0, sizeof( hwconfig )); - hwconfig.rx_filter = HWTSTAMP_FILTER_PTP_V2_EVENT; - hwconfig.tx_type = HWTSTAMP_TX_ON; - err = ioctl( sd, SIOCSHWTSTAMP, &device ); - if( err == -1 ) { - GPTP_LOG_ERROR - ("Failed to configure timestamping: %s", strerror(errno)); - return false; - } - - timestamp_flags |= SOF_TIMESTAMPING_TX_HARDWARE; - timestamp_flags |= SOF_TIMESTAMPING_RX_HARDWARE; - timestamp_flags |= SOF_TIMESTAMPING_SYS_HARDWARE; - timestamp_flags |= SOF_TIMESTAMPING_RAW_HARDWARE; - err = setsockopt - ( sd, SOL_SOCKET, SO_TIMESTAMPING, ×tamp_flags, - sizeof(timestamp_flags) ); - if( err == -1 ) { - GPTP_LOG_ERROR - ("Failed to configure timestamping on socket: %s", - strerror(errno)); - return false; - } - - return true; -} - -#define MAX_NSEC 1000000000 - -/* Return *a - *b */ -static inline ptp_clock_time pct_diff -( struct ptp_clock_time *a, struct ptp_clock_time *b ) { - ptp_clock_time result; - if( a->nsec >= b->nsec ) { - result.nsec = a->nsec - b->nsec; - } else { - --a->sec; - result.nsec = (MAX_NSEC - b->nsec) + a->nsec; - } - result.sec = a->sec - b->sec; - - return result; -} - -static inline int64_t pctns(struct ptp_clock_time t) -{ - return t.sec * 1000000000LL + t.nsec; -} - -static inline Timestamp pctTimestamp( struct ptp_clock_time *t ) { - Timestamp result; - - result.seconds_ls = t->sec & 0xFFFFFFFF; - result.seconds_ms = t->sec >> sizeof(result.seconds_ls)*8; - result.nanoseconds = t->nsec; - - return result; -} - -// Use HW cross-timestamp if available -bool LinuxTimestamperGeneric::HWTimestamper_gettime -( Timestamp *system_time, Timestamp *device_time, uint32_t *local_clock, - uint32_t *nominal_clock_rate ) const -{ - if( phc_fd == -1 ) - return false; - -#ifdef PTP_HW_CROSSTSTAMP - if( precise_timestamp_enabled ) - { - struct ptp_sys_offset_precise offset; - memset( &offset, 0, sizeof(offset)); - if( ioctl( phc_fd, PTP_SYS_OFFSET_PRECISE, &offset ) != 0 ) - { - GPTP_LOG_ERROR( "Read PHC Crosstime IOCTL failed" ); - - return false; - } - - *device_time = pctTimestamp( &offset.device ); - - if( system_clockid == CLOCK_REALTIME ) - *system_time = pctTimestamp( &offset.sys_realtime ); - else if( system_clockid == CLOCK_MONOTONIC_RAW ) - *system_time = pctTimestamp( &offset.sys_monoraw ); - - else - { - const char * clock_name = - getClockNameFromId( system_clockid ); - GPTP_LOG_ERROR( - "Requested clock type: '%s' not supported", - clock_name != NULL ? clock_name : "Unknown" - ); - - return false; - } - - return true; - } -#endif - - { - unsigned i; - struct ptp_clock_time *pct; - struct ptp_clock_time *system_time_l = NULL, *device_time_l = NULL; - int64_t interval = LLONG_MAX; - struct ptp_sys_offset offset; - - memset( &offset, 0, sizeof(offset)); - offset.n_samples = PTP_MAX_SAMPLES; - if( ioctl( phc_fd, PTP_SYS_OFFSET, &offset ) == -1 ) - { - GPTP_LOG_ERROR( "Read PHC Crosstime IOCTL failed" ); - - return false; - } - - pct = &offset.ts[0]; - for( i = 0; i < offset.n_samples; ++i ) { - int64_t interval_t; - interval_t = pctns(pct_diff( pct+2*i+2, pct+2*i )); - if( interval_t < interval ) { - system_time_l = pct+2*i; - device_time_l = pct+2*i+1; - interval = interval_t; - } - } - - if( !device_time_l || !system_time_l ) - { - GPTP_LOG_ERROR( "PHC Crosstime result is empty" ); - - return false; - } - - *device_time = pctTimestamp( device_time_l ); - - if( system_clockid == CLOCK_REALTIME ) - *system_time = pctTimestamp( system_time_l ); - else - { - const char *clock_name = - getClockNameFromId( system_clockid ); - GPTP_LOG_ERROR( - "Requested clock type: '%s' not supported", - clock_name != NULL ? clock_name : "Unknown" - ); - } - } - - return true; -} diff --git a/daemons/gptp/linux/src/linux_hal_generic.hpp b/daemons/gptp/linux/src/linux_hal_generic.hpp deleted file mode 100644 index 76b09015..00000000 --- a/daemons/gptp/linux/src/linux_hal_generic.hpp +++ /dev/null @@ -1,217 +0,0 @@ -/****************************************************************************** - - Copyright (c) 2012, Intel Corporation - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. Neither the name of the Intel Corporation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - -******************************************************************************/ - -#ifndef LINUX_HAL_GENERIC_HPP -#define LINUX_HAL_GENERIC_HPP - -#include <linux_hal_common.hpp> - -/**@file*/ - -struct LinuxTimestamperGenericPrivate; -/** - * @brief Provides LinuxTimestamperGeneric a private type - */ -typedef struct LinuxTimestamperGenericPrivate * LinuxTimestamperGenericPrivate_t; - -#ifdef WITH_IGBLIB -struct LinuxTimestamperIGBPrivate; -typedef struct LinuxTimestamperIGBPrivate * LinuxTimestamperIGBPrivate_t; -#endif - -/** - * @brief Linux timestamper generic interface - */ -class LinuxTimestamperGeneric : public LinuxTimestamper { -private: - int sd; - int phc_fd; - Timestamp crstamp_system; - Timestamp crstamp_device; - LinuxTimestamperGenericPrivate_t _private; - bool cross_stamp_good; - std::list<Timestamp> rxTimestampList; - LinuxNetworkInterfaceList iface_list; -#ifdef PTP_HW_CROSSTSTAMP - bool precise_timestamp_enabled; -#endif - - TicketingLock *net_lock; - clockid_t system_clockid; - -#ifdef WITH_IGBLIB - LinuxTimestamperIGBPrivate_t igb_private; -#endif - - struct clock_map_t - { - clockid_t clockid; - const char *clock_name; - }; - - static clock_map_t system_clock_map[]; - - const char *getClockNameFromId( clockid_t clockid ) const; - -public: - /** - * @brief Default constructor. Initializes internal variables - */ - LinuxTimestamperGeneric(); - - /** - * @brief Resets frequency adjustment value to zero and calls - * linux system calls for frequency adjustment. - * @return TRUE if success, FALSE if error. - */ - bool resetFrequencyAdjustment(); - - /** - * @brief Calls linux system call for adjusting frequency or phase. - * @param tmx [in] Void pointer that must be cast (and filled in correctly) to - * the struct timex - * @return TRUE if ok, FALSE if error. - */ - bool Adjust( void *tmx ) const; - - /** - * @brief Initializes the Hardware timestamp interface - * @param iface_label [in] Network interface label (used to find the phc index) - * @param iface [in] Network interface - * @return FALSE in case of error, TRUE if success. - */ - virtual bool HWTimestamper_init - ( InterfaceLabel *iface_label, OSNetworkInterface *iface ); - - /** - * @brief Reset the Hardware timestamp interface - * @return void - */ - virtual void HWTimestamper_reset(); - - virtual bool HWTimestamper_setsystemclock - ( const char *system_clock_desc ); - - /** - * @brief Inserts a new timestamp to the beginning of the - * RX timestamp list. - * @param tstamp [in] RX timestamp - * @return void - */ - void pushRXTimestamp( Timestamp *tstamp ) { - tstamp->_version = version; - rxTimestampList.push_front(*tstamp); - } - - /** - * @brief Post initialization procedure. - * @param ifindex struct ifreq.ifr_ifindex value - * @param sd Socket file descriptor - * @param lock [in] Instance of TicketingLock object - * @return TRUE if ok. FALSE if error. - */ - bool post_init( int ifindex, int sd, TicketingLock *lock ); - - /** - * @brief Gets the ptp clock time information - * @param system_time [out] System time - * @param device_time [out] Device time - * @param local_clock Not Used - * @param nominal_clock_rate Not Used - * @return TRUE if got the time successfully, FALSE otherwise - */ - virtual bool HWTimestamper_gettime - ( Timestamp *system_time, Timestamp *device_time, - uint32_t *local_clock, uint32_t *nominal_clock_rate ) const; - - /** - * @brief Gets the TX timestamp from hardware interface - * @param identity PTP port identity - * @param PTPMessageId Message ID - * @param timestamp [out] Timestamp value - * @param clock_value [out] Clock value - * @param last Signalizes that it is the last timestamp to get. When TRUE, releases the lock when its done. - * @return GPTP_EC_SUCCESS if no error, GPTP_EC_FAILURE if error and GPTP_EC_EAGAIN to try again. - */ - virtual int HWTimestamper_txtimestamp - ( PortIdentity *identity, PTPMessageId messageId, Timestamp ×tamp, - unsigned &clock_value, bool last ); - - /** - * @brief Gets the RX timestamp from the hardware interface. This - * Currently the RX timestamp is retrieved at LinuxNetworkInterface::nrecv method. - * @param identity PTP port identity - * @param PTPMessageId Message ID - * @param timestamp [out] Timestamp value - * @param clock_value [out] Clock value - * @param last Signalizes that it is the last timestamp to get. When TRUE, releases the lock when its done. - * @return GPTP_EC_SUCCESS if no error, GPTP_EC_FAILURE if error and GPTP_EC_EAGAIN to try again. - */ - virtual int HWTimestamper_rxtimestamp - ( PortIdentity *identity, PTPMessageId messageId, Timestamp ×tamp, - unsigned &clock_value, bool last ) { - /* This shouldn't happen. Ever. */ - if( rxTimestampList.empty() ) return GPTP_EC_EAGAIN; - timestamp = rxTimestampList.back(); - rxTimestampList.pop_back(); - - return GPTP_EC_SUCCESS; - } - - /** - * @brief Adjusts the clock phase - * @param phase_adjust Phase adjustment - * @return TRUE if success, FALSE if error. - */ - virtual bool HWTimestamper_adjclockphase( int64_t phase_adjust ); - - /** - * @brief Adjusts the frequency - * @param freq_offset Frequency adjustment - * @return TRUE in case of sucess, FALSE if error. - */ - virtual bool HWTimestamper_adjclockrate( float freq_offset ) const; - -#ifdef WITH_IGBLIB - bool HWTimestamper_PPS_start( ); - bool HWTimestamper_PPS_stop(); -#endif - - /** - * @brief deletes LinuxTimestamperGeneric object - */ - virtual ~LinuxTimestamperGeneric(); -}; - - -#endif/*LINUX_HAL_GENERIC_HPP*/ diff --git a/daemons/gptp/linux/src/linux_hal_generic_adj.cpp b/daemons/gptp/linux/src/linux_hal_generic_adj.cpp deleted file mode 100644 index 7f1d59c8..00000000 --- a/daemons/gptp/linux/src/linux_hal_generic_adj.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/****************************************************************************** - - Copyright (c) 2009-2012, Intel Corporation - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. Neither the name of the Intel Corporation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - -******************************************************************************/ - -#include <sys/timex.h> -#define ADJ_SETOFFSET 0x0100 // Missing from older header files -#include <linux_hal_generic.hpp> -#include <syscall.h> -#include <math.h> - -bool LinuxTimestamperGeneric::resetFrequencyAdjustment() { - struct timex tx; - tx.modes = ADJ_FREQUENCY; - tx.freq = 0; - - return Adjust(&tx); -} - -bool LinuxTimestamperGeneric::HWTimestamper_adjclockphase( int64_t phase_adjust ) { - struct timex tx; - LinuxNetworkInterfaceList::iterator iface_iter; - bool ret = true; - LinuxTimerFactory factory; - OSTimer *timer = factory.createTimer(); - - /* Walk list of interfaces disabling them all */ - iface_iter = iface_list.begin(); - for - ( iface_iter = iface_list.begin(); iface_iter != iface_list.end(); - ++iface_iter ) { - (*iface_iter)->disable_rx_queue(); - } - - rxTimestampList.clear(); - - /* Wait 180 ms - This is plenty of time for any time sync frames - to clear the queue */ - timer->sleep(180000); - - ++version; - - tx.modes = ADJ_SETOFFSET | ADJ_NANO; - if( phase_adjust >= 0 ) { - tx.time.tv_sec = phase_adjust / 1000000000LL; - tx.time.tv_usec = phase_adjust % 1000000000LL; - } else { - tx.time.tv_sec = (phase_adjust / 1000000000LL)-1; - tx.time.tv_usec = (phase_adjust % 1000000000LL)+1000000000; - } - - if( !Adjust( &tx )) { - ret = false; - } - - // Walk list of interfaces re-enabling them - iface_iter = iface_list.begin(); - for( iface_iter = iface_list.begin(); iface_iter != iface_list.end(); - ++iface_iter ) { - (*iface_iter)->clear_reenable_rx_queue(); - } - - delete timer; - return ret; -} - -bool LinuxTimestamperGeneric::HWTimestamper_adjclockrate( float freq_offset ) const { - struct timex tx; - tx.modes = ADJ_FREQUENCY; - tx.freq = long(freq_offset) << 16; - tx.freq += long(fmodf( freq_offset, 1.0 )*65536.0); - - return Adjust(&tx); -} diff --git a/daemons/gptp/linux/src/linux_hal_generic_tsprivate.hpp b/daemons/gptp/linux/src/linux_hal_generic_tsprivate.hpp deleted file mode 100644 index a43e1c37..00000000 --- a/daemons/gptp/linux/src/linux_hal_generic_tsprivate.hpp +++ /dev/null @@ -1,61 +0,0 @@ -/****************************************************************************** - - Copyright (c) 2012 Intel Corporation - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. Neither the name of the Intel Corporation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - -******************************************************************************/ - -#ifndef LINUX_HAL_TSPRIVATE -#define LINUX_HAL_TSPRIVATE - -/**@file*/ - -#include <pthread.h> -#ifdef WITH_IGBLIB -extern "C" { -#include <igb.h> -} -/** - * @brief Private IGB structure. - */ -struct LinuxTimestamperIGBPrivate { - device_t igb_dev; - bool igb_initd; -}; -#endif - -/** - * @brief Provides private members for the LinuxTimestamperGeneric class - */ -struct LinuxTimestamperGenericPrivate { - pthread_mutex_t cross_stamp_lock; /*!< Cross timestamp lock*/ - clockid_t clockid; /*!< Clock ID */ -}; - -#endif/*LINUX_HAL_TSPRIVATE*/ diff --git a/daemons/gptp/linux/src/linux_hal_i210.cpp b/daemons/gptp/linux/src/linux_hal_i210.cpp deleted file mode 100644 index 117a590a..00000000 --- a/daemons/gptp/linux/src/linux_hal_i210.cpp +++ /dev/null @@ -1,162 +0,0 @@ -/****************************************************************************** - - Copyright (c) 2012, Intel Corporation - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. Neither the name of the Intel Corporation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - -******************************************************************************/ - -#include <linux_hal_generic.hpp> -#include <linux_hal_generic_tsprivate.hpp> -#include <errno.h> - -extern "C" { -#include <pci/pci.h> -#include <igb.h> -} - -#define IGB_BIND_NAMESZ 24 - -#define TSSDP 0x003C // Time Sync SDP Configuration Register -#define FREQOUT0 0xB654 -#define TSAUXC 0xB640 -#define IGB_CTRL 0x0000 -#define SYSTIMH 0xB604 -#define TRGTTIML0 0xB644 -#define TRGTTIMH0 0xB648 - - -static int -pci_connect( device_t *igb_dev ) -{ - char devpath[IGB_BIND_NAMESZ]; - struct pci_access *pacc; - struct pci_dev *dev; - int err; - - memset(igb_dev, 0, sizeof(device_t)); - pacc = pci_alloc(); - pci_init(pacc); - pci_scan_bus(pacc); - - for (dev = pacc->devices; dev; dev = dev->next) { - pci_fill_info(dev, PCI_FILL_IDENT | PCI_FILL_BASES | PCI_FILL_CLASS); - igb_dev->pci_vendor_id = dev->vendor_id; - igb_dev->pci_device_id = dev->device_id; - igb_dev->domain = dev->domain; - igb_dev->bus = dev->bus; - igb_dev->dev = dev->dev; - igb_dev->func = dev->func; - snprintf(devpath, IGB_BIND_NAMESZ, "%04x:%02x:%02x.%d", - dev->domain, dev->bus, dev->dev, dev->func); - err = igb_probe(igb_dev); - if (err) { - continue; - } - GPTP_LOG_INFO("attaching to %s", devpath); - err = igb_attach(devpath, igb_dev); - if (err) { - GPTP_LOG_ERROR("attach failed! (%s)", strerror(err)); - continue; - } - /*igb_attach_tx missing here ???*/ - goto out; - } - pci_cleanup(pacc); - return ENXIO; -out: - pci_cleanup(pacc); - return 0; -} - - -bool LinuxTimestamperGeneric::HWTimestamper_PPS_start( ) { - unsigned tssdp; - unsigned freqout; - unsigned ctrl; - unsigned tsauxc; - unsigned trgttimh; - - if( igb_private == NULL ) { - igb_private = new LinuxTimestamperIGBPrivate; - } - - if( pci_connect( &igb_private->igb_dev ) != 0 ) { - return false; - } - - if( igb_init( &igb_private->igb_dev ) != 0 ) { - return false; - } - - igb_private->igb_initd = true; - - igb_lock( &igb_private->igb_dev ); - - // Edges must be second aligned - igb_readreg( &igb_private->igb_dev, SYSTIMH, &trgttimh ); - trgttimh += 2; // First edge in 1-2 seconds - igb_writereg(&igb_private->igb_dev, TRGTTIMH0, trgttimh ); - igb_writereg(&igb_private->igb_dev, TRGTTIML0, 0 ); - - freqout = 500000000; - igb_writereg(&igb_private->igb_dev, FREQOUT0, freqout ); - - igb_readreg(&igb_private->igb_dev, IGB_CTRL, &ctrl ); - ctrl |= 0x400000; // set bit 22 SDP0 enabling output - igb_writereg(&igb_private->igb_dev, IGB_CTRL, ctrl ); - - igb_readreg(&igb_private->igb_dev, TSSDP, &tssdp); - tssdp &= ~0x40; // Set SDP0 output to freq clock 0 - tssdp |= 0x80; - igb_writereg(&igb_private->igb_dev, TSSDP, tssdp); - - igb_readreg(&igb_private->igb_dev, TSSDP, &tssdp); - tssdp |= 0x100; // set bit 8 -> SDP0 Time Sync Output - igb_writereg(&igb_private->igb_dev, TSSDP, tssdp); - - igb_readreg( &igb_private->igb_dev, TSAUXC, &tsauxc ); - tsauxc |= 0x14; - igb_writereg( &igb_private->igb_dev, TSAUXC, tsauxc ); - - igb_unlock( &igb_private->igb_dev ); - - return true; -} - -bool LinuxTimestamperGeneric::HWTimestamper_PPS_stop() { - unsigned tsauxc; - - if( !igb_private->igb_initd ) return false; - - igb_readreg( &igb_private->igb_dev, TSAUXC, &tsauxc ); - tsauxc &= ~0x14; // set bit 4 and bit 2 -> AUXC ST0 and EN_CLK0 - igb_writereg( &igb_private->igb_dev, TSAUXC, tsauxc ); - - return true; -} diff --git a/daemons/gptp/linux/src/linux_hal_intelce.cpp b/daemons/gptp/linux/src/linux_hal_intelce.cpp deleted file mode 100644 index 99c0fe2a..00000000 --- a/daemons/gptp/linux/src/linux_hal_intelce.cpp +++ /dev/null @@ -1,243 +0,0 @@ -/****************************************************************************** - - Copyright (c) 2012, Intel Corporation - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. Neither the name of the Intel Corporation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - -******************************************************************************/ - -#include <linux_hal_intelce.hpp> -#include <avbts_message.hpp> -extern "C" { -#include <ismd_sysclk.h> -#include <ismd_core.h> -} -#include <netpacket/packet.h> -#include <errno.h> -#include <sys/socket.h> -#include <sys/types.h> - -#define NOMINAL_NET_CLOCK_RATE (25)/* MHz */ -#define NET_CLOCK_ADJUST (1000/NOMINAL_NET_CLOCK_RATE) - -#define TX_PHY_TIME 8000 -#define RX_PHY_TIME 8000 - -uint64_t scale_clock( uint64_t count ) { - return count*NET_CLOCK_ADJUST; -} - -int LinuxTimestamperIntelCE::ce_timestamp_common -( PortIdentity *identity, uint16_t sequenceId, Timestamp ×tamp, - unsigned &clock_value, bool tx ) { - uint64_t timestamp_s; - uint16_t captured_sequence; - uint16_t port_no; - PortIdentity captured_id; - ismd_sysclk_msg_t message; - ismd_result_t result; - int ret = GPTP_EC_EAGAIN; - - if( tx ) { - result = ismd_sysclk_get_tx_time( ×tamp_s, &message ); - if( timestamp_s == last_tx_time ) { - result = ISMD_ERROR_NO_DATA_AVAILABLE; - } else { - last_tx_time = timestamp_s; - } - } else { - struct timespec ts; - clock_gettime( CLOCK_REALTIME, &ts ); - result = ismd_sysclk_get_rx_time( ×tamp_s, &message ); - if( timestamp_s == last_rx_time ) { - result = ISMD_ERROR_NO_DATA_AVAILABLE; - } else { - last_rx_time = timestamp_s; - } - } - - if( result == ISMD_ERROR_NO_DATA_AVAILABLE ) { - goto fail; - } else if( result != ISMD_SUCCESS ) { - ret = GPTP_EC_FAILURE; - goto fail; - } - - timestamp_s = scale_clock( timestamp_s ); - - captured_id.setClockIdentity( ClockIdentity(message.msgid) ); - port_no = - PLAT_ntohs(*((uint16_t *)(message.msgid+PTP_CLOCK_IDENTITY_LENGTH))); - captured_id.setPortNumber( &port_no ); - captured_sequence = PLAT_ntohs( *((uint16_t *)message.msgseq )); - - if( captured_sequence != sequenceId || captured_id != *identity ) { - uint16_t cap_port_no; - uint16_t id_port_no; - captured_id.getPortNumber(&cap_port_no); - identity->getPortNumber(&id_port_no); - goto fail; - } - - ret = GPTP_EC_SUCCESS; - - if( tx ) { - timestamp_s += TX_PHY_TIME; - } else { - timestamp_s -= RX_PHY_TIME; - } - - timestamp.set64( timestamp_s ); - timestamp._version = version; - clock_value = (unsigned) timestamp_s; - - fail: - return ret; -} - -int LinuxTimestamperIntelCE::HWTimestamper_txtimestamp -( PortIdentity *identity, PTPMessageId messageId, Timestamp ×tamp, - unsigned &clock_value, bool last ) { - return ce_timestamp_common - ( identity, messageId.getSequenceId(), timestamp, clock_value, true ); -} - -int LinuxTimestamperIntelCE::HWTimestamper_rxtimestamp -( PortIdentity *identity, PTPMessageId messageId, Timestamp ×tamp, - unsigned &clock_value, bool last ) { - return ce_timestamp_common - ( identity, messageId.getSequenceId(), timestamp, clock_value, false ); -} - -bool LinuxTimestamperIntelCE::post_init( int ifindex, int sd, TicketingLock *lock ) { - ismd_sysclk_ptp_filter_config_t filter_config; - filter_config.tx_filter_enable = true; - filter_config.rx_filter_enable = true; - filter_config.compare_ptp_ver = true; - filter_config.ip_l2 = false; - filter_config.ptp_version = GPTP_VERSION; - filter_config.ether_type = PTP_ETHERTYPE; - filter_config.da_hash_inclusion = false; - ismd_result_t result; - - result = ismd_sysclk_set_ptp_filter( filter_config ); - if( result != ISMD_SUCCESS ) return false; - - return true; -} -bool LinuxTimestamperIntelCE::HWTimestamper_init -( InterfaceLabel *iface_label, OSNetworkInterface *iface ) { - ismd_result_t result; - - // Allocate clock - result = ismd_clock_alloc_typed - ( ISMD_CLOCK_CLASS_SLAVE, ISMD_CLOCK_DOMAIN_TYPE_AV, &iclock ); - if( result != ISMD_SUCCESS ) return false; - - return true; -} - -bool LinuxTimestamperIntelCE::HWTimestamper_gettime -( Timestamp *system_time, Timestamp *device_time, uint32_t *local_clock, - uint32_t *nominal_clock_rate ) { - uint64_t system_time_s; - uint64_t device_time_s; - - if( ismd_clock_trigger_software_event( iclock ) != ISMD_SUCCESS ) - return false; - - if( ismd_clock_get_last_trigger_correlated_time - ( iclock, &system_time_s, &device_time_s ) != ISMD_SUCCESS ) - return false; - - system_time->set64( system_time_s ); - - device_time_s = scale_clock( device_time_s ); - device_time->set64( device_time_s ); - - return true; -} - - - -net_result LinuxNetworkInterface::nrecv -( LinkLayerAddress *addr, uint8_t *payload, size_t &length ) { - fd_set readfds; - int err; - struct sockaddr_ll remote; - net_result ret = net_succeed; - bool got_net_lock; - - struct timeval timeout = { 0, 16000 }; // 16 ms - - if( !net_lock.lock( &got_net_lock ) || !got_net_lock ) { - GPTP_LOG_ERROR( "A Failed to lock mutex" ); - return net_fatal; - } - - FD_ZERO( &readfds ); - FD_SET( sd_event, &readfds ); - - err = select( sd_event+1, &readfds, NULL, NULL, &timeout ); - if( err == 0 ) { - ret = net_trfail; - goto done; - } else if( err == -1 ) { - if( err == EINTR ) { - // Caught signal - GPTP_LOG_ERROR( "select() recv signal" ); - ret = net_trfail; - goto done; - } else { - GPTP_LOG_ERROR( "select() failed" ); - ret = net_fatal; - goto done; - } - } else if( !FD_ISSET( sd_event, &readfds )) { - ret = net_trfail; - goto done; - } - - err = recv( sd_event, payload, length, 0 ); - if( err < 0 ) { - GPTP_LOG_ERROR( "recvmsg() failed: %s", strerror(errno) ); - ret = net_fatal; - goto done; - } - *addr = LinkLayerAddress( remote.sll_addr ); - - length = err; - - done: - if( !net_lock.unlock()) { - GPTP_LOG_ERROR( "A Failed to unlock, %d", err ); - return net_fatal; - } - - return ret; -} diff --git a/daemons/gptp/linux/src/linux_hal_intelce.hpp b/daemons/gptp/linux/src/linux_hal_intelce.hpp deleted file mode 100644 index f0f57814..00000000 --- a/daemons/gptp/linux/src/linux_hal_intelce.hpp +++ /dev/null @@ -1,127 +0,0 @@ -/****************************************************************************** - - Copyright (c) 2012, Intel Corporation - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. Neither the name of the Intel Corporation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - -******************************************************************************/ - -#ifndef LINUX_HAL_INTELCE_HPP -#define LINUX_HAL_INTELCE_HPP - -#include <linux_hal_common.hpp> -#include <ismd_core.h> - -/**@file*/ - -/** - * @brief Extends the LinuxTimestamper to IntelCE cards - */ -class LinuxTimestamperIntelCE : public LinuxTimestamper { -private: - ismd_clock_t iclock; - uint64_t last_tx_time; - uint64_t last_rx_time; - int ce_timestamp_common - ( PortIdentity *identity, uint16_t sequenceId, Timestamp ×tamp, - unsigned &clock_value, bool tx ); -public: - - /** - * @brief Initializes the hardware timestamp unit. - * @param iface_label [in] Interface label - * @param iface [in] Network interface - * @return TRUE if success, FALSE otherwise - */ - virtual bool HWTimestamper_init - ( InterfaceLabel *iface_label, OSNetworkInterface *iface ); - - /** - * @brief Gets the TX hardware timestamp value - * @param identity Clock Identity - * @param PTPMessageId Message ID - * @param timestamp [out] Reference to the TX timestamps - * @param clock_value [out] 64 bit timestamp value - * @param last Not used - * @return 0 if success. -72 if there is an error in the captured sequence or if there - * is no data available. -1 in case of error when reading data from hardware interface. - */ - virtual int HWTimestamper_txtimestamp - ( PortIdentity *identity, PTPMessageId messageId, Timestamp ×tamp, - unsigned &clock_value, bool last ); - - /** - * @brief Gets the RX hardware timestamp value - * @param identity Clock identity - * @param PTPMessageId Message ID - * @param timestamp [out] Reference to the RX timestamps - * @param clock_value [out] 64 bit timestamp value - * @param last Not used - * @return 0 if success. -72 if there is an error in the captured sequence or if there - * is no data available. -1 in case of error when reading data from hardware interface. - */ - virtual int HWTimestamper_rxtimestamp - ( PortIdentity *identity, PTPMessageId messageId, Timestamp ×tamp, - unsigned &clock_value, bool last ); - - /** - * @brief Post initialization procedure. Configures hardware ptp filter - * @param ifindex Not used - * @param sd Not used - * @param lock Not used - * @return TRUE if success, FALSE otherwise. - */ - bool post_init( int ifindex, int sd, TicketingLock *lock ); - - /** - * @brief Destroys timestamper - */ - virtual ~LinuxTimestamperIntelCE() { - } - - /** - * @brief Default constructor. Initialize some internal variables - */ - LinuxTimestamperIntelCE() { - last_tx_time = 0; - last_rx_time = 0; - } - - /** - * @brief Gets time from hardware interface and stores internally in the object's memory. - * @param system_time Not used - * @param device_time Not used - * @param local_clock Not used - * @param nominal_clock_rate Not used - */ - virtual bool HWTimestamper_gettime - ( Timestamp *system_time, Timestamp *device_time, uint32_t *local_clock, - uint32_t *nominal_clock_rate ); -}; - -#endif/*LINUX_HAL_INTELCE_HPP*/ diff --git a/daemons/gptp/linux/src/linux_hal_persist_file.cpp b/daemons/gptp/linux/src/linux_hal_persist_file.cpp deleted file mode 100644 index 335c44c6..00000000 --- a/daemons/gptp/linux/src/linux_hal_persist_file.cpp +++ /dev/null @@ -1,155 +0,0 @@ -/************************************************************************************************************* -Copyright (c) 2012-2016, Harman International Industries, Incorporated -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LISTED "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS LISTED BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*************************************************************************************************************/ - -#include <stdio.h> -#include <string> -#include <string.h> -#include <stdlib.h> -#include <stdint.h> -#include <ctype.h> -#include <fcntl.h> -#include <sys/mman.h> -#include <errno.h> -#include <sys/stat.h> -#include <unistd.h> - -#include <gptp_log.hpp> -#include "linux_hal_persist_file.hpp" - -class LinuxGPTPPersistFile : public GPTPPersist { -private: - std::string persistIDStr; - gPTPPersistWriteCB_t writeCB; - - int persistFD; - void *restoredata; - off_t storedDataLength; - off_t memoryDataLength; - -public: - LinuxGPTPPersistFile() { - persistFD = -1; - restoredata = ((void *)-1); - storedDataLength = 0; - memoryDataLength = 0; - } - - ~LinuxGPTPPersistFile() {} ; - - bool initStorage(const char *persistID) { - persistIDStr = persistID; - - persistFD = open(persistID, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); - if (persistFD == -1) { - GPTP_LOG_ERROR("Failed to open restore file"); - return false; - } - return true; - } - - bool closeStorage(void) { - if (persistFD != -1) { - if (restoredata != ((void *) -1)) - munmap(restoredata, storedDataLength); - close(persistFD); - } - return true; - } - - bool readStorage(char **bufPtr, uint32_t *bufSize) { - bool result = false; - if (persistFD != -1) { - // MMAP file - struct stat stat0; - if (fstat(persistFD, &stat0) == -1) { - GPTP_LOG_ERROR("Failed to stat restore file, %s", strerror(errno)); - storedDataLength = 0; - } - else { - storedDataLength = stat0.st_size; - if (storedDataLength != 0) { - if ((restoredata = mmap(NULL, storedDataLength, PROT_READ | PROT_WRITE, MAP_SHARED, persistFD, 0)) == ((void *)-1)) { - GPTP_LOG_ERROR("Failed to mmap restore file, %s", strerror(errno)); - } - else { - *bufSize = storedDataLength; - *bufPtr = (char *)restoredata; - result = true; - } - } - } - } - - return result; - } - - void registerWriteCB(gPTPPersistWriteCB_t writeCB) - { - this->writeCB = writeCB; - } - - void setWriteSize(uint32_t dataSize) - { - memoryDataLength = dataSize; - } - - bool triggerWriteStorage(void) - { - if (!writeCB) { - GPTP_LOG_ERROR("Persistent write callback not registered"); - } - - bool result = false; - if (memoryDataLength > storedDataLength) { - int ret = ftruncate(persistFD, memoryDataLength); - if (ret != 0) { - GPTP_LOG_ERROR("Failed to extend stored data length from %ld to %ld, %s", storedDataLength, memoryDataLength, strerror(errno)); - } - if (restoredata != ((void *)-1)) { - restoredata = mremap(restoredata, storedDataLength, memoryDataLength, MREMAP_MAYMOVE); - } - else { - restoredata = mmap(NULL, memoryDataLength, PROT_READ | PROT_WRITE, MAP_SHARED, persistFD, 0); - } - if (restoredata == ((void *)-1)) { - - } - else { - storedDataLength = memoryDataLength; - result = true; - } - } - - writeCB((char *)restoredata, storedDataLength); - return result; - } -}; - - - -GPTPPersist* makeLinuxGPTPPersistFile() { - return new LinuxGPTPPersistFile(); -} - diff --git a/daemons/gptp/linux/src/linux_hal_persist_file.hpp b/daemons/gptp/linux/src/linux_hal_persist_file.hpp deleted file mode 100644 index 4ff1bbdc..00000000 --- a/daemons/gptp/linux/src/linux_hal_persist_file.hpp +++ /dev/null @@ -1,42 +0,0 @@ -/************************************************************************************************************* -Copyright (c) 2012-2016, Harman International Industries, Incorporated -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LISTED "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS LISTED BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*************************************************************************************************************/ - - -#ifndef LINUX_HAL_PERSIST_FILE_HPP -#define LINUX_HAL_PERSIST_FILE_HPP - -#include "avbts_persist.hpp" - - -/**@file*/ - -/** - * @brief Creates an instance of a GPTPPersist - * @return Pointer to the GPTPPersist instance or NULL on failure - */ -GPTPPersist *makeLinuxGPTPPersistFile(); - - -#endif /* LINUX_HAL_PERSIST_FILE_HPP */ diff --git a/daemons/gptp/linux/src/linux_ipc.hpp b/daemons/gptp/linux/src/linux_ipc.hpp deleted file mode 100644 index 624e6bff..00000000 --- a/daemons/gptp/linux/src/linux_ipc.hpp +++ /dev/null @@ -1,43 +0,0 @@ -/****************************************************************************** - - Copyright (c) 2009-2012, Intel Corporation - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. Neither the name of the Intel Corporation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - ******************************************************************************/ - -#ifndef LINUXIPC_HPP -#define LINUXIPC_HPP - -#include "ipcdef.hpp" - -#define SHM_SIZE (sizeof(gPtpTimeData) + sizeof(pthread_mutex_t)) /*!< Shared memory size*/ -#define SHM_NAME "/ptp" /*!< Shared memory name*/ - - -#endif /*LINUXPIC_HPP*/ diff --git a/daemons/gptp/linux/src/platform.cpp b/daemons/gptp/linux/src/platform.cpp deleted file mode 100644 index 134ec628..00000000 --- a/daemons/gptp/linux/src/platform.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/****************************************************************************** - - Copyright (c) 2012 Intel Corporation - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. Neither the name of the Intel Corporation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - -******************************************************************************/ - -#include <platform.hpp> -#include <arpa/inet.h> -#include <time.h> - -uint16_t PLAT_htons( uint16_t s ) { - return htons( s ); -} -uint32_t PLAT_htonl( uint32_t l ) { - return htonl( l ); -} -uint16_t PLAT_ntohs( uint16_t s ) { - return ntohs( s ); -} -uint32_t PLAT_ntohl( uint32_t l ) { - return ntohl( l ); -} -uint64_t PLAT_htonll(uint64_t x) -{ - return ( (htonl(1) == 1) ? x : ((uint64_t)htonl((x) & 0xFFFFFFFF) << 32) | htonl((x) >> 32) ); -} -uint64_t PLAT_ntohll(uint64_t x) -{ - return( (ntohl(1) == 1) ? x : ((uint64_t)ntohl((x) & 0xFFFFFFFF) << 32) | ntohl((x) >> 32) ); -} -int PLAT_localtime(const time_t * inTime, struct tm * outTm) -{ - if (localtime_r(inTime, outTm)) { - return 0; - } else { - return -1; - } -} diff --git a/daemons/gptp/linux/src/platform.hpp b/daemons/gptp/linux/src/platform.hpp deleted file mode 100644 index 32ad739e..00000000 --- a/daemons/gptp/linux/src/platform.hpp +++ /dev/null @@ -1,108 +0,0 @@ -/****************************************************************************** - - Copyright (c) 2012 Intel Corporation - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. Neither the name of the Intel Corporation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - -******************************************************************************/ - -#ifndef PLATFORM_HPP -#define PLATFORM_HPP - -#include <stdint.h> -#include <time.h> - -/**@file*/ - -#define PLAT_strncpy( dest, src, max ) strncpy( dest, src, max+1 ) /*!< Provides strncpy */ -#define PLAT_snprintf(...) snprintf( __VA_ARGS__ ) /*!< Provides snprintf*/ - -/** - * @brief Converts the unsigned short integer hostshort - * from host byte order to network byte order. - * @param s short host byte order - * @return short value in network order - */ -uint16_t PLAT_htons( uint16_t s ); - -/** - * @brief Converts the unsigned integer hostlong - * from host byte order to network byte order. - * @param l Host long byte order - * @return value in network byte order - */ -uint32_t PLAT_htonl( uint32_t l ); - -/** - * @brief Converts the unsigned short integer netshort - * from network byte order to host byte order. - * @param s Network order short integer - * @return host order value - */ -uint16_t PLAT_ntohs( uint16_t s ); - -/** - * @brief Converts the unsigned integer netlong - * from network byte order to host byte order. - * @param l Long value in network order - * @return Long value on host byte order - */ -uint32_t PLAT_ntohl( uint32_t l ); - -/** - * @brief Converts a 64-bit word from host to network order - * @param x Value to be converted - * @return Converted value - */ -uint64_t PLAT_htonll(uint64_t x); - -/** - * @brief Converts a 64 bit word from network to host order - * @param x Value to be converted - * @return Converted value - */ -uint64_t PLAT_ntohll(uint64_t x); - -#ifndef _LINUX_TIMEX_H -/* - * linux_hal_generic_adj.cpp includes linux/timex.h, which precludes definition - * of time_h, so we can't make this function available there or we will get an - * error about time_t not having a type. - */ - -/** - * @brief Converts a time_t structure into a tm structure - * @param[in] inTime The time_t to be converted - * @param[out] outTm The tm to store the converted value in - * @return An error code - */ -int PLAT_localtime(const time_t * inTime, struct tm * outTm); -#endif - - -#endif diff --git a/daemons/gptp/linux/src/watchdog.cpp b/daemons/gptp/linux/src/watchdog.cpp deleted file mode 100644 index 1406fb55..00000000 --- a/daemons/gptp/linux/src/watchdog.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#include "watchdog.hpp" -#include "avbts_osthread.hpp" -#include "gptp_log.hpp" -#include <systemd/sd-daemon.h> - - -OSThreadExitCode watchdogUpdateThreadFunction(void *arg) -{ - SystemdWatchdogHandler *watchdog = (SystemdWatchdogHandler*) arg; - watchdog->run_update(); - return osthread_ok; -} - - -SystemdWatchdogHandler::SystemdWatchdogHandler() -{ - GPTP_LOG_INFO("Creating Systemd watchdog handler."); - LinuxTimerFactory timer_factory = LinuxTimerFactory(); - timer = timer_factory.createTimer(); -} - -SystemdWatchdogHandler::~SystemdWatchdogHandler() -{ - //Do nothing -} - -long unsigned int -SystemdWatchdogHandler::getSystemdWatchdogInterval(int *result) -{ - long unsigned int watchdog_interval; //in microseconds - *result = sd_watchdog_enabled(0, &watchdog_interval); - return watchdog_interval; -} - -void SystemdWatchdogHandler::run_update() -{ - while(1) - { - GPTP_LOG_DEBUG("NOTIFYING WATCHDOG."); - sd_notify(0, "WATCHDOG=1"); - GPTP_LOG_DEBUG("GOING TO SLEEP %lld", update_interval); - timer->sleep(update_interval); - GPTP_LOG_DEBUG("WATCHDOG WAKE UP"); - } -} - diff --git a/daemons/gptp/linux/src/watchdog.hpp b/daemons/gptp/linux/src/watchdog.hpp deleted file mode 100644 index b2e05ccf..00000000 --- a/daemons/gptp/linux/src/watchdog.hpp +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef SYSTEMDWATCHDOGHANDLER_H -#define SYSTEMDWATCHDOGHANDLER_H -#include <linux_hal_common.hpp> -#include <avbts_ostimer.hpp> - - -OSThreadExitCode watchdogUpdateThreadFunction(void *arg); - -class SystemdWatchdogHandler -{ -public: - long unsigned int update_interval; - long unsigned int getSystemdWatchdogInterval(int *result); - void run_update(); - SystemdWatchdogHandler(); - virtual ~SystemdWatchdogHandler(); -private: - OSTimer *timer; -}; - -#endif // SYSTEMDWATCHDOGHANDLER_H |