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