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