Accuracy of PI controller that calculates actual clock frequency adjustment needed to synchronize clocks can be improved with trivial change to achieve <20ns synch with hardware support.
Currently the resolution of PI controller is limited by the way the error value is integrated using following method
ptpClock->observed_drift += ptpClock->offsetFromMaster.nanoseconds / ptpClock->observed_drift*rtOpts->ai;
adj = ptpClock->offsetFromMaster.nanoseconds/rtOpts->ap + ptpClock->observed_drift;
If offsetFromMaster < rtOpts->ai nanoseconds, the error is not accumulated into observed_drift and cannot be used to tune the PI-controller.
If the code is changed to
ptpClock->observed_drift += ptpClock->offsetFromMaster.nanoseconds;
adj = ptpClock->offsetFromMaster.nanoseconds/rtOpts->ap + ptpClock->observed_drift/rtOpts->ai;
Accuracy is greatly improved. I've managed to get accuracies down to 5-10 ns with 5 syncs/second with pretty inexpensive microcontroller that has PTP hardware support.