ptpd.c 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437
  1. /*
  2. * SPDX-FileCopyrightText: 2020-2024 The Apache Software Foundation
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * SPDX-FileContributor: 2024-2025 Espressif Systems (Shanghai) CO LTD
  7. */
  8. /****************************************************************************
  9. * apps/netutils/ptpd/ptpd.c
  10. *
  11. * Licensed to the Apache Software Foundation (ASF) under one or more
  12. * contributor license agreements. See the NOTICE file distributed with
  13. * this work for additional information regarding copyright ownership. The
  14. * ASF licenses this file to you under the Apache License, Version 2.0 (the
  15. * "License"); you may not use this file except in compliance with the
  16. * License. You may obtain a copy of the License at
  17. *
  18. * http://www.apache.org/licenses/LICENSE-2.0
  19. *
  20. * Unless required by applicable law or agreed to in writing, software
  21. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  22. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  23. * License for the specific language governing permissions and limitations
  24. * under the License.
  25. *
  26. ****************************************************************************/
  27. #define ESP_PTP 1
  28. /****************************************************************************
  29. * Included Files
  30. ****************************************************************************/
  31. #ifndef ESP_PTP
  32. #include <nuttx/config.h>
  33. #endif
  34. #include <stdbool.h>
  35. #include <stdint.h>
  36. #include <sys/socket.h>
  37. #include <sys/time.h>
  38. #include <stdio.h>
  39. #include <stdlib.h>
  40. #include <string.h>
  41. #include <time.h>
  42. #include <sched.h>
  43. #include <assert.h>
  44. #include <errno.h>
  45. #ifndef ESP_PTP
  46. #include <debug.h>
  47. #endif
  48. #include <unistd.h>
  49. #include <fcntl.h>
  50. #include <netinet/in.h>
  51. #include <arpa/inet.h>
  52. #ifndef ESP_PTP
  53. #include <netutils/ipmsfilter.h>
  54. #endif
  55. #include <net/if.h>
  56. #include <sys/ioctl.h>
  57. #include <sys/poll.h>
  58. #ifndef ESP_PTP
  59. #include <nuttx/net/netconfig.h>
  60. #include <netutils/ptpd.h>
  61. #endif
  62. #include "ptpv2.h"
  63. #ifdef ESP_PTP
  64. #include "ptpd.h"
  65. #include "esp_netif.h"
  66. #include "esp_eth_mac_esp.h"
  67. #include "esp_eth_driver.h"
  68. #include "esp_vfs_l2tap.h"
  69. #include "semaphore.h"
  70. #include "esp_log.h"
  71. #include "esp_err.h"
  72. #include "lwip/prot/ethernet.h" // Ethernet headers
  73. #include "esp_eth_time.h"
  74. #define ETH_TYPE_PTP 0x88F7
  75. #define SET_MAC_ADDR(addr, a, b, c, d, e, f) do { \
  76. addr[0] = a; addr[1] = b; addr[2] = c; \
  77. addr[3] = d; addr[4] = e; addr[5] = f; \
  78. } while(0)
  79. #define ERROR ESP_FAIL
  80. #define OK ESP_OK
  81. #define UNUSED (void)
  82. #define MSEC_PER_SEC 1000
  83. #define NSEC_PER_USEC 1000
  84. #define NSEC_PER_MSEC 1000000ll
  85. #define NSEC_PER_SEC 1000000000ll
  86. // To able to set either only server or only client
  87. #ifndef CONFIG_NETUTILS_PTPD_TIMEOUT_MS
  88. #define CONFIG_NETUTILS_PTPD_TIMEOUT_MS 0
  89. #endif
  90. #ifndef CONFIG_NETUTILS_PTPD_SETTIME_THRESHOLD_MS
  91. #define CONFIG_NETUTILS_PTPD_SETTIME_THRESHOLD_MS 0
  92. #endif
  93. #ifndef CONFIG_NETUTILS_PTPD_MAX_PATH_DELAY_NS
  94. #define CONFIG_NETUTILS_PTPD_MAX_PATH_DELAY_NS 0
  95. #endif
  96. #ifndef CONFIG_NETUTILS_PTPD_DELAYREQ_AVGCOUNT
  97. #define CONFIG_NETUTILS_PTPD_DELAYREQ_AVGCOUNT 0
  98. #endif
  99. #ifndef CONFIG_NETUTILS_PTPD_DELAYRESP_INTERVAL
  100. #define CONFIG_NETUTILS_PTPD_DELAYRESP_INTERVAL 0
  101. #endif
  102. #ifndef CONFIG_NETUTILS_PTPD_PATH_DELAY_STABILITY_NS
  103. #define CONFIG_NETUTILS_PTPD_PATH_DELAY_STABILITY_NS 0
  104. #endif
  105. #define clock_timespec_subtract(ts1, ts2, ts3) timespecsub(ts1, ts2, ts3)
  106. #define clock_timespec_add(ts1, ts2, ts3) timespecadd(ts1, ts2, ts3)
  107. #endif // ESP_PTP
  108. /****************************************************************************
  109. * Private Data
  110. ****************************************************************************/
  111. #ifdef ESP_PTP
  112. #define ADJ_FREQ_MAX 512000 // TODO tuneup
  113. typedef struct
  114. {
  115. int32_t kp;
  116. int32_t ki;
  117. int32_t drift_acc;
  118. } pi_cntrl_t;
  119. #endif // ESP_PTP
  120. /* Carrier structure for querying PTPD status */
  121. struct ptpd_statusreq_s
  122. {
  123. FAR sem_t *done;
  124. FAR struct ptpd_status_s *dest;
  125. };
  126. /* Main PTPD state storage */
  127. struct ptp_state_s
  128. {
  129. /* Request for PTPD task to stop or report status */
  130. bool stop;
  131. struct ptpd_statusreq_s status_req;
  132. #ifdef ESP_PTP
  133. uint8_t intf_hw_addr[ETH_ADDR_LEN];
  134. int ptp_socket;
  135. esp_eth_handle_t cached_eth_handle; /* Cached for freq adj calls */
  136. int64_t remote_time_ns_prev;
  137. int64_t local_time_ns_prev;
  138. int64_t last_offset_ns;
  139. pi_cntrl_t offset_pi;
  140. #endif // ESP_PTP
  141. /* Address of network interface we are operating on */
  142. struct sockaddr_in interface_addr;
  143. /* Socket bound to interface for transmission (UDP) */
  144. int tx_socket;
  145. /* Sockets for PTP event and information ports (UDP) */
  146. int event_socket;
  147. int info_socket;
  148. /* Our own identity as a clock source */
  149. struct ptp_announce_s own_identity;
  150. /* Sequence number counters per message type */
  151. uint16_t announce_seq;
  152. uint16_t sync_seq;
  153. uint16_t delay_req_seq;
  154. /* Previous measurement and estimated clock drift rate */
  155. struct timespec last_delta_timestamp;
  156. int64_t last_delta_ns;
  157. int64_t last_adjtime_ns;
  158. long drift_avg_total_ms;
  159. long drift_ppb;
  160. /* Identity of currently selected clock source,
  161. * from the latest announcement message.
  162. *
  163. * The timestamps are used for timeout when a source disappears.
  164. * They are from the local CLOCK_MONOTONIC.
  165. */
  166. bool selected_source_valid; /* True if operating as client */
  167. struct ptp_announce_s selected_source; /* Currently selected server */
  168. struct timespec last_received_multicast; /* Any multicast packet */
  169. struct timespec last_received_announce; /* Announce from any server */
  170. struct timespec last_received_sync; /* Sync from selected source */
  171. /* Last transmitted packet timestamps (CLOCK_MONOTONIC)
  172. * Used to set transmission interval.
  173. */
  174. struct timespec last_transmitted_sync;
  175. struct timespec last_transmitted_announce;
  176. struct timespec last_transmitted_delayresp;
  177. struct timespec last_transmitted_delayreq;
  178. /* Timestamps related to path delay calculation (CLOCK_REALTIME) */
  179. bool can_send_delayreq;
  180. struct timespec delayreq_time;
  181. int path_delay_avgcount;
  182. long path_delay_ns;
  183. long delayreq_interval;
  184. /* Latest received packet and its timestamp (CLOCK_REALTIME) */
  185. struct timespec rxtime;
  186. union
  187. {
  188. struct ptp_header_s header;
  189. struct ptp_announce_s announce;
  190. struct ptp_sync_s sync;
  191. struct ptp_follow_up_s follow_up;
  192. struct ptp_delay_req_s delay_req;
  193. struct ptp_delay_resp_s delay_resp;
  194. uint8_t raw[128];
  195. } rxbuf;
  196. #ifndef ESP_PTP
  197. uint8_t rxcmsg[CMSG_LEN(sizeof(struct timeval))];
  198. #endif // ESP_PTP
  199. /* Buffered sync packet for two-step clock setting where server sends
  200. * the accurate timestamp in a separate follow-up message.
  201. */
  202. struct ptp_sync_s twostep_packet;
  203. struct timespec twostep_rxtime;
  204. };
  205. #ifdef CONFIG_NETUTILS_PTPD_SERVER
  206. # define PTPD_POLL_INTERVAL CONFIG_NETUTILS_PTPD_SYNC_INTERVAL_MSEC
  207. #else
  208. # define PTPD_POLL_INTERVAL CONFIG_NETUTILS_PTPD_TIMEOUT_MS
  209. #endif
  210. /* PTP debug messages are enabled by either CONFIG_DEBUG_NET_INFO
  211. * or separately by CONFIG_NETUTILS_PTPD_DEBUG. This simplifies
  212. * debugging without having excessive amount of logging from net.
  213. */
  214. #ifdef ESP_PTP
  215. static const char *TAG = "ptpd";
  216. #define ptpinfo(format, ...) ESP_LOGI(TAG, format, ##__VA_ARGS__)
  217. #define ptpwarn(format, ...) ESP_LOGW(TAG, format, ##__VA_ARGS__)
  218. #define ptperr(format, ...) ESP_LOGE(TAG, format, ##__VA_ARGS__)
  219. #else
  220. #ifdef CONFIG_NETUTILS_PTPD_DEBUG
  221. # define ptpinfo _info
  222. # define ptpwarn _warn
  223. # define ptperr _err
  224. #else
  225. # define ptpinfo ninfo
  226. # define ptpwarn nwarn
  227. # define ptperr nerr
  228. #endif
  229. #endif // ESP_PTP
  230. #ifdef ESP_PTP
  231. static struct ptp_state_s *s_state;
  232. #endif
  233. /****************************************************************************
  234. * Private Functions
  235. ****************************************************************************/
  236. #ifdef ESP_PTP
  237. static void ptp_create_eth_frame(struct ptp_state_s *state, uint8_t *eth_frame, void *ptp_msg, uint16_t ptp_msg_len)
  238. {
  239. struct eth_hdr eth_hdr = {
  240. //.dest.addr = {0x01, 0x80, 0xC2, 0x00, 0x00, 0x0E}, // TODO only for Pdelay_Req, Pdelay_Resp and Pdelay_Resp_Follow_Up
  241. .dest.addr = {0x01, 0x1B, 0x19, 0x00, 0x00, 0x00}, // All except peer delay messages, ptp4l sends everything at this addr
  242. .type = htons(ETH_TYPE_PTP)
  243. };
  244. memcpy(&eth_hdr.src.addr, state->intf_hw_addr, ETH_ADDR_LEN);
  245. memcpy(eth_frame, &eth_hdr, sizeof(eth_hdr));
  246. memcpy(eth_frame + sizeof(eth_hdr), ptp_msg, ptp_msg_len);
  247. }
  248. static int ptp_net_send(FAR struct ptp_state_s *state, void *ptp_msg, uint16_t ptp_msg_len, struct timespec *ts)
  249. {
  250. uint8_t eth_frame[ptp_msg_len + ETH_HEADER_LEN];
  251. ptp_create_eth_frame(state, eth_frame, ptp_msg, ptp_msg_len);
  252. // wrap "Info Records Buffer" into union to ensure proper alignment of data (this is typically needed when
  253. // accessing double word variables or structs containing double word variables)
  254. union {
  255. uint8_t info_recs_buff[L2TAP_IREC_SPACE(sizeof(struct timespec))];
  256. l2tap_irec_hdr_t align;
  257. } u;
  258. l2tap_extended_buff_t ptp_msg_ext_buff;
  259. ptp_msg_ext_buff.info_recs_len = sizeof(u.info_recs_buff);
  260. ptp_msg_ext_buff.info_recs_buff = u.info_recs_buff;
  261. ptp_msg_ext_buff.buff = eth_frame;
  262. ptp_msg_ext_buff.buff_len = sizeof(eth_frame);
  263. l2tap_irec_hdr_t *ts_info = L2TAP_IREC_FIRST(&ptp_msg_ext_buff);
  264. ts_info->len = L2TAP_IREC_LEN(sizeof(struct timespec));
  265. ts_info->type = L2TAP_IREC_TIME_STAMP;
  266. int ret = write(state->ptp_socket, &ptp_msg_ext_buff, 0);
  267. // check if write was successful, ts exists and ts_info is valid
  268. if (ret > 0 && ts && ts_info->type == L2TAP_IREC_TIME_STAMP)
  269. {
  270. *ts = *(struct timespec *)ts_info->data;
  271. }
  272. return ret;
  273. }
  274. static int ptp_net_recv(FAR struct ptp_state_s *state, void *ptp_msg, uint16_t ptp_msg_len, struct timespec *ts)
  275. {
  276. uint8_t eth_frame[ptp_msg_len + ETH_HEADER_LEN];
  277. // wrap "Info Records Buffer" into union to ensure proper alignment of data (this is typically needed when
  278. // accessing double word variables or structs containing double word variables)
  279. union {
  280. uint8_t info_recs_buff[L2TAP_IREC_SPACE(sizeof(struct timespec))];
  281. l2tap_irec_hdr_t align;
  282. } u;
  283. l2tap_extended_buff_t ptp_msg_ext_buff;
  284. ptp_msg_ext_buff.info_recs_len = sizeof(u.info_recs_buff);
  285. ptp_msg_ext_buff.info_recs_buff = u.info_recs_buff;
  286. ptp_msg_ext_buff.buff = eth_frame;
  287. ptp_msg_ext_buff.buff_len = sizeof(eth_frame);
  288. l2tap_irec_hdr_t *ts_info = L2TAP_IREC_FIRST(&ptp_msg_ext_buff);
  289. ts_info->len = L2TAP_IREC_LEN(sizeof(struct timespec));
  290. ts_info->type = L2TAP_IREC_TIME_STAMP;
  291. int ret = read(state->ptp_socket, &ptp_msg_ext_buff, 0);
  292. // check if read was successful, ts exists and ts_info is valid
  293. if (ret > 0 && ts && ts_info->type == L2TAP_IREC_TIME_STAMP)
  294. {
  295. *ts = *(struct timespec *)ts_info->data;
  296. }
  297. memcpy(ptp_msg, &eth_frame[ETH_HEADER_LEN], ret);
  298. return ret;
  299. }
  300. static int64_t timespec_to_ns(FAR const struct timespec *ts)
  301. {
  302. return ts->tv_sec * NSEC_PER_SEC + (ts->tv_nsec);
  303. }
  304. #endif // ESP_PTP
  305. /* Convert from timespec to PTP format */
  306. static void timespec_to_ptp_format(FAR struct timespec *ts,
  307. FAR uint8_t *timestamp)
  308. {
  309. /* IEEE 1588 uses 48 bits for seconds and 32 bits for nanoseconds,
  310. * both fields big-endian.
  311. */
  312. #ifdef CONFIG_SYSTEM_TIME64
  313. timestamp[0] = (uint8_t)(ts->tv_sec >> 40);
  314. timestamp[1] = (uint8_t)(ts->tv_sec >> 32);
  315. #else
  316. timestamp[0] = 0;
  317. timestamp[1] = 0;
  318. #endif
  319. timestamp[2] = (uint8_t)(ts->tv_sec >> 24);
  320. timestamp[3] = (uint8_t)(ts->tv_sec >> 16);
  321. timestamp[4] = (uint8_t)(ts->tv_sec >> 8);
  322. timestamp[5] = (uint8_t)(ts->tv_sec >> 0);
  323. timestamp[6] = (uint8_t)(ts->tv_nsec >> 24);
  324. timestamp[7] = (uint8_t)(ts->tv_nsec >> 16);
  325. timestamp[8] = (uint8_t)(ts->tv_nsec >> 8);
  326. timestamp[9] = (uint8_t)(ts->tv_nsec >> 0);
  327. }
  328. /* Convert from PTP format to timespec */
  329. static void ptp_format_to_timespec(FAR const uint8_t *timestamp,
  330. FAR struct timespec *ts)
  331. {
  332. ts->tv_sec =
  333. (((int64_t)timestamp[0]) << 40)
  334. | (((int64_t)timestamp[1]) << 32)
  335. | (((int64_t)timestamp[2]) << 24)
  336. | (((int64_t)timestamp[3]) << 16)
  337. | (((int64_t)timestamp[4]) << 8)
  338. | (((int64_t)timestamp[5]) << 0);
  339. ts->tv_nsec =
  340. (((long)timestamp[6]) << 24)
  341. | (((long)timestamp[7]) << 16)
  342. | (((long)timestamp[8]) << 8)
  343. | (((long)timestamp[9]) << 0);
  344. }
  345. /* Returns true if A is a better clock source than B.
  346. * Implements Best Master Clock algorithm from IEEE-1588.
  347. */
  348. static bool is_better_clock(FAR const struct ptp_announce_s *a,
  349. FAR const struct ptp_announce_s *b)
  350. {
  351. if (a->gm_priority1 < b->gm_priority1 /* Main priority field */
  352. || a->gm_quality[0] < b->gm_quality[0] /* Clock class */
  353. || a->gm_quality[1] < b->gm_quality[1] /* Clock accuracy */
  354. || a->gm_quality[2] < b->gm_quality[2] /* Clock variance high byte */
  355. || a->gm_quality[3] < b->gm_quality[3] /* Clock variance low byte */
  356. || a->gm_priority2 < b->gm_priority2 /* Sub priority field */
  357. || memcmp(a->gm_identity, b->gm_identity, sizeof(a->gm_identity)) < 0)
  358. {
  359. return true;
  360. }
  361. else
  362. {
  363. return false;
  364. }
  365. }
  366. static int64_t timespec_to_ms(FAR const struct timespec *ts)
  367. {
  368. return ts->tv_sec * MSEC_PER_SEC + (ts->tv_nsec / NSEC_PER_MSEC);
  369. }
  370. /* Get positive or negative delta between two timespec values.
  371. * If value would exceed int64 limit (292 years), return INT64_MAX/MIN.
  372. */
  373. static int64_t timespec_delta_ns(FAR const struct timespec *ts1,
  374. FAR const struct timespec *ts2)
  375. {
  376. int64_t delta_s;
  377. delta_s = ts1->tv_sec - ts2->tv_sec;
  378. #ifdef CONFIG_SYSTEM_TIME64
  379. /* Conversion to nanoseconds could overflow if the system time is 64-bit */
  380. if (delta_s >= INT64_MAX / NSEC_PER_SEC)
  381. {
  382. return INT64_MAX;
  383. }
  384. else if (delta_s <= INT64_MIN / NSEC_PER_SEC)
  385. {
  386. return INT64_MIN;
  387. }
  388. #endif
  389. return delta_s * NSEC_PER_SEC + (ts1->tv_nsec - ts2->tv_nsec);
  390. }
  391. /* Check if the currently selected source is still valid */
  392. static bool is_selected_source_valid(FAR struct ptp_state_s *state)
  393. {
  394. struct timespec time_now;
  395. struct timespec delta;
  396. if ((state->selected_source.header.messagetype & PTP_MSGTYPE_MASK)
  397. != PTP_MSGTYPE_ANNOUNCE)
  398. {
  399. return false; /* Uninitialized value */
  400. }
  401. /* Note: this uses monotonic clock to track the timeout even when
  402. * system clock is adjusted.
  403. */
  404. clock_gettime(CLOCK_MONOTONIC, &time_now);
  405. clock_timespec_subtract(&time_now, &state->last_received_sync, &delta);
  406. if (timespec_to_ms(&delta) > CONFIG_NETUTILS_PTPD_TIMEOUT_MS)
  407. {
  408. #ifdef ESP_PTP
  409. ESP_LOGD(TAG, "Too long time since received packet\n");
  410. #endif // ESP_PTP
  411. return false; /* Too long time since received packet */
  412. }
  413. return true;
  414. }
  415. /* Increment sequence number for packet type, and copy to header */
  416. static void ptp_increment_sequence(FAR uint16_t *sequence_num,
  417. FAR struct ptp_header_s *hdr)
  418. {
  419. *sequence_num += 1;
  420. hdr->sequenceid[0] = (uint8_t)(*sequence_num >> 8);
  421. hdr->sequenceid[1] = (uint8_t)(*sequence_num);
  422. }
  423. /* Get sequence number from received packet */
  424. static uint16_t ptp_get_sequence(FAR const struct ptp_header_s *hdr)
  425. {
  426. return ((uint16_t)hdr->sequenceid[0] << 8) | hdr->sequenceid[1];
  427. }
  428. /* Get current system timestamp as a timespec
  429. * TODO: Possibly add support for selecting different clock or using
  430. * architecture-specific interface for clock access.
  431. */
  432. static int ptp_gettime(FAR struct ptp_state_s *state,
  433. FAR struct timespec *ts)
  434. {
  435. UNUSED(state);
  436. #ifdef ESP_PTP
  437. return esp_eth_clock_gettime(CLOCK_PTP_SYSTEM, ts);
  438. #else
  439. return clock_gettime(CLOCK_REALTIME, ts);
  440. #endif // ESP_PTP
  441. }
  442. /* Change current system timestamp by jumping */
  443. static int ptp_settime(FAR struct ptp_state_s *state,
  444. FAR struct timespec *ts)
  445. {
  446. UNUSED(state);
  447. #ifdef ESP_PTP
  448. return esp_eth_clock_settime(CLOCK_PTP_SYSTEM, ts);
  449. #else
  450. return clock_settime(CLOCK_REALTIME, ts);
  451. #endif // ESP_PTP
  452. }
  453. #ifndef ESP_PTP
  454. /* Smoothly adjust timestamp. */
  455. static int ptp_adjtime(FAR struct ptp_state_s *state, int64_t delta_ns)
  456. {
  457. struct timeval delta;
  458. delta.tv_sec = delta_ns / NSEC_PER_SEC;
  459. delta_ns -= (int64_t)delta.tv_sec * NSEC_PER_SEC;
  460. delta.tv_usec = delta_ns / NSEC_PER_USEC;
  461. return adjtime(&delta, NULL);
  462. }
  463. #endif // !ESP_PTP
  464. #ifndef ESP_PTP
  465. /* Get timestamp of latest received packet */
  466. static int ptp_getrxtime(FAR struct ptp_state_s *state,
  467. FAR struct msghdr *rxhdr,
  468. FAR struct timespec *ts)
  469. {
  470. /* Get hardware or kernel timestamp if available */
  471. #ifdef CONFIG_NET_TIMESTAMP
  472. struct cmsghdr *cmsg;
  473. for_each_cmsghdr(cmsg, rxhdr)
  474. {
  475. if (cmsg->cmsg_level == SOL_SOCKET &&
  476. cmsg->cmsg_type == SO_TIMESTAMP &&
  477. cmsg->cmsg_len == CMSG_LEN(sizeof(struct timeval)))
  478. {
  479. TIMEVAL_TO_TIMESPEC((FAR struct timeval *)CMSG_DATA(cmsg), ts);
  480. /* Sanity-check the value */
  481. if (ts->tv_sec > 0 || ts->tv_nsec > 0)
  482. {
  483. return OK;
  484. }
  485. }
  486. }
  487. ptpwarn("CONFIG_NET_TIMESTAMP enabled but did not get packet timestamp\n");
  488. #endif
  489. /* Fall back to current timestamp */
  490. return ptp_gettime(state, ts);
  491. }
  492. #endif // !ESP_PTP
  493. /* Initialize PTP client/server state and create sockets */
  494. #ifdef ESP_PTP
  495. static int ptp_initialize_state(FAR struct ptp_state_s *state,
  496. FAR const char *interface)
  497. {
  498. state->ptp_socket = open("/dev/net/tap", 0);
  499. if (state->ptp_socket < 0)
  500. {
  501. ptperr("Failed to create tx socket: %d\n", errno);
  502. return ERROR;
  503. }
  504. // Set Ethernet interface on which to get raw frames
  505. if (ioctl(state->ptp_socket, L2TAP_S_INTF_DEVICE, interface) < 0)
  506. {
  507. ptperr("failed to set network interface at socket: %d\n", errno);
  508. return ERROR;
  509. }
  510. // Set the Ethertype filter (frames with this type will be available through the state->tx_socket)
  511. uint16_t eth_type_filter = ETH_TYPE_PTP;
  512. if (ioctl(state->ptp_socket, L2TAP_S_RCV_FILTER, &eth_type_filter) < 0)
  513. {
  514. ptperr("failed to set Ethertype filter: %d\n", errno);
  515. return ERROR;
  516. }
  517. // Enable time stamping in driver
  518. esp_eth_handle_t eth_handle;
  519. if (ioctl(state->ptp_socket, L2TAP_G_DEVICE_DRV_HNDL, &eth_handle) < 0)
  520. {
  521. ptperr("failed to get socket eth_handle %d\n", errno);
  522. return ERROR;
  523. }
  524. state->cached_eth_handle = eth_handle;
  525. esp_eth_clock_cfg_t clk_cfg = {
  526. .eth_hndl = eth_handle,
  527. };
  528. esp_eth_clock_init(CLOCK_PTP_SYSTEM, &clk_cfg);
  529. // Enable time stamping in L2TAP
  530. if(ioctl(state->ptp_socket, L2TAP_S_TIMESTAMP_EN) < 0)
  531. {
  532. ptperr("failed to enable time stamping in l2 socket: %d\n", errno);
  533. return ERROR;
  534. }
  535. // get HW address
  536. esp_eth_ioctl(eth_handle, ETH_CMD_G_MAC_ADDR, &state->intf_hw_addr);
  537. // Add well-known PTP multicast destination MAC addresses to the filter
  538. uint8_t dest_addr[ETH_ADDR_LEN];
  539. SET_MAC_ADDR(dest_addr, 0x01, 0x1B, 0x19, 0x00, 0x00, 0x00);
  540. esp_eth_ioctl(eth_handle, ETH_CMD_ADD_MAC_FILTER, dest_addr);
  541. SET_MAC_ADDR(dest_addr, 0x01, 0x80, 0xC2, 0x00, 0x00, 0x0E);
  542. esp_eth_ioctl(eth_handle, ETH_CMD_ADD_MAC_FILTER, dest_addr);
  543. state->remote_time_ns_prev = 0;
  544. state->local_time_ns_prev = 0;
  545. /* PI controller gains (multiplicative, fixed-point * 1000).
  546. * These are the default gains used when offset is small (<1ms).
  547. * When offset is large, adaptive scaling increases them. */
  548. state->offset_pi.kp = 150; /* 0.15 as fixed-point *1000 */
  549. state->offset_pi.ki = 10; /* 0.01 as fixed-point *1000 */
  550. state->offset_pi.drift_acc = 0;
  551. state->own_identity.header.version = 2;
  552. state->own_identity.header.domain = CONFIG_NETUTILS_PTPD_DOMAIN;
  553. state->own_identity.header.sourceidentity[0] = state->intf_hw_addr[0];
  554. state->own_identity.header.sourceidentity[1] = state->intf_hw_addr[1];
  555. state->own_identity.header.sourceidentity[2] = state->intf_hw_addr[2];
  556. state->own_identity.header.sourceidentity[3] = 0xff;
  557. state->own_identity.header.sourceidentity[4] = 0xfe;
  558. state->own_identity.header.sourceidentity[5] = state->intf_hw_addr[3];
  559. state->own_identity.header.sourceidentity[6] = state->intf_hw_addr[4];
  560. state->own_identity.header.sourceidentity[7] = state->intf_hw_addr[5];
  561. state->own_identity.header.sourceportindex[0] = 0;
  562. state->own_identity.header.sourceportindex[1] = 1;
  563. #ifdef CONFIG_NETUTILS_PTPD_SERVER
  564. state->own_identity.gm_priority1 = CONFIG_NETUTILS_PTPD_PRIORITY1;
  565. state->own_identity.gm_quality[0] = CONFIG_NETUTILS_PTPD_CLASS;
  566. state->own_identity.gm_quality[1] = CONFIG_NETUTILS_PTPD_ACCURACY;
  567. state->own_identity.gm_quality[2] = 0xff; /* No variance estimate */
  568. state->own_identity.gm_quality[3] = 0xff;
  569. state->own_identity.gm_priority2 = CONFIG_NETUTILS_PTPD_PRIORITY2;
  570. memcpy(state->own_identity.gm_identity,
  571. state->own_identity.header.sourceidentity,
  572. sizeof(state->own_identity.gm_identity));
  573. state->own_identity.timesource = CONFIG_NETUTILS_PTPD_CLOCKSOURCE;
  574. #else
  575. state->own_identity.gm_priority1 = 255; // When daemon is statically configured as slave, set the worst
  576. #endif
  577. /* --- UDP socket setup for AES67 interoperability ---
  578. * In addition to L2 TAP, set up standard UDP sockets on the PTP
  579. * multicast group (224.0.1.129) so we can communicate with devices
  580. * that use PTP over UDP/IPv4 (which is most AES67 gear). */
  581. /* Get interface IP for binding and IGMP */
  582. esp_netif_t *netif = esp_netif_get_handle_from_ifkey(interface);
  583. if (netif) {
  584. esp_netif_ip_info_t ip_info;
  585. if (esp_netif_get_ip_info(netif, &ip_info) == ESP_OK) {
  586. state->interface_addr.sin_family = AF_INET;
  587. state->interface_addr.sin_addr.s_addr = ip_info.ip.addr;
  588. }
  589. }
  590. /* Create UDP sockets */
  591. state->tx_socket = socket(AF_INET, SOCK_DGRAM, 0);
  592. state->event_socket = socket(AF_INET, SOCK_DGRAM, 0);
  593. state->info_socket = socket(AF_INET, SOCK_DGRAM, 0);
  594. if (state->tx_socket < 0 || state->event_socket < 0 || state->info_socket < 0) {
  595. ptperr("Failed to create UDP sockets for PTP: %d\n", errno);
  596. /* Non-fatal: L2 transport still works */
  597. } else {
  598. struct sockaddr_in bind_addr;
  599. memset(&bind_addr, 0, sizeof(bind_addr));
  600. bind_addr.sin_family = AF_INET;
  601. bind_addr.sin_addr.s_addr = htonl(PTP_MULTICAST_ADDR);
  602. /* Join PTP multicast group via IGMP */
  603. struct ip_mreq mreq;
  604. mreq.imr_multiaddr.s_addr = htonl(PTP_MULTICAST_ADDR);
  605. mreq.imr_interface.s_addr = state->interface_addr.sin_addr.s_addr;
  606. if (setsockopt(state->event_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP,
  607. &mreq, sizeof(mreq)) < 0) {
  608. ptperr("Failed to join PTP multicast on event socket: %d\n", errno);
  609. }
  610. if (setsockopt(state->info_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP,
  611. &mreq, sizeof(mreq)) < 0) {
  612. ptperr("Failed to join PTP multicast on info socket: %d\n", errno);
  613. }
  614. /* Allow address reuse so multiple sockets can bind to the same port */
  615. int reuse = 1;
  616. setsockopt(state->event_socket, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
  617. setsockopt(state->info_socket, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
  618. /* Bind event socket to port 319 */
  619. bind_addr.sin_port = htons(PTP_UDP_PORT_EVENT);
  620. if (bind(state->event_socket, (struct sockaddr *)&bind_addr,
  621. sizeof(bind_addr)) < 0) {
  622. ptperr("Failed to bind event socket to port %d: %d\n",
  623. PTP_UDP_PORT_EVENT, errno);
  624. }
  625. /* Bind info socket to port 320 */
  626. bind_addr.sin_port = htons(PTP_UDP_PORT_INFO);
  627. if (bind(state->info_socket, (struct sockaddr *)&bind_addr,
  628. sizeof(bind_addr)) < 0) {
  629. ptperr("Failed to bind info socket to port %d: %d\n",
  630. PTP_UDP_PORT_INFO, errno);
  631. }
  632. /* Bind TX socket to local interface address */
  633. bind_addr.sin_addr = state->interface_addr.sin_addr;
  634. bind_addr.sin_port = 0; /* Any port */
  635. bind(state->tx_socket, (struct sockaddr *)&bind_addr, sizeof(bind_addr));
  636. /* Set multicast TTL */
  637. int ttl = 64;
  638. setsockopt(state->tx_socket, IPPROTO_IP, IP_MULTICAST_TTL,
  639. &ttl, sizeof(ttl));
  640. ptpinfo("UDP PTP sockets ready (event:%d, info:%d, tx:%d)\n",
  641. state->event_socket, state->info_socket, state->tx_socket);
  642. }
  643. s_state = state;
  644. return OK;
  645. }
  646. #else
  647. static int ptp_initialize_state(FAR struct ptp_state_s *state,
  648. FAR const char *interface)
  649. {
  650. int ret;
  651. struct ifreq req;
  652. struct sockaddr_in bind_addr;
  653. #ifdef CONFIG_NET_TIMESTAMP
  654. int arg;
  655. #endif
  656. /* Create sockets */
  657. state->tx_socket = socket(AF_INET, SOCK_DGRAM, 0);
  658. if (state->tx_socket < 0)
  659. {
  660. ptperr("Failed to create tx socket: %d\n", errno);
  661. return ERROR;
  662. }
  663. state->event_socket = socket(AF_INET, SOCK_DGRAM, 0);
  664. if (state->event_socket < 0)
  665. {
  666. ptperr("Failed to create event socket: %d\n", errno);
  667. return ERROR;
  668. }
  669. state->info_socket = socket(AF_INET, SOCK_DGRAM, 0);
  670. if (state->info_socket < 0)
  671. {
  672. ptperr("Failed to create info socket: %d\n", errno);
  673. return ERROR;
  674. }
  675. /* Get address information of the specified interface for binding socket
  676. * Only supports IPv4 currently.
  677. */
  678. memset(&req, 0, sizeof(req));
  679. strncpy(req.ifr_name, interface, sizeof(req.ifr_name));
  680. if (ioctl(state->event_socket, SIOCGIFADDR, (unsigned long)&req) < 0)
  681. {
  682. ptperr("Failed to get IP address information for interface %s\n",
  683. interface);
  684. return ERROR;
  685. }
  686. state->interface_addr = *(struct sockaddr_in *)&req.ifr_ifru.ifru_addr;
  687. /* Get hardware address to initialize the identity field in header.
  688. * Clock identity is EUI-64, which we make from EUI-48.
  689. */
  690. if (ioctl(state->event_socket, SIOCGIFHWADDR, (unsigned long)&req) < 0)
  691. {
  692. ptperr("Failed to get HW address information for interface %s\n",
  693. interface);
  694. return ERROR;
  695. }
  696. state->own_identity.header.version = 2;
  697. state->own_identity.header.domain = CONFIG_NETUTILS_PTPD_DOMAIN;
  698. state->own_identity.header.sourceidentity[0] = req.ifr_hwaddr.sa_data[0];
  699. state->own_identity.header.sourceidentity[1] = req.ifr_hwaddr.sa_data[1];
  700. state->own_identity.header.sourceidentity[2] = req.ifr_hwaddr.sa_data[2];
  701. state->own_identity.header.sourceidentity[3] = 0xff;
  702. state->own_identity.header.sourceidentity[4] = 0xfe;
  703. state->own_identity.header.sourceidentity[5] = req.ifr_hwaddr.sa_data[3];
  704. state->own_identity.header.sourceidentity[6] = req.ifr_hwaddr.sa_data[4];
  705. state->own_identity.header.sourceidentity[7] = req.ifr_hwaddr.sa_data[5];
  706. state->own_identity.header.sourceportindex[0] = 0;
  707. state->own_identity.header.sourceportindex[1] = 1;
  708. state->own_identity.gm_priority1 = CONFIG_NETUTILS_PTPD_PRIORITY1;
  709. state->own_identity.gm_quality[0] = CONFIG_NETUTILS_PTPD_CLASS;
  710. state->own_identity.gm_quality[1] = CONFIG_NETUTILS_PTPD_ACCURACY;
  711. state->own_identity.gm_quality[2] = 0xff; /* No variance estimate */
  712. state->own_identity.gm_quality[3] = 0xff;
  713. state->own_identity.gm_priority2 = CONFIG_NETUTILS_PTPD_PRIORITY2;
  714. memcpy(state->own_identity.gm_identity,
  715. state->own_identity.header.sourceidentity,
  716. sizeof(state->own_identity.gm_identity));
  717. state->own_identity.timesource = CONFIG_NETUTILS_PTPD_CLOCKSOURCE;
  718. /* Subscribe to PTP multicast address */
  719. bind_addr.sin_family = AF_INET;
  720. bind_addr.sin_addr.s_addr = htonl(PTP_MULTICAST_ADDR);
  721. clock_gettime(CLOCK_MONOTONIC, &state->last_received_multicast);
  722. ret = ipmsfilter(&state->interface_addr.sin_addr,
  723. &bind_addr.sin_addr,
  724. MCAST_INCLUDE);
  725. if (ret < 0)
  726. {
  727. ptperr("Failed to bind multicast address: %d\n", errno);
  728. return ERROR;
  729. }
  730. /* Bind socket for events */
  731. bind_addr.sin_port = htons(PTP_UDP_PORT_EVENT);
  732. ret = bind(state->event_socket, (struct sockaddr *)&bind_addr,
  733. sizeof(bind_addr));
  734. if (ret < 0)
  735. {
  736. ptperr("Failed to bind to udp port %d\n", bind_addr.sin_port);
  737. return ERROR;
  738. }
  739. #ifdef CONFIG_NET_TIMESTAMP
  740. arg = 1;
  741. ret = setsockopt(state->event_socket, SOL_SOCKET, SO_TIMESTAMP,
  742. &arg, sizeof(arg));
  743. if (ret < 0)
  744. {
  745. ptperr("Failed to enable SO_TIMESTAMP: %s\n", strerror(errno));
  746. /* PTPD can operate without, but with worse accuracy */
  747. }
  748. #endif
  749. /* Bind socket for announcements */
  750. bind_addr.sin_port = htons(PTP_UDP_PORT_INFO);
  751. ret = bind(state->info_socket, (struct sockaddr *)&bind_addr,
  752. sizeof(bind_addr));
  753. if (ret < 0)
  754. {
  755. ptperr("Failed to bind to udp port %d\n", bind_addr.sin_port);
  756. return ERROR;
  757. }
  758. /* Bind TX socket to interface address (local addr cannot be multicast) */
  759. bind_addr.sin_addr = state->interface_addr.sin_addr;
  760. ret = bind(state->tx_socket, (struct sockaddr *)&bind_addr,
  761. sizeof(bind_addr));
  762. if (ret < 0)
  763. {
  764. ptperr("Failed to bind tx to port %d\n", bind_addr.sin_port);
  765. return ERROR;
  766. }
  767. return OK;
  768. }
  769. #endif // ESP_PTP
  770. /* Unsubscribe multicast and destroy sockets */
  771. static int ptp_destroy_state(FAR struct ptp_state_s *state)
  772. {
  773. #ifdef ESP_PTP
  774. // Remove well-known PTP multicast destination MAC addresses from the filter
  775. esp_eth_handle_t eth_handle;
  776. if (ioctl(state->ptp_socket, L2TAP_G_DEVICE_DRV_HNDL, &eth_handle) < 0)
  777. {
  778. ptperr("failed to get socket eth_handle %d\n", errno);
  779. return ERROR;
  780. }
  781. uint8_t dest_addr[ETH_ADDR_LEN];
  782. SET_MAC_ADDR(dest_addr, 0x01, 0x1B, 0x19, 0x00, 0x00, 0x00);
  783. esp_eth_ioctl(eth_handle, ETH_CMD_DEL_MAC_FILTER, dest_addr);
  784. SET_MAC_ADDR(dest_addr, 0x01, 0x80, 0xC2, 0x00, 0x00, 0x0E);
  785. esp_eth_ioctl(eth_handle, ETH_CMD_DEL_MAC_FILTER, dest_addr);
  786. if (state->ptp_socket > 0)
  787. {
  788. close(state->ptp_socket);
  789. state->ptp_socket = -1;
  790. }
  791. #else
  792. struct in_addr mcast_addr;
  793. mcast_addr.s_addr = htonl(PTP_MULTICAST_ADDR);
  794. ipmsfilter(&state->interface_addr.sin_addr,
  795. &mcast_addr,
  796. MCAST_EXCLUDE);
  797. if (state->tx_socket > 0)
  798. {
  799. close(state->tx_socket);
  800. state->tx_socket = -1;
  801. }
  802. if (state->event_socket > 0)
  803. {
  804. close(state->event_socket);
  805. state->event_socket = -1;
  806. }
  807. if (state->info_socket > 0)
  808. {
  809. close(state->info_socket);
  810. state->info_socket = -1;
  811. }
  812. #endif // ESP_PTP
  813. return OK;
  814. }
  815. #ifndef ESP_PTP
  816. /* Re-subscribe multicast address.
  817. * This can become necessary if Ethernet interface gets reset or if external
  818. * IGMP-compliant Ethernet switch gets plugged in.
  819. */
  820. static int ptp_check_multicast_status(FAR struct ptp_state_s *state)
  821. {
  822. #if CONFIG_NETUTILS_PTPD_MULTICAST_TIMEOUT_MS > 0
  823. struct in_addr mcast_addr;
  824. struct timespec time_now;
  825. struct timespec delta;
  826. clock_gettime(CLOCK_MONOTONIC, &time_now);
  827. clock_timespec_subtract(&time_now, &state->last_received_multicast,
  828. &delta);
  829. if (timespec_to_ms(&delta) > CONFIG_NETUTILS_PTPD_MULTICAST_TIMEOUT_MS)
  830. {
  831. /* Remove and re-add the multicast group */
  832. state->last_received_multicast = time_now;
  833. mcast_addr.s_addr = htonl(PTP_MULTICAST_ADDR);
  834. ipmsfilter(&state->interface_addr.sin_addr,
  835. &mcast_addr,
  836. MCAST_EXCLUDE);
  837. return ipmsfilter(&state->interface_addr.sin_addr,
  838. &mcast_addr,
  839. MCAST_INCLUDE);
  840. }
  841. #else
  842. UNUSED(state);
  843. #endif /* CONFIG_NETUTILS_PTPD_MULTICAST_TIMEOUT_MS */
  844. return OK;
  845. }
  846. #endif // !ESP_PTP
  847. /* Send PTP server announcement packet */
  848. static int ptp_send_announce(FAR struct ptp_state_s *state)
  849. {
  850. struct ptp_announce_s msg;
  851. #ifndef ESP_PTP
  852. struct sockaddr_in addr;
  853. #endif // !ESP_PTP
  854. struct timespec ts;
  855. int ret;
  856. #ifndef ESP_PTP
  857. addr.sin_family = AF_INET;
  858. addr.sin_addr.s_addr = htonl(PTP_MULTICAST_ADDR);
  859. addr.sin_port = htons(PTP_UDP_PORT_INFO);
  860. #endif // !ESP_PTP
  861. memset(&msg, 0, sizeof(msg));
  862. msg = state->own_identity;
  863. msg.header.messagetype = PTP_MSGTYPE_ANNOUNCE;
  864. msg.header.messagelength[1] = sizeof(msg);
  865. ptp_increment_sequence(&state->announce_seq, &msg.header);
  866. ptp_gettime(state, &ts);
  867. timespec_to_ptp_format(&ts, msg.origintimestamp);
  868. #ifdef ESP_PTP
  869. /* Send via L2 TAP for hardware timestamped transport */
  870. ret = ptp_net_send(state, &msg, sizeof(msg), NULL);
  871. /* Also send via UDP for interoperability with standard PTP/AES67 devices */
  872. {
  873. struct sockaddr_in udp_addr;
  874. udp_addr.sin_family = AF_INET;
  875. udp_addr.sin_addr.s_addr = htonl(PTP_MULTICAST_ADDR);
  876. udp_addr.sin_port = htons(PTP_UDP_PORT_INFO);
  877. sendto(state->tx_socket, &msg, sizeof(msg), 0,
  878. (struct sockaddr *)&udp_addr, sizeof(udp_addr));
  879. }
  880. #else
  881. ret = sendto(state->tx_socket, &msg, sizeof(msg), 0,
  882. (struct sockaddr *)&addr, sizeof(addr));
  883. #endif // ESP_PTP
  884. if (ret < 0)
  885. {
  886. ptperr("sendto failed: %d", errno);
  887. }
  888. else
  889. {
  890. ESP_LOGD(TAG, "Sent announce, seq %ld",
  891. (long)ptp_get_sequence(&msg.header));
  892. }
  893. return ret;
  894. }
  895. /* Send PTP server synchronization packet */
  896. static int ptp_send_sync(FAR struct ptp_state_s *state)
  897. {
  898. #ifndef ESP_PTP
  899. struct msghdr txhdr;
  900. struct iovec txiov;
  901. #endif // !ESP_PTP
  902. struct ptp_sync_s msg;
  903. #ifndef ESP_PTP
  904. struct sockaddr_in addr;
  905. #endif // !ESP_PTP
  906. struct timespec ts;
  907. #ifndef ESP_PTP
  908. uint8_t controlbuf[64];
  909. #endif // !ESP_PTP
  910. int ret;
  911. #ifndef ESP_PTP
  912. memset(&txhdr, 0, sizeof(txhdr));
  913. memset(&txiov, 0, sizeof(txiov));
  914. addr.sin_family = AF_INET;
  915. addr.sin_addr.s_addr = htonl(PTP_MULTICAST_ADDR);
  916. addr.sin_port = htons(PTP_UDP_PORT_EVENT);
  917. #endif // !ESP_PTP
  918. memset(&msg, 0, sizeof(msg));
  919. msg.header = state->own_identity.header;
  920. msg.header.messagetype = PTP_MSGTYPE_SYNC;
  921. msg.header.messagelength[1] = sizeof(msg);
  922. #ifdef CONFIG_NETUTILS_PTPD_TWOSTEP_SYNC
  923. msg.header.flags[0] = PTP_FLAGS0_TWOSTEP;
  924. #endif
  925. #ifndef ESP_PTP
  926. txhdr.msg_name = &addr;
  927. txhdr.msg_namelen = sizeof(addr);
  928. txhdr.msg_iov = &txiov;
  929. txhdr.msg_iovlen = 1;
  930. txhdr.msg_control = controlbuf;
  931. txhdr.msg_controllen = sizeof(controlbuf);
  932. txiov.iov_base = &msg;
  933. txiov.iov_len = sizeof(msg);
  934. #endif //!ESP_PTP
  935. /* Timestamp and send the sync message */
  936. ptp_increment_sequence(&state->sync_seq, &msg.header);
  937. ptp_gettime(state, &ts);
  938. timespec_to_ptp_format(&ts, msg.origintimestamp);
  939. #ifdef ESP_PTP
  940. ret = ptp_net_send(state, &msg, sizeof(msg), &ts);
  941. /* Also send sync via UDP for AES67 interoperability */
  942. {
  943. struct sockaddr_in udp_addr;
  944. udp_addr.sin_family = AF_INET;
  945. udp_addr.sin_addr.s_addr = htonl(PTP_MULTICAST_ADDR);
  946. udp_addr.sin_port = htons(PTP_UDP_PORT_EVENT);
  947. sendto(state->tx_socket, &msg, sizeof(msg), 0,
  948. (struct sockaddr *)&udp_addr, sizeof(udp_addr));
  949. }
  950. #else
  951. ret = sendmsg(state->tx_socket, &txhdr, 0);
  952. #endif // ESP_PTP
  953. if (ret < 0)
  954. {
  955. ptperr("sendmsg for sync message failed: %d\n", errno);
  956. return ret;
  957. }
  958. #ifdef CONFIG_NETUTILS_PTPD_TWOSTEP_SYNC
  959. #ifndef ESP_PTP
  960. /* Get timestamp after send completes and send follow-up message
  961. *
  962. * TODO: Implement SO_TIMESTAMPING and use the actual tx timestamp here.
  963. */
  964. ptp_gettime(state, &ts);
  965. #endif // !ESP_PTP
  966. timespec_to_ptp_format(&ts, msg.origintimestamp);
  967. msg.header.messagetype = PTP_MSGTYPE_FOLLOW_UP;
  968. msg.header.flags[0] = 0;
  969. #ifdef ESP_PTP
  970. ret = ptp_net_send(state, &msg, sizeof(msg), NULL);
  971. /* Also send follow-up via UDP */
  972. {
  973. struct sockaddr_in udp_addr;
  974. udp_addr.sin_family = AF_INET;
  975. udp_addr.sin_addr.s_addr = htonl(PTP_MULTICAST_ADDR);
  976. udp_addr.sin_port = htons(PTP_UDP_PORT_INFO);
  977. sendto(state->tx_socket, &msg, sizeof(msg), 0,
  978. (struct sockaddr *)&udp_addr, sizeof(udp_addr));
  979. }
  980. #else
  981. addr.sin_port = htons(PTP_UDP_PORT_INFO);
  982. ret = sendto(state->tx_socket, &msg, sizeof(msg), 0,
  983. (struct sockaddr *)&addr, sizeof(addr));
  984. #endif // ESP_PTP
  985. if (ret < 0)
  986. {
  987. ptperr("sendto for follow-up message failed: %d\n", errno);
  988. return ret;
  989. }
  990. ESP_LOGD(TAG, "Sent sync + follow-up, seq %ld",
  991. (long)ptp_get_sequence(&msg.header));
  992. #else
  993. ESP_LOGD(TAG, "Sent sync, seq %ld",
  994. (long)ptp_get_sequence(&msg.header));
  995. #endif /* CONFIG_NETUTILS_PTPD_TWOSTEP_SYNC */
  996. return OK;
  997. }
  998. /* Send delay request packet to selected source */
  999. static int ptp_send_delay_req(FAR struct ptp_state_s *state)
  1000. {
  1001. struct ptp_delay_req_s req;
  1002. #ifndef ESP_PTP
  1003. struct sockaddr_in addr;
  1004. #endif // !ESP_PTP
  1005. int ret;
  1006. #ifndef ESP_PTP
  1007. addr.sin_family = AF_INET;
  1008. addr.sin_addr.s_addr = htonl(PTP_MULTICAST_ADDR);
  1009. addr.sin_port = htons(PTP_UDP_PORT_EVENT);
  1010. #endif // !ESP_PTP
  1011. memset(&req, 0, sizeof(req));
  1012. req.header = state->own_identity.header;
  1013. req.header.messagetype = PTP_MSGTYPE_DELAY_REQ;
  1014. req.header.messagelength[1] = sizeof(req);
  1015. ptp_increment_sequence(&state->delay_req_seq, &req.header);
  1016. ptp_gettime(state, &state->delayreq_time);
  1017. timespec_to_ptp_format(&state->delayreq_time, req.origintimestamp);
  1018. #ifdef ESP_PTP
  1019. ret = ptp_net_send(state, &req, sizeof(req), &state->delayreq_time);
  1020. /* Also send delay_req via UDP */
  1021. {
  1022. struct sockaddr_in udp_addr;
  1023. udp_addr.sin_family = AF_INET;
  1024. udp_addr.sin_addr.s_addr = htonl(PTP_MULTICAST_ADDR);
  1025. udp_addr.sin_port = htons(PTP_UDP_PORT_EVENT);
  1026. sendto(state->tx_socket, &req, sizeof(req), 0,
  1027. (struct sockaddr *)&udp_addr, sizeof(udp_addr));
  1028. }
  1029. #else
  1030. ret = sendto(state->tx_socket, &req, sizeof(req), 0,
  1031. (FAR struct sockaddr *)&addr, sizeof(addr));
  1032. /* Get timestamp after send completes.
  1033. * TODO: Implement SO_TIMESTAMPING and use the actual tx timestamp here.
  1034. */
  1035. ptp_gettime(state, &state->delayreq_time);
  1036. #endif // ESP_PTP
  1037. if (ret < 0)
  1038. {
  1039. ptperr("sendto failed: %d", errno);
  1040. }
  1041. else
  1042. {
  1043. clock_gettime(CLOCK_MONOTONIC, &state->last_transmitted_delayreq);
  1044. ESP_LOGD(TAG, "Sent delay req, seq %ld",
  1045. (long)ptp_get_sequence(&req.header));
  1046. }
  1047. return ret;
  1048. }
  1049. /* Check if we need to send packets */
  1050. static int ptp_periodic_send(FAR struct ptp_state_s *state)
  1051. {
  1052. #ifdef CONFIG_NETUTILS_PTPD_SERVER
  1053. /* If there is no better master clock on the network,
  1054. * act as the reference source and send server packets.
  1055. */
  1056. if (!state->selected_source_valid)
  1057. {
  1058. struct timespec time_now;
  1059. struct timespec delta;
  1060. clock_gettime(CLOCK_MONOTONIC, &time_now);
  1061. clock_timespec_subtract(&time_now,
  1062. &state->last_transmitted_announce, &delta);
  1063. if (timespec_to_ms(&delta)
  1064. > CONFIG_NETUTILS_PTPD_ANNOUNCE_INTERVAL_MSEC)
  1065. {
  1066. state->last_transmitted_announce = time_now;
  1067. ptp_send_announce(state);
  1068. }
  1069. clock_timespec_subtract(&time_now,
  1070. &state->last_transmitted_sync, &delta);
  1071. if (timespec_to_ms(&delta) > CONFIG_NETUTILS_PTPD_SYNC_INTERVAL_MSEC)
  1072. {
  1073. state->last_transmitted_sync = time_now;
  1074. ptp_send_sync(state);
  1075. }
  1076. }
  1077. #endif /* CONFIG_NETUTILS_PTPD_SERVER */
  1078. #ifdef CONFIG_NETUTILS_PTPD_SEND_DELAYREQ
  1079. if (state->selected_source_valid && state->can_send_delayreq)
  1080. {
  1081. struct timespec time_now;
  1082. struct timespec delta;
  1083. clock_gettime(CLOCK_MONOTONIC, &time_now);
  1084. clock_timespec_subtract(&time_now,
  1085. &state->last_transmitted_delayreq, &delta);
  1086. if (timespec_to_ms(&delta) > state->delayreq_interval * MSEC_PER_SEC)
  1087. {
  1088. ptp_send_delay_req(state);
  1089. }
  1090. }
  1091. #endif
  1092. return OK;
  1093. }
  1094. /* Process received PTP announcement */
  1095. static int ptp_process_announce(FAR struct ptp_state_s *state,
  1096. FAR struct ptp_announce_s *msg)
  1097. {
  1098. clock_gettime(CLOCK_MONOTONIC, &state->last_received_announce);
  1099. /* Log announce only when it's from a new/different GM than our current source,
  1100. * or if it's better than us and we haven't selected it yet. */
  1101. bool better = is_better_clock(msg, &state->own_identity);
  1102. bool is_new_gm = !state->selected_source_valid ||
  1103. memcmp(msg->gm_identity,
  1104. state->selected_source.gm_identity,
  1105. sizeof(msg->gm_identity)) != 0;
  1106. if (is_new_gm || !state->selected_source_valid) {
  1107. ESP_LOGI(TAG, "Announce from GM %02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X "
  1108. "(p1=%u, class=%u, acc=%u, p2=%u) %s",
  1109. msg->gm_identity[0], msg->gm_identity[1],
  1110. msg->gm_identity[2], msg->gm_identity[3],
  1111. msg->gm_identity[4], msg->gm_identity[5],
  1112. msg->gm_identity[6], msg->gm_identity[7],
  1113. msg->gm_priority1,
  1114. msg->gm_quality[0], /* clock class */
  1115. msg->gm_quality[1], /* clock accuracy */
  1116. msg->gm_priority2,
  1117. better ? "<- BETTER than us" : "(not better)");
  1118. }
  1119. if (better)
  1120. {
  1121. if (!state->selected_source_valid ||
  1122. is_better_clock(msg, &state->selected_source))
  1123. {
  1124. ESP_LOGI(TAG, "Selecting GM %02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X as clock source",
  1125. msg->gm_identity[0], msg->gm_identity[1],
  1126. msg->gm_identity[2], msg->gm_identity[3],
  1127. msg->gm_identity[4], msg->gm_identity[5],
  1128. msg->gm_identity[6], msg->gm_identity[7]);
  1129. state->selected_source = *msg;
  1130. state->last_received_sync = state->last_received_announce;
  1131. state->path_delay_avgcount = 0;
  1132. state->path_delay_ns = 0;
  1133. state->delayreq_time.tv_sec = 0;
  1134. }
  1135. }
  1136. return OK;
  1137. }
  1138. #ifdef ESP_PTP
  1139. static void ptp_lock_local_clock_freq(FAR struct ptp_state_s *state,
  1140. FAR struct timespec *remote_timestamp,
  1141. FAR struct timespec *local_timestamp)
  1142. {
  1143. /* Compute clock offset against master */
  1144. int64_t offset_ns = timespec_delta_ns(remote_timestamp, local_timestamp);
  1145. offset_ns += state->path_delay_ns;
  1146. /* Outlier filter: reject measurements where the offset changes by
  1147. * more than 2ms from the previous sample. These are caused by network
  1148. * jitter (delayed packets), not real clock error. Skip adjustment
  1149. * but still update timestamps for the next cycle. */
  1150. if (state->last_offset_ns != 0) {
  1151. int64_t delta = offset_ns - state->last_offset_ns;
  1152. if (delta > 500000LL || delta < -500000LL) {
  1153. ESP_LOGD(TAG, "Outlier filtered: offset %+lld ns (prev %+lld, delta %+lld)",
  1154. offset_ns, state->last_offset_ns, delta);
  1155. /* Update prev timestamps but skip PI adjustment */
  1156. state->remote_time_ns_prev = timespec_to_ns(remote_timestamp);
  1157. state->local_time_ns_prev = timespec_to_ns(local_timestamp);
  1158. state->last_offset_ns = offset_ns;
  1159. state->last_delta_ns = offset_ns;
  1160. return;
  1161. }
  1162. }
  1163. state->last_offset_ns = offset_ns;
  1164. /* Convert offset from nanoseconds to ppb using the actual sync interval.
  1165. * ppb = offset_ns * 1e9 / interval_ns */
  1166. int64_t local_time_ns_now = timespec_to_ns(local_timestamp);
  1167. int64_t interval_ns = 1000000000LL;
  1168. if (state->local_time_ns_prev > 0) {
  1169. int64_t measured = local_time_ns_now - state->local_time_ns_prev;
  1170. if (measured > 100000000LL && measured < 5000000000LL) {
  1171. interval_ns = measured;
  1172. }
  1173. }
  1174. int64_t offset_ppb = (offset_ns * 1000000000LL) / interval_ns;
  1175. /* Adaptive gain scaling: use stronger gains when offset is large
  1176. * to converge quickly, then ease off for stable fine tracking.
  1177. * > 1ms offset: gains * 3 (aggressive pull-in)
  1178. * > 100us offset: gains * 2 (moderate convergence)
  1179. * < 100us offset: base gains (fine tracking) */
  1180. int32_t kp = state->offset_pi.kp;
  1181. int32_t ki = state->offset_pi.ki;
  1182. int64_t abs_offset = (offset_ns < 0) ? -offset_ns : offset_ns;
  1183. if (abs_offset > 1000000) { /* > 1ms */
  1184. kp *= 2;
  1185. ki *= 2;
  1186. }
  1187. /* No extra scaling for 100us-1ms range -- let the base gains handle it */
  1188. /* PI controller with multiplicative gains.
  1189. * P term = offset_ppb * kp / 1000
  1190. * I term: drift_acc += offset_ppb * ki / 1000 */
  1191. int32_t p_term = (int32_t)((offset_ppb * kp) / 1000);
  1192. state->offset_pi.drift_acc += (int32_t)((offset_ppb * ki) / 1000);
  1193. /* Clamp I term to +/- 50 ppm to prevent overshoot */
  1194. if (state->offset_pi.drift_acc > 50000) {
  1195. state->offset_pi.drift_acc = 50000;
  1196. } else if (state->offset_pi.drift_acc < -50000) {
  1197. state->offset_pi.drift_acc = -50000;
  1198. }
  1199. int32_t adj_ppb = p_term + state->offset_pi.drift_acc;
  1200. /* Clamp total output to +/- 200 ppm */
  1201. if (adj_ppb > 200000) adj_ppb = 200000;
  1202. if (adj_ppb < -200000) adj_ppb = -200000;
  1203. #ifndef AES67_DISABLE_PTP_PI
  1204. /* Use the ppb-based API (ETH_MAC_ESP_CMD_ADJ_PTP_TIME) which calls
  1205. * emac_hal_ptp_adj_inc. This is idempotent: it always computes the
  1206. * new addend relative to the stored base addend, avoiding the
  1207. * compounding problem of the freq_scale API. */
  1208. esp_err_t adj_err = esp_eth_ioctl(state->cached_eth_handle,
  1209. ETH_MAC_ESP_CMD_ADJ_PTP_TIME, &adj_ppb);
  1210. if (adj_err != ESP_OK) {
  1211. ESP_LOGW(TAG, "PTP freq adj failed: %s", esp_err_to_name(adj_err));
  1212. }
  1213. #else
  1214. (void)adj_ppb;
  1215. /* PI disabled: PTP clock runs free, no frequency discipline */
  1216. #endif
  1217. /* Track timestamps for drift measurement */
  1218. int64_t remote_time_ns = timespec_to_ns(remote_timestamp);
  1219. int64_t local_time_ns = timespec_to_ns(local_timestamp);
  1220. if (state->remote_time_ns_prev != 0 && state->local_time_ns_prev != 0) {
  1221. int64_t local_delta_ns = local_time_ns - state->local_time_ns_prev;
  1222. int64_t remote_delta_ns = remote_time_ns - state->remote_time_ns_prev;
  1223. if (local_delta_ns > 0 && local_delta_ns < 5000000000LL) {
  1224. int64_t tick_diff = remote_delta_ns - local_delta_ns;
  1225. state->drift_ppb = (long)((tick_diff * 1000000000LL) / local_delta_ns);
  1226. }
  1227. }
  1228. state->remote_time_ns_prev = remote_time_ns;
  1229. state->local_time_ns_prev = local_time_ns;
  1230. state->last_delta_ns = offset_ns;
  1231. ESP_LOGD(TAG, "offset %+lld ns, p=%+ld, i=%+ld, adj=%+ld ppb",
  1232. offset_ns, (long)p_term, (long)state->offset_pi.drift_acc, (long)adj_ppb);
  1233. // Get the path delay only when clock is stable enough. If we were in process of adjustion (speeding/slowing slave),
  1234. // we would get incorrect delay
  1235. int64_t diff = llabs(offset_ns) - llabs(state->last_offset_ns);
  1236. static int cnt = 0;
  1237. if (llabs(diff) < CONFIG_NETUTILS_PTPD_PATH_DELAY_STABILITY_NS) {
  1238. if (cnt <= 3)
  1239. cnt++;
  1240. } else {
  1241. cnt = 0;
  1242. }
  1243. if (cnt > 3)
  1244. {
  1245. state->can_send_delayreq = true;
  1246. }
  1247. state->last_offset_ns = offset_ns;
  1248. }
  1249. void ptp_clean_after_step(FAR struct ptp_state_s *state)
  1250. {
  1251. state->remote_time_ns_prev = 0;
  1252. state->local_time_ns_prev = 0;
  1253. state->offset_pi.drift_acc = 0;
  1254. state->last_offset_ns = 0;
  1255. }
  1256. #endif // ESP_PTP
  1257. /* Update local clock either by smooth adjustment or by jumping.
  1258. * Remote time was remote_timestamp at local_timestamp.
  1259. */
  1260. static int ptp_update_local_clock(FAR struct ptp_state_s *state,
  1261. FAR struct timespec *remote_timestamp,
  1262. FAR struct timespec *local_timestamp)
  1263. {
  1264. int ret = OK;
  1265. int64_t delta_ns;
  1266. int64_t absdelta_ns;
  1267. const int64_t adj_limit_ns = CONFIG_NETUTILS_PTPD_SETTIME_THRESHOLD_MS
  1268. * (int64_t)NSEC_PER_MSEC;
  1269. ESP_LOGD(TAG, "Local time: %lld.%09ld, remote time %lld.%09ld",
  1270. (long long)local_timestamp->tv_sec,
  1271. (long)local_timestamp->tv_nsec,
  1272. (long long)remote_timestamp->tv_sec,
  1273. (long)remote_timestamp->tv_nsec);
  1274. delta_ns = timespec_delta_ns(remote_timestamp, local_timestamp);
  1275. delta_ns += state->path_delay_ns;
  1276. absdelta_ns = (delta_ns < 0) ? -delta_ns : delta_ns;
  1277. if (absdelta_ns > adj_limit_ns)
  1278. {
  1279. /* Large difference, move by jumping.
  1280. * Account for delay since packet was received.
  1281. */
  1282. struct timespec new_time;
  1283. ptp_gettime(state, &new_time);
  1284. clock_timespec_subtract(&new_time, local_timestamp, &new_time);
  1285. clock_timespec_add(&new_time, remote_timestamp, &new_time);
  1286. ret = ptp_settime(state, &new_time);
  1287. /* Reinitialize drift adjustment parameters */
  1288. state->last_delta_timestamp = new_time;
  1289. state->last_delta_ns = 0;
  1290. state->last_adjtime_ns = 0;
  1291. state->drift_avg_total_ms = 0;
  1292. state->drift_ppb = 0;
  1293. #ifdef ESP_PTP
  1294. ptp_clean_after_step(state);
  1295. #endif // ESP_PTP
  1296. if (ret == OK)
  1297. {
  1298. ESP_LOGI(TAG, "Jumped to timestamp %lld.%09ld s",
  1299. (long long)new_time.tv_sec, (long)new_time.tv_nsec);
  1300. }
  1301. else
  1302. {
  1303. ptperr("ptp_settime() failed: %d\n", errno);
  1304. }
  1305. }
  1306. else
  1307. {
  1308. #ifdef ESP_PTP
  1309. ptp_lock_local_clock_freq(state, remote_timestamp, local_timestamp);
  1310. #else
  1311. /* Track drift rate based on two consecutive measurements and
  1312. * the adjustment that was made previously.
  1313. */
  1314. int64_t drift_ppb;
  1315. struct timespec interval;
  1316. int interval_ms;
  1317. int max_avg_period_ms;
  1318. int64_t adjustment_ns;
  1319. clock_timespec_subtract(local_timestamp,
  1320. &state->last_delta_timestamp,
  1321. &interval);
  1322. interval_ms = timespec_to_ms(&interval);
  1323. if (interval_ms > 0 && interval_ms < CONFIG_NETUTILS_PTPD_TIMEOUT_MS)
  1324. {
  1325. drift_ppb = (delta_ns - state->last_delta_ns) * MSEC_PER_SEC
  1326. / interval_ms;
  1327. }
  1328. else
  1329. {
  1330. ptpwarn("Measurement interval out of range: %d ms\n", interval_ms);
  1331. drift_ppb = 0;
  1332. interval_ms = 1;
  1333. }
  1334. /* Account for the adjustment previously made */
  1335. drift_ppb += state->last_adjtime_ns * MSEC_PER_SEC
  1336. / CONFIG_CLOCK_ADJTIME_PERIOD_MS;
  1337. if (drift_ppb > CONFIG_CLOCK_ADJTIME_SLEWLIMIT_PPM * 1000 ||
  1338. drift_ppb < -CONFIG_CLOCK_ADJTIME_SLEWLIMIT_PPM * 1000)
  1339. {
  1340. ptpwarn("Drift estimate out of range: %lld\n",
  1341. (long long)drift_ppb);
  1342. drift_ppb = state->drift_ppb;
  1343. }
  1344. /* Take direct average of drift estimate for first measurements,
  1345. * after that update the exponential sliding average.
  1346. * Measurements are weighted according to the interval, because
  1347. * drift estimate is more accurate over longer timespan.
  1348. */
  1349. state->drift_avg_total_ms += interval_ms;
  1350. max_avg_period_ms = CONFIG_NETUTILS_PTPD_DRIFT_AVERAGE_S
  1351. * MSEC_PER_SEC;
  1352. if (state->drift_avg_total_ms > max_avg_period_ms)
  1353. {
  1354. state->drift_avg_total_ms = max_avg_period_ms;
  1355. }
  1356. state->drift_ppb += (drift_ppb - state->drift_ppb) * interval_ms
  1357. / state->drift_avg_total_ms;
  1358. /* Compute the value we need to give to adjtime() to match the
  1359. * drift rate.
  1360. */
  1361. adjustment_ns = state->drift_ppb * CONFIG_CLOCK_ADJTIME_PERIOD_MS
  1362. / MSEC_PER_SEC;
  1363. /* Drift estimation ensures local clock runs at same rate as remote.
  1364. *
  1365. * Adding the current clock offset to adjustment brings the clocks
  1366. * to match. To avoid individual outliers from causing jitter, we
  1367. * take the larger signed value of two previous deltas. This is based
  1368. * on the logic that packets can get delayed in transit, but do not
  1369. * travel backwards in time.
  1370. *
  1371. * Clock offset is applied over ADJTIME_PERIOD. If there is significant
  1372. * noise in measurements, increasing ADJTIME_PERIOD will reduce its
  1373. * effect on the local clock run rate.
  1374. */
  1375. if (state->last_delta_ns > delta_ns)
  1376. {
  1377. adjustment_ns += state->last_delta_ns;
  1378. }
  1379. else
  1380. {
  1381. adjustment_ns += delta_ns;
  1382. }
  1383. /* Apply adjustment and store information for next time */
  1384. state->last_delta_ns = delta_ns;
  1385. state->last_delta_timestamp = *local_timestamp;
  1386. state->last_adjtime_ns = adjustment_ns;
  1387. ESP_LOGD(TAG, "Delta: %+lld ns, adjustment %+lld ns, drift rate %+lld ppb",
  1388. (long long)delta_ns,
  1389. (long long)state->last_adjtime_ns,
  1390. (long long)state->drift_ppb);
  1391. ret = ptp_adjtime(state, adjustment_ns);
  1392. if (ret != OK)
  1393. {
  1394. ptperr("ptp_adjtime() failed: %d\n", errno);
  1395. }
  1396. /* Check if clock is stable enough for sending delay requests */
  1397. if (absdelta_ns < CONFIG_NETUTILS_PTPD_MAX_PATH_DELAY_NS)
  1398. {
  1399. state->can_send_delayreq = true;
  1400. }
  1401. #endif // ESP_PTP
  1402. }
  1403. return ret;
  1404. }
  1405. /* Process received PTP sync packet */
  1406. static int ptp_process_sync(FAR struct ptp_state_s *state,
  1407. FAR struct ptp_sync_s *msg)
  1408. {
  1409. struct timespec remote_time;
  1410. if (memcmp(msg->header.sourceidentity,
  1411. state->selected_source.header.sourceidentity,
  1412. sizeof(msg->header.sourceidentity)) != 0)
  1413. {
  1414. /* This packet wasn't from the currently selected source */
  1415. #ifdef ESP_PTP
  1416. ESP_LOGD(TAG, "This packet wasn't from the currently selected source");
  1417. #endif // ESP_PTP
  1418. return OK;
  1419. }
  1420. /* Update timeout tracking */
  1421. clock_gettime(CLOCK_MONOTONIC, &state->last_received_sync);
  1422. if (msg->header.flags[0] & PTP_FLAGS0_TWOSTEP)
  1423. {
  1424. /* We need to wait for a follow-up packet before setting the clock. */
  1425. state->twostep_rxtime = state->rxtime;
  1426. state->twostep_packet = *msg;
  1427. ESP_LOGD(TAG, "Waiting for follow-up");
  1428. return OK;
  1429. }
  1430. /* Update local clock */
  1431. ptp_format_to_timespec(msg->origintimestamp, &remote_time);
  1432. return ptp_update_local_clock(state, &remote_time, &state->rxtime);
  1433. }
  1434. static int ptp_process_followup(FAR struct ptp_state_s *state,
  1435. FAR struct ptp_follow_up_s *msg)
  1436. {
  1437. struct timespec remote_time;
  1438. if (memcmp(msg->header.sourceidentity,
  1439. state->twostep_packet.header.sourceidentity,
  1440. sizeof(msg->header.sourceidentity)) != 0)
  1441. {
  1442. return OK; /* This packet wasn't from the currently selected source */
  1443. }
  1444. if (ptp_get_sequence(&msg->header)
  1445. != ptp_get_sequence(&state->twostep_packet.header))
  1446. {
  1447. ptpwarn("PTP follow-up packet sequence %ld does not match initial "
  1448. "sync packet sequence %ld, ignoring\n",
  1449. (long)ptp_get_sequence(&msg->header),
  1450. (long)ptp_get_sequence(&state->twostep_packet.header));
  1451. return OK;
  1452. }
  1453. /* Update local clock based on the remote timestamp we received now
  1454. * and the local timestamp of when the sync packet was received.
  1455. */
  1456. ptp_format_to_timespec(msg->origintimestamp, &remote_time);
  1457. return ptp_update_local_clock(state, &remote_time, &state->twostep_rxtime);
  1458. }
  1459. static int ptp_process_delay_req(FAR struct ptp_state_s *state,
  1460. FAR struct ptp_delay_req_s *msg)
  1461. {
  1462. struct ptp_delay_resp_s resp;
  1463. #ifndef ESP_PTP
  1464. struct sockaddr_in addr;
  1465. #endif // !ESP_PTP
  1466. int ret;
  1467. if (state->selected_source_valid)
  1468. {
  1469. /* We are operating as a client, ignore delay requests */
  1470. return OK;
  1471. }
  1472. #ifndef ESP_PTP
  1473. addr.sin_family = AF_INET;
  1474. addr.sin_addr.s_addr = htonl(PTP_MULTICAST_ADDR);
  1475. addr.sin_port = htons(PTP_UDP_PORT_INFO);
  1476. #endif // !ESP_PTP
  1477. memset(&resp, 0, sizeof(resp));
  1478. resp.header = state->own_identity.header;
  1479. resp.header.messagetype = PTP_MSGTYPE_DELAY_RESP;
  1480. resp.header.messagelength[1] = sizeof(resp);
  1481. timespec_to_ptp_format(&state->rxtime, resp.receivetimestamp);
  1482. memcpy(resp.reqidentity, msg->header.sourceidentity,
  1483. sizeof(resp.reqidentity));
  1484. memcpy(resp.reqportindex, msg->header.sourceportindex,
  1485. sizeof(resp.reqportindex));
  1486. memcpy(resp.header.sequenceid, msg->header.sequenceid,
  1487. sizeof(resp.header.sequenceid));
  1488. resp.header.logmessageinterval = CONFIG_NETUTILS_PTPD_DELAYRESP_INTERVAL;
  1489. #ifdef ESP_PTP
  1490. ret = ptp_net_send(state, &resp, sizeof(resp), NULL);
  1491. /* Also send delay_resp via UDP */
  1492. {
  1493. struct sockaddr_in udp_addr;
  1494. udp_addr.sin_family = AF_INET;
  1495. udp_addr.sin_addr.s_addr = htonl(PTP_MULTICAST_ADDR);
  1496. udp_addr.sin_port = htons(PTP_UDP_PORT_INFO);
  1497. sendto(state->tx_socket, &resp, sizeof(resp), 0,
  1498. (struct sockaddr *)&udp_addr, sizeof(udp_addr));
  1499. }
  1500. #else
  1501. ret = sendto(state->tx_socket, &resp, sizeof(resp), 0,
  1502. (FAR struct sockaddr *)&addr, sizeof(addr));
  1503. #endif // ESP_PTP
  1504. if (ret < 0)
  1505. {
  1506. ptperr("sendto failed: %d", errno);
  1507. }
  1508. else
  1509. {
  1510. clock_gettime(CLOCK_MONOTONIC, &state->last_transmitted_delayresp);
  1511. ESP_LOGD(TAG, "Sent delay resp, seq %ld",
  1512. (long)ptp_get_sequence(&msg->header));
  1513. }
  1514. return ret;
  1515. }
  1516. static int ptp_process_delay_resp(FAR struct ptp_state_s *state,
  1517. FAR struct ptp_delay_resp_s *msg)
  1518. {
  1519. int64_t path_delay;
  1520. int64_t sync_delay;
  1521. struct timespec remote_rxtime;
  1522. uint16_t sequence;
  1523. int interval;
  1524. if (!state->selected_source_valid ||
  1525. memcmp(msg->header.sourceidentity,
  1526. state->selected_source.header.sourceidentity,
  1527. sizeof(msg->header.sourceidentity)) != 0 ||
  1528. memcmp(msg->reqidentity,
  1529. state->own_identity.header.sourceidentity,
  1530. sizeof(msg->reqidentity)) != 0)
  1531. {
  1532. return OK; /* This packet wasn't for us */
  1533. }
  1534. sequence = ptp_get_sequence(&msg->header);
  1535. if (sequence != state->delay_req_seq)
  1536. {
  1537. ptpwarn("Ignoring out-of-sequence delay resp (%d vs. expected %d)\n",
  1538. (int)sequence, (int)state->delay_req_seq);
  1539. return OK;
  1540. }
  1541. /* Path delay is calculated as the average between delta for sync
  1542. * message and delta for delay req message.
  1543. * (IEEE-1588 section 11.3: Delay request-response mechanism)
  1544. */
  1545. ptp_format_to_timespec(msg->receivetimestamp, &remote_rxtime);
  1546. path_delay = timespec_delta_ns(&remote_rxtime, &state->delayreq_time);
  1547. sync_delay = state->path_delay_ns - state->last_delta_ns;
  1548. path_delay = (path_delay + sync_delay) / 2;
  1549. if (path_delay >= 0 && path_delay < CONFIG_NETUTILS_PTPD_MAX_PATH_DELAY_NS)
  1550. {
  1551. if (state->path_delay_avgcount <
  1552. CONFIG_NETUTILS_PTPD_DELAYREQ_AVGCOUNT)
  1553. {
  1554. state->path_delay_avgcount++;
  1555. }
  1556. state->path_delay_ns += (path_delay - state->path_delay_ns)
  1557. / state->path_delay_avgcount;
  1558. ESP_LOGD(TAG, "Path delay: %ld ns (avg: %ld ns)",
  1559. (long)path_delay, (long)state->path_delay_ns);
  1560. }
  1561. else
  1562. {
  1563. ESP_LOGD(TAG, "Path delay out of range: %lld ns",
  1564. (long long)path_delay);
  1565. }
  1566. /* Calculate interval until next packet */
  1567. if (msg->header.logmessageinterval <= 12)
  1568. {
  1569. interval = (1 << msg->header.logmessageinterval);
  1570. }
  1571. else
  1572. {
  1573. interval = 4096; /* Refuse to obey excessively long intervals */
  1574. }
  1575. /* Randomize up to 2x nominal delay) */
  1576. state->delayreq_interval = interval + (random() % interval);
  1577. return OK;
  1578. }
  1579. /* Determine received packet type and process it */
  1580. static int ptp_process_rx_packet(FAR struct ptp_state_s *state,
  1581. ssize_t length)
  1582. {
  1583. if (length < sizeof(struct ptp_header_s))
  1584. {
  1585. ptpwarn("Ignoring invalid PTP packet, length only %d bytes\n",
  1586. (int)length);
  1587. return OK;
  1588. }
  1589. if (state->rxbuf.header.domain != CONFIG_NETUTILS_PTPD_DOMAIN)
  1590. {
  1591. /* Part of different clock domain, ignore */
  1592. return OK;
  1593. }
  1594. clock_gettime(CLOCK_MONOTONIC, &state->last_received_multicast);
  1595. switch (state->rxbuf.header.messagetype & PTP_MSGTYPE_MASK)
  1596. {
  1597. #ifdef CONFIG_NETUTILS_PTPD_CLIENT
  1598. case PTP_MSGTYPE_ANNOUNCE:
  1599. ESP_LOGD(TAG, "Got announce packet, seq %ld",
  1600. (long)ptp_get_sequence(&state->rxbuf.header));
  1601. return ptp_process_announce(state, &state->rxbuf.announce);
  1602. case PTP_MSGTYPE_SYNC:
  1603. ESP_LOGD(TAG, "Got sync packet, seq %ld",
  1604. (long)ptp_get_sequence(&state->rxbuf.header));
  1605. return ptp_process_sync(state, &state->rxbuf.sync);
  1606. case PTP_MSGTYPE_FOLLOW_UP:
  1607. ESP_LOGD(TAG, "Got follow-up packet, seq %ld",
  1608. (long)ptp_get_sequence(&state->rxbuf.header));
  1609. return ptp_process_followup(state, &state->rxbuf.follow_up);
  1610. case PTP_MSGTYPE_DELAY_RESP:
  1611. ESP_LOGD(TAG, "Got delay-resp, seq %ld",
  1612. (long)ptp_get_sequence(&state->rxbuf.header));
  1613. return ptp_process_delay_resp(state, &state->rxbuf.delay_resp);
  1614. #endif
  1615. #ifdef CONFIG_NETUTILS_PTPD_SERVER
  1616. case PTP_MSGTYPE_DELAY_REQ:
  1617. ESP_LOGD(TAG, "Got delay req, seq %ld",
  1618. (long)ptp_get_sequence(&state->rxbuf.header));
  1619. return ptp_process_delay_req(state, &state->rxbuf.delay_req);
  1620. #endif
  1621. default:
  1622. ptpinfo("Ignoring unknown PTP packet type: 0x%02x\n",
  1623. state->rxbuf.header.messagetype);
  1624. return OK;
  1625. }
  1626. }
  1627. /* Signal handler for status / stop requests */
  1628. #ifndef ESP_PTP
  1629. static void ptp_signal_handler(int signo, FAR siginfo_t *siginfo,
  1630. FAR void *context)
  1631. {
  1632. FAR struct ptp_state_s *state = (FAR struct ptp_state_s *)siginfo->si_user;
  1633. if (signo == SIGHUP)
  1634. {
  1635. state->stop = true;
  1636. }
  1637. else if (signo == SIGUSR1 && siginfo->si_value.sival_ptr)
  1638. {
  1639. state->status_req =
  1640. *(FAR struct ptpd_statusreq_s *)siginfo->si_value.sival_ptr;
  1641. }
  1642. }
  1643. static void ptp_setup_sighandlers(FAR struct ptp_state_s *state)
  1644. {
  1645. struct sigaction act;
  1646. act.sa_sigaction = ptp_signal_handler;
  1647. sigfillset(&act.sa_mask);
  1648. act.sa_flags = SA_SIGINFO;
  1649. act.sa_user = state;
  1650. sigaction(SIGHUP, &act, NULL);
  1651. sigaction(SIGUSR1, &act, NULL);
  1652. }
  1653. #endif // !ESP_PTP
  1654. /* Process status information request */
  1655. static void ptp_process_statusreq(FAR struct ptp_state_s *state)
  1656. {
  1657. FAR struct ptpd_status_s *status;
  1658. if (!state->status_req.dest)
  1659. {
  1660. return; /* No active request */
  1661. }
  1662. status = state->status_req.dest;
  1663. status->clock_source_valid = state->selected_source_valid;
  1664. if (status->clock_source_valid)
  1665. {
  1666. /* Copy relevant parts of announce info to status struct */
  1667. FAR struct ptp_announce_s *s = &state->selected_source;
  1668. memcpy(status->clock_source_info.id,
  1669. s->header.sourceidentity,
  1670. sizeof(status->clock_source_info.id));
  1671. status->clock_source_info.utcoffset =
  1672. (int16_t)(((uint16_t)s->utcoffset[0] << 8) | s->utcoffset[1]);
  1673. status->clock_source_info.priority1 = s->gm_priority1;
  1674. status->clock_source_info.clockclass = s->gm_quality[0];
  1675. status->clock_source_info.accuracy = s->gm_quality[1];
  1676. status->clock_source_info.priority2 = s->gm_priority2;
  1677. status->clock_source_info.variance =
  1678. ((uint16_t)s->gm_quality[2] << 8) | s->gm_quality[3];
  1679. memcpy(status->clock_source_info.gm_id,
  1680. s->gm_identity,
  1681. sizeof(status->clock_source_info.gm_id));
  1682. status->clock_source_info.stepsremoved =
  1683. ((uint16_t)s->stepsremoved[0] << 8) | s->stepsremoved[1];
  1684. status->clock_source_info.timesource = s->timesource;
  1685. }
  1686. /* Copy latest adjustment info */
  1687. status->last_clock_update = state->last_delta_timestamp;
  1688. status->last_delta_ns = state->last_delta_ns;
  1689. status->last_adjtime_ns = state->last_adjtime_ns;
  1690. status->drift_ppb = state->drift_ppb;
  1691. status->path_delay_ns = state->path_delay_ns;
  1692. /* Copy timestamps */
  1693. status->last_received_multicast = state->last_received_multicast;
  1694. status->last_received_announce = state->last_received_announce;
  1695. status->last_received_sync = state->last_received_sync;
  1696. status->last_transmitted_sync = state->last_transmitted_sync;
  1697. status->last_transmitted_announce = state->last_transmitted_announce;
  1698. status->last_transmitted_delayresp = state->last_transmitted_delayresp;
  1699. status->last_transmitted_delayreq = state->last_transmitted_delayreq;
  1700. /* Post semaphore to inform that we are done */
  1701. if (state->status_req.done)
  1702. {
  1703. sem_post(state->status_req.done);
  1704. }
  1705. state->status_req.done = NULL;
  1706. state->status_req.dest = NULL;
  1707. }
  1708. /* Main PTPD task */
  1709. #ifdef ESP_PTP
  1710. static void ptp_daemon(void *task_param)
  1711. #else
  1712. static int ptp_daemon(int argc, FAR char** argv)
  1713. #endif // ESP_PTP
  1714. {
  1715. FAR const char *interface = "eth0";
  1716. FAR struct ptp_state_s *state;
  1717. #ifdef ESP_PTP
  1718. struct pollfd pollfds[3]; /* L2 TAP + UDP event (319) + UDP info (320) */
  1719. #else
  1720. struct pollfd pollfds[2];
  1721. struct msghdr rxhdr;
  1722. struct iovec rxiov;
  1723. #endif // ESP_PTP
  1724. int ret;
  1725. #ifndef ESP_PTP
  1726. memset(&rxhdr, 0, sizeof(rxhdr));
  1727. memset(&rxiov, 0, sizeof(rxiov));
  1728. #endif // !ESP_PTP
  1729. state = calloc(1, sizeof(struct ptp_state_s));
  1730. #ifdef ESP_PTP
  1731. if (task_param != NULL)
  1732. {
  1733. interface = task_param;
  1734. }
  1735. #else
  1736. if (argc > 1)
  1737. {
  1738. interface = argv[1];
  1739. }
  1740. #endif // ESP_PTP
  1741. if (ptp_initialize_state(state, interface) != OK)
  1742. {
  1743. ptperr("Failed to initialize PTP state, exiting\n");
  1744. ptp_destroy_state(state);
  1745. free(state);
  1746. #ifdef ESP_PTP
  1747. goto err;
  1748. #else
  1749. return ERROR;
  1750. #endif // ESP_PTP
  1751. }
  1752. #ifndef ESP_PTP
  1753. ptp_setup_sighandlers(state);
  1754. #endif // !ESP_PTP
  1755. pollfds[0].events = POLLIN;
  1756. #ifdef ESP_PTP
  1757. /* Poll L2 TAP (for HW timestamps) and UDP event socket (for
  1758. * interoperability with devices that send PTP over UDP/IPv4).
  1759. * The info socket (port 320) is also polled for announce and
  1760. * follow-up messages. */
  1761. pollfds[0].fd = state->ptp_socket;
  1762. pollfds[1].events = POLLIN;
  1763. pollfds[1].fd = state->event_socket;
  1764. pollfds[2].events = POLLIN;
  1765. pollfds[2].fd = state->info_socket;
  1766. #else
  1767. pollfds[0].fd = state->event_socket;
  1768. pollfds[1].events = POLLIN;
  1769. pollfds[1].fd = state->info_socket;
  1770. #endif // ESP_PTP
  1771. while (!state->stop)
  1772. {
  1773. state->can_send_delayreq = false;
  1774. #ifndef ESP_PTP
  1775. rxhdr.msg_name = NULL;
  1776. rxhdr.msg_namelen = 0;
  1777. rxhdr.msg_iov = &rxiov;
  1778. rxhdr.msg_iovlen = 1;
  1779. rxhdr.msg_control = &state->rxcmsg;
  1780. rxhdr.msg_controllen = sizeof(state->rxcmsg);
  1781. rxhdr.msg_flags = 0;
  1782. rxiov.iov_base = &state->rxbuf;
  1783. rxiov.iov_len = sizeof(state->rxbuf);
  1784. #endif // !ESP_PTP
  1785. pollfds[0].revents = 0;
  1786. pollfds[1].revents = 0;
  1787. #ifdef ESP_PTP
  1788. pollfds[2].revents = 0;
  1789. ret = poll(pollfds, 3, PTPD_POLL_INTERVAL);
  1790. #else
  1791. ret = poll(pollfds, 2, PTPD_POLL_INTERVAL);
  1792. #endif
  1793. if (pollfds[0].revents)
  1794. {
  1795. /* Receive time-critical packet, potentially with cmsg
  1796. * indicating the timestamp.
  1797. */
  1798. #ifdef ESP_PTP
  1799. ret = ptp_net_recv(state, &state->rxbuf, sizeof(state->rxbuf), &state->rxtime);
  1800. #else
  1801. ret = recvmsg(state->event_socket, &rxhdr, MSG_DONTWAIT);
  1802. #endif // ESP_PTP
  1803. if (ret > 0)
  1804. {
  1805. #ifndef ESP_PTP
  1806. ptp_getrxtime(state, &rxhdr, &state->rxtime);
  1807. #endif
  1808. ptp_process_rx_packet(state, ret);
  1809. }
  1810. }
  1811. #ifdef ESP_PTP
  1812. if (pollfds[1].revents)
  1813. {
  1814. /* Receive PTP packet from UDP event socket (port 319:
  1815. * sync, delay_req - time-critical). */
  1816. ret = recv(state->event_socket, &state->rxbuf, sizeof(state->rxbuf),
  1817. MSG_DONTWAIT);
  1818. if (ret > 0)
  1819. {
  1820. ptp_gettime(state, &state->rxtime);
  1821. ptp_process_rx_packet(state, ret);
  1822. }
  1823. }
  1824. if (pollfds[2].revents)
  1825. {
  1826. /* Receive PTP packet from UDP info socket (port 320:
  1827. * announce, follow_up, delay_resp - non-time-critical). */
  1828. ret = recv(state->info_socket, &state->rxbuf, sizeof(state->rxbuf),
  1829. MSG_DONTWAIT);
  1830. if (ret > 0)
  1831. {
  1832. ptp_gettime(state, &state->rxtime);
  1833. ptp_process_rx_packet(state, ret);
  1834. }
  1835. }
  1836. #else
  1837. if (pollfds[1].revents)
  1838. {
  1839. /* Receive non-time-critical packet. */
  1840. ret = recv(state->info_socket, &state->rxbuf, sizeof(state->rxbuf),
  1841. MSG_DONTWAIT);
  1842. if (ret > 0)
  1843. {
  1844. ptp_process_rx_packet(state, ret);
  1845. }
  1846. }
  1847. if (pollfds[0].revents == 0 && pollfds[1].revents == 0)
  1848. {
  1849. /* No packets received, check for multicast timeout */
  1850. ptp_check_multicast_status(state);
  1851. }
  1852. #endif // !ESP_PTP
  1853. ptp_periodic_send(state);
  1854. state->selected_source_valid = is_selected_source_valid(state);
  1855. ptp_process_statusreq(state);
  1856. #ifdef ESP_PTP
  1857. /* Yield to lower-priority tasks (IDLE watchdog) after each iteration.
  1858. * poll() may return immediately if the L2 TAP socket has pending events,
  1859. * which would otherwise starve the IDLE task and trigger the watchdog. */
  1860. vTaskDelay(1);
  1861. #endif
  1862. }
  1863. ptp_destroy_state(state);
  1864. free(state);
  1865. #ifdef ESP_PTP
  1866. err:
  1867. s_state = NULL;
  1868. vTaskDelete(NULL);
  1869. #else
  1870. return 0;
  1871. #endif // ESP_PTP
  1872. }
  1873. /****************************************************************************
  1874. * Public Functions
  1875. ****************************************************************************/
  1876. /****************************************************************************
  1877. * Name: ptpd_start
  1878. *
  1879. * Description:
  1880. * Start the PTP daemon and bind it to specified interface.
  1881. *
  1882. * Input Parameters:
  1883. * interface - Name of the network interface to bind to, e.g. "eth0"
  1884. *
  1885. * Returned Value:
  1886. * On success, the non-negative task ID of the PTP daemon is returned;
  1887. * On failure, a negated errno value is returned.
  1888. *
  1889. ****************************************************************************/
  1890. int ptpd_start(FAR const char *interface)
  1891. {
  1892. #ifdef ESP_PTP
  1893. if (s_state == NULL) {
  1894. xTaskCreate(ptp_daemon, "PTPD", CONFIG_NETUTILS_PTPD_STACKSIZE,
  1895. (void *)interface, tskIDLE_PRIORITY + 2, NULL);
  1896. return 1;
  1897. }
  1898. ESP_LOGE(TAG, "Other instance of PTP is already running");
  1899. return -1;
  1900. #else
  1901. int pid;
  1902. FAR char *task_argv[] = {
  1903. (FAR char *)interface,
  1904. NULL
  1905. };
  1906. pid = task_create("PTPD", CONFIG_NETUTILS_PTPD_SERVERPRIO,
  1907. CONFIG_NETUTILS_PTPD_STACKSIZE, ptp_daemon, task_argv);
  1908. /* Use kill with signal 0 to check if the process is still alive
  1909. * after initialization.
  1910. */
  1911. usleep(USEC_PER_TICK);
  1912. if (kill(pid, 0) != OK)
  1913. {
  1914. return ERROR;
  1915. }
  1916. else
  1917. {
  1918. return pid;
  1919. }
  1920. #endif // ESP_PTP
  1921. }
  1922. /****************************************************************************
  1923. * Name: ptpd_status
  1924. *
  1925. * Description:
  1926. * Query status from a running PTP daemon.
  1927. *
  1928. * Input Parameters:
  1929. * pid - Process ID previously returned by ptpd_start()
  1930. * status - Pointer to storage for status information.
  1931. *
  1932. * Returned Value:
  1933. * On success, returns OK.
  1934. * On failure, a negated errno value is returned.
  1935. *
  1936. * Assumptions/Limitations:
  1937. * Multiple threads with priority less than CONFIG_NETUTILS_PTPD_SERVERPRIO
  1938. * can request status simultaneously. If higher priority threads request
  1939. * status simultaneously, some of the requests may timeout.
  1940. *
  1941. ****************************************************************************/
  1942. int ptpd_status(int pid, FAR struct ptpd_status_s *status)
  1943. {
  1944. #ifdef ESP_PTP
  1945. int ret = 0;
  1946. sem_t donesem;
  1947. struct ptpd_statusreq_s req;
  1948. struct timespec timeout;
  1949. /* Fill in the status request */
  1950. memset(status, 0, sizeof(struct ptpd_status_s));
  1951. sem_init(&donesem, 0, 0);
  1952. req.done = &donesem;
  1953. req.dest = status;
  1954. s_state->status_req = req;
  1955. /* Wait for status request to be handled */
  1956. clock_gettime(CLOCK_REALTIME, &timeout); // sem_timedwait uses CLOCK_REALTIME
  1957. timeout.tv_sec += 1;
  1958. if (sem_timedwait(&donesem, &timeout) != 0)
  1959. {
  1960. req.done = NULL;
  1961. req.dest = NULL;
  1962. s_state->status_req = req;
  1963. ret = -errno;
  1964. }
  1965. sem_destroy(&donesem);
  1966. return ret;
  1967. #endif
  1968. #ifndef CONFIG_BUILD_FLAT
  1969. /* TODO: Use SHM memory to pass the status information if processes
  1970. * do not share the same memory space.
  1971. */
  1972. return -ENOTSUP;
  1973. #else
  1974. int ret = OK;
  1975. sem_t donesem;
  1976. struct ptpd_statusreq_s req;
  1977. union sigval val;
  1978. struct timespec timeout;
  1979. /* Fill in the status request */
  1980. memset(status, 0, sizeof(struct ptpd_status_s));
  1981. sem_init(&donesem, 0, 0);
  1982. req.done = &donesem;
  1983. req.dest = status;
  1984. val.sival_ptr = &req;
  1985. if (sigqueue(pid, SIGUSR1, val) != OK)
  1986. {
  1987. return -errno;
  1988. }
  1989. /* Wait for status request to be handled */
  1990. clock_gettime(CLOCK_MONOTONIC, &timeout);
  1991. timeout.tv_sec += 1;
  1992. if (sem_clockwait(&donesem, CLOCK_MONOTONIC, &timeout) != 0)
  1993. {
  1994. ret = -errno;
  1995. }
  1996. return ret;
  1997. #endif /* CONFIG_BUILD_FLAT */
  1998. }
  1999. /****************************************************************************
  2000. * Name: ptpd_stop
  2001. *
  2002. * Description:
  2003. * Stop PTP daemon
  2004. *
  2005. * Input Parameters:
  2006. * pid - Process ID previously returned by ptpd_start()
  2007. *
  2008. * Returned Value:
  2009. * On success, returns OK.
  2010. * On failure, a negated errno value is returned.
  2011. *
  2012. ****************************************************************************/
  2013. int ptpd_stop(int pid)
  2014. {
  2015. #ifdef ESP_PTP
  2016. s_state->stop = true;
  2017. return OK;
  2018. #else
  2019. if (kill(pid, SIGHUP) == OK)
  2020. {
  2021. return OK;
  2022. }
  2023. else
  2024. {
  2025. return -errno;
  2026. }
  2027. #endif
  2028. }