You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ppsthread.c 51KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334
  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. int64_t 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. // (long long) for 32-bit compat. PRId64 segfaults
  772. thread_context->log_hook(thread_context, THREAD_PROG,
  773. "TPPS:%s %.10s, cycle: %lld, duration: %lld @ %s\n",
  774. thread_context->devicename, edge_str,
  775. (long long)cycle, (long long)duration,
  776. timespec_str(&clock_ts, ts_str1, sizeof(ts_str1)));
  777. }
  778. #endif /* TIOCMIWAIT */
  779. /* ok and log used by KPPS and TIOCMIWAIT */
  780. log = NULL;
  781. #if defined(HAVE_SYS_TIMEPPS_H)
  782. if ( 0 <= inner_context.kernelpps_handle ) {
  783. int ret;
  784. int edge_kpps = 0; /* 0 = clear edge, 1 = assert edge */
  785. /* time of the last edge */
  786. struct timespec clock_ts_kpps = {0, 0};
  787. /* time of the edge before the last edge */
  788. struct timespec prev_clock_ts = {0, 0};
  789. /* direction of next to last edge 1 = assert, 0 = clear */
  790. int prev_edge = 0;
  791. /* get last and previous edges, in order
  792. * optionally wait for goood data
  793. */
  794. ret = get_edge_rfc2783(&inner_context,
  795. &prev_clock_ts,
  796. &prev_edge,
  797. &clock_ts_kpps,
  798. &edge_kpps,
  799. &last_fixtime);
  800. if ( -1 == ret ) {
  801. /* error, so break */
  802. thread_context->log_hook(thread_context, THREAD_ERROR,
  803. "PPS:%s die: RFC2783 Error\n",
  804. thread_context->devicename);
  805. break;
  806. }
  807. if ( 1 == ret ) {
  808. /* no edge found, so continue */
  809. /* maybe use TIOCMIWAIT edge instead?? */
  810. continue;
  811. }
  812. /* for now, as we have been doing all of gpsd 3.x, just
  813. *use the last edge, not the previous edge */
  814. /* compute time from previous saved similar edge */
  815. cycle_kpps = timespec_diff_ns(clock_ts_kpps, pulse_kpps[edge_kpps]);
  816. cycle_kpps /= 1000;
  817. /* compute time from previous saved dis-similar edge */
  818. duration_kpps = timespec_diff_ns(clock_ts_kpps, prev_clock_ts) /
  819. 1000;
  820. /* save for later */
  821. pulse_kpps[edge_kpps] = clock_ts_kpps;
  822. pulse_kpps[edge_kpps ? 0 : 1] = prev_clock_ts;
  823. /* sanity checks are later */
  824. /* use this data */
  825. state = edge_kpps;
  826. edge = edge_kpps;
  827. edge_str = edge ? "Assert" : "Clear";
  828. clock_ts = clock_ts_kpps;
  829. cycle = cycle_kpps;
  830. duration = duration_kpps;
  831. // (long long) for 32-bit compat. PRId64 segfaults
  832. thread_context->log_hook(thread_context, THREAD_PROG,
  833. "KPPS:%s %.10s cycle: %lld, duration: %lld @ %s\n",
  834. thread_context->devicename,
  835. edge_str,
  836. (long long)cycle_kpps, (long long)duration_kpps,
  837. timespec_str(&clock_ts_kpps, ts_str1, sizeof(ts_str1)));
  838. }
  839. #endif /* defined(HAVE_SYS_TIMEPPS_H) */
  840. if ( not_a_tty && !inner_context.pps_canwait ) {
  841. /* uh, oh, no TIOMCIWAIT, nor RFC2783, die */
  842. thread_context->log_hook(thread_context, THREAD_WARN,
  843. "PPS:%s die: no TIOMCIWAIT, nor RFC2783 CANWAIT\n",
  844. thread_context->devicename);
  845. break;
  846. }
  847. /*
  848. * End of Stge One
  849. * we now know this about the exact moment of current pulse:
  850. * GPS (real) time
  851. * system (clock) time
  852. * edge type: Assert (rising) or Clear (falling)
  853. *
  854. * we have computed:
  855. * cycle length
  856. * pulse length (duration)
  857. */
  858. /*
  859. * Stage Two: Categorize the current edge
  860. * Decide if we have 0.5Hz, 1Hz, 5 Hz cycle time
  861. * determine if we have the leading or trailing edge
  862. */
  863. /* FIXME! this block duplicates a lot of the next block
  864. * of cycle detetion code */
  865. if (state != state_last) {
  866. thread_context->log_hook(thread_context, THREAD_RAW,
  867. "PPS:%s %.10s pps-detect changed to %d\n",
  868. thread_context->devicename, edge_str, state);
  869. unchanged = 0;
  870. } else if ( (180000 < cycle && 220000 > cycle) /* 5Hz */
  871. || (900000 < cycle && 1100000 > cycle) /* 1Hz */
  872. || (1800000 < cycle && 2200000 > cycle) ) { /* 0.5Hz */
  873. /* some pulses may be so short that state never changes
  874. * and some RFC2783 only can detect one edge */
  875. duration = 0;
  876. unchanged = 0;
  877. thread_context->log_hook(thread_context, THREAD_RAW,
  878. "PPS:%s %.10s pps-detect invisible pulse\n",
  879. thread_context->devicename, edge_str);
  880. }
  881. /* else, unchannged state, and weird cycle time */
  882. state_last = state;
  883. // (long long) for 32-bit compat. PRId64 segfaults
  884. thread_context->log_hook(thread_context, THREAD_PROG,
  885. "PPS:%s %.10s cycle: %lld, duration: %lld @ %s\n",
  886. thread_context->devicename,
  887. edge_str,
  888. (long long)cycle, (long long)duration,
  889. timespec_str(&clock_ts, ts_str1, sizeof(ts_str1)));
  890. if (unchanged) {
  891. // strange, try again
  892. continue;
  893. }
  894. /*
  895. * The PPS pulse is normally a short pulse with a frequency of
  896. * 1 Hz, and the UTC second is defined by the front edge. But we
  897. * don't know the polarity of the pulse (different receivers
  898. * emit different polarities). The duration variable is used to
  899. * determine which way the pulse is going. When the duration
  900. * is less than 1/2 the cycle we are on the trailing edge.
  901. *
  902. * Some GPSes instead output a square wave that is 0.5 Hz and each
  903. * edge denotes the start of a second.
  904. *
  905. * Some GPSes, like the Globalsat MR-350P, output a 1uS pulse.
  906. * The pulse is so short that TIOCMIWAIT sees a state change
  907. * but by the time TIOCMGET is called the pulse is gone. gpsd
  908. * calls that an invisible pulse.
  909. *
  910. * A few stupid GPSes, like the Furuno GPSClock, output a 1.0 Hz
  911. * square wave where the leading edge is the start of a second
  912. * gpsd can only guess the correct edge.
  913. *
  914. * 5Hz GPS (Garmin 18-5Hz) pulses at 5Hz. Set the pulse length to
  915. * 40ms which gives a 160ms pulse before going high.
  916. *
  917. * You may think that PPS is very accurate, so the cycle time
  918. * valid window should be very small. This is not the case,
  919. * The Raspberry Pi clock is very coarse when it starts and/or chronyd
  920. * may be doing a fast slew. chronyd by default will slew up
  921. * to 8.334%! So the cycle time as measured by the system clock
  922. * may be almost +/- 9%. Therefore, gpsd uses a 10% window.
  923. * Don't worry, ntpd and chronyd will do further validation.
  924. */
  925. log = "Unknown error";
  926. if ( 0 > cycle ) {
  927. log = "Rejecting negative cycle\n";
  928. } else if (180000 > cycle) {
  929. /* shorter than 200 milliSec - 10%
  930. * too short to even be a 5Hz pulse */
  931. log = "Too short for 5Hz\n";
  932. } else if (201000 > cycle) {
  933. /* longer than 200 milliSec - 10%
  934. * shorter than 200 milliSec + 10%
  935. * about 200 milliSec cycle */
  936. /* looks like 5hz PPS pulse */
  937. if (100000 > duration) {
  938. /* this is the end of the long part */
  939. /* BUG: how does the code know to tell ntpd
  940. * which 1/5 of a second to use?? */
  941. ok = true;
  942. log = "5Hz PPS pulse\n";
  943. }
  944. } else if (900000 > cycle) {
  945. /* longer than 200 milliSec + 10%
  946. * shorter than 1.000 Sec - 10% */
  947. /* Yes, 10% window. The Raspberry Pi clock is very coarse
  948. * when it starts and chronyd may be doing a fast slew.
  949. * chronyd by default will slew up to 8.334% ! */
  950. log = "Too long for 5Hz, too short for 1Hz\n";
  951. } else if (1100000 > cycle) {
  952. /* longer than 1.000 Sec - 10%
  953. * shorter than 1.000 Sec + 10% */
  954. /* Yes, 10% window. */
  955. /* looks like 1Hz PPS pulse or square wave */
  956. if (0 == duration) {
  957. ok = true;
  958. log = "invisible pulse\n";
  959. } else if (450000 > duration) {
  960. /* pulse shorter than 500 milliSec - 10%
  961. * end of the short "half" of the cycle
  962. * aka the trailing edge */
  963. log = "1Hz trailing edge\n";
  964. } else if (555000 > duration) {
  965. /* pulse longer than 500 milliSec - 10%
  966. * pulse shorter than 500 milliSec + 10%
  967. * looks like 1.0 Hz square wave, ignore trailing edge
  968. * except we can't tell which is which, so we guess */
  969. // cppcheck-suppress knownConditionTrueFalse
  970. if (edge == 1) {
  971. ok = true;
  972. log = "square\n";
  973. }
  974. } else {
  975. /* pulse longer than 500 milliSec + 10%
  976. * end of the long "half" of the cycle
  977. * aka the leading edge,
  978. * the edge that marks the start of the second */
  979. ok = true;
  980. log = "1Hz leading edge\n";
  981. }
  982. } else if (1800000 > cycle) {
  983. /* cycle longer than 1.000 Sec + 10%
  984. * cycle shorter than 2.000 Sec - 10%
  985. * Too long for 1Hz, too short for 2Hz */
  986. log = "Too long for 1Hz, too short for 2Hz\n";
  987. } else if (2200000 > cycle) {
  988. /* cycle longer than 2.000 Sec - 10%
  989. * cycle shorter than 2.000 Sec + 10%
  990. * looks like 0.5 Hz square wave */
  991. if (990000 > duration) {
  992. /* pulse shorter than 1.000 Sec - 10%
  993. * too short to be a 2Hx square wave */
  994. log = "0.5 Hz square too short duration\n";
  995. } else if (1100000 > duration) {
  996. /* pulse longer than 1.000 Sec - 10%
  997. * pulse shorter than 1.000 Sec + 10%
  998. * and nice 0.5Hz square wave */
  999. ok = true;
  1000. log = "0.5 Hz square wave\n";
  1001. } else {
  1002. log = "0.5 Hz square too long duration\n";
  1003. }
  1004. } else {
  1005. /* cycle longer than 2.000 Sec + 10%
  1006. * can't be anything */
  1007. log = "Too long for 0.5Hz\n";
  1008. }
  1009. /* end of Stage two
  1010. * we now know what type of PPS pulse, and if we have a good
  1011. * leading edge or not
  1012. */
  1013. /* Stage Three: Calculate
  1014. * Calculate the offset (difference) between the system time
  1015. * and the GPS time at the pulse moment
  1016. */
  1017. /*
  1018. * If there has not yet been any valid in-band time stashed
  1019. * from the GPS when the PPS event was asserted, we can do
  1020. * nothing further. gpsd can not tell what second this pulse is
  1021. * in reference to.
  1022. *
  1023. * Some GPSes like Garmin always send a PPS, valid or not.
  1024. * Other GPSes like some uBlox may only send PPS when time is valid.
  1025. * It is common to get PPS, and no fixtime, while autobauding.
  1026. */
  1027. /* FIXME, some GPS, like Skytraq, may output a the fixtime so
  1028. * late in the cycle as to be ambiguous. */
  1029. if (last_fixtime.real.tv_sec == 0) {
  1030. /* probably should log computed offset just for grins here */
  1031. ok = false;
  1032. log = "missing last_fixtime\n";
  1033. } else if ( ok && last_second_used >= last_fixtime.real.tv_sec ) {
  1034. /* uh, oh, this second already handled */
  1035. ok = false;
  1036. log = "this second already handled\n";
  1037. }
  1038. if ( !ok ) {
  1039. /* can not use this pulse, reject and retry */
  1040. thread_context->log_hook(thread_context, THREAD_PROG,
  1041. "PPS:%s %.10s ignored %.100s",
  1042. thread_context->devicename, edge_str, log);
  1043. continue;
  1044. }
  1045. /* we have validated a goood cycle, mark it */
  1046. unchanged = 0;
  1047. /* offset is the skew from expected to observed pulse time */
  1048. struct timespec offset;
  1049. /* offset as a printable string */
  1050. char offset_str[TIMESPEC_LEN];
  1051. /* delay after last fix */
  1052. struct timespec delay;
  1053. /* delay as a printable string */
  1054. char delay_str[TIMESPEC_LEN];
  1055. char *log1 = "";
  1056. /* ppstimes.real is the time we think the pulse represents */
  1057. struct timedelta_t ppstimes;
  1058. thread_context->log_hook(thread_context, THREAD_RAW,
  1059. "PPS:%s %.10s categorized %.100s",
  1060. thread_context->devicename, edge_str, log);
  1061. /* FIXME! The GR-601W at 38,400 or faster can send the
  1062. * serial fix before the interrupt event carrying the PPS
  1063. * line assertion by about 10 mSec!
  1064. */
  1065. /*
  1066. * We get the time of the last fix recorded before the PPS came in,
  1067. * which is for the previous cycle. Only works for integral cycle
  1068. * times, but more than 1Hz is pointless.
  1069. */
  1070. ppstimes.real.tv_sec = (time_t)last_fixtime.real.tv_sec + 1;
  1071. ppstimes.real.tv_nsec = 0; /* need to be fixed for 5Hz */
  1072. ppstimes.clock = clock_ts;
  1073. // Here would be a good place to apply qErr
  1074. TS_SUB( &offset, &ppstimes.real, &ppstimes.clock);
  1075. TS_SUB( &delay, &ppstimes.clock, &last_fixtime.clock);
  1076. timespec_str(&delay, delay_str, sizeof(delay_str));
  1077. /* end Stage Three: now known about the exact edge moment:
  1078. * UTC time of PPS edge
  1079. * offset of system time to PS time
  1080. */
  1081. /* Stage Four: Tell ntpd, chronyd, or gpsmon what we learned
  1082. * a few more sanity checks
  1083. * call the report hook with our PPS report
  1084. */
  1085. if (0 > delay.tv_sec || 0 > delay.tv_nsec) {
  1086. thread_context->log_hook(thread_context, THREAD_RAW,
  1087. "PPS:%s %.10s system clock went backwards: %.20s\n",
  1088. thread_context->devicename,
  1089. edge_str,
  1090. delay_str);
  1091. log1 = "system clock went backwards";
  1092. } else if ((2 < delay.tv_sec)
  1093. || (1 == delay.tv_sec && 100000000 < delay.tv_nsec)) {
  1094. /* system clock could be slewing so allow up to 1.1 sec delay */
  1095. /* chronyd can slew +/-8.33% */
  1096. thread_context->log_hook(thread_context, THREAD_RAW,
  1097. "PPS:%s %.10s no current GPS seconds: %.20s\n",
  1098. thread_context->devicename,
  1099. edge_str,
  1100. delay_str);
  1101. log1 = "timestamp out of range";
  1102. } else {
  1103. last_second_used = last_fixtime.real.tv_sec;
  1104. if (thread_context->report_hook != NULL)
  1105. log1 = thread_context->report_hook(thread_context, &ppstimes);
  1106. else
  1107. log1 = "no report hook";
  1108. thread_lock(thread_context);
  1109. thread_context->pps_out = ppstimes;
  1110. thread_context->ppsout_count++;
  1111. thread_unlock(thread_context);
  1112. thread_context->log_hook(thread_context, THREAD_INF,
  1113. "PPS:%s %.10s hooks called clock: %s real: %s: %.20s\n",
  1114. thread_context->devicename,
  1115. edge_str,
  1116. timespec_str(&ppstimes.clock, ts_str1, sizeof(ts_str1)),
  1117. timespec_str(&ppstimes.real, ts_str2, sizeof(ts_str2)),
  1118. log1);
  1119. }
  1120. thread_context->log_hook(thread_context, THREAD_PROG,
  1121. "PPS:%s %.10s %.30s @ %s offset %.20s\n",
  1122. thread_context->devicename,
  1123. edge_str,
  1124. log1,
  1125. timespec_str(&clock_ts, ts_str1, sizeof(ts_str1)),
  1126. timespec_str(&offset, offset_str, sizeof(offset_str)));
  1127. /* end Stage four, end of the loop, do it again */
  1128. }
  1129. #if defined(HAVE_SYS_TIMEPPS_H)
  1130. if (inner_context.kernelpps_handle > 0) {
  1131. thread_context->log_hook(thread_context, THREAD_PROG,
  1132. "KPPS:%s descriptor cleaned up\n",
  1133. thread_context->devicename);
  1134. (void)time_pps_destroy(inner_context.kernelpps_handle);
  1135. }
  1136. #endif
  1137. thread_context->log_hook(thread_context, THREAD_PROG,
  1138. "PPS:%s gpsd_ppsmonitor exited.\n",
  1139. thread_context->devicename);
  1140. return NULL;
  1141. }
  1142. /*
  1143. * Entry points begin here.
  1144. */
  1145. void pps_thread_activate(volatile struct pps_thread_t *pps_thread)
  1146. /* activate a thread to watch the device's PPS transitions */
  1147. {
  1148. int retval;
  1149. pthread_t pt;
  1150. struct timespec start_delay = {0, 1000000}; /* 1 ms */
  1151. /*
  1152. * FIXME: this launch code is not itself thread-safe!
  1153. * It would be if inner_context could be auto, but the monitor
  1154. * routine gets garbage when we try that. Ideally the body
  1155. * of this function would be guarded by a separate mutex.
  1156. * Either that, or this should be an exception to the no-malloc rule.
  1157. */
  1158. static struct inner_context_t inner_context;
  1159. inner_context.pps_thread = pps_thread;
  1160. #if defined(HAVE_SYS_TIMEPPS_H)
  1161. /* some operations in init_kernel_pps() require root privs */
  1162. (void)init_kernel_pps(&inner_context);
  1163. if ( 0 <= inner_context.kernelpps_handle ) {
  1164. pps_thread->log_hook(pps_thread, THREAD_INF,
  1165. "KPPS:%s kernel PPS will be used\n",
  1166. pps_thread->devicename);
  1167. } else {
  1168. pps_thread->log_hook(pps_thread, THREAD_WARN,
  1169. "KPPS:%s kernel PPS unavailable, PPS accuracy will suffer\n",
  1170. pps_thread->devicename);
  1171. }
  1172. #else
  1173. pps_thread->log_hook(pps_thread, THREAD_WARN,
  1174. "KPPS:%s no HAVE_SYS_TIMEPPS_H, PPS accuracy will suffer\n",
  1175. pps_thread->devicename);
  1176. #endif
  1177. memset( &pt, 0, sizeof(pt));
  1178. retval = pthread_create(&pt, NULL, gpsd_ppsmonitor, (void *)&inner_context);
  1179. pps_thread->log_hook(pps_thread, THREAD_PROG, "PPS:%s thread %s\n",
  1180. pps_thread->devicename,
  1181. (retval==0) ? "launched" : "FAILED");
  1182. /* The monitor thread may not run immediately, particularly on a single-
  1183. * core machine, so we need to wait for it to acknowledge its copying
  1184. * of the inner_context struct before proceeding.
  1185. */
  1186. while (inner_context.pps_thread)
  1187. (void) nanosleep(&start_delay, NULL);
  1188. }
  1189. void pps_thread_deactivate(volatile struct pps_thread_t *pps_thread)
  1190. /* cleanly terminate PPS thread */
  1191. {
  1192. pps_thread->report_hook = NULL;
  1193. }
  1194. /* thread-safe update of last fix time - only way we pass data in */
  1195. void pps_thread_fixin(volatile struct pps_thread_t *pps_thread,
  1196. volatile struct timedelta_t *fix_in)
  1197. {
  1198. thread_lock(pps_thread);
  1199. pps_thread->fix_in = *fix_in;
  1200. thread_unlock(pps_thread);
  1201. }
  1202. /* thread-safe update of qErr and qErr_time - only way we pass data in */
  1203. void pps_thread_qErrin(volatile struct pps_thread_t *pps_thread,
  1204. long qErr, struct timespec qErr_time)
  1205. {
  1206. thread_lock(pps_thread);
  1207. pps_thread->qErr = qErr;
  1208. pps_thread->qErr_time = qErr_time;
  1209. thread_unlock(pps_thread);
  1210. }
  1211. int pps_thread_ppsout(volatile struct pps_thread_t *pps_thread,
  1212. volatile struct timedelta_t *td)
  1213. /* return the delta at the time of the last PPS - only way we pass data out */
  1214. {
  1215. volatile int ret;
  1216. thread_lock(pps_thread);
  1217. *td = pps_thread->pps_out;
  1218. ret = pps_thread->ppsout_count;
  1219. thread_unlock(pps_thread);
  1220. return ret;
  1221. }
  1222. /* end */
  1223. // vim: set expandtab shiftwidth=4