xref: /linux/include/linux/ptp_clock_kernel.h (revision 6b3f7af57881f6d6250c6dcc4d910fe8e855a607)
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 /*
3  * PTP 1588 clock support
4  *
5  * Copyright (C) 2010 OMICRON electronics GmbH
6  */
7 
8 #ifndef _PTP_CLOCK_KERNEL_H_
9 #define _PTP_CLOCK_KERNEL_H_
10 
11 #include <linux/device.h>
12 #include <linux/pps_kernel.h>
13 #include <linux/ptp_clock.h>
14 #include <linux/timecounter.h>
15 #include <linux/timekeeping.h>
16 #include <linux/skbuff.h>
17 
18 #define PTP_CLOCK_NAME_LEN	32
19 /**
20  * struct ptp_clock_request - request PTP clock event
21  *
22  * @type:   The type of the request.
23  *	    EXTTS:  Configure external trigger timestamping
24  *	    PEROUT: Configure periodic output signal (e.g. PPS)
25  *	    PPS:    trigger internal PPS event for input
26  *	            into kernel PPS subsystem
27  * @extts:  describes configuration for external trigger timestamping.
28  *          This is only valid when event == PTP_CLK_REQ_EXTTS.
29  * @perout: describes configuration for periodic output.
30  *	    This is only valid when event == PTP_CLK_REQ_PEROUT.
31  */
32 
33 struct ptp_clock_request {
34 	enum {
35 		PTP_CLK_REQ_EXTTS,
36 		PTP_CLK_REQ_PEROUT,
37 		PTP_CLK_REQ_PPS,
38 	} type;
39 	union {
40 		struct ptp_extts_request extts;
41 		struct ptp_perout_request perout;
42 	};
43 };
44 
45 struct system_device_crosststamp;
46 
47 /**
48  * struct ptp_system_timestamp - system time corresponding to a PHC timestamp
49  * @pre_sts:	system time snapshot before capturing PHC
50  * @post_sts:	system time snapshot after capturing PHC
51  * @clockid:	clock-base used for capturing the system timestamps
52  */
53 struct ptp_system_timestamp {
54 	struct system_time_snapshot pre_sts;
55 	struct system_time_snapshot post_sts;
56 	clockid_t clockid;
57 };
58 
59 /**
60  * struct ptp_clock_info - describes a PTP hardware clock
61  *
62  * @owner:     The clock driver should set to THIS_MODULE.
63  * @name:      A short "friendly name" to identify the clock and to
64  *             help distinguish PHY based devices from MAC based ones.
65  *             The string is not meant to be a unique id.
66  * @max_adj:   The maximum possible frequency adjustment, in parts per billon.
67  * @n_alarm:   The number of programmable alarms.
68  * @n_ext_ts:  The number of external time stamp channels.
69  * @n_per_out: The number of programmable periodic signals.
70  * @n_pins:    The number of programmable pins.
71  * @n_per_lp:  The number of channels that support loopback the periodic
72  *             output signal.
73  * @pps:       Indicates whether the clock supports a PPS callback.
74  *
75  * @supported_perout_flags:  The set of flags the driver supports for the
76  *                           PTP_PEROUT_REQUEST ioctl. The PTP core will
77  *                           reject a request with any flag not specified
78  *                           here.
79  *
80  * @supported_extts_flags:  The set of flags the driver supports for the
81  *                          PTP_EXTTS_REQUEST ioctl. The PTP core will use
82  *                          this list to reject unsupported requests.
83  *                          PTP_ENABLE_FEATURE is assumed and does not need to
84  *                          be included. If PTP_STRICT_FLAGS is *not* set,
85  *                          then both PTP_RISING_EDGE and PTP_FALLING_EDGE
86  *                          will be assumed. Note that PTP_STRICT_FLAGS must
87  *                          be set if the drivers wants to honor
88  *                          PTP_EXTTS_REQUEST2 and any future flags.
89  *
90  * @pin_config: Array of length 'n_pins'. If the number of
91  *              programmable pins is nonzero, then drivers must
92  *              allocate and initialize this array.
93  *
94  * clock operations
95  *
96  * @adjfine:  Adjusts the frequency of the hardware clock.
97  *            parameter scaled_ppm: Desired frequency offset from
98  *            nominal frequency in parts per million, but with a
99  *            16 bit binary fractional field.
100  *
101  * @adjphase:  Indicates that the PHC should use an internal servo
102  *             algorithm to correct the provided phase offset.
103  *             parameter delta: PHC servo phase adjustment target
104  *                              in nanoseconds.
105  *
106  * @getmaxphase:  Advertises maximum offset that can be provided
107  *                to the hardware clock's phase control functionality
108  *                through adjphase.
109  *
110  * @adjtime:  Shifts the time of the hardware clock.
111  *            parameter delta: Desired change in nanoseconds.
112  *
113  * @gettime64:  Reads the current time from the hardware clock.
114  *              This method is deprecated.  New drivers should implement
115  *              the @gettimex64 method instead.
116  *              parameter ts: Holds the result.
117  *
118  * @gettimex64:  Reads the current time from the hardware clock and optionally
119  *               also the system clock.
120  *               parameter ts: Holds the PHC timestamp.
121  *               parameter sts: If not NULL, it holds a pair of timestamps from
122  *               the system clock. The first reading is made right before
123  *               reading the lowest bits of the PHC timestamp and the second
124  *               reading immediately follows that.
125  *
126  * @getcrosststamp:  Reads the current time from the hardware clock and
127  *                   system clock simultaneously.
128  *                   parameter cts: Contains timestamp (device,system) pair,
129  *                   where system time is realtime and monotonic.
130  *
131  * @settime64:  Set the current time on the hardware clock.
132  *              parameter ts: Time value to set.
133  *
134  * @getcycles64:  Reads the current free running cycle counter from the hardware
135  *                clock.
136  *                If @getcycles64 and @getcyclesx64 are not supported, then
137  *                @gettime64 or @gettimex64 will be used as default
138  *                implementation.
139  *                parameter ts: Holds the result.
140  *
141  * @getcyclesx64:  Reads the current free running cycle counter from the
142  *                 hardware clock and optionally also the system clock.
143  *                 If @getcycles64 and @getcyclesx64 are not supported, then
144  *                 @gettimex64 will be used as default implementation if
145  *                 available.
146  *                 parameter ts: Holds the PHC timestamp.
147  *                 parameter sts: If not NULL, it holds a pair of timestamps
148  *                 from the system clock. The first reading is made right before
149  *                 reading the lowest bits of the PHC timestamp and the second
150  *                 reading immediately follows that.
151  *
152  * @getcrosscycles:  Reads the current free running cycle counter from the
153  *                   hardware clock and system clock simultaneously.
154  *                   If @getcycles64 and @getcyclesx64 are not supported, then
155  *                   @getcrosststamp will be used as default implementation if
156  *                   available.
157  *                   parameter cts: Contains timestamp (device,system) pair,
158  *                   where system time is realtime and monotonic.
159  *
160  * @enable:   Request driver to enable or disable an ancillary feature.
161  *            parameter request: Desired resource to enable or disable.
162  *            parameter on: Caller passes one to enable or zero to disable.
163  *
164  * @verify:   Confirm that a pin can perform a given function. The PTP
165  *            Hardware Clock subsystem maintains the 'pin_config'
166  *            array on behalf of the drivers, but the PHC subsystem
167  *            assumes that every pin can perform every function. This
168  *            hook gives drivers a way of telling the core about
169  *            limitations on specific pins. This function must return
170  *            zero if the function can be assigned to this pin, and
171  *            nonzero otherwise.
172  *            parameter pin: index of the pin in question.
173  *            parameter func: the desired function to use.
174  *            parameter chan: the function channel index to use.
175  *
176  * @do_aux_work:  Request driver to perform auxiliary (periodic) operations
177  *                Driver should return delay of the next auxiliary work
178  *                scheduling time (>=0) or negative value in case further
179  *                scheduling is not required.
180  *
181  * @perout_loopback: Request driver to enable or disable the periodic output
182  *                   signal loopback.
183  *                   parameter index: index of the periodic output signal channel.
184  *                   parameter on: caller passes one to enable or zero to disable.
185  *
186  * Drivers should embed their ptp_clock_info within a private
187  * structure, obtaining a reference to it using container_of().
188  *
189  * The callbacks must all return zero on success, non-zero otherwise.
190  */
191 
192 struct ptp_clock_info {
193 	struct module *owner;
194 	char name[PTP_CLOCK_NAME_LEN];
195 	s32 max_adj;
196 	int n_alarm;
197 	int n_ext_ts;
198 	int n_per_out;
199 	int n_pins;
200 	int n_per_lp;
201 	int pps;
202 	unsigned int supported_perout_flags;
203 	unsigned int supported_extts_flags;
204 	struct ptp_pin_desc *pin_config;
205 	int (*adjfine)(struct ptp_clock_info *ptp, long scaled_ppm);
206 	int (*adjphase)(struct ptp_clock_info *ptp, s32 phase);
207 	s32 (*getmaxphase)(struct ptp_clock_info *ptp);
208 	int (*adjtime)(struct ptp_clock_info *ptp, s64 delta);
209 	int (*gettime64)(struct ptp_clock_info *ptp, struct timespec64 *ts);
210 	int (*gettimex64)(struct ptp_clock_info *ptp, struct timespec64 *ts,
211 			  struct ptp_system_timestamp *sts);
212 	int (*getcrosststamp)(struct ptp_clock_info *ptp,
213 			      struct system_device_crosststamp *cts);
214 	int (*settime64)(struct ptp_clock_info *p, const struct timespec64 *ts);
215 	int (*getcycles64)(struct ptp_clock_info *ptp, struct timespec64 *ts);
216 	int (*getcyclesx64)(struct ptp_clock_info *ptp, struct timespec64 *ts,
217 			    struct ptp_system_timestamp *sts);
218 	int (*getcrosscycles)(struct ptp_clock_info *ptp,
219 			      struct system_device_crosststamp *cts);
220 	int (*enable)(struct ptp_clock_info *ptp,
221 		      struct ptp_clock_request *request, int on);
222 	int (*verify)(struct ptp_clock_info *ptp, unsigned int pin,
223 		      enum ptp_pin_function func, unsigned int chan);
224 	long (*do_aux_work)(struct ptp_clock_info *ptp);
225 	int (*perout_loopback)(struct ptp_clock_info *ptp, unsigned int index,
226 			       int on);
227 };
228 
229 struct ptp_clock;
230 
231 enum ptp_clock_events {
232 	PTP_CLOCK_ALARM,
233 	PTP_CLOCK_EXTTS,
234 	PTP_CLOCK_EXTOFF,
235 	PTP_CLOCK_PPS,
236 	PTP_CLOCK_PPSUSR,
237 };
238 
239 /**
240  * struct ptp_clock_event - decribes a PTP hardware clock event
241  *
242  * @type:  One of the ptp_clock_events enumeration values.
243  * @index: Identifies the source of the event.
244  * @timestamp: When the event occurred (%PTP_CLOCK_EXTTS only).
245  * @offset:    When the event occurred (%PTP_CLOCK_EXTOFF only).
246  * @pps_times: When the event occurred (%PTP_CLOCK_PPSUSR only).
247  */
248 
249 struct ptp_clock_event {
250 	int type;
251 	int index;
252 	union {
253 		u64 timestamp;
254 		s64 offset;
255 		struct pps_event_time pps_times;
256 	};
257 };
258 
259 /**
260  * scaled_ppm_to_ppb() - convert scaled ppm to ppb
261  *
262  * @ppm:    Parts per million, but with a 16 bit binary fractional field
263  */
264 static inline long scaled_ppm_to_ppb(long ppm)
265 {
266 	/*
267 	 * The 'freq' field in the 'struct timex' is in parts per
268 	 * million, but with a 16 bit binary fractional field.
269 	 *
270 	 * We want to calculate
271 	 *
272 	 *    ppb = scaled_ppm * 1000 / 2^16
273 	 *
274 	 * which simplifies to
275 	 *
276 	 *    ppb = scaled_ppm * 125 / 2^13
277 	 */
278 	s64 ppb = 1 + ppm;
279 
280 	ppb *= 125;
281 	ppb >>= 13;
282 	return (long)ppb;
283 }
284 
285 /**
286  * diff_by_scaled_ppm - Calculate difference using scaled ppm
287  * @base: the base increment value to adjust
288  * @scaled_ppm: scaled parts per million to adjust by
289  * @diff: on return, the absolute value of calculated diff
290  *
291  * Calculate the difference to adjust the base increment using scaled parts
292  * per million.
293  *
294  * Use mul_u64_u64_div_u64 to perform the difference calculation in avoid
295  * possible overflow.
296  *
297  * Returns: true if scaled_ppm is negative, false otherwise
298  */
299 static inline bool diff_by_scaled_ppm(u64 base, long scaled_ppm, u64 *diff)
300 {
301 	bool negative = false;
302 
303 	if (scaled_ppm < 0) {
304 		negative = true;
305 		scaled_ppm = -scaled_ppm;
306 	}
307 
308 	*diff = mul_u64_u64_div_u64(base, (u64)scaled_ppm, 1000000ULL << 16);
309 
310 	return negative;
311 }
312 
313 /**
314  * adjust_by_scaled_ppm - Adjust a base increment by scaled parts per million
315  * @base: the base increment value to adjust
316  * @scaled_ppm: scaled parts per million frequency adjustment
317  *
318  * Helper function which calculates a new increment value based on the
319  * requested scaled parts per million adjustment.
320  */
321 static inline u64 adjust_by_scaled_ppm(u64 base, long scaled_ppm)
322 {
323 	u64 diff;
324 
325 	if (diff_by_scaled_ppm(base, scaled_ppm, &diff))
326 		return base - diff;
327 
328 	return base + diff;
329 }
330 
331 #if IS_ENABLED(CONFIG_PTP_1588_CLOCK)
332 
333 /**
334  * ptp_clock_register() - register a PTP hardware clock driver
335  *
336  * @info:   Structure describing the new clock.
337  * @parent: Pointer to the parent device of the new clock.
338  *
339  * Returns: a valid pointer on success or PTR_ERR on failure.  If PHC
340  * support is missing at the configuration level, this function
341  * returns NULL, and drivers are expected to gracefully handle that
342  * case separately.
343  */
344 
345 extern struct ptp_clock *ptp_clock_register(struct ptp_clock_info *info,
346 					    struct device *parent);
347 
348 /**
349  * ptp_clock_unregister() - unregister a PTP hardware clock driver
350  *
351  * @ptp:  The clock to remove from service.
352  */
353 
354 extern int ptp_clock_unregister(struct ptp_clock *ptp);
355 
356 /**
357  * ptp_clock_event() - notify the PTP layer about an event
358  *
359  * @ptp:    The clock obtained from ptp_clock_register().
360  * @event:  Message structure describing the event.
361  */
362 
363 extern void ptp_clock_event(struct ptp_clock *ptp,
364 			    struct ptp_clock_event *event);
365 
366 /**
367  * ptp_clock_index() - obtain the device index of a PTP clock
368  *
369  * @ptp:    The clock obtained from ptp_clock_register().
370  */
371 
372 extern int ptp_clock_index(struct ptp_clock *ptp);
373 
374 /**
375  * ptp_clock_index_by_of_node() - obtain the device index of
376  * a PTP clock based on the PTP device of_node
377  *
378  * @np:    The device of_node pointer of the PTP device.
379  * Return: The PHC index on success or -1 on failure.
380  */
381 int ptp_clock_index_by_of_node(struct device_node *np);
382 
383 /**
384  * ptp_clock_index_by_dev() - obtain the device index of
385  * a PTP clock based on the PTP device.
386  *
387  * @parent:    The parent device (PTP device) pointer of the PTP clock.
388  * Return: The PHC index on success or -1 on failure.
389  */
390 int ptp_clock_index_by_dev(struct device *parent);
391 
392 /**
393  * ptp_find_pin() - obtain the pin index of a given auxiliary function
394  *
395  * The caller must hold ptp_clock::pincfg_mux.  Drivers do not have
396  * access to that mutex as ptp_clock is an opaque type.  However, the
397  * core code acquires the mutex before invoking the driver's
398  * ptp_clock_info::enable() callback, and so drivers may call this
399  * function from that context.
400  *
401  * @ptp:    The clock obtained from ptp_clock_register().
402  * @func:   One of the ptp_pin_function enumerated values.
403  * @chan:   The particular functional channel to find.
404  * Return:  Pin index in the range of zero to ptp_clock_caps.n_pins - 1,
405  *          or -1 if the auxiliary function cannot be found.
406  */
407 
408 int ptp_find_pin(struct ptp_clock *ptp,
409 		 enum ptp_pin_function func, unsigned int chan);
410 
411 /**
412  * ptp_find_pin_unlocked() - wrapper for ptp_find_pin()
413  *
414  * This function acquires the ptp_clock::pincfg_mux mutex before
415  * invoking ptp_find_pin().  Instead of using this function, drivers
416  * should most likely call ptp_find_pin() directly from their
417  * ptp_clock_info::enable() method.
418  *
419 * @ptp:    The clock obtained from ptp_clock_register().
420 * @func:   One of the ptp_pin_function enumerated values.
421 * @chan:   The particular functional channel to find.
422 * Return:  Pin index in the range of zero to ptp_clock_caps.n_pins - 1,
423 *          or -1 if the auxiliary function cannot be found.
424  */
425 
426 int ptp_find_pin_unlocked(struct ptp_clock *ptp,
427 			  enum ptp_pin_function func, unsigned int chan);
428 
429 /**
430  * ptp_schedule_worker() - schedule ptp auxiliary work
431  *
432  * @ptp:    The clock obtained from ptp_clock_register().
433  * @delay:  number of jiffies to wait before queuing
434  *          See kthread_queue_delayed_work() for more info.
435  */
436 
437 int ptp_schedule_worker(struct ptp_clock *ptp, unsigned long delay);
438 
439 /**
440  * ptp_cancel_worker_sync() - cancel ptp auxiliary clock
441  *
442  * @ptp:     The clock obtained from ptp_clock_register().
443  */
444 void ptp_cancel_worker_sync(struct ptp_clock *ptp);
445 
446 #else
447 static inline struct ptp_clock *ptp_clock_register(struct ptp_clock_info *info,
448 						   struct device *parent)
449 { return NULL; }
450 static inline int ptp_clock_unregister(struct ptp_clock *ptp)
451 { return 0; }
452 static inline void ptp_clock_event(struct ptp_clock *ptp,
453 				   struct ptp_clock_event *event)
454 { }
455 static inline int ptp_clock_index(struct ptp_clock *ptp)
456 { return -1; }
457 static inline int ptp_clock_index_by_of_node(struct device_node *np)
458 { return -1; }
459 static inline int ptp_clock_index_by_dev(struct device *parent)
460 { return -1; }
461 static inline int ptp_find_pin(struct ptp_clock *ptp,
462 			       enum ptp_pin_function func, unsigned int chan)
463 { return -1; }
464 static inline int ptp_find_pin_unlocked(struct ptp_clock *ptp,
465 					enum ptp_pin_function func,
466 					unsigned int chan)
467 { return -1; }
468 static inline int ptp_schedule_worker(struct ptp_clock *ptp,
469 				      unsigned long delay)
470 { return -EOPNOTSUPP; }
471 static inline void ptp_cancel_worker_sync(struct ptp_clock *ptp)
472 { }
473 #endif
474 
475 #if IS_BUILTIN(CONFIG_PTP_1588_CLOCK)
476 /*
477  * These are called by the network core, and don't work if PTP is in
478  * a loadable module.
479  */
480 
481 /**
482  * ptp_get_vclocks_index() - get all vclocks index on pclock, and
483  *                           caller is responsible to free memory
484  *                           of vclock_index
485  *
486  * @pclock_index: phc index of ptp pclock.
487  * @vclock_index: pointer to pointer of vclock index.
488  *
489  * return number of vclocks.
490  */
491 int ptp_get_vclocks_index(int pclock_index, int **vclock_index);
492 
493 /**
494  * ptp_convert_timestamp() - convert timestamp to a ptp vclock time
495  *
496  * @hwtstamp:     timestamp
497  * @vclock_index: phc index of ptp vclock.
498  *
499  * Returns: converted timestamp, or 0 on error.
500  */
501 ktime_t ptp_convert_timestamp(const ktime_t *hwtstamp, int vclock_index);
502 #else
503 static inline int ptp_get_vclocks_index(int pclock_index, int **vclock_index)
504 { return 0; }
505 static inline ktime_t ptp_convert_timestamp(const ktime_t *hwtstamp,
506 					    int vclock_index)
507 { return 0; }
508 
509 #endif
510 
511 static inline void ptp_read_system_prets(struct ptp_system_timestamp *sts)
512 {
513 	if (sts)
514 		ktime_get_snapshot_id(sts->clockid, &sts->pre_sts);
515 }
516 
517 static inline void ptp_read_system_postts(struct ptp_system_timestamp *sts)
518 {
519 	if (sts)
520 		ktime_get_snapshot_id(sts->clockid, &sts->post_sts);
521 }
522 
523 #endif
524