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  * @adjfreq:  Adjusts the frequency of the hardware clock.
81  *            This method is deprecated.  New drivers should implement
82  *            the @adjfine method instead.
83  *            parameter delta: Desired frequency offset from nominal frequency
84  *            in parts per billion
85  *
86  * @adjphase:  Adjusts the phase offset of the hardware clock.
87  *             parameter delta: Desired change in nanoseconds.
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 (*adjfreq)(struct ptp_clock_info *ptp, s32 delta);
178 	int (*adjphase)(struct ptp_clock_info *ptp, s32 phase);
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_PPS,
204 	PTP_CLOCK_PPSUSR,
205 };
206 
207 /**
208  * struct ptp_clock_event - decribes a PTP hardware clock event
209  *
210  * @type:  One of the ptp_clock_events enumeration values.
211  * @index: Identifies the source of the event.
212  * @timestamp: When the event occurred (%PTP_CLOCK_EXTTS only).
213  * @pps_times: When the event occurred (%PTP_CLOCK_PPSUSR only).
214  */
215 
216 struct ptp_clock_event {
217 	int type;
218 	int index;
219 	union {
220 		u64 timestamp;
221 		struct pps_event_time pps_times;
222 	};
223 };
224 
225 /**
226  * scaled_ppm_to_ppb() - convert scaled ppm to ppb
227  *
228  * @ppm:    Parts per million, but with a 16 bit binary fractional field
229  */
230 static inline long scaled_ppm_to_ppb(long ppm)
231 {
232 	/*
233 	 * The 'freq' field in the 'struct timex' is in parts per
234 	 * million, but with a 16 bit binary fractional field.
235 	 *
236 	 * We want to calculate
237 	 *
238 	 *    ppb = scaled_ppm * 1000 / 2^16
239 	 *
240 	 * which simplifies to
241 	 *
242 	 *    ppb = scaled_ppm * 125 / 2^13
243 	 */
244 	s64 ppb = 1 + ppm;
245 
246 	ppb *= 125;
247 	ppb >>= 13;
248 	return (long)ppb;
249 }
250 
251 #if IS_ENABLED(CONFIG_PTP_1588_CLOCK)
252 
253 /**
254  * ptp_clock_register() - register a PTP hardware clock driver
255  *
256  * @info:   Structure describing the new clock.
257  * @parent: Pointer to the parent device of the new clock.
258  *
259  * Returns a valid pointer on success or PTR_ERR on failure.  If PHC
260  * support is missing at the configuration level, this function
261  * returns NULL, and drivers are expected to gracefully handle that
262  * case separately.
263  */
264 
265 extern struct ptp_clock *ptp_clock_register(struct ptp_clock_info *info,
266 					    struct device *parent);
267 
268 /**
269  * ptp_clock_unregister() - unregister a PTP hardware clock driver
270  *
271  * @ptp:  The clock to remove from service.
272  */
273 
274 extern int ptp_clock_unregister(struct ptp_clock *ptp);
275 
276 /**
277  * ptp_clock_event() - notify the PTP layer about an event
278  *
279  * @ptp:    The clock obtained from ptp_clock_register().
280  * @event:  Message structure describing the event.
281  */
282 
283 extern void ptp_clock_event(struct ptp_clock *ptp,
284 			    struct ptp_clock_event *event);
285 
286 /**
287  * ptp_clock_index() - obtain the device index of a PTP clock
288  *
289  * @ptp:    The clock obtained from ptp_clock_register().
290  */
291 
292 extern int ptp_clock_index(struct ptp_clock *ptp);
293 
294 /**
295  * ptp_find_pin() - obtain the pin index of a given auxiliary function
296  *
297  * The caller must hold ptp_clock::pincfg_mux.  Drivers do not have
298  * access to that mutex as ptp_clock is an opaque type.  However, the
299  * core code acquires the mutex before invoking the driver's
300  * ptp_clock_info::enable() callback, and so drivers may call this
301  * function from that context.
302  *
303  * @ptp:    The clock obtained from ptp_clock_register().
304  * @func:   One of the ptp_pin_function enumerated values.
305  * @chan:   The particular functional channel to find.
306  * Return:  Pin index in the range of zero to ptp_clock_caps.n_pins - 1,
307  *          or -1 if the auxiliary function cannot be found.
308  */
309 
310 int ptp_find_pin(struct ptp_clock *ptp,
311 		 enum ptp_pin_function func, unsigned int chan);
312 
313 /**
314  * ptp_find_pin_unlocked() - wrapper for ptp_find_pin()
315  *
316  * This function acquires the ptp_clock::pincfg_mux mutex before
317  * invoking ptp_find_pin().  Instead of using this function, drivers
318  * should most likely call ptp_find_pin() directly from their
319  * ptp_clock_info::enable() method.
320  *
321 * @ptp:    The clock obtained from ptp_clock_register().
322 * @func:   One of the ptp_pin_function enumerated values.
323 * @chan:   The particular functional channel to find.
324 * Return:  Pin index in the range of zero to ptp_clock_caps.n_pins - 1,
325 *          or -1 if the auxiliary function cannot be found.
326  */
327 
328 int ptp_find_pin_unlocked(struct ptp_clock *ptp,
329 			  enum ptp_pin_function func, unsigned int chan);
330 
331 /**
332  * ptp_schedule_worker() - schedule ptp auxiliary work
333  *
334  * @ptp:    The clock obtained from ptp_clock_register().
335  * @delay:  number of jiffies to wait before queuing
336  *          See kthread_queue_delayed_work() for more info.
337  */
338 
339 int ptp_schedule_worker(struct ptp_clock *ptp, unsigned long delay);
340 
341 /**
342  * ptp_cancel_worker_sync() - cancel ptp auxiliary clock
343  *
344  * @ptp:     The clock obtained from ptp_clock_register().
345  */
346 void ptp_cancel_worker_sync(struct ptp_clock *ptp);
347 
348 #else
349 static inline struct ptp_clock *ptp_clock_register(struct ptp_clock_info *info,
350 						   struct device *parent)
351 { return NULL; }
352 static inline int ptp_clock_unregister(struct ptp_clock *ptp)
353 { return 0; }
354 static inline void ptp_clock_event(struct ptp_clock *ptp,
355 				   struct ptp_clock_event *event)
356 { }
357 static inline int ptp_clock_index(struct ptp_clock *ptp)
358 { return -1; }
359 static inline int ptp_find_pin(struct ptp_clock *ptp,
360 			       enum ptp_pin_function func, unsigned int chan)
361 { return -1; }
362 static inline int ptp_find_pin_unlocked(struct ptp_clock *ptp,
363 					enum ptp_pin_function func,
364 					unsigned int chan)
365 { return -1; }
366 static inline int ptp_schedule_worker(struct ptp_clock *ptp,
367 				      unsigned long delay)
368 { return -EOPNOTSUPP; }
369 static inline void ptp_cancel_worker_sync(struct ptp_clock *ptp)
370 { }
371 #endif
372 
373 #if IS_BUILTIN(CONFIG_PTP_1588_CLOCK)
374 /*
375  * These are called by the network core, and don't work if PTP is in
376  * a loadable module.
377  */
378 
379 /**
380  * ptp_get_vclocks_index() - get all vclocks index on pclock, and
381  *                           caller is responsible to free memory
382  *                           of vclock_index
383  *
384  * @pclock_index: phc index of ptp pclock.
385  * @vclock_index: pointer to pointer of vclock index.
386  *
387  * return number of vclocks.
388  */
389 int ptp_get_vclocks_index(int pclock_index, int **vclock_index);
390 
391 /**
392  * ptp_convert_timestamp() - convert timestamp to a ptp vclock time
393  *
394  * @hwtstamp:     timestamp
395  * @vclock_index: phc index of ptp vclock.
396  *
397  * Returns converted timestamp, or 0 on error.
398  */
399 ktime_t ptp_convert_timestamp(const ktime_t *hwtstamp, int vclock_index);
400 #else
401 static inline int ptp_get_vclocks_index(int pclock_index, int **vclock_index)
402 { return 0; }
403 static inline ktime_t ptp_convert_timestamp(const ktime_t *hwtstamp,
404 					    int vclock_index)
405 { return 0; }
406 
407 #endif
408 
409 static inline void ptp_read_system_prets(struct ptp_system_timestamp *sts)
410 {
411 	if (sts)
412 		ktime_get_real_ts64(&sts->pre_ts);
413 }
414 
415 static inline void ptp_read_system_postts(struct ptp_system_timestamp *sts)
416 {
417 	if (sts)
418 		ktime_get_real_ts64(&sts->post_ts);
419 }
420 
421 #endif
422