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