ppsthread.c 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  1. /*
  2. * ppsthread.c - manage PPS watcher threads
  3. *
  4. * To enable KPPS, this file needs to be compiled with HAVE_SYS_TIMEPPS_H
  5. *
  6. * If you are not good at threads do not touch this file!
  7. * For example: errno is thread safe; strerror() is not.
  8. *
  9. * It helps to know that there are two PPS measurement methods in
  10. * play. One is defined by RFC2783 and typically implemented in the
  11. * kernel. It is available on FreeBSD, Linux, and NetBSD. In gpsd it
  12. * is referred to as KPPS. KPPS is accessed on Linux via /dev/ppsN
  13. * devices. On BSD it is accessed via the same device as the serial
  14. * port. This mechanism is preferred as it should provide the smallest
  15. * latency and jitter from control line transition to timestamp.
  16. *
  17. * The other mechanism is user-space PPS, which uses the (not
  18. * standardized) TIOCMIWAIT ioctl to wait for PPS transitions on
  19. * serial port control lines. It is implemented on Linux and OpenBSD.
  20. *
  21. * On Linux, RFC2783 PPS requires root permissions for initialization;
  22. * user-space PPS does not. User-space PPS loses some functionality
  23. * when not initialized as root. In gpsd, user-space PPS is referred
  24. * to as "plain PPS".
  25. *
  26. * On {Free,Net}BSD, RFC2783 PPS should only require access to the
  27. * serial port, but details have not yet been tested and documented
  28. * here.
  29. *
  30. * Note that for easy debugging all logging from this file is prefixed
  31. * with PPS or KPPS.
  32. *
  33. * To use the thread manager, you need to first fill in the
  34. * devicefd, devicename, and the four hook function members in the thread
  35. * context structure. The void *context member is available for your hook
  36. * functions to use; the thread-monitor code doesn't touch it.
  37. *
  38. * After this setup, you can call pps_thread_activate() and the
  39. * thread will launch. It is OK to do this before the device is open,
  40. * the thread will wait on that.
  41. *
  42. * WARNING! Loss of precision
  43. * UNIX time to nanoSec precision is 62 significant bits
  44. * UNIX time to nanoSec precision after 2038 is 63 bits
  45. * a double is only 53 significant bits.
  46. *
  47. * You cannot do PPS math with doubles
  48. *
  49. * This file is Copyright (c)2013-2019 by the GPSD project
  50. * SPDX-License-Identifier: BSD-2-clause
  51. */
  52. #include "gpsd_config.h" /* must be before all includes */
  53. #include <errno.h>
  54. #include <inttypes.h>
  55. #include <limits.h>
  56. #include <math.h>
  57. #include <pthread.h> /* pacifies OpenBSD's compiler */
  58. #include <stdbool.h>
  59. #include <stdio.h>
  60. #include <string.h>
  61. #include <sys/socket.h>
  62. #include <sys/time.h>
  63. #include <unistd.h>
  64. /* use RFC 2783 PPS API */
  65. /* this needs linux >= 2.6.34 and
  66. * CONFIG_PPS=y
  67. * CONFIG_PPS_DEBUG=y [optional to kernel log pulses]
  68. * CONFIG_PPS_CLIENT_LDISC=y
  69. *
  70. * Also beware that setting
  71. * CONFIG_PPS_CLIENT_KTIMER=y
  72. * adds a fake software-generated PPS intended for testing. This
  73. * doesn't even run at exactly 1Hz, so any attempt to use it for
  74. * real timing is disastrous. Hence we try to avoid it.
  75. */
  76. #define FAKE_PPS_NAME "ktimer"
  77. #if defined(HAVE_SYS_TIMEPPS_H)
  78. // include unistd.h here as it is missing on older pps-tools releases.
  79. // 'close' is not defined otherwise.
  80. #include <unistd.h>
  81. #include <sys/timepps.h>
  82. #endif
  83. #include "timespec.h"
  84. #include "ppsthread.h"
  85. #include "os_compat.h"
  86. /*
  87. * Tell GCC that we want thread-safe behavior with _REENTRANT;
  88. * in particular, errno must be thread-local.
  89. * Tell POSIX-conforming implementations with _POSIX_THREAD_SAFE_FUNCTIONS.
  90. * See http://www.unix.org/whitepapers/reentrant.html
  91. */
  92. #ifndef _REENTRANT
  93. #define _REENTRANT
  94. #endif
  95. #ifndef _POSIX_THREAD_SAFE_FUNCTIONS
  96. #define _POSIX_THREAD_SAFE_FUNCTIONS
  97. #endif
  98. /*
  99. * Warning: This is a potential portability problem.
  100. * It's needed so that TIOCMIWAIT will be defined and the plain PPS
  101. * code will work, but it's not a SuS/POSIX standard header. We're
  102. * going to include it unconditionally here because we expect both
  103. * Linux and BSD to have it and we want compilation to break with
  104. * an audible snapping sound if it's not present.
  105. */
  106. #include <sys/ioctl.h>
  107. #if defined(HAVE_SYS_TIMEPPS_H)
  108. #include <glob.h>
  109. #include <fcntl.h> /* needed for open() and friends */
  110. #endif
  111. #if defined(TIOCMIWAIT)
  112. static int get_edge_tiocmiwait( volatile struct pps_thread_t *,
  113. struct timespec *, int *,
  114. volatile struct timedelta_t *);
  115. #endif /* TIOCMIWAIT */
  116. struct inner_context_t {
  117. volatile struct pps_thread_t *pps_thread;
  118. bool pps_canwait; /* can RFC2783 wait? */
  119. #if defined(HAVE_SYS_TIMEPPS_H)
  120. int pps_caps; /* RFC2783 getcaps() */
  121. pps_handle_t kernelpps_handle;
  122. #endif /* defined(HAVE_SYS_TIMEPPS_H) */
  123. };
  124. #if defined(HAVE_SYS_TIMEPPS_H)
  125. static int get_edge_rfc2783(struct inner_context_t *,
  126. struct timespec *,
  127. int *,
  128. struct timespec *,
  129. int *,
  130. volatile struct timedelta_t *);
  131. #endif /* defined(HAVE_SYS_TIMEPPS_H) */
  132. static pthread_mutex_t ppslast_mutex = PTHREAD_MUTEX_INITIALIZER;
  133. /*
  134. * Version of strerror_r() which explicitly ignores the return value.
  135. * This is needed to avoid warnings from some overly pedantic compilers.
  136. * Unfortunately, the return type is platform-dependent, making it
  137. * impractical to actually use the return value.
  138. */
  139. static void pps_strerror_r(int errnum, char *buf, size_t len)
  140. {
  141. if (strerror_r(errnum, buf, len)) {
  142. return;
  143. } else {
  144. return;
  145. }
  146. }
  147. static void thread_lock(volatile struct pps_thread_t *pps_thread)
  148. {
  149. int pthread_err = pthread_mutex_lock(&ppslast_mutex);
  150. if ( 0 != pthread_err ) {
  151. char errbuf[BUFSIZ] = "unknown error";
  152. pps_strerror_r(errno, errbuf, sizeof(errbuf));
  153. pps_thread->log_hook(pps_thread, THREAD_ERROR,
  154. "PPS:%s pthread_mutex_lock() : %s\n",
  155. pps_thread->devicename, errbuf);
  156. }
  157. }
  158. static void thread_unlock(volatile struct pps_thread_t *pps_thread)
  159. {
  160. int pthread_err = pthread_mutex_unlock(&ppslast_mutex);
  161. if ( 0 != pthread_err ) {
  162. char errbuf[BUFSIZ] = "unknown error";
  163. pps_strerror_r(errno, errbuf, sizeof(errbuf));
  164. pps_thread->log_hook(pps_thread, THREAD_ERROR,
  165. "TPPS:%s pthread_mutex_unlock() : %s\n",
  166. pps_thread->devicename, errno, errbuf);
  167. }
  168. }
  169. #if defined(HAVE_SYS_TIMEPPS_H)
  170. #ifdef __linux__
  171. /* Obtain contents of specified sysfs variable; null string if failure */
  172. static void get_sysfs_var(const char *path, char *buf, size_t bufsize)
  173. {
  174. buf[0] = '\0';
  175. int fd = open(path, O_RDONLY);
  176. if ( 0 <= fd ) {
  177. ssize_t r = read( fd, buf, bufsize -1);
  178. if ( 0 < r ) {
  179. buf[r - 1] = '\0'; /* remove trailing \x0a */
  180. }
  181. (void)close(fd);
  182. }
  183. }
  184. /* Check to see whether the named PPS source is the fake one */
  185. int pps_check_fake(const char *name) {
  186. char path[PATH_MAX] = "";
  187. char buf[32] = "";
  188. snprintf(path, sizeof(path), "/sys/devices/virtual/pps/%s/name", name);
  189. get_sysfs_var(path, buf, sizeof(buf));
  190. return strcmp(buf, FAKE_PPS_NAME) == 0;
  191. }
  192. /* Get first "real" PPS device, skipping the fake, if any */
  193. char *pps_get_first(void)
  194. {
  195. if (pps_check_fake("pps0"))
  196. return "/dev/pps1";
  197. return "/dev/pps0";
  198. }
  199. #endif /* __linux__ */
  200. static int init_kernel_pps(struct inner_context_t *inner_context)
  201. /* return handle for kernel pps, or -1; requires root privileges */
  202. {
  203. pps_params_t pp;
  204. int ret;
  205. #ifdef __linux__
  206. /* These variables are only needed by Linux to find /dev/ppsN. */
  207. int ldisc = 18; /* the PPS line discipline */
  208. glob_t globbuf;
  209. #endif
  210. char path[PATH_MAX] = "";
  211. volatile struct pps_thread_t *pps_thread = inner_context->pps_thread;
  212. inner_context->kernelpps_handle = -1;
  213. inner_context->pps_canwait = false;
  214. /*
  215. * This next code block abuses "ret" by storing the filedescriptor
  216. * to use for RFC2783 calls.
  217. */
  218. #ifndef __clang_analyzer__
  219. ret = -1; /* this ret will not be unneeded when the 'else' part
  220. * of the followinng ifdef becomes an #elif */
  221. #endif /* __clang_analyzer__ */
  222. #ifdef __linux__
  223. /*
  224. * Some Linuxes, like the RasPi's, have PPS devices preexisting.
  225. * Other OS have no way to automatically determine the proper /dev/ppsX.
  226. * Allow user to pass in an explicit PPS device path.
  227. *
  228. * (We use strncpy() here because this might be compiled where
  229. * strlcpy() is not available.)
  230. */
  231. if (strncmp(pps_thread->devicename, "/dev/pps", 8) == 0) {
  232. if (pps_check_fake(pps_thread->devicename + 5))
  233. pps_thread->log_hook(pps_thread, THREAD_WARN,
  234. "KPPS:%s is fake PPS,"
  235. " timing will be inaccurate\n",
  236. pps_thread->devicename);
  237. (void)strncpy(path, pps_thread->devicename, sizeof(path)-1);
  238. }
  239. else {
  240. char pps_num = '\0'; /* /dev/pps[pps_num] is our device */
  241. size_t i; /* to match type of globbuf.gl_pathc */
  242. /*
  243. * Otherwise one must make calls to associate a serial port with a
  244. * /dev/ppsN device and then grovel in system data to determine
  245. * the association.
  246. */
  247. /* Attach the line PPS discipline, so no need to ldattach */
  248. /* This activates the magic /dev/pps0 device */
  249. /* Note: this ioctl() requires root, and device is a tty */
  250. if ( 0 > ioctl(pps_thread->devicefd, TIOCSETD, &ldisc)) {
  251. char errbuf[BUFSIZ] = "unknown error";
  252. pps_strerror_r(errno, errbuf, sizeof(errbuf));
  253. pps_thread->log_hook(pps_thread, THREAD_INF,
  254. "KPPS:%s cannot set PPS line discipline %s\n",
  255. pps_thread->devicename, errbuf);
  256. return -1;
  257. }
  258. /* uh, oh, magic file names!, RFC2783 neglects to specify how
  259. * to associate the serial device and pps device names */
  260. /* need to look in /sys/devices/virtual/pps/pps?/path
  261. * (/sys/class/pps/pps?/path is just a link to that)
  262. * to find the /dev/pps? that matches our serial port.
  263. * this code fails if there are more then 10 pps devices.
  264. *
  265. * yes, this could be done with libsysfs, but trying to keep
  266. * the number of required libs small, and libsysfs would still
  267. * be linux only */
  268. memset( (void *)&globbuf, 0, sizeof(globbuf));
  269. (void)glob("/sys/devices/virtual/pps/pps?/path", 0, NULL, &globbuf);
  270. memset( (void *)&path, 0, sizeof(path));
  271. for ( i = 0; i < globbuf.gl_pathc; i++ ) {
  272. get_sysfs_var(globbuf.gl_pathv[i], path, sizeof(path));
  273. pps_thread->log_hook(pps_thread, THREAD_PROG,
  274. "KPPS:%s checking %s, %s\n",
  275. pps_thread->devicename,
  276. globbuf.gl_pathv[i], path);
  277. if ( 0 == strncmp( path, pps_thread->devicename, sizeof(path))) {
  278. /* this is the pps we are looking for */
  279. /* FIXME, now build the proper pps device path */
  280. pps_num = globbuf.gl_pathv[i][28];
  281. break;
  282. }
  283. memset( (void *)&path, 0, sizeof(path));
  284. }
  285. /* done with blob, clear it */
  286. globfree(&globbuf);
  287. if ( 0 == (int)pps_num ) {
  288. pps_thread->log_hook(pps_thread, THREAD_INF,
  289. "KPPS:%s device not found.\n",
  290. pps_thread->devicename);
  291. return -1;
  292. }
  293. /* construct the magic device path */
  294. (void)snprintf(path, sizeof(path), "/dev/pps%c", pps_num);
  295. }
  296. /* root privs are probably required for this device open
  297. * do not bother to check uid, just go for the open() */
  298. ret = open(path, O_RDWR);
  299. if ( 0 > ret ) {
  300. char errbuf[BUFSIZ] = "unknown error";
  301. pps_strerror_r(errno, errbuf, sizeof(errbuf));
  302. pps_thread->log_hook(pps_thread, THREAD_INF,
  303. "KPPS:%s running as %d/%d, cannot open %s: %s\n",
  304. pps_thread->devicename,
  305. getuid(), geteuid(),
  306. path, errbuf);
  307. return -1;
  308. }
  309. #else /* not __linux__ */
  310. /*
  311. * On BSDs that support RFC2783, one uses the API calls on serial
  312. * port file descriptor.
  313. *
  314. * FIXME! need more specific than 'not linux'
  315. */
  316. (void)strlcpy(path, pps_thread->devicename, sizeof(path));
  317. // cppcheck-suppress redundantAssignment
  318. ret = pps_thread->devicefd;
  319. #endif
  320. /* assert(ret >= 0); */
  321. pps_thread->log_hook(pps_thread, THREAD_INF,
  322. "KPPS:%s RFC2783 path:%s, fd is %d\n",
  323. pps_thread->devicename, path,
  324. ret);
  325. /* RFC 2783 implies the time_pps_setcap() needs priviledges *
  326. * keep root a tad longer just in case */
  327. if ( 0 > time_pps_create(ret, (pps_handle_t *)&inner_context->kernelpps_handle )) {
  328. char errbuf[BUFSIZ] = "unknown error";
  329. pps_strerror_r(errno, errbuf, sizeof(errbuf));
  330. pps_thread->log_hook(pps_thread, THREAD_INF,
  331. "KPPS:%s time_pps_create(%d) failed: %s\n",
  332. pps_thread->devicename,
  333. ret, errbuf);
  334. return -1;
  335. }
  336. /* have kernel PPS handle */
  337. /* get RFC2783 features supported */
  338. inner_context->pps_caps = 0;
  339. if ( 0 > time_pps_getcap(inner_context->kernelpps_handle,
  340. &inner_context->pps_caps)) {
  341. char errbuf[BUFSIZ] = "unknown error";
  342. inner_context->pps_caps = 0;
  343. pps_strerror_r(errno, errbuf, sizeof(errbuf));
  344. pps_thread->log_hook(pps_thread, THREAD_INF,
  345. "KPPS:%s time_pps_getcap() failed: %.100s\n",
  346. pps_thread->devicename, errbuf);
  347. return -1;
  348. } else {
  349. pps_thread->log_hook(pps_thread, THREAD_INF,
  350. "KPPS:%s pps_caps 0x%02X\n",
  351. pps_thread->devicename,
  352. inner_context->pps_caps);
  353. }
  354. /* construct the setparms structure */
  355. memset( (void *)&pp, 0, sizeof(pps_params_t));
  356. pp.api_version = PPS_API_VERS_1; /* version 1 protocol */
  357. if ( 0 == (PPS_TSFMT_TSPEC & inner_context->pps_caps ) ) {
  358. /* PPS_TSFMT_TSPEC means return a timespec
  359. * mandatory for driver to implement, require it */
  360. pps_thread->log_hook(pps_thread, THREAD_WARN,
  361. "KPPS:%s fail, missing mandatory PPS_TSFMT_TSPEC\n",
  362. pps_thread->devicename);
  363. return -1;
  364. }
  365. if ( 0 != (PPS_CANWAIT & inner_context->pps_caps ) ) {
  366. /* we can wait! so no need for TIOCMIWAIT */
  367. pps_thread->log_hook(pps_thread, THREAD_INF,
  368. "KPPS:%s have PPS_CANWAIT\n",
  369. pps_thread->devicename);
  370. inner_context->pps_canwait = true;
  371. }
  372. pp.mode = PPS_TSFMT_TSPEC;
  373. switch ( (PPS_CAPTUREASSERT | PPS_CAPTURECLEAR) & inner_context->pps_caps ) {
  374. case PPS_CAPTUREASSERT:
  375. pps_thread->log_hook(pps_thread, THREAD_WARN,
  376. "KPPS:%s missing PPS_CAPTURECLEAR, pulse may be offset\n",
  377. pps_thread->devicename);
  378. pp.mode |= PPS_CAPTUREASSERT;
  379. break;
  380. case PPS_CAPTURECLEAR:
  381. pps_thread->log_hook(pps_thread, THREAD_WARN,
  382. "KPPS:%s missing PPS_CAPTUREASSERT, pulse may be offset\n",
  383. pps_thread->devicename);
  384. pp.mode |= PPS_CAPTURECLEAR;
  385. break;
  386. case PPS_CAPTUREASSERT | PPS_CAPTURECLEAR:
  387. pp.mode |= PPS_CAPTUREASSERT | PPS_CAPTURECLEAR;
  388. break;
  389. default:
  390. /* THREAD_ERR in the calling routine */
  391. pps_thread->log_hook(pps_thread, THREAD_INF,
  392. "KPPS:%s missing PPS_CAPTUREASSERT and CLEAR\n",
  393. pps_thread->devicename);
  394. return -1;
  395. }
  396. if ( 0 > time_pps_setparams(inner_context->kernelpps_handle, &pp)) {
  397. char errbuf[BUFSIZ] = "unknown error";
  398. pps_strerror_r(errno, errbuf, sizeof(errbuf));
  399. pps_thread->log_hook(pps_thread, THREAD_ERROR,
  400. "KPPS:%s time_pps_setparams(mode=0x%02X) failed: %s\n",
  401. pps_thread->devicename, pp.mode,
  402. errbuf);
  403. (void)time_pps_destroy(inner_context->kernelpps_handle);
  404. return -1;
  405. }
  406. return 0;
  407. }
  408. #endif /* defined(HAVE_SYS_TIMEPPS_H) */
  409. #if defined(TIOCMIWAIT)
  410. /* wait for, and get, an edge using TIOCMIWAIT
  411. * return -1 for error
  412. * 0 for OK
  413. */
  414. static int get_edge_tiocmiwait( volatile struct pps_thread_t *thread_context,
  415. struct timespec *clock_ts,
  416. int *state,
  417. volatile struct timedelta_t *last_fixtime)
  418. {
  419. char ts_str[TIMESPEC_LEN];
  420. /* we are lucky to have TIOCMIWAIT, so wait for next edge */
  421. #define PPS_LINE_TIOC (TIOCM_CD|TIOCM_RI|TIOCM_CTS|TIOCM_DSR)
  422. /*
  423. * DB9 DB25 Name Full name
  424. * --- ---- ---- --------------------
  425. * 3 2 TXD --> Transmit Data
  426. * 2 3 RXD <-- Receive Data
  427. * 7 4 RTS --> Request To Send
  428. * 8 5 CTS <-- Clear To Send
  429. * 6 6 DSR <-- Data Set Ready
  430. * 4 20 DTR --> Data Terminal Ready
  431. * 1 8 DCD <-- Data Carrier Detect
  432. * 9 22 RI <-- Ring Indicator
  433. * 5 7 GND Signal ground
  434. *
  435. * Wait for status change on any handshake line. Just one edge,
  436. * we do not want to be spinning waiting for the trailing edge of
  437. * a pulse. The only assumption here is that no GPS lights up more
  438. * than one of these pins. By waiting on all of them we remove a
  439. * configuration switch.
  440. *
  441. * Note that it only makes sense to wait on handshake lines
  442. * activated from the receive side (DCE->DTE) here; in this
  443. * context "DCE" is the GPS. {CD,RI,CTS,DSR} is the
  444. * entire set of these.
  445. *
  446. */
  447. if (ioctl(thread_context->devicefd, TIOCMIWAIT, PPS_LINE_TIOC) != 0) {
  448. char errbuf[BUFSIZ] = "unknown error";
  449. pps_strerror_r(errno, errbuf, sizeof(errbuf));
  450. thread_context->log_hook(thread_context, THREAD_WARN,
  451. "TPPS:%s ioctl(TIOCMIWAIT) failed: %d %.40s\n",
  452. thread_context->devicename, errno, errbuf);
  453. return -1;;
  454. }
  455. /*
  456. * Start of time critical section
  457. * Only error reporting, not success reporting in critical section
  458. */
  459. /* duplicate copy in get_edge_rfc2783 */
  460. /* quick, grab a copy of last_fixtime before it changes */
  461. thread_lock(thread_context);
  462. *last_fixtime = thread_context->fix_in;
  463. thread_unlock(thread_context);
  464. /* end duplicate copy in get_edge_rfc2783 */
  465. /* get the time after we just woke up */
  466. if ( 0 > clock_gettime(CLOCK_REALTIME, clock_ts) ) {
  467. /* uh, oh, can not get time! */
  468. char errbuf[BUFSIZ] = "unknown error";
  469. pps_strerror_r(errno, errbuf, sizeof(errbuf));
  470. thread_context->log_hook(thread_context, THREAD_ERROR,
  471. "TPPS:%s clock_gettime() failed: %.100s\n",
  472. thread_context->devicename, errbuf);
  473. return -1;;
  474. }
  475. /* got the edge, got the time just after the edge, now quickly
  476. * get the edge state */
  477. if (ioctl(thread_context->devicefd, (unsigned long)TIOCMGET, state) != 0) {
  478. char errbuf[BUFSIZ] = "unknown error";
  479. pps_strerror_r(errno, errbuf, sizeof(errbuf));
  480. thread_context->log_hook(thread_context, THREAD_ERROR,
  481. "TPPS:%s ioctl(TIOCMGET) failed: %.100s\n",
  482. thread_context->devicename, errbuf);
  483. return -1;
  484. }
  485. /* end of time critical section */
  486. /* mask for monitored lines */
  487. *state &= PPS_LINE_TIOC;
  488. thread_context->log_hook(thread_context, THREAD_PROG,
  489. "TPPS:%s ioctl(TIOCMIWAIT) succeeded, time:%s, state: %d\n",
  490. thread_context->devicename,
  491. timespec_str(clock_ts, ts_str, sizeof(ts_str)),
  492. *state);
  493. return 0;
  494. }
  495. #endif /* TIOCMIWAIT */
  496. #if defined(HAVE_SYS_TIMEPPS_H)
  497. /* wait for, and get, last two edges using RFC2783
  498. * return -1 for error
  499. * 0 for OK
  500. * 1 no edge found, continue
  501. *
  502. * on a quad core 2.4GHz Xeon using KPPS timestamp instead of plain
  503. * PPS timestamp removes about 20uS of latency, and about +/-5uS
  504. * of jitter
  505. */
  506. static int get_edge_rfc2783(struct inner_context_t *inner_context,
  507. struct timespec *prev_clock_ts,
  508. int *prev_edge,
  509. struct timespec *clock_ts,
  510. int *edge,
  511. volatile struct timedelta_t *last_fixtime)
  512. {
  513. pps_info_t pi;
  514. char ts_str1[TIMESPEC_LEN], ts_str2[TIMESPEC_LEN];
  515. struct timespec kernelpps_tv;
  516. volatile struct pps_thread_t *thread_context = inner_context->pps_thread;
  517. if ( inner_context->pps_canwait ) {
  518. /*
  519. * RFC2783 specifies that a NULL timeval means to wait, if
  520. * PPS_CANWAIT is available.
  521. *
  522. * since we pps_canwait, we skipped the TIOMCIWAIT
  523. *
  524. * 3 second time out, some GPS output 0.5Hz and some RFC2783
  525. * can only trigger on one edge
  526. * a better and more complex solution would be to wait
  527. * for 1/20 second and suffer the cycles
  528. */
  529. kernelpps_tv.tv_sec = 3;
  530. kernelpps_tv.tv_nsec = 0;
  531. } else {
  532. /*
  533. * We use of a non-NULL zero timespec here,
  534. * which means to return immediately with -1 (section
  535. * 3.4.3). This is because we know we just got a pulse because
  536. * TIOCMIWAIT just woke up.
  537. * The timestamp has already been captured in the kernel, and we
  538. * are merely fetching it here.
  539. */
  540. memset( (void *)&kernelpps_tv, 0, sizeof(kernelpps_tv));
  541. }
  542. memset( (void *)&pi, 0, sizeof(pi)); /* paranoia */
  543. if ( 0 > time_pps_fetch(inner_context->kernelpps_handle, PPS_TSFMT_TSPEC
  544. , &pi, &kernelpps_tv)) {
  545. char errbuf[BUFSIZ] = "unknown error";
  546. pps_strerror_r(errno, errbuf, sizeof(errbuf));
  547. if ( ETIMEDOUT == errno || EINTR == errno ) {
  548. /* just a timeout */
  549. thread_context->log_hook(thread_context, THREAD_INF,
  550. "KPPS:%s kernel PPS timeout %s\n",
  551. thread_context->devicename, errbuf);
  552. return 1;
  553. }
  554. thread_context->log_hook(thread_context, THREAD_WARN,
  555. "KPPS:%s kernel PPS failed %s\n",
  556. thread_context->devicename, errbuf);
  557. return 0;
  558. }
  559. if ( inner_context->pps_canwait ) {
  560. /* get_edge_tiocmiwait() got this if !pps_canwait */
  561. /* quick, grab a copy of last fixtime before it changes */
  562. thread_lock(thread_context);
  563. *last_fixtime = thread_context->fix_in;
  564. thread_unlock(thread_context);
  565. }
  566. // find the last edge
  567. if ( pi.assert_timestamp.tv_sec > pi.clear_timestamp.tv_sec ) {
  568. /* assert 1 sec or more after than clear */
  569. *edge = 1;
  570. } else if ( pi.assert_timestamp.tv_sec < pi.clear_timestamp.tv_sec ) {
  571. /* assert 1 sec or more before than clear */
  572. *edge = 0;
  573. } else if ( pi.assert_timestamp.tv_nsec > pi.clear_timestamp.tv_nsec ) {
  574. /* assert less than 1 sec after clear */
  575. *edge = 1;
  576. } else {
  577. /* assert less than 1 sec before clear */
  578. *edge = 0;
  579. }
  580. if ( 1 == *edge ) {
  581. /* assert after clear */
  582. *prev_edge = 0;
  583. if ( 0 == pi.clear_timestamp.tv_sec ) {
  584. /* brain damaged pps-gpio sometimes never fills in clear
  585. * so make it look like an invisible pulse
  586. * if clear is the leading edge, then we are off by the
  587. * pulse width */
  588. *prev_clock_ts = pi.assert_timestamp;
  589. } else {
  590. *prev_clock_ts = pi.clear_timestamp;
  591. }
  592. *clock_ts = pi.assert_timestamp;
  593. } else {
  594. /* assert before clear */
  595. *prev_edge = 1;
  596. *prev_clock_ts = pi.assert_timestamp;
  597. *clock_ts = pi.clear_timestamp;
  598. }
  599. /*
  600. * pps_seq_t is uint32_t on NetBSD, so cast to
  601. * unsigned long as a wider-or-equal type to
  602. * accomodate Linux's type.
  603. */
  604. thread_context->log_hook(thread_context, THREAD_PROG,
  605. "KPPS:%s assert %s, sequence: %lu, "
  606. "clear %s, sequence: %lu - using: %.10s\n",
  607. thread_context->devicename,
  608. timespec_str(&pi.assert_timestamp, ts_str1, sizeof(ts_str1)),
  609. (unsigned long) pi.assert_sequence,
  610. timespec_str(&pi.clear_timestamp, ts_str2, sizeof(ts_str2)),
  611. (unsigned long) pi.clear_sequence,
  612. *edge ? "assert" : "clear");
  613. return 0;
  614. }
  615. #endif /* defined(HAVE_SYS_TIMEPPS_H) */
  616. /* gpsd_ppsmonitor()
  617. *
  618. * the core loop of the PPS thread.
  619. * All else is initialization, cleanup or subroutine
  620. */
  621. static void *gpsd_ppsmonitor(void *arg)
  622. {
  623. char ts_str1[TIMESPEC_LEN], ts_str2[TIMESPEC_LEN];
  624. struct inner_context_t inner_context = *((struct inner_context_t *)arg);
  625. volatile struct pps_thread_t *thread_context = inner_context.pps_thread;
  626. /* the GPS time and system clock timme, to the nSec,
  627. * when the last fix received
  628. * using a double would cause loss of precision */
  629. volatile struct timedelta_t last_fixtime = {{0, 0}, {0, 0}};
  630. struct timespec clock_ts = {0, 0};
  631. time_t last_second_used = 0;
  632. int64_t cycle = 0, duration = 0;
  633. /* state is the last state of the tty control signals */
  634. int state = 0;
  635. /* count of how many cycles unchanged data */
  636. int unchanged = 0;
  637. /* state_last is previous state */
  638. int state_last = 0;
  639. /* edge, used as index into pulse to find previous edges */
  640. int edge = 0; /* 0 = clear edge, 1 = assert edge */
  641. #if defined(TIOCMIWAIT)
  642. int edge_tio = 0;
  643. long long cycle_tio = 0;
  644. int64_t duration_tio = 0;
  645. int state_tio = 0;
  646. int state_last_tio = 0;
  647. struct timespec clock_ts_tio = {0, 0};
  648. /* pulse stores the time of the last two edges */
  649. struct timespec pulse_tio[2] = { {0, 0}, {0, 0} };
  650. #endif /* TIOCMIWAIT */
  651. #if defined(HAVE_SYS_TIMEPPS_H)
  652. int64_t cycle_kpps = 0, duration_kpps = 0;
  653. /* kpps_pulse stores the time of the last two edges */
  654. struct timespec pulse_kpps[2] = { {0, 0}, {0, 0} };
  655. #endif /* defined(HAVE_SYS_TIMEPPS_H) */
  656. bool not_a_tty = false;
  657. /* Acknowledge that we've grabbed the inner_context data */
  658. ((volatile struct inner_context_t *)arg)->pps_thread = NULL;
  659. /* before the loop, figure out how we can detect edges:
  660. * TIOMCIWAIT, which is linux specifix
  661. * RFC2783, a.k.a kernel PPS (KPPS)
  662. * or if KPPS is deficient a combination of the two */
  663. if ( 0 > thread_context->devicefd
  664. || 0 == isatty(thread_context->devicefd) ) {
  665. thread_context->log_hook(thread_context, THREAD_PROG,
  666. "KPPS:%s gps_fd:%d not a tty, can not use TIOMCIWAIT\n",
  667. thread_context->devicename,
  668. thread_context->devicefd);
  669. /* why do we care the device is a tty? so as not to ioctl(TIO..)
  670. * /dev/pps0 is not a tty and we need to use it */
  671. not_a_tty = true;
  672. }
  673. /* if no TIOCMIWAIT, we hope to have PPS_CANWAIT */
  674. if ( not_a_tty && !inner_context.pps_canwait ) {
  675. /* for now, no way to wait for an edge, in the future maybe figure out
  676. * a sleep */
  677. }
  678. /*
  679. * this is the main loop, exit and never any further PPS processing.
  680. *
  681. * Four stages to the loop,
  682. * an unwanted condition at any point and the loop restarts
  683. * an error condition and we exit for all time.
  684. *
  685. * Stage One: wait for the next edge.
  686. * If we have KPPS
  687. * If we have PPS_CANWAIT
  688. * use KPPS and PPS_CANWAIT - this is the most accurate
  689. * else
  690. * use KPPS and TIOMCIWAIT together - this is pretty accurate
  691. * else If we have TIOMCIWAIT
  692. * use TIOMCIWAIT - this is the least accurate
  693. * else
  694. * give up
  695. *
  696. * Success is we have a good edge, otherwise loop some more
  697. *
  698. * On a successul stage one, we know this about the exact moment
  699. * of current pulse:
  700. * GPS (real) time
  701. * system (clock) time
  702. * edge type: Assert (rising) or Clear (falling)
  703. *
  704. * From the above 3 items, we can compute:
  705. * cycle length - elapsed time from the previous edge of the same type
  706. * pulse length (duration) - elapsed time from the previous edge
  707. * (the previous edge would be the opposite type)
  708. *
  709. * Stage Two: Categorize the current edge
  710. * Decide if we have 0.5Hz, 1Hz, 5 Hz cycle time
  711. * knowing cycle time determine if we have the leading or trailing edge
  712. * restart the loop if the edge looks dodgy
  713. *
  714. * Stage Three: Calculate
  715. * Calculate the offset (difference) between the system time
  716. * and the GPS time at the pulse moment
  717. * restart the loop if the offset looks dodgy
  718. *
  719. * Stage Four: Tell ntpd, chronyd, or gpsmon what we learned
  720. * a few more sanity checks
  721. * call the report hook with our PPS report
  722. */
  723. while (thread_context->report_hook != NULL) {
  724. bool ok = false;
  725. char *log = NULL;
  726. char *edge_str = "";
  727. if (++unchanged == 10) {
  728. /* last ten edges no good, stop spinning, just wait 10 seconds */
  729. unchanged = 0;
  730. thread_context->log_hook(thread_context, THREAD_WARN,
  731. "PPS:%s unchanged state, ppsmonitor sleeps 10\n",
  732. thread_context->devicename);
  733. (void)sleep(10);
  734. }
  735. /* Stage One; wait for the next edge */
  736. #if defined(TIOCMIWAIT)
  737. if ( !not_a_tty && !inner_context.pps_canwait ) {
  738. int ret;
  739. /* we are a tty, so can TIOCMIWAIT */
  740. /* we have no PPS_CANWAIT, so must TIOCMIWAIT */
  741. ret = get_edge_tiocmiwait( thread_context, &clock_ts_tio,
  742. &state_tio, &last_fixtime );
  743. if ( 0 != ret ) {
  744. thread_context->log_hook(thread_context, THREAD_PROG,
  745. "PPS:%s die: TIOCMIWAIT Error\n",
  746. thread_context->devicename);
  747. break;
  748. }
  749. edge_tio = (state_tio > state_last_tio) ? 1 : 0;
  750. state_last_tio = state_tio;
  751. /* three things now known about the current edge:
  752. * clock_ts - time of the edge
  753. * state - the serial line input states
  754. * edge - rising edge (1), falling edge (0) or invisble edge (0)
  755. */
  756. /* calculate cycle and duration from previous edges */
  757. cycle_tio = timespec_diff_ns(clock_ts_tio, pulse_tio[edge_tio]);
  758. cycle_tio /= 1000; /* nsec to usec */
  759. duration_tio = timespec_diff_ns(clock_ts_tio,
  760. pulse_tio[edge_tio ? 0 : 1])/1000;
  761. /* save this edge so we know next cycle time */
  762. pulse_tio[edge_tio] = clock_ts_tio;
  763. /* use this data */
  764. ok = true;
  765. clock_ts = clock_ts_tio;
  766. state = edge_tio;
  767. edge = edge_tio;
  768. edge_str = edge ? "Assert" : "Clear";
  769. cycle = cycle_tio;
  770. duration = duration_tio;
  771. thread_context->log_hook(thread_context, THREAD_PROG,
  772. "TPPS:%s %.10s, cycle: " PRId64 ", duration: " PRId64
  773. " @ %s\n",
  774. thread_context->devicename, edge_str, cycle, duration,
  775. timespec_str(&clock_ts, ts_str1, sizeof(ts_str1)));
  776. }
  777. #endif /* TIOCMIWAIT */
  778. /* ok and log used by KPPS and TIOCMIWAIT */
  779. log = NULL;
  780. #if defined(HAVE_SYS_TIMEPPS_H)
  781. if ( 0 <= inner_context.kernelpps_handle ) {
  782. int ret;
  783. int edge_kpps = 0; /* 0 = clear edge, 1 = assert edge */
  784. /* time of the last edge */
  785. struct timespec clock_ts_kpps = {0, 0};
  786. /* time of the edge before the last edge */
  787. struct timespec prev_clock_ts = {0, 0};
  788. /* direction of next to last edge 1 = assert, 0 = clear */
  789. int prev_edge = 0;
  790. /* get last and previous edges, in order
  791. * optionally wait for goood data
  792. */
  793. ret = get_edge_rfc2783(&inner_context,
  794. &prev_clock_ts,
  795. &prev_edge,
  796. &clock_ts_kpps,
  797. &edge_kpps,
  798. &last_fixtime);
  799. if ( -1 == ret ) {
  800. /* error, so break */
  801. thread_context->log_hook(thread_context, THREAD_ERROR,
  802. "PPS:%s die: RFC2783 Error\n",
  803. thread_context->devicename);
  804. break;
  805. }
  806. if ( 1 == ret ) {
  807. /* no edge found, so continue */
  808. /* maybe use TIOCMIWAIT edge instead?? */
  809. continue;
  810. }
  811. /* for now, as we have been doing all of gpsd 3.x, just
  812. *use the last edge, not the previous edge */
  813. /* compute time from previous saved similar edge */
  814. cycle_kpps = timespec_diff_ns(clock_ts_kpps, pulse_kpps[edge_kpps]);
  815. cycle_kpps /= 1000;
  816. /* compute time from previous saved dis-similar edge */
  817. duration_kpps = timespec_diff_ns(clock_ts_kpps, prev_clock_ts) /
  818. 1000;
  819. /* save for later */
  820. pulse_kpps[edge_kpps] = clock_ts_kpps;
  821. pulse_kpps[edge_kpps ? 0 : 1] = prev_clock_ts;
  822. /* sanity checks are later */
  823. /* use this data */
  824. state = edge_kpps;
  825. edge = edge_kpps;
  826. edge_str = edge ? "Assert" : "Clear";
  827. clock_ts = clock_ts_kpps;
  828. cycle = cycle_kpps;
  829. duration = duration_kpps;
  830. thread_context->log_hook(thread_context, THREAD_PROG,
  831. "KPPS:%s %.10s cycle: " PRId64 ", duration: " PRId64 " @ %s\n",
  832. thread_context->devicename,
  833. edge_str,
  834. cycle_kpps, duration_kpps,
  835. timespec_str(&clock_ts_kpps, ts_str1, sizeof(ts_str1)));
  836. }
  837. #endif /* defined(HAVE_SYS_TIMEPPS_H) */
  838. if ( not_a_tty && !inner_context.pps_canwait ) {
  839. /* uh, oh, no TIOMCIWAIT, nor RFC2783, die */
  840. thread_context->log_hook(thread_context, THREAD_WARN,
  841. "PPS:%s die: no TIOMCIWAIT, nor RFC2783 CANWAIT\n",
  842. thread_context->devicename);
  843. break;
  844. }
  845. /*
  846. * End of Stge One
  847. * we now know this about the exact moment of current pulse:
  848. * GPS (real) time
  849. * system (clock) time
  850. * edge type: Assert (rising) or Clear (falling)
  851. *
  852. * we have computed:
  853. * cycle length
  854. * pulse length (duration)
  855. */
  856. /*
  857. * Stage Two: Categorize the current edge
  858. * Decide if we have 0.5Hz, 1Hz, 5 Hz cycle time
  859. * determine if we have the leading or trailing edge
  860. */
  861. /* FIXME! this block duplicates a lot of the next block
  862. * of cycle detetion code */
  863. if (state != state_last) {
  864. thread_context->log_hook(thread_context, THREAD_RAW,
  865. "PPS:%s %.10s pps-detect changed to %d\n",
  866. thread_context->devicename, edge_str, state);
  867. unchanged = 0;
  868. } else if ( (180000 < cycle && 220000 > cycle) /* 5Hz */
  869. || (900000 < cycle && 1100000 > cycle) /* 1Hz */
  870. || (1800000 < cycle && 2200000 > cycle) ) { /* 0.5Hz */
  871. /* some pulses may be so short that state never changes
  872. * and some RFC2783 only can detect one edge */
  873. duration = 0;
  874. unchanged = 0;
  875. thread_context->log_hook(thread_context, THREAD_RAW,
  876. "PPS:%s %.10s pps-detect invisible pulse\n",
  877. thread_context->devicename, edge_str);
  878. }
  879. /* else, unchannged state, and weird cycle time */
  880. state_last = state;
  881. thread_context->log_hook(thread_context, THREAD_PROG,
  882. "PPS:%s %.10s cycle: " PRId64 ", duration: " PRId64 " @ %s\n",
  883. thread_context->devicename,
  884. edge_str,
  885. cycle, duration,
  886. timespec_str(&clock_ts, ts_str1, sizeof(ts_str1)));
  887. if (unchanged) {
  888. // strange, try again
  889. continue;
  890. }
  891. /*
  892. * The PPS pulse is normally a short pulse with a frequency of
  893. * 1 Hz, and the UTC second is defined by the front edge. But we
  894. * don't know the polarity of the pulse (different receivers
  895. * emit different polarities). The duration variable is used to
  896. * determine which way the pulse is going. When the duration
  897. * is less than 1/2 the cycle we are on the trailing edge.
  898. *
  899. * Some GPSes instead output a square wave that is 0.5 Hz and each
  900. * edge denotes the start of a second.
  901. *
  902. * Some GPSes, like the Globalsat MR-350P, output a 1uS pulse.
  903. * The pulse is so short that TIOCMIWAIT sees a state change
  904. * but by the time TIOCMGET is called the pulse is gone. gpsd
  905. * calls that an invisible pulse.
  906. *
  907. * A few stupid GPSes, like the Furuno GPSClock, output a 1.0 Hz
  908. * square wave where the leading edge is the start of a second
  909. * gpsd can only guess the correct edge.
  910. *
  911. * 5Hz GPS (Garmin 18-5Hz) pulses at 5Hz. Set the pulse length to
  912. * 40ms which gives a 160ms pulse before going high.
  913. *
  914. * You may think that PPS is very accurate, so the cycle time
  915. * valid window should be very small. This is not the case,
  916. * The Raspberry Pi clock is very coarse when it starts and/or chronyd
  917. * may be doing a fast slew. chronyd by default will slew up
  918. * to 8.334%! So the cycle time as measured by the system clock
  919. * may be almost +/- 9%. Therefore, gpsd uses a 10% window.
  920. * Don't worry, ntpd and chronyd will do further validation.
  921. */
  922. log = "Unknown error";
  923. if ( 0 > cycle ) {
  924. log = "Rejecting negative cycle\n";
  925. } else if (180000 > cycle) {
  926. /* shorter than 200 milliSec - 10%
  927. * too short to even be a 5Hz pulse */
  928. log = "Too short for 5Hz\n";
  929. } else if (201000 > cycle) {
  930. /* longer than 200 milliSec - 10%
  931. * shorter than 200 milliSec + 10%
  932. * about 200 milliSec cycle */
  933. /* looks like 5hz PPS pulse */
  934. if (100000 > duration) {
  935. /* this is the end of the long part */
  936. /* BUG: how does the code know to tell ntpd
  937. * which 1/5 of a second to use?? */
  938. ok = true;
  939. log = "5Hz PPS pulse\n";
  940. }
  941. } else if (900000 > cycle) {
  942. /* longer than 200 milliSec + 10%
  943. * shorter than 1.000 Sec - 10% */
  944. /* Yes, 10% window. The Raspberry Pi clock is very coarse
  945. * when it starts and chronyd may be doing a fast slew.
  946. * chronyd by default will slew up to 8.334% ! */
  947. log = "Too long for 5Hz, too short for 1Hz\n";
  948. } else if (1100000 > cycle) {
  949. /* longer than 1.000 Sec - 10%
  950. * shorter than 1.000 Sec + 10% */
  951. /* Yes, 10% window. */
  952. /* looks like 1Hz PPS pulse or square wave */
  953. if (0 == duration) {
  954. ok = true;
  955. log = "invisible pulse\n";
  956. } else if (450000 > duration) {
  957. /* pulse shorter than 500 milliSec - 10%
  958. * end of the short "half" of the cycle
  959. * aka the trailing edge */
  960. log = "1Hz trailing edge\n";
  961. } else if (555000 > duration) {
  962. /* pulse longer than 500 milliSec - 10%
  963. * pulse shorter than 500 milliSec + 10%
  964. * looks like 1.0 Hz square wave, ignore trailing edge
  965. * except we can't tell which is which, so we guess */
  966. // cppcheck-suppress knownConditionTrueFalse
  967. if (edge == 1) {
  968. ok = true;
  969. log = "square\n";
  970. }
  971. } else {
  972. /* pulse longer than 500 milliSec + 10%
  973. * end of the long "half" of the cycle
  974. * aka the leading edge,
  975. * the edge that marks the start of the second */
  976. ok = true;
  977. log = "1Hz leading edge\n";
  978. }
  979. } else if (1800000 > cycle) {
  980. /* cycle longer than 1.000 Sec + 10%
  981. * cycle shorter than 2.000 Sec - 10%
  982. * Too long for 1Hz, too short for 2Hz */
  983. log = "Too long for 1Hz, too short for 2Hz\n";
  984. } else if (2200000 > cycle) {
  985. /* cycle longer than 2.000 Sec - 10%
  986. * cycle shorter than 2.000 Sec + 10%
  987. * looks like 0.5 Hz square wave */
  988. if (990000 > duration) {
  989. /* pulse shorter than 1.000 Sec - 10%
  990. * too short to be a 2Hx square wave */
  991. log = "0.5 Hz square too short duration\n";
  992. } else if (1100000 > duration) {
  993. /* pulse longer than 1.000 Sec - 10%
  994. * pulse shorter than 1.000 Sec + 10%
  995. * and nice 0.5Hz square wave */
  996. ok = true;
  997. log = "0.5 Hz square wave\n";
  998. } else {
  999. log = "0.5 Hz square too long duration\n";
  1000. }
  1001. } else {
  1002. /* cycle longer than 2.000 Sec + 10%
  1003. * can't be anything */
  1004. log = "Too long for 0.5Hz\n";
  1005. }
  1006. /* end of Stage two
  1007. * we now know what type of PPS pulse, and if we have a good
  1008. * leading edge or not
  1009. */
  1010. /* Stage Three: Calculate
  1011. * Calculate the offset (difference) between the system time
  1012. * and the GPS time at the pulse moment
  1013. */
  1014. /*
  1015. * If there has not yet been any valid in-band time stashed
  1016. * from the GPS when the PPS event was asserted, we can do
  1017. * nothing further. gpsd can not tell what second this pulse is
  1018. * in reference to.
  1019. *
  1020. * Some GPSes like Garmin always send a PPS, valid or not.
  1021. * Other GPSes like some uBlox may only send PPS when time is valid.
  1022. * It is common to get PPS, and no fixtime, while autobauding.
  1023. */
  1024. /* FIXME, some GPS, like Skytraq, may output a the fixtime so
  1025. * late in the cycle as to be ambiguous. */
  1026. if (last_fixtime.real.tv_sec == 0) {
  1027. /* probably should log computed offset just for grins here */
  1028. ok = false;
  1029. log = "missing last_fixtime\n";
  1030. } else if ( ok && last_second_used >= last_fixtime.real.tv_sec ) {
  1031. /* uh, oh, this second already handled */
  1032. ok = false;
  1033. log = "this second already handled\n";
  1034. }
  1035. if ( !ok ) {
  1036. /* can not use this pulse, reject and retry */
  1037. thread_context->log_hook(thread_context, THREAD_PROG,
  1038. "PPS:%s %.10s ignored %.100s",
  1039. thread_context->devicename, edge_str, log);
  1040. continue;
  1041. }
  1042. /* we have validated a goood cycle, mark it */
  1043. unchanged = 0;
  1044. /* offset is the skew from expected to observed pulse time */
  1045. struct timespec offset;
  1046. /* offset as a printable string */
  1047. char offset_str[TIMESPEC_LEN];
  1048. /* delay after last fix */
  1049. struct timespec delay;
  1050. /* delay as a printable string */
  1051. char delay_str[TIMESPEC_LEN];
  1052. char *log1 = "";
  1053. /* ppstimes.real is the time we think the pulse represents */
  1054. struct timedelta_t ppstimes;
  1055. thread_context->log_hook(thread_context, THREAD_RAW,
  1056. "PPS:%s %.10s categorized %.100s",
  1057. thread_context->devicename, edge_str, log);
  1058. /* FIXME! The GR-601W at 38,400 or faster can send the
  1059. * serial fix before the interrupt event carrying the PPS
  1060. * line assertion by about 10 mSec!
  1061. */
  1062. /*
  1063. * We get the time of the last fix recorded before the PPS came in,
  1064. * which is for the previous cycle. Only works for integral cycle
  1065. * times, but more than 1Hz is pointless.
  1066. */
  1067. ppstimes.real.tv_sec = (time_t)last_fixtime.real.tv_sec + 1;
  1068. ppstimes.real.tv_nsec = 0; /* need to be fixed for 5Hz */
  1069. ppstimes.clock = clock_ts;
  1070. // Here would be a good place to apply qErr
  1071. TS_SUB( &offset, &ppstimes.real, &ppstimes.clock);
  1072. TS_SUB( &delay, &ppstimes.clock, &last_fixtime.clock);
  1073. timespec_str(&delay, delay_str, sizeof(delay_str));
  1074. /* end Stage Three: now known about the exact edge moment:
  1075. * UTC time of PPS edge
  1076. * offset of system time to PS time
  1077. */
  1078. /* Stage Four: Tell ntpd, chronyd, or gpsmon what we learned
  1079. * a few more sanity checks
  1080. * call the report hook with our PPS report
  1081. */
  1082. if (0 > delay.tv_sec || 0 > delay.tv_nsec) {
  1083. thread_context->log_hook(thread_context, THREAD_RAW,
  1084. "PPS:%s %.10s system clock went backwards: %.20s\n",
  1085. thread_context->devicename,
  1086. edge_str,
  1087. delay_str);
  1088. log1 = "system clock went backwards";
  1089. } else if ((2 < delay.tv_sec)
  1090. || (1 == delay.tv_sec && 100000000 < delay.tv_nsec)) {
  1091. /* system clock could be slewing so allow up to 1.1 sec delay */
  1092. /* chronyd can slew +/-8.33% */
  1093. thread_context->log_hook(thread_context, THREAD_RAW,
  1094. "PPS:%s %.10s no current GPS seconds: %.20s\n",
  1095. thread_context->devicename,
  1096. edge_str,
  1097. delay_str);
  1098. log1 = "timestamp out of range";
  1099. } else {
  1100. last_second_used = last_fixtime.real.tv_sec;
  1101. if (thread_context->report_hook != NULL)
  1102. log1 = thread_context->report_hook(thread_context, &ppstimes);
  1103. else
  1104. log1 = "no report hook";
  1105. thread_lock(thread_context);
  1106. thread_context->pps_out = ppstimes;
  1107. thread_context->ppsout_count++;
  1108. thread_unlock(thread_context);
  1109. thread_context->log_hook(thread_context, THREAD_INF,
  1110. "PPS:%s %.10s hooks called clock: %s real: %s: %.20s\n",
  1111. thread_context->devicename,
  1112. edge_str,
  1113. timespec_str(&ppstimes.clock, ts_str1, sizeof(ts_str1)),
  1114. timespec_str(&ppstimes.real, ts_str2, sizeof(ts_str2)),
  1115. log1);
  1116. }
  1117. thread_context->log_hook(thread_context, THREAD_PROG,
  1118. "PPS:%s %.10s %.30s @ %s offset %.20s\n",
  1119. thread_context->devicename,
  1120. edge_str,
  1121. log1,
  1122. timespec_str(&clock_ts, ts_str1, sizeof(ts_str1)),
  1123. timespec_str(&offset, offset_str, sizeof(offset_str)));
  1124. /* end Stage four, end of the loop, do it again */
  1125. }
  1126. #if defined(HAVE_SYS_TIMEPPS_H)
  1127. if (inner_context.kernelpps_handle > 0) {
  1128. thread_context->log_hook(thread_context, THREAD_PROG,
  1129. "KPPS:%s descriptor cleaned up\n",
  1130. thread_context->devicename);
  1131. (void)time_pps_destroy(inner_context.kernelpps_handle);
  1132. }
  1133. #endif
  1134. thread_context->log_hook(thread_context, THREAD_PROG,
  1135. "PPS:%s gpsd_ppsmonitor exited.\n",
  1136. thread_context->devicename);
  1137. return NULL;
  1138. }
  1139. /*
  1140. * Entry points begin here.
  1141. */
  1142. void pps_thread_activate(volatile struct pps_thread_t *pps_thread)
  1143. /* activate a thread to watch the device's PPS transitions */
  1144. {
  1145. int retval;
  1146. pthread_t pt;
  1147. struct timespec start_delay = {0, 1000000}; /* 1 ms */
  1148. /*
  1149. * FIXME: this launch code is not itself thread-safe!
  1150. * It would be if inner_context could be auto, but the monitor
  1151. * routine gets garbage when we try that. Ideally the body
  1152. * of this function would be guarded by a separate mutex.
  1153. * Either that, or this should be an exception to the no-malloc rule.
  1154. */
  1155. static struct inner_context_t inner_context;
  1156. inner_context.pps_thread = pps_thread;
  1157. #if defined(HAVE_SYS_TIMEPPS_H)
  1158. /* some operations in init_kernel_pps() require root privs */
  1159. (void)init_kernel_pps(&inner_context);
  1160. if ( 0 <= inner_context.kernelpps_handle ) {
  1161. pps_thread->log_hook(pps_thread, THREAD_INF,
  1162. "KPPS:%s kernel PPS will be used\n",
  1163. pps_thread->devicename);
  1164. } else {
  1165. pps_thread->log_hook(pps_thread, THREAD_WARN,
  1166. "KPPS:%s kernel PPS unavailable, PPS accuracy will suffer\n",
  1167. pps_thread->devicename);
  1168. }
  1169. #else
  1170. pps_thread->log_hook(pps_thread, THREAD_WARN,
  1171. "KPPS:%s no HAVE_SYS_TIMEPPS_H, PPS accuracy will suffer\n",
  1172. pps_thread->devicename);
  1173. #endif
  1174. memset( &pt, 0, sizeof(pt));
  1175. retval = pthread_create(&pt, NULL, gpsd_ppsmonitor, (void *)&inner_context);
  1176. pps_thread->log_hook(pps_thread, THREAD_PROG, "PPS:%s thread %s\n",
  1177. pps_thread->devicename,
  1178. (retval==0) ? "launched" : "FAILED");
  1179. /* The monitor thread may not run immediately, particularly on a single-
  1180. * core machine, so we need to wait for it to acknowledge its copying
  1181. * of the inner_context struct before proceeding.
  1182. */
  1183. while (inner_context.pps_thread)
  1184. (void) nanosleep(&start_delay, NULL);
  1185. }
  1186. void pps_thread_deactivate(volatile struct pps_thread_t *pps_thread)
  1187. /* cleanly terminate PPS thread */
  1188. {
  1189. pps_thread->report_hook = NULL;
  1190. }
  1191. /* thread-safe update of last fix time - only way we pass data in */
  1192. void pps_thread_fixin(volatile struct pps_thread_t *pps_thread,
  1193. volatile struct timedelta_t *fix_in)
  1194. {
  1195. thread_lock(pps_thread);
  1196. pps_thread->fix_in = *fix_in;
  1197. thread_unlock(pps_thread);
  1198. }
  1199. /* thread-safe update of qErr and qErr_time - only way we pass data in */
  1200. void pps_thread_qErrin(volatile struct pps_thread_t *pps_thread,
  1201. long qErr, struct timespec qErr_time)
  1202. {
  1203. thread_lock(pps_thread);
  1204. pps_thread->qErr = qErr;
  1205. pps_thread->qErr_time = qErr_time;
  1206. thread_unlock(pps_thread);
  1207. }
  1208. int pps_thread_ppsout(volatile struct pps_thread_t *pps_thread,
  1209. volatile struct timedelta_t *td)
  1210. /* return the delta at the time of the last PPS - only way we pass data out */
  1211. {
  1212. volatile int ret;
  1213. thread_lock(pps_thread);
  1214. *td = pps_thread->pps_out;
  1215. ret = pps_thread->ppsout_count;
  1216. thread_unlock(pps_thread);
  1217. return ret;
  1218. }
  1219. /* end */
  1220. // vim: set expandtab shiftwidth=4