1 // SPDX-License-Identifier: GPL-2.0-only
2 /****************************************************************************
3  * Driver for Solarflare network controllers and boards
4  * Copyright 2011-2013 Solarflare Communications Inc.
5  */
6 
7 /* Theory of operation:
8  *
9  * PTP support is assisted by firmware running on the MC, which provides
10  * the hardware timestamping capabilities.  Both transmitted and received
11  * PTP event packets are queued onto internal queues for subsequent processing;
12  * this is because the MC operations are relatively long and would block
13  * block NAPI/interrupt operation.
14  *
15  * Receive event processing:
16  *	The event contains the packet's UUID and sequence number, together
17  *	with the hardware timestamp.  The PTP receive packet queue is searched
18  *	for this UUID/sequence number and, if found, put on a pending queue.
19  *	Packets not matching are delivered without timestamps (MCDI events will
20  *	always arrive after the actual packet).
21  *	It is important for the operation of the PTP protocol that the ordering
22  *	of packets between the event and general port is maintained.
23  *
24  * Work queue processing:
25  *	If work waiting, synchronise host/hardware time
26  *
27  *	Transmit: send packet through MC, which returns the transmission time
28  *	that is converted to an appropriate timestamp.
29  *
30  *	Receive: the packet's reception time is converted to an appropriate
31  *	timestamp.
32  */
33 #include <linux/ip.h>
34 #include <linux/udp.h>
35 #include <linux/time.h>
36 #include <linux/ktime.h>
37 #include <linux/module.h>
38 #include <linux/pps_kernel.h>
39 #include <linux/ptp_clock_kernel.h>
40 #include "net_driver.h"
41 #include "efx.h"
42 #include "mcdi.h"
43 #include "mcdi_pcol.h"
44 #include "io.h"
45 #include "farch_regs.h"
46 #include "tx.h"
47 #include "nic.h" /* indirectly includes ptp.h */
48 #include "efx_channels.h"
49 
50 /* Maximum number of events expected to make up a PTP event */
51 #define	MAX_EVENT_FRAGS			3
52 
53 /* Maximum delay, ms, to begin synchronisation */
54 #define	MAX_SYNCHRONISE_WAIT_MS		2
55 
56 /* How long, at most, to spend synchronising */
57 #define	SYNCHRONISE_PERIOD_NS		250000
58 
59 /* How often to update the shared memory time */
60 #define	SYNCHRONISATION_GRANULARITY_NS	200
61 
62 /* Minimum permitted length of a (corrected) synchronisation time */
63 #define	DEFAULT_MIN_SYNCHRONISATION_NS	120
64 
65 /* Maximum permitted length of a (corrected) synchronisation time */
66 #define	MAX_SYNCHRONISATION_NS		1000
67 
68 /* How many (MC) receive events that can be queued */
69 #define	MAX_RECEIVE_EVENTS		8
70 
71 /* Length of (modified) moving average. */
72 #define	AVERAGE_LENGTH			16
73 
74 /* How long an unmatched event or packet can be held */
75 #define PKT_EVENT_LIFETIME_MS		10
76 
77 /* Offsets into PTP packet for identification.  These offsets are from the
78  * start of the IP header, not the MAC header.  Note that neither PTP V1 nor
79  * PTP V2 permit the use of IPV4 options.
80  */
81 #define PTP_DPORT_OFFSET	22
82 
83 #define PTP_V1_VERSION_LENGTH	2
84 #define PTP_V1_VERSION_OFFSET	28
85 
86 #define PTP_V1_UUID_LENGTH	6
87 #define PTP_V1_UUID_OFFSET	50
88 
89 #define PTP_V1_SEQUENCE_LENGTH	2
90 #define PTP_V1_SEQUENCE_OFFSET	58
91 
92 /* The minimum length of a PTP V1 packet for offsets, etc. to be valid:
93  * includes IP header.
94  */
95 #define	PTP_V1_MIN_LENGTH	64
96 
97 #define PTP_V2_VERSION_LENGTH	1
98 #define PTP_V2_VERSION_OFFSET	29
99 
100 #define PTP_V2_UUID_LENGTH	8
101 #define PTP_V2_UUID_OFFSET	48
102 
103 /* Although PTP V2 UUIDs are comprised a ClockIdentity (8) and PortNumber (2),
104  * the MC only captures the last six bytes of the clock identity. These values
105  * reflect those, not the ones used in the standard.  The standard permits
106  * mapping of V1 UUIDs to V2 UUIDs with these same values.
107  */
108 #define PTP_V2_MC_UUID_LENGTH	6
109 #define PTP_V2_MC_UUID_OFFSET	50
110 
111 #define PTP_V2_SEQUENCE_LENGTH	2
112 #define PTP_V2_SEQUENCE_OFFSET	58
113 
114 /* The minimum length of a PTP V2 packet for offsets, etc. to be valid:
115  * includes IP header.
116  */
117 #define	PTP_V2_MIN_LENGTH	63
118 
119 #define	PTP_MIN_LENGTH		63
120 
121 #define PTP_RXFILTERS_LEN	5
122 
123 #define PTP_ADDR_IPV4		0xe0000181	/* 224.0.1.129 */
124 #define PTP_ADDR_IPV6		{0xff, 0x0e, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
125 				0, 0x01, 0x81}	/* ff0e::181 */
126 #define PTP_EVENT_PORT		319
127 #define PTP_GENERAL_PORT	320
128 #define PTP_ADDR_ETHER		{0x01, 0x1b, 0x19, 0, 0, 0} /* 01-1B-19-00-00-00 */
129 
130 /* Annoyingly the format of the version numbers are different between
131  * versions 1 and 2 so it isn't possible to simply look for 1 or 2.
132  */
133 #define	PTP_VERSION_V1		1
134 
135 #define	PTP_VERSION_V2		2
136 #define	PTP_VERSION_V2_MASK	0x0f
137 
138 enum ptp_packet_state {
139 	PTP_PACKET_STATE_UNMATCHED = 0,
140 	PTP_PACKET_STATE_MATCHED,
141 	PTP_PACKET_STATE_TIMED_OUT,
142 	PTP_PACKET_STATE_MATCH_UNWANTED
143 };
144 
145 /* NIC synchronised with single word of time only comprising
146  * partial seconds and full nanoseconds: 10^9 ~ 2^30 so 2 bits for seconds.
147  */
148 #define	MC_NANOSECOND_BITS	30
149 #define	MC_NANOSECOND_MASK	((1 << MC_NANOSECOND_BITS) - 1)
150 #define	MC_SECOND_MASK		((1 << (32 - MC_NANOSECOND_BITS)) - 1)
151 
152 /* Maximum parts-per-billion adjustment that is acceptable */
153 #define MAX_PPB			1000000
154 
155 /* Precalculate scale word to avoid long long division at runtime */
156 /* This is equivalent to 2^66 / 10^9. */
157 #define PPB_SCALE_WORD  ((1LL << (57)) / 1953125LL)
158 
159 /* How much to shift down after scaling to convert to FP40 */
160 #define PPB_SHIFT_FP40		26
161 /* ... and FP44. */
162 #define PPB_SHIFT_FP44		22
163 
164 #define PTP_SYNC_ATTEMPTS	4
165 
166 /**
167  * struct efx_ptp_match - Matching structure, stored in sk_buff's cb area.
168  * @words: UUID and (partial) sequence number
169  * @expiry: Time after which the packet should be delivered irrespective of
170  *            event arrival.
171  * @state: The state of the packet - whether it is ready for processing or
172  *         whether that is of no interest.
173  */
174 struct efx_ptp_match {
175 	u32 words[DIV_ROUND_UP(PTP_V1_UUID_LENGTH, 4)];
176 	unsigned long expiry;
177 	enum ptp_packet_state state;
178 };
179 
180 /**
181  * struct efx_ptp_event_rx - A PTP receive event (from MC)
182  * @link: list of events
183  * @seq0: First part of (PTP) UUID
184  * @seq1: Second part of (PTP) UUID and sequence number
185  * @hwtimestamp: Event timestamp
186  * @expiry: Time which the packet arrived
187  */
188 struct efx_ptp_event_rx {
189 	struct list_head link;
190 	u32 seq0;
191 	u32 seq1;
192 	ktime_t hwtimestamp;
193 	unsigned long expiry;
194 };
195 
196 /**
197  * struct efx_ptp_timeset - Synchronisation between host and MC
198  * @host_start: Host time immediately before hardware timestamp taken
199  * @major: Hardware timestamp, major
200  * @minor: Hardware timestamp, minor
201  * @host_end: Host time immediately after hardware timestamp taken
202  * @wait: Number of NIC clock ticks between hardware timestamp being read and
203  *          host end time being seen
204  * @window: Difference of host_end and host_start
205  * @valid: Whether this timeset is valid
206  */
207 struct efx_ptp_timeset {
208 	u32 host_start;
209 	u32 major;
210 	u32 minor;
211 	u32 host_end;
212 	u32 wait;
213 	u32 window;	/* Derived: end - start, allowing for wrap */
214 };
215 
216 /**
217  * struct efx_ptp_data - Precision Time Protocol (PTP) state
218  * @efx: The NIC context
219  * @channel: The PTP channel (Siena only)
220  * @rx_ts_inline: Flag for whether RX timestamps are inline (else they are
221  *	separate events)
222  * @rxq: Receive SKB queue (awaiting timestamps)
223  * @txq: Transmit SKB queue
224  * @evt_list: List of MC receive events awaiting packets
225  * @evt_free_list: List of free events
226  * @evt_lock: Lock for manipulating evt_list and evt_free_list
227  * @rx_evts: Instantiated events (on evt_list and evt_free_list)
228  * @workwq: Work queue for processing pending PTP operations
229  * @work: Work task
230  * @reset_required: A serious error has occurred and the PTP task needs to be
231  *                  reset (disable, enable).
232  * @rxfilters: Receive filters when operating
233  * @rxfilters_count: Num of installed rxfilters, should be == PTP_RXFILTERS_LEN
234  * @config: Current timestamp configuration
235  * @enabled: PTP operation enabled
236  * @mode: Mode in which PTP operating (PTP version)
237  * @ns_to_nic_time: Function to convert from scalar nanoseconds to NIC time
238  * @nic_to_kernel_time: Function to convert from NIC to kernel time
239  * @nic_time: contains time details
240  * @nic_time.minor_max: Wrap point for NIC minor times
241  * @nic_time.sync_event_diff_min: Minimum acceptable difference between time
242  * in packet prefix and last MCDI time sync event i.e. how much earlier than
243  * the last sync event time a packet timestamp can be.
244  * @nic_time.sync_event_diff_max: Maximum acceptable difference between time
245  * in packet prefix and last MCDI time sync event i.e. how much later than
246  * the last sync event time a packet timestamp can be.
247  * @nic_time.sync_event_minor_shift: Shift required to make minor time from
248  * field in MCDI time sync event.
249  * @min_synchronisation_ns: Minimum acceptable corrected sync window
250  * @capabilities: Capabilities flags from the NIC
251  * @ts_corrections: contains corrections details
252  * @ts_corrections.ptp_tx: Required driver correction of PTP packet transmit
253  *                         timestamps
254  * @ts_corrections.ptp_rx: Required driver correction of PTP packet receive
255  *                         timestamps
256  * @ts_corrections.pps_out: PPS output error (information only)
257  * @ts_corrections.pps_in: Required driver correction of PPS input timestamps
258  * @ts_corrections.general_tx: Required driver correction of general packet
259  *                             transmit timestamps
260  * @ts_corrections.general_rx: Required driver correction of general packet
261  *                             receive timestamps
262  * @evt_frags: Partly assembled PTP events
263  * @evt_frag_idx: Current fragment number
264  * @evt_code: Last event code
265  * @start: Address at which MC indicates ready for synchronisation
266  * @host_time_pps: Host time at last PPS
267  * @adjfreq_ppb_shift: Shift required to convert scaled parts-per-billion
268  * frequency adjustment into a fixed point fractional nanosecond format.
269  * @current_adjfreq: Current ppb adjustment.
270  * @phc_clock: Pointer to registered phc device (if primary function)
271  * @phc_clock_info: Registration structure for phc device
272  * @pps_work: pps work task for handling pps events
273  * @pps_workwq: pps work queue
274  * @nic_ts_enabled: Flag indicating if NIC generated TS events are handled
275  * @txbuf: Buffer for use when transmitting (PTP) packets to MC (avoids
276  *         allocations in main data path).
277  * @good_syncs: Number of successful synchronisations.
278  * @fast_syncs: Number of synchronisations requiring short delay
279  * @bad_syncs: Number of failed synchronisations.
280  * @sync_timeouts: Number of synchronisation timeouts
281  * @no_time_syncs: Number of synchronisations with no good times.
282  * @invalid_sync_windows: Number of sync windows with bad durations.
283  * @undersize_sync_windows: Number of corrected sync windows that are too small
284  * @oversize_sync_windows: Number of corrected sync windows that are too large
285  * @rx_no_timestamp: Number of packets received without a timestamp.
286  * @timeset: Last set of synchronisation statistics.
287  * @xmit_skb: Transmit SKB function.
288  */
289 struct efx_ptp_data {
290 	struct efx_nic *efx;
291 	struct efx_channel *channel;
292 	bool rx_ts_inline;
293 	struct sk_buff_head rxq;
294 	struct sk_buff_head txq;
295 	struct list_head evt_list;
296 	struct list_head evt_free_list;
297 	spinlock_t evt_lock;
298 	struct efx_ptp_event_rx rx_evts[MAX_RECEIVE_EVENTS];
299 	struct workqueue_struct *workwq;
300 	struct work_struct work;
301 	bool reset_required;
302 	u32 rxfilters[PTP_RXFILTERS_LEN];
303 	size_t rxfilters_count;
304 	struct hwtstamp_config config;
305 	bool enabled;
306 	unsigned int mode;
307 	void (*ns_to_nic_time)(s64 ns, u32 *nic_major, u32 *nic_minor);
308 	ktime_t (*nic_to_kernel_time)(u32 nic_major, u32 nic_minor,
309 				      s32 correction);
310 	struct {
311 		u32 minor_max;
312 		u32 sync_event_diff_min;
313 		u32 sync_event_diff_max;
314 		unsigned int sync_event_minor_shift;
315 	} nic_time;
316 	unsigned int min_synchronisation_ns;
317 	unsigned int capabilities;
318 	struct {
319 		s32 ptp_tx;
320 		s32 ptp_rx;
321 		s32 pps_out;
322 		s32 pps_in;
323 		s32 general_tx;
324 		s32 general_rx;
325 	} ts_corrections;
326 	efx_qword_t evt_frags[MAX_EVENT_FRAGS];
327 	int evt_frag_idx;
328 	int evt_code;
329 	struct efx_buffer start;
330 	struct pps_event_time host_time_pps;
331 	unsigned int adjfreq_ppb_shift;
332 	s64 current_adjfreq;
333 	struct ptp_clock *phc_clock;
334 	struct ptp_clock_info phc_clock_info;
335 	struct work_struct pps_work;
336 	struct workqueue_struct *pps_workwq;
337 	bool nic_ts_enabled;
338 	efx_dword_t txbuf[MCDI_TX_BUF_LEN(MC_CMD_PTP_IN_TRANSMIT_LENMAX)];
339 
340 	unsigned int good_syncs;
341 	unsigned int fast_syncs;
342 	unsigned int bad_syncs;
343 	unsigned int sync_timeouts;
344 	unsigned int no_time_syncs;
345 	unsigned int invalid_sync_windows;
346 	unsigned int undersize_sync_windows;
347 	unsigned int oversize_sync_windows;
348 	unsigned int rx_no_timestamp;
349 	struct efx_ptp_timeset
350 	timeset[MC_CMD_PTP_OUT_SYNCHRONIZE_TIMESET_MAXNUM];
351 	void (*xmit_skb)(struct efx_nic *efx, struct sk_buff *skb);
352 };
353 
354 static int efx_phc_adjfreq(struct ptp_clock_info *ptp, s32 delta);
355 static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta);
356 static int efx_phc_gettime(struct ptp_clock_info *ptp, struct timespec64 *ts);
357 static int efx_phc_settime(struct ptp_clock_info *ptp,
358 			   const struct timespec64 *e_ts);
359 static int efx_phc_enable(struct ptp_clock_info *ptp,
360 			  struct ptp_clock_request *request, int on);
361 
efx_ptp_use_mac_tx_timestamps(struct efx_nic * efx)362 bool efx_ptp_use_mac_tx_timestamps(struct efx_nic *efx)
363 {
364 	return efx_has_cap(efx, TX_MAC_TIMESTAMPING);
365 }
366 
367 /* PTP 'extra' channel is still a traffic channel, but we only create TX queues
368  * if PTP uses MAC TX timestamps, not if PTP uses the MC directly to transmit.
369  */
efx_ptp_want_txqs(struct efx_channel * channel)370 static bool efx_ptp_want_txqs(struct efx_channel *channel)
371 {
372 	return efx_ptp_use_mac_tx_timestamps(channel->efx);
373 }
374 
375 #define PTP_SW_STAT(ext_name, field_name)				\
376 	{ #ext_name, 0, offsetof(struct efx_ptp_data, field_name) }
377 #define PTP_MC_STAT(ext_name, mcdi_name)				\
378 	{ #ext_name, 32, MC_CMD_PTP_OUT_STATUS_STATS_ ## mcdi_name ## _OFST }
379 static const struct efx_hw_stat_desc efx_ptp_stat_desc[] = {
380 	PTP_SW_STAT(ptp_good_syncs, good_syncs),
381 	PTP_SW_STAT(ptp_fast_syncs, fast_syncs),
382 	PTP_SW_STAT(ptp_bad_syncs, bad_syncs),
383 	PTP_SW_STAT(ptp_sync_timeouts, sync_timeouts),
384 	PTP_SW_STAT(ptp_no_time_syncs, no_time_syncs),
385 	PTP_SW_STAT(ptp_invalid_sync_windows, invalid_sync_windows),
386 	PTP_SW_STAT(ptp_undersize_sync_windows, undersize_sync_windows),
387 	PTP_SW_STAT(ptp_oversize_sync_windows, oversize_sync_windows),
388 	PTP_SW_STAT(ptp_rx_no_timestamp, rx_no_timestamp),
389 	PTP_MC_STAT(ptp_tx_timestamp_packets, TX),
390 	PTP_MC_STAT(ptp_rx_timestamp_packets, RX),
391 	PTP_MC_STAT(ptp_timestamp_packets, TS),
392 	PTP_MC_STAT(ptp_filter_matches, FM),
393 	PTP_MC_STAT(ptp_non_filter_matches, NFM),
394 };
395 #define PTP_STAT_COUNT ARRAY_SIZE(efx_ptp_stat_desc)
396 static const unsigned long efx_ptp_stat_mask[] = {
397 	[0 ... BITS_TO_LONGS(PTP_STAT_COUNT) - 1] = ~0UL,
398 };
399 
efx_ptp_describe_stats(struct efx_nic * efx,u8 * strings)400 size_t efx_ptp_describe_stats(struct efx_nic *efx, u8 *strings)
401 {
402 	if (!efx->ptp_data)
403 		return 0;
404 
405 	return efx_nic_describe_stats(efx_ptp_stat_desc, PTP_STAT_COUNT,
406 				      efx_ptp_stat_mask, strings);
407 }
408 
efx_ptp_update_stats(struct efx_nic * efx,u64 * stats)409 size_t efx_ptp_update_stats(struct efx_nic *efx, u64 *stats)
410 {
411 	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_STATUS_LEN);
412 	MCDI_DECLARE_BUF(outbuf, MC_CMD_PTP_OUT_STATUS_LEN);
413 	size_t i;
414 	int rc;
415 
416 	if (!efx->ptp_data)
417 		return 0;
418 
419 	/* Copy software statistics */
420 	for (i = 0; i < PTP_STAT_COUNT; i++) {
421 		if (efx_ptp_stat_desc[i].dma_width)
422 			continue;
423 		stats[i] = *(unsigned int *)((char *)efx->ptp_data +
424 					     efx_ptp_stat_desc[i].offset);
425 	}
426 
427 	/* Fetch MC statistics.  We *must* fill in all statistics or
428 	 * risk leaking kernel memory to userland, so if the MCDI
429 	 * request fails we pretend we got zeroes.
430 	 */
431 	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_STATUS);
432 	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
433 	rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
434 			  outbuf, sizeof(outbuf), NULL);
435 	if (rc)
436 		memset(outbuf, 0, sizeof(outbuf));
437 	efx_nic_update_stats(efx_ptp_stat_desc, PTP_STAT_COUNT,
438 			     efx_ptp_stat_mask,
439 			     stats, _MCDI_PTR(outbuf, 0), false);
440 
441 	return PTP_STAT_COUNT;
442 }
443 
444 /* For Siena platforms NIC time is s and ns */
efx_ptp_ns_to_s_ns(s64 ns,u32 * nic_major,u32 * nic_minor)445 static void efx_ptp_ns_to_s_ns(s64 ns, u32 *nic_major, u32 *nic_minor)
446 {
447 	struct timespec64 ts = ns_to_timespec64(ns);
448 	*nic_major = (u32)ts.tv_sec;
449 	*nic_minor = ts.tv_nsec;
450 }
451 
efx_ptp_s_ns_to_ktime_correction(u32 nic_major,u32 nic_minor,s32 correction)452 static ktime_t efx_ptp_s_ns_to_ktime_correction(u32 nic_major, u32 nic_minor,
453 						s32 correction)
454 {
455 	ktime_t kt = ktime_set(nic_major, nic_minor);
456 	if (correction >= 0)
457 		kt = ktime_add_ns(kt, (u64)correction);
458 	else
459 		kt = ktime_sub_ns(kt, (u64)-correction);
460 	return kt;
461 }
462 
463 /* To convert from s27 format to ns we multiply then divide by a power of 2.
464  * For the conversion from ns to s27, the operation is also converted to a
465  * multiply and shift.
466  */
467 #define S27_TO_NS_SHIFT	(27)
468 #define NS_TO_S27_MULT	(((1ULL << 63) + NSEC_PER_SEC / 2) / NSEC_PER_SEC)
469 #define NS_TO_S27_SHIFT	(63 - S27_TO_NS_SHIFT)
470 #define S27_MINOR_MAX	(1 << S27_TO_NS_SHIFT)
471 
472 /* For Huntington platforms NIC time is in seconds and fractions of a second
473  * where the minor register only uses 27 bits in units of 2^-27s.
474  */
efx_ptp_ns_to_s27(s64 ns,u32 * nic_major,u32 * nic_minor)475 static void efx_ptp_ns_to_s27(s64 ns, u32 *nic_major, u32 *nic_minor)
476 {
477 	struct timespec64 ts = ns_to_timespec64(ns);
478 	u32 maj = (u32)ts.tv_sec;
479 	u32 min = (u32)(((u64)ts.tv_nsec * NS_TO_S27_MULT +
480 			 (1ULL << (NS_TO_S27_SHIFT - 1))) >> NS_TO_S27_SHIFT);
481 
482 	/* The conversion can result in the minor value exceeding the maximum.
483 	 * In this case, round up to the next second.
484 	 */
485 	if (min >= S27_MINOR_MAX) {
486 		min -= S27_MINOR_MAX;
487 		maj++;
488 	}
489 
490 	*nic_major = maj;
491 	*nic_minor = min;
492 }
493 
efx_ptp_s27_to_ktime(u32 nic_major,u32 nic_minor)494 static inline ktime_t efx_ptp_s27_to_ktime(u32 nic_major, u32 nic_minor)
495 {
496 	u32 ns = (u32)(((u64)nic_minor * NSEC_PER_SEC +
497 			(1ULL << (S27_TO_NS_SHIFT - 1))) >> S27_TO_NS_SHIFT);
498 	return ktime_set(nic_major, ns);
499 }
500 
efx_ptp_s27_to_ktime_correction(u32 nic_major,u32 nic_minor,s32 correction)501 static ktime_t efx_ptp_s27_to_ktime_correction(u32 nic_major, u32 nic_minor,
502 					       s32 correction)
503 {
504 	/* Apply the correction and deal with carry */
505 	nic_minor += correction;
506 	if ((s32)nic_minor < 0) {
507 		nic_minor += S27_MINOR_MAX;
508 		nic_major--;
509 	} else if (nic_minor >= S27_MINOR_MAX) {
510 		nic_minor -= S27_MINOR_MAX;
511 		nic_major++;
512 	}
513 
514 	return efx_ptp_s27_to_ktime(nic_major, nic_minor);
515 }
516 
517 /* For Medford2 platforms the time is in seconds and quarter nanoseconds. */
efx_ptp_ns_to_s_qns(s64 ns,u32 * nic_major,u32 * nic_minor)518 static void efx_ptp_ns_to_s_qns(s64 ns, u32 *nic_major, u32 *nic_minor)
519 {
520 	struct timespec64 ts = ns_to_timespec64(ns);
521 
522 	*nic_major = (u32)ts.tv_sec;
523 	*nic_minor = ts.tv_nsec * 4;
524 }
525 
efx_ptp_s_qns_to_ktime_correction(u32 nic_major,u32 nic_minor,s32 correction)526 static ktime_t efx_ptp_s_qns_to_ktime_correction(u32 nic_major, u32 nic_minor,
527 						 s32 correction)
528 {
529 	ktime_t kt;
530 
531 	nic_minor = DIV_ROUND_CLOSEST(nic_minor, 4);
532 	correction = DIV_ROUND_CLOSEST(correction, 4);
533 
534 	kt = ktime_set(nic_major, nic_minor);
535 
536 	if (correction >= 0)
537 		kt = ktime_add_ns(kt, (u64)correction);
538 	else
539 		kt = ktime_sub_ns(kt, (u64)-correction);
540 	return kt;
541 }
542 
efx_ptp_channel(struct efx_nic * efx)543 struct efx_channel *efx_ptp_channel(struct efx_nic *efx)
544 {
545 	return efx->ptp_data ? efx->ptp_data->channel : NULL;
546 }
547 
efx_ptp_update_channel(struct efx_nic * efx,struct efx_channel * channel)548 void efx_ptp_update_channel(struct efx_nic *efx, struct efx_channel *channel)
549 {
550 	if (efx->ptp_data)
551 		efx->ptp_data->channel = channel;
552 }
553 
last_sync_timestamp_major(struct efx_nic * efx)554 static u32 last_sync_timestamp_major(struct efx_nic *efx)
555 {
556 	struct efx_channel *channel = efx_ptp_channel(efx);
557 	u32 major = 0;
558 
559 	if (channel)
560 		major = channel->sync_timestamp_major;
561 	return major;
562 }
563 
564 /* The 8000 series and later can provide the time from the MAC, which is only
565  * 48 bits long and provides meta-information in the top 2 bits.
566  */
567 static ktime_t
efx_ptp_mac_nic_to_ktime_correction(struct efx_nic * efx,struct efx_ptp_data * ptp,u32 nic_major,u32 nic_minor,s32 correction)568 efx_ptp_mac_nic_to_ktime_correction(struct efx_nic *efx,
569 				    struct efx_ptp_data *ptp,
570 				    u32 nic_major, u32 nic_minor,
571 				    s32 correction)
572 {
573 	u32 sync_timestamp;
574 	ktime_t kt = { 0 };
575 	s16 delta;
576 
577 	if (!(nic_major & 0x80000000)) {
578 		WARN_ON_ONCE(nic_major >> 16);
579 
580 		/* Medford provides 48 bits of timestamp, so we must get the top
581 		 * 16 bits from the timesync event state.
582 		 *
583 		 * We only have the lower 16 bits of the time now, but we do
584 		 * have a full resolution timestamp at some point in past. As
585 		 * long as the difference between the (real) now and the sync
586 		 * is less than 2^15, then we can reconstruct the difference
587 		 * between those two numbers using only the lower 16 bits of
588 		 * each.
589 		 *
590 		 * Put another way
591 		 *
592 		 * a - b = ((a mod k) - b) mod k
593 		 *
594 		 * when -k/2 < (a-b) < k/2. In our case k is 2^16. We know
595 		 * (a mod k) and b, so can calculate the delta, a - b.
596 		 *
597 		 */
598 		sync_timestamp = last_sync_timestamp_major(efx);
599 
600 		/* Because delta is s16 this does an implicit mask down to
601 		 * 16 bits which is what we need, assuming
602 		 * MEDFORD_TX_SECS_EVENT_BITS is 16. delta is signed so that
603 		 * we can deal with the (unlikely) case of sync timestamps
604 		 * arriving from the future.
605 		 */
606 		delta = nic_major - sync_timestamp;
607 
608 		/* Recover the fully specified time now, by applying the offset
609 		 * to the (fully specified) sync time.
610 		 */
611 		nic_major = sync_timestamp + delta;
612 
613 		kt = ptp->nic_to_kernel_time(nic_major, nic_minor,
614 					     correction);
615 	}
616 	return kt;
617 }
618 
efx_ptp_nic_to_kernel_time(struct efx_tx_queue * tx_queue)619 ktime_t efx_ptp_nic_to_kernel_time(struct efx_tx_queue *tx_queue)
620 {
621 	struct efx_nic *efx = tx_queue->efx;
622 	struct efx_ptp_data *ptp = efx->ptp_data;
623 	ktime_t kt;
624 
625 	if (efx_ptp_use_mac_tx_timestamps(efx))
626 		kt = efx_ptp_mac_nic_to_ktime_correction(efx, ptp,
627 				tx_queue->completed_timestamp_major,
628 				tx_queue->completed_timestamp_minor,
629 				ptp->ts_corrections.general_tx);
630 	else
631 		kt = ptp->nic_to_kernel_time(
632 				tx_queue->completed_timestamp_major,
633 				tx_queue->completed_timestamp_minor,
634 				ptp->ts_corrections.general_tx);
635 	return kt;
636 }
637 
638 /* Get PTP attributes and set up time conversions */
efx_ptp_get_attributes(struct efx_nic * efx)639 static int efx_ptp_get_attributes(struct efx_nic *efx)
640 {
641 	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_GET_ATTRIBUTES_LEN);
642 	MCDI_DECLARE_BUF(outbuf, MC_CMD_PTP_OUT_GET_ATTRIBUTES_LEN);
643 	struct efx_ptp_data *ptp = efx->ptp_data;
644 	int rc;
645 	u32 fmt;
646 	size_t out_len;
647 
648 	/* Get the PTP attributes. If the NIC doesn't support the operation we
649 	 * use the default format for compatibility with older NICs i.e.
650 	 * seconds and nanoseconds.
651 	 */
652 	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_GET_ATTRIBUTES);
653 	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
654 	rc = efx_mcdi_rpc_quiet(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
655 				outbuf, sizeof(outbuf), &out_len);
656 	if (rc == 0) {
657 		fmt = MCDI_DWORD(outbuf, PTP_OUT_GET_ATTRIBUTES_TIME_FORMAT);
658 	} else if (rc == -EINVAL) {
659 		fmt = MC_CMD_PTP_OUT_GET_ATTRIBUTES_SECONDS_NANOSECONDS;
660 	} else if (rc == -EPERM) {
661 		pci_info(efx->pci_dev, "no PTP support\n");
662 		return rc;
663 	} else {
664 		efx_mcdi_display_error(efx, MC_CMD_PTP, sizeof(inbuf),
665 				       outbuf, sizeof(outbuf), rc);
666 		return rc;
667 	}
668 
669 	switch (fmt) {
670 	case MC_CMD_PTP_OUT_GET_ATTRIBUTES_SECONDS_27FRACTION:
671 		ptp->ns_to_nic_time = efx_ptp_ns_to_s27;
672 		ptp->nic_to_kernel_time = efx_ptp_s27_to_ktime_correction;
673 		ptp->nic_time.minor_max = 1 << 27;
674 		ptp->nic_time.sync_event_minor_shift = 19;
675 		break;
676 	case MC_CMD_PTP_OUT_GET_ATTRIBUTES_SECONDS_NANOSECONDS:
677 		ptp->ns_to_nic_time = efx_ptp_ns_to_s_ns;
678 		ptp->nic_to_kernel_time = efx_ptp_s_ns_to_ktime_correction;
679 		ptp->nic_time.minor_max = 1000000000;
680 		ptp->nic_time.sync_event_minor_shift = 22;
681 		break;
682 	case MC_CMD_PTP_OUT_GET_ATTRIBUTES_SECONDS_QTR_NANOSECONDS:
683 		ptp->ns_to_nic_time = efx_ptp_ns_to_s_qns;
684 		ptp->nic_to_kernel_time = efx_ptp_s_qns_to_ktime_correction;
685 		ptp->nic_time.minor_max = 4000000000UL;
686 		ptp->nic_time.sync_event_minor_shift = 24;
687 		break;
688 	default:
689 		return -ERANGE;
690 	}
691 
692 	/* Precalculate acceptable difference between the minor time in the
693 	 * packet prefix and the last MCDI time sync event. We expect the
694 	 * packet prefix timestamp to be after of sync event by up to one
695 	 * sync event interval (0.25s) but we allow it to exceed this by a
696 	 * fuzz factor of (0.1s)
697 	 */
698 	ptp->nic_time.sync_event_diff_min = ptp->nic_time.minor_max
699 		- (ptp->nic_time.minor_max / 10);
700 	ptp->nic_time.sync_event_diff_max = (ptp->nic_time.minor_max / 4)
701 		+ (ptp->nic_time.minor_max / 10);
702 
703 	/* MC_CMD_PTP_OP_GET_ATTRIBUTES has been extended twice from an older
704 	 * operation MC_CMD_PTP_OP_GET_TIME_FORMAT. The function now may return
705 	 * a value to use for the minimum acceptable corrected synchronization
706 	 * window and may return further capabilities.
707 	 * If we have the extra information store it. For older firmware that
708 	 * does not implement the extended command use the default value.
709 	 */
710 	if (rc == 0 &&
711 	    out_len >= MC_CMD_PTP_OUT_GET_ATTRIBUTES_CAPABILITIES_OFST)
712 		ptp->min_synchronisation_ns =
713 			MCDI_DWORD(outbuf,
714 				   PTP_OUT_GET_ATTRIBUTES_SYNC_WINDOW_MIN);
715 	else
716 		ptp->min_synchronisation_ns = DEFAULT_MIN_SYNCHRONISATION_NS;
717 
718 	if (rc == 0 &&
719 	    out_len >= MC_CMD_PTP_OUT_GET_ATTRIBUTES_LEN)
720 		ptp->capabilities = MCDI_DWORD(outbuf,
721 					PTP_OUT_GET_ATTRIBUTES_CAPABILITIES);
722 	else
723 		ptp->capabilities = 0;
724 
725 	/* Set up the shift for conversion between frequency
726 	 * adjustments in parts-per-billion and the fixed-point
727 	 * fractional ns format that the adapter uses.
728 	 */
729 	if (ptp->capabilities & (1 << MC_CMD_PTP_OUT_GET_ATTRIBUTES_FP44_FREQ_ADJ_LBN))
730 		ptp->adjfreq_ppb_shift = PPB_SHIFT_FP44;
731 	else
732 		ptp->adjfreq_ppb_shift = PPB_SHIFT_FP40;
733 
734 	return 0;
735 }
736 
737 /* Get PTP timestamp corrections */
efx_ptp_get_timestamp_corrections(struct efx_nic * efx)738 static int efx_ptp_get_timestamp_corrections(struct efx_nic *efx)
739 {
740 	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_GET_TIMESTAMP_CORRECTIONS_LEN);
741 	MCDI_DECLARE_BUF(outbuf, MC_CMD_PTP_OUT_GET_TIMESTAMP_CORRECTIONS_V2_LEN);
742 	int rc;
743 	size_t out_len;
744 
745 	/* Get the timestamp corrections from the NIC. If this operation is
746 	 * not supported (older NICs) then no correction is required.
747 	 */
748 	MCDI_SET_DWORD(inbuf, PTP_IN_OP,
749 		       MC_CMD_PTP_OP_GET_TIMESTAMP_CORRECTIONS);
750 	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
751 
752 	rc = efx_mcdi_rpc_quiet(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
753 				outbuf, sizeof(outbuf), &out_len);
754 	if (rc == 0) {
755 		efx->ptp_data->ts_corrections.ptp_tx = MCDI_DWORD(outbuf,
756 			PTP_OUT_GET_TIMESTAMP_CORRECTIONS_TRANSMIT);
757 		efx->ptp_data->ts_corrections.ptp_rx = MCDI_DWORD(outbuf,
758 			PTP_OUT_GET_TIMESTAMP_CORRECTIONS_RECEIVE);
759 		efx->ptp_data->ts_corrections.pps_out = MCDI_DWORD(outbuf,
760 			PTP_OUT_GET_TIMESTAMP_CORRECTIONS_PPS_OUT);
761 		efx->ptp_data->ts_corrections.pps_in = MCDI_DWORD(outbuf,
762 			PTP_OUT_GET_TIMESTAMP_CORRECTIONS_PPS_IN);
763 
764 		if (out_len >= MC_CMD_PTP_OUT_GET_TIMESTAMP_CORRECTIONS_V2_LEN) {
765 			efx->ptp_data->ts_corrections.general_tx = MCDI_DWORD(
766 				outbuf,
767 				PTP_OUT_GET_TIMESTAMP_CORRECTIONS_V2_GENERAL_TX);
768 			efx->ptp_data->ts_corrections.general_rx = MCDI_DWORD(
769 				outbuf,
770 				PTP_OUT_GET_TIMESTAMP_CORRECTIONS_V2_GENERAL_RX);
771 		} else {
772 			efx->ptp_data->ts_corrections.general_tx =
773 				efx->ptp_data->ts_corrections.ptp_tx;
774 			efx->ptp_data->ts_corrections.general_rx =
775 				efx->ptp_data->ts_corrections.ptp_rx;
776 		}
777 	} else if (rc == -EINVAL) {
778 		efx->ptp_data->ts_corrections.ptp_tx = 0;
779 		efx->ptp_data->ts_corrections.ptp_rx = 0;
780 		efx->ptp_data->ts_corrections.pps_out = 0;
781 		efx->ptp_data->ts_corrections.pps_in = 0;
782 		efx->ptp_data->ts_corrections.general_tx = 0;
783 		efx->ptp_data->ts_corrections.general_rx = 0;
784 	} else {
785 		efx_mcdi_display_error(efx, MC_CMD_PTP, sizeof(inbuf), outbuf,
786 				       sizeof(outbuf), rc);
787 		return rc;
788 	}
789 
790 	return 0;
791 }
792 
793 /* Enable MCDI PTP support. */
efx_ptp_enable(struct efx_nic * efx)794 static int efx_ptp_enable(struct efx_nic *efx)
795 {
796 	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_ENABLE_LEN);
797 	MCDI_DECLARE_BUF_ERR(outbuf);
798 	int rc;
799 
800 	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_ENABLE);
801 	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
802 	MCDI_SET_DWORD(inbuf, PTP_IN_ENABLE_QUEUE,
803 		       efx->ptp_data->channel ?
804 		       efx->ptp_data->channel->channel : 0);
805 	MCDI_SET_DWORD(inbuf, PTP_IN_ENABLE_MODE, efx->ptp_data->mode);
806 
807 	rc = efx_mcdi_rpc_quiet(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
808 				outbuf, sizeof(outbuf), NULL);
809 	rc = (rc == -EALREADY) ? 0 : rc;
810 	if (rc)
811 		efx_mcdi_display_error(efx, MC_CMD_PTP,
812 				       MC_CMD_PTP_IN_ENABLE_LEN,
813 				       outbuf, sizeof(outbuf), rc);
814 	return rc;
815 }
816 
817 /* Disable MCDI PTP support.
818  *
819  * Note that this function should never rely on the presence of ptp_data -
820  * may be called before that exists.
821  */
efx_ptp_disable(struct efx_nic * efx)822 static int efx_ptp_disable(struct efx_nic *efx)
823 {
824 	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_DISABLE_LEN);
825 	MCDI_DECLARE_BUF_ERR(outbuf);
826 	int rc;
827 
828 	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_DISABLE);
829 	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
830 	rc = efx_mcdi_rpc_quiet(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
831 				outbuf, sizeof(outbuf), NULL);
832 	rc = (rc == -EALREADY) ? 0 : rc;
833 	/* If we get ENOSYS, the NIC doesn't support PTP, and thus this function
834 	 * should only have been called during probe.
835 	 */
836 	if (rc == -ENOSYS || rc == -EPERM)
837 		pci_info(efx->pci_dev, "no PTP support\n");
838 	else if (rc)
839 		efx_mcdi_display_error(efx, MC_CMD_PTP,
840 				       MC_CMD_PTP_IN_DISABLE_LEN,
841 				       outbuf, sizeof(outbuf), rc);
842 	return rc;
843 }
844 
efx_ptp_deliver_rx_queue(struct sk_buff_head * q)845 static void efx_ptp_deliver_rx_queue(struct sk_buff_head *q)
846 {
847 	struct sk_buff *skb;
848 
849 	while ((skb = skb_dequeue(q))) {
850 		local_bh_disable();
851 		netif_receive_skb(skb);
852 		local_bh_enable();
853 	}
854 }
855 
efx_ptp_handle_no_channel(struct efx_nic * efx)856 static void efx_ptp_handle_no_channel(struct efx_nic *efx)
857 {
858 	netif_err(efx, drv, efx->net_dev,
859 		  "ERROR: PTP requires MSI-X and 1 additional interrupt"
860 		  "vector. PTP disabled\n");
861 }
862 
863 /* Repeatedly send the host time to the MC which will capture the hardware
864  * time.
865  */
efx_ptp_send_times(struct efx_nic * efx,struct pps_event_time * last_time)866 static void efx_ptp_send_times(struct efx_nic *efx,
867 			       struct pps_event_time *last_time)
868 {
869 	struct pps_event_time now;
870 	struct timespec64 limit;
871 	struct efx_ptp_data *ptp = efx->ptp_data;
872 	int *mc_running = ptp->start.addr;
873 
874 	pps_get_ts(&now);
875 	limit = now.ts_real;
876 	timespec64_add_ns(&limit, SYNCHRONISE_PERIOD_NS);
877 
878 	/* Write host time for specified period or until MC is done */
879 	while ((timespec64_compare(&now.ts_real, &limit) < 0) &&
880 	       READ_ONCE(*mc_running)) {
881 		struct timespec64 update_time;
882 		unsigned int host_time;
883 
884 		/* Don't update continuously to avoid saturating the PCIe bus */
885 		update_time = now.ts_real;
886 		timespec64_add_ns(&update_time, SYNCHRONISATION_GRANULARITY_NS);
887 		do {
888 			pps_get_ts(&now);
889 		} while ((timespec64_compare(&now.ts_real, &update_time) < 0) &&
890 			 READ_ONCE(*mc_running));
891 
892 		/* Synchronise NIC with single word of time only */
893 		host_time = (now.ts_real.tv_sec << MC_NANOSECOND_BITS |
894 			     now.ts_real.tv_nsec);
895 		/* Update host time in NIC memory */
896 		efx->type->ptp_write_host_time(efx, host_time);
897 	}
898 	*last_time = now;
899 }
900 
901 /* Read a timeset from the MC's results and partial process. */
efx_ptp_read_timeset(MCDI_DECLARE_STRUCT_PTR (data),struct efx_ptp_timeset * timeset)902 static void efx_ptp_read_timeset(MCDI_DECLARE_STRUCT_PTR(data),
903 				 struct efx_ptp_timeset *timeset)
904 {
905 	unsigned start_ns, end_ns;
906 
907 	timeset->host_start = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_HOSTSTART);
908 	timeset->major = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_MAJOR);
909 	timeset->minor = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_MINOR);
910 	timeset->host_end = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_HOSTEND),
911 	timeset->wait = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_WAITNS);
912 
913 	/* Ignore seconds */
914 	start_ns = timeset->host_start & MC_NANOSECOND_MASK;
915 	end_ns = timeset->host_end & MC_NANOSECOND_MASK;
916 	/* Allow for rollover */
917 	if (end_ns < start_ns)
918 		end_ns += NSEC_PER_SEC;
919 	/* Determine duration of operation */
920 	timeset->window = end_ns - start_ns;
921 }
922 
923 /* Process times received from MC.
924  *
925  * Extract times from returned results, and establish the minimum value
926  * seen.  The minimum value represents the "best" possible time and events
927  * too much greater than this are rejected - the machine is, perhaps, too
928  * busy. A number of readings are taken so that, hopefully, at least one good
929  * synchronisation will be seen in the results.
930  */
931 static int
efx_ptp_process_times(struct efx_nic * efx,MCDI_DECLARE_STRUCT_PTR (synch_buf),size_t response_length,const struct pps_event_time * last_time)932 efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf),
933 		      size_t response_length,
934 		      const struct pps_event_time *last_time)
935 {
936 	unsigned number_readings =
937 		MCDI_VAR_ARRAY_LEN(response_length,
938 				   PTP_OUT_SYNCHRONIZE_TIMESET);
939 	unsigned i;
940 	unsigned ngood = 0;
941 	unsigned last_good = 0;
942 	struct efx_ptp_data *ptp = efx->ptp_data;
943 	u32 last_sec;
944 	u32 start_sec;
945 	struct timespec64 delta;
946 	ktime_t mc_time;
947 
948 	if (number_readings == 0)
949 		return -EAGAIN;
950 
951 	/* Read the set of results and find the last good host-MC
952 	 * synchronization result. The MC times when it finishes reading the
953 	 * host time so the corrected window time should be fairly constant
954 	 * for a given platform. Increment stats for any results that appear
955 	 * to be erroneous.
956 	 */
957 	for (i = 0; i < number_readings; i++) {
958 		s32 window, corrected;
959 		struct timespec64 wait;
960 
961 		efx_ptp_read_timeset(
962 			MCDI_ARRAY_STRUCT_PTR(synch_buf,
963 					      PTP_OUT_SYNCHRONIZE_TIMESET, i),
964 			&ptp->timeset[i]);
965 
966 		wait = ktime_to_timespec64(
967 			ptp->nic_to_kernel_time(0, ptp->timeset[i].wait, 0));
968 		window = ptp->timeset[i].window;
969 		corrected = window - wait.tv_nsec;
970 
971 		/* We expect the uncorrected synchronization window to be at
972 		 * least as large as the interval between host start and end
973 		 * times. If it is smaller than this then this is mostly likely
974 		 * to be a consequence of the host's time being adjusted.
975 		 * Check that the corrected sync window is in a reasonable
976 		 * range. If it is out of range it is likely to be because an
977 		 * interrupt or other delay occurred between reading the system
978 		 * time and writing it to MC memory.
979 		 */
980 		if (window < SYNCHRONISATION_GRANULARITY_NS) {
981 			++ptp->invalid_sync_windows;
982 		} else if (corrected >= MAX_SYNCHRONISATION_NS) {
983 			++ptp->oversize_sync_windows;
984 		} else if (corrected < ptp->min_synchronisation_ns) {
985 			++ptp->undersize_sync_windows;
986 		} else {
987 			ngood++;
988 			last_good = i;
989 		}
990 	}
991 
992 	if (ngood == 0) {
993 		netif_warn(efx, drv, efx->net_dev,
994 			   "PTP no suitable synchronisations\n");
995 		return -EAGAIN;
996 	}
997 
998 	/* Calculate delay from last good sync (host time) to last_time.
999 	 * It is possible that the seconds rolled over between taking
1000 	 * the start reading and the last value written by the host.  The
1001 	 * timescales are such that a gap of more than one second is never
1002 	 * expected.  delta is *not* normalised.
1003 	 */
1004 	start_sec = ptp->timeset[last_good].host_start >> MC_NANOSECOND_BITS;
1005 	last_sec = last_time->ts_real.tv_sec & MC_SECOND_MASK;
1006 	if (start_sec != last_sec &&
1007 	    ((start_sec + 1) & MC_SECOND_MASK) != last_sec) {
1008 		netif_warn(efx, hw, efx->net_dev,
1009 			   "PTP bad synchronisation seconds\n");
1010 		return -EAGAIN;
1011 	}
1012 	delta.tv_sec = (last_sec - start_sec) & 1;
1013 	delta.tv_nsec =
1014 		last_time->ts_real.tv_nsec -
1015 		(ptp->timeset[last_good].host_start & MC_NANOSECOND_MASK);
1016 
1017 	/* Convert the NIC time at last good sync into kernel time.
1018 	 * No correction is required - this time is the output of a
1019 	 * firmware process.
1020 	 */
1021 	mc_time = ptp->nic_to_kernel_time(ptp->timeset[last_good].major,
1022 					  ptp->timeset[last_good].minor, 0);
1023 
1024 	/* Calculate delay from NIC top of second to last_time */
1025 	delta.tv_nsec += ktime_to_timespec64(mc_time).tv_nsec;
1026 
1027 	/* Set PPS timestamp to match NIC top of second */
1028 	ptp->host_time_pps = *last_time;
1029 	pps_sub_ts(&ptp->host_time_pps, delta);
1030 
1031 	return 0;
1032 }
1033 
1034 /* Synchronize times between the host and the MC */
efx_ptp_synchronize(struct efx_nic * efx,unsigned int num_readings)1035 static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings)
1036 {
1037 	struct efx_ptp_data *ptp = efx->ptp_data;
1038 	MCDI_DECLARE_BUF(synch_buf, MC_CMD_PTP_OUT_SYNCHRONIZE_LENMAX);
1039 	size_t response_length;
1040 	int rc;
1041 	unsigned long timeout;
1042 	struct pps_event_time last_time = {};
1043 	unsigned int loops = 0;
1044 	int *start = ptp->start.addr;
1045 
1046 	MCDI_SET_DWORD(synch_buf, PTP_IN_OP, MC_CMD_PTP_OP_SYNCHRONIZE);
1047 	MCDI_SET_DWORD(synch_buf, PTP_IN_PERIPH_ID, 0);
1048 	MCDI_SET_DWORD(synch_buf, PTP_IN_SYNCHRONIZE_NUMTIMESETS,
1049 		       num_readings);
1050 	MCDI_SET_QWORD(synch_buf, PTP_IN_SYNCHRONIZE_START_ADDR,
1051 		       ptp->start.dma_addr);
1052 
1053 	/* Clear flag that signals MC ready */
1054 	WRITE_ONCE(*start, 0);
1055 	rc = efx_mcdi_rpc_start(efx, MC_CMD_PTP, synch_buf,
1056 				MC_CMD_PTP_IN_SYNCHRONIZE_LEN);
1057 	EFX_WARN_ON_ONCE_PARANOID(rc);
1058 
1059 	/* Wait for start from MCDI (or timeout) */
1060 	timeout = jiffies + msecs_to_jiffies(MAX_SYNCHRONISE_WAIT_MS);
1061 	while (!READ_ONCE(*start) && (time_before(jiffies, timeout))) {
1062 		udelay(20);	/* Usually start MCDI execution quickly */
1063 		loops++;
1064 	}
1065 
1066 	if (loops <= 1)
1067 		++ptp->fast_syncs;
1068 	if (!time_before(jiffies, timeout))
1069 		++ptp->sync_timeouts;
1070 
1071 	if (READ_ONCE(*start))
1072 		efx_ptp_send_times(efx, &last_time);
1073 
1074 	/* Collect results */
1075 	rc = efx_mcdi_rpc_finish(efx, MC_CMD_PTP,
1076 				 MC_CMD_PTP_IN_SYNCHRONIZE_LEN,
1077 				 synch_buf, sizeof(synch_buf),
1078 				 &response_length);
1079 	if (rc == 0) {
1080 		rc = efx_ptp_process_times(efx, synch_buf, response_length,
1081 					   &last_time);
1082 		if (rc == 0)
1083 			++ptp->good_syncs;
1084 		else
1085 			++ptp->no_time_syncs;
1086 	}
1087 
1088 	/* Increment the bad syncs counter if the synchronize fails, whatever
1089 	 * the reason.
1090 	 */
1091 	if (rc != 0)
1092 		++ptp->bad_syncs;
1093 
1094 	return rc;
1095 }
1096 
1097 /* Transmit a PTP packet via the dedicated hardware timestamped queue. */
efx_ptp_xmit_skb_queue(struct efx_nic * efx,struct sk_buff * skb)1098 static void efx_ptp_xmit_skb_queue(struct efx_nic *efx, struct sk_buff *skb)
1099 {
1100 	struct efx_ptp_data *ptp_data = efx->ptp_data;
1101 	u8 type = efx_tx_csum_type_skb(skb);
1102 	struct efx_tx_queue *tx_queue;
1103 
1104 	tx_queue = efx_channel_get_tx_queue(ptp_data->channel, type);
1105 	if (tx_queue && tx_queue->timestamping) {
1106 		/* This code invokes normal driver TX code which is always
1107 		 * protected from softirqs when called from generic TX code,
1108 		 * which in turn disables preemption. Look at __dev_queue_xmit
1109 		 * which uses rcu_read_lock_bh disabling preemption for RCU
1110 		 * plus disabling softirqs. We do not need RCU reader
1111 		 * protection here.
1112 		 *
1113 		 * Although it is theoretically safe for current PTP TX/RX code
1114 		 * running without disabling softirqs, there are three good
1115 		 * reasond for doing so:
1116 		 *
1117 		 *      1) The code invoked is mainly implemented for non-PTP
1118 		 *         packets and it is always executed with softirqs
1119 		 *         disabled.
1120 		 *      2) This being a single PTP packet, better to not
1121 		 *         interrupt its processing by softirqs which can lead
1122 		 *         to high latencies.
1123 		 *      3) netdev_xmit_more checks preemption is disabled and
1124 		 *         triggers a BUG_ON if not.
1125 		 */
1126 		local_bh_disable();
1127 		efx_enqueue_skb(tx_queue, skb);
1128 		local_bh_enable();
1129 	} else {
1130 		WARN_ONCE(1, "PTP channel has no timestamped tx queue\n");
1131 		dev_kfree_skb_any(skb);
1132 	}
1133 }
1134 
1135 /* Transmit a PTP packet, via the MCDI interface, to the wire. */
efx_ptp_xmit_skb_mc(struct efx_nic * efx,struct sk_buff * skb)1136 static void efx_ptp_xmit_skb_mc(struct efx_nic *efx, struct sk_buff *skb)
1137 {
1138 	struct efx_ptp_data *ptp_data = efx->ptp_data;
1139 	struct skb_shared_hwtstamps timestamps;
1140 	int rc = -EIO;
1141 	MCDI_DECLARE_BUF(txtime, MC_CMD_PTP_OUT_TRANSMIT_LEN);
1142 	size_t len;
1143 
1144 	MCDI_SET_DWORD(ptp_data->txbuf, PTP_IN_OP, MC_CMD_PTP_OP_TRANSMIT);
1145 	MCDI_SET_DWORD(ptp_data->txbuf, PTP_IN_PERIPH_ID, 0);
1146 	MCDI_SET_DWORD(ptp_data->txbuf, PTP_IN_TRANSMIT_LENGTH, skb->len);
1147 	if (skb_shinfo(skb)->nr_frags != 0) {
1148 		rc = skb_linearize(skb);
1149 		if (rc != 0)
1150 			goto fail;
1151 	}
1152 
1153 	if (skb->ip_summed == CHECKSUM_PARTIAL) {
1154 		rc = skb_checksum_help(skb);
1155 		if (rc != 0)
1156 			goto fail;
1157 	}
1158 	skb_copy_from_linear_data(skb,
1159 				  MCDI_PTR(ptp_data->txbuf,
1160 					   PTP_IN_TRANSMIT_PACKET),
1161 				  skb->len);
1162 	rc = efx_mcdi_rpc(efx, MC_CMD_PTP,
1163 			  ptp_data->txbuf, MC_CMD_PTP_IN_TRANSMIT_LEN(skb->len),
1164 			  txtime, sizeof(txtime), &len);
1165 	if (rc != 0)
1166 		goto fail;
1167 
1168 	memset(&timestamps, 0, sizeof(timestamps));
1169 	timestamps.hwtstamp = ptp_data->nic_to_kernel_time(
1170 		MCDI_DWORD(txtime, PTP_OUT_TRANSMIT_MAJOR),
1171 		MCDI_DWORD(txtime, PTP_OUT_TRANSMIT_MINOR),
1172 		ptp_data->ts_corrections.ptp_tx);
1173 
1174 	skb_tstamp_tx(skb, &timestamps);
1175 
1176 	rc = 0;
1177 
1178 fail:
1179 	dev_kfree_skb_any(skb);
1180 
1181 	return;
1182 }
1183 
efx_ptp_drop_time_expired_events(struct efx_nic * efx)1184 static void efx_ptp_drop_time_expired_events(struct efx_nic *efx)
1185 {
1186 	struct efx_ptp_data *ptp = efx->ptp_data;
1187 	struct list_head *cursor;
1188 	struct list_head *next;
1189 
1190 	if (ptp->rx_ts_inline)
1191 		return;
1192 
1193 	/* Drop time-expired events */
1194 	spin_lock_bh(&ptp->evt_lock);
1195 	list_for_each_safe(cursor, next, &ptp->evt_list) {
1196 		struct efx_ptp_event_rx *evt;
1197 
1198 		evt = list_entry(cursor, struct efx_ptp_event_rx,
1199 				 link);
1200 		if (time_after(jiffies, evt->expiry)) {
1201 			list_move(&evt->link, &ptp->evt_free_list);
1202 			netif_warn(efx, hw, efx->net_dev,
1203 				   "PTP rx event dropped\n");
1204 		}
1205 	}
1206 	spin_unlock_bh(&ptp->evt_lock);
1207 }
1208 
efx_ptp_match_rx(struct efx_nic * efx,struct sk_buff * skb)1209 static enum ptp_packet_state efx_ptp_match_rx(struct efx_nic *efx,
1210 					      struct sk_buff *skb)
1211 {
1212 	struct efx_ptp_data *ptp = efx->ptp_data;
1213 	bool evts_waiting;
1214 	struct list_head *cursor;
1215 	struct list_head *next;
1216 	struct efx_ptp_match *match;
1217 	enum ptp_packet_state rc = PTP_PACKET_STATE_UNMATCHED;
1218 
1219 	WARN_ON_ONCE(ptp->rx_ts_inline);
1220 
1221 	spin_lock_bh(&ptp->evt_lock);
1222 	evts_waiting = !list_empty(&ptp->evt_list);
1223 	spin_unlock_bh(&ptp->evt_lock);
1224 
1225 	if (!evts_waiting)
1226 		return PTP_PACKET_STATE_UNMATCHED;
1227 
1228 	match = (struct efx_ptp_match *)skb->cb;
1229 	/* Look for a matching timestamp in the event queue */
1230 	spin_lock_bh(&ptp->evt_lock);
1231 	list_for_each_safe(cursor, next, &ptp->evt_list) {
1232 		struct efx_ptp_event_rx *evt;
1233 
1234 		evt = list_entry(cursor, struct efx_ptp_event_rx, link);
1235 		if ((evt->seq0 == match->words[0]) &&
1236 		    (evt->seq1 == match->words[1])) {
1237 			struct skb_shared_hwtstamps *timestamps;
1238 
1239 			/* Match - add in hardware timestamp */
1240 			timestamps = skb_hwtstamps(skb);
1241 			timestamps->hwtstamp = evt->hwtimestamp;
1242 
1243 			match->state = PTP_PACKET_STATE_MATCHED;
1244 			rc = PTP_PACKET_STATE_MATCHED;
1245 			list_move(&evt->link, &ptp->evt_free_list);
1246 			break;
1247 		}
1248 	}
1249 	spin_unlock_bh(&ptp->evt_lock);
1250 
1251 	return rc;
1252 }
1253 
1254 /* Process any queued receive events and corresponding packets
1255  *
1256  * q is returned with all the packets that are ready for delivery.
1257  */
efx_ptp_process_events(struct efx_nic * efx,struct sk_buff_head * q)1258 static void efx_ptp_process_events(struct efx_nic *efx, struct sk_buff_head *q)
1259 {
1260 	struct efx_ptp_data *ptp = efx->ptp_data;
1261 	struct sk_buff *skb;
1262 
1263 	while ((skb = skb_dequeue(&ptp->rxq))) {
1264 		struct efx_ptp_match *match;
1265 
1266 		match = (struct efx_ptp_match *)skb->cb;
1267 		if (match->state == PTP_PACKET_STATE_MATCH_UNWANTED) {
1268 			__skb_queue_tail(q, skb);
1269 		} else if (efx_ptp_match_rx(efx, skb) ==
1270 			   PTP_PACKET_STATE_MATCHED) {
1271 			__skb_queue_tail(q, skb);
1272 		} else if (time_after(jiffies, match->expiry)) {
1273 			match->state = PTP_PACKET_STATE_TIMED_OUT;
1274 			++ptp->rx_no_timestamp;
1275 			__skb_queue_tail(q, skb);
1276 		} else {
1277 			/* Replace unprocessed entry and stop */
1278 			skb_queue_head(&ptp->rxq, skb);
1279 			break;
1280 		}
1281 	}
1282 }
1283 
1284 /* Complete processing of a received packet */
efx_ptp_process_rx(struct efx_nic * efx,struct sk_buff * skb)1285 static inline void efx_ptp_process_rx(struct efx_nic *efx, struct sk_buff *skb)
1286 {
1287 	local_bh_disable();
1288 	netif_receive_skb(skb);
1289 	local_bh_enable();
1290 }
1291 
efx_ptp_remove_multicast_filters(struct efx_nic * efx)1292 static void efx_ptp_remove_multicast_filters(struct efx_nic *efx)
1293 {
1294 	struct efx_ptp_data *ptp = efx->ptp_data;
1295 
1296 	while (ptp->rxfilters_count) {
1297 		ptp->rxfilters_count--;
1298 		efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
1299 					  ptp->rxfilters[ptp->rxfilters_count]);
1300 	}
1301 }
1302 
efx_ptp_init_filter(struct efx_nic * efx,struct efx_filter_spec * rxfilter)1303 static void efx_ptp_init_filter(struct efx_nic *efx,
1304 				struct efx_filter_spec *rxfilter)
1305 {
1306 	struct efx_channel *channel = efx->ptp_data->channel;
1307 	struct efx_rx_queue *queue = efx_channel_get_rx_queue(channel);
1308 
1309 	efx_filter_init_rx(rxfilter, EFX_FILTER_PRI_REQUIRED, 0,
1310 			   efx_rx_queue_index(queue));
1311 }
1312 
efx_ptp_insert_filter(struct efx_nic * efx,struct efx_filter_spec * rxfilter)1313 static int efx_ptp_insert_filter(struct efx_nic *efx,
1314 				 struct efx_filter_spec *rxfilter)
1315 {
1316 	struct efx_ptp_data *ptp = efx->ptp_data;
1317 
1318 	int rc = efx_filter_insert_filter(efx, rxfilter, true);
1319 	if (rc < 0)
1320 		return rc;
1321 	ptp->rxfilters[ptp->rxfilters_count] = rc;
1322 	ptp->rxfilters_count++;
1323 	return 0;
1324 }
1325 
efx_ptp_insert_ipv4_filter(struct efx_nic * efx,u16 port)1326 static int efx_ptp_insert_ipv4_filter(struct efx_nic *efx, u16 port)
1327 {
1328 	struct efx_filter_spec rxfilter;
1329 
1330 	efx_ptp_init_filter(efx, &rxfilter);
1331 	efx_filter_set_ipv4_local(&rxfilter, IPPROTO_UDP, htonl(PTP_ADDR_IPV4),
1332 				  htons(port));
1333 	return efx_ptp_insert_filter(efx, &rxfilter);
1334 }
1335 
efx_ptp_insert_ipv6_filter(struct efx_nic * efx,u16 port)1336 static int efx_ptp_insert_ipv6_filter(struct efx_nic *efx, u16 port)
1337 {
1338 	const struct in6_addr addr = {{PTP_ADDR_IPV6}};
1339 	struct efx_filter_spec rxfilter;
1340 
1341 	efx_ptp_init_filter(efx, &rxfilter);
1342 	efx_filter_set_ipv6_local(&rxfilter, IPPROTO_UDP, &addr, htons(port));
1343 	return efx_ptp_insert_filter(efx, &rxfilter);
1344 }
1345 
efx_ptp_insert_eth_filter(struct efx_nic * efx)1346 static int efx_ptp_insert_eth_filter(struct efx_nic *efx)
1347 {
1348 	const u8 addr[ETH_ALEN] = PTP_ADDR_ETHER;
1349 	struct efx_filter_spec rxfilter;
1350 
1351 	efx_ptp_init_filter(efx, &rxfilter);
1352 	efx_filter_set_eth_local(&rxfilter, EFX_FILTER_VID_UNSPEC, addr);
1353 	rxfilter.match_flags |= EFX_FILTER_MATCH_ETHER_TYPE;
1354 	rxfilter.ether_type = htons(ETH_P_1588);
1355 	return efx_ptp_insert_filter(efx, &rxfilter);
1356 }
1357 
efx_ptp_insert_multicast_filters(struct efx_nic * efx)1358 static int efx_ptp_insert_multicast_filters(struct efx_nic *efx)
1359 {
1360 	struct efx_ptp_data *ptp = efx->ptp_data;
1361 	int rc;
1362 
1363 	if (!ptp->channel || ptp->rxfilters_count)
1364 		return 0;
1365 
1366 	/* Must filter on both event and general ports to ensure
1367 	 * that there is no packet re-ordering.
1368 	 */
1369 	rc = efx_ptp_insert_ipv4_filter(efx, PTP_EVENT_PORT);
1370 	if (rc < 0)
1371 		goto fail;
1372 
1373 	rc = efx_ptp_insert_ipv4_filter(efx, PTP_GENERAL_PORT);
1374 	if (rc < 0)
1375 		goto fail;
1376 
1377 	/* if the NIC supports hw timestamps by the MAC, we can support
1378 	 * PTP over IPv6 and Ethernet
1379 	 */
1380 	if (efx_ptp_use_mac_tx_timestamps(efx)) {
1381 		rc = efx_ptp_insert_ipv6_filter(efx, PTP_EVENT_PORT);
1382 		if (rc < 0)
1383 			goto fail;
1384 
1385 		rc = efx_ptp_insert_ipv6_filter(efx, PTP_GENERAL_PORT);
1386 		if (rc < 0)
1387 			goto fail;
1388 
1389 		rc = efx_ptp_insert_eth_filter(efx);
1390 		if (rc < 0)
1391 			goto fail;
1392 	}
1393 
1394 	return 0;
1395 
1396 fail:
1397 	efx_ptp_remove_multicast_filters(efx);
1398 	return rc;
1399 }
1400 
efx_ptp_start(struct efx_nic * efx)1401 static int efx_ptp_start(struct efx_nic *efx)
1402 {
1403 	struct efx_ptp_data *ptp = efx->ptp_data;
1404 	int rc;
1405 
1406 	ptp->reset_required = false;
1407 
1408 	rc = efx_ptp_insert_multicast_filters(efx);
1409 	if (rc)
1410 		return rc;
1411 
1412 	rc = efx_ptp_enable(efx);
1413 	if (rc != 0)
1414 		goto fail;
1415 
1416 	ptp->evt_frag_idx = 0;
1417 	ptp->current_adjfreq = 0;
1418 
1419 	return 0;
1420 
1421 fail:
1422 	efx_ptp_remove_multicast_filters(efx);
1423 	return rc;
1424 }
1425 
efx_ptp_stop(struct efx_nic * efx)1426 static int efx_ptp_stop(struct efx_nic *efx)
1427 {
1428 	struct efx_ptp_data *ptp = efx->ptp_data;
1429 	struct list_head *cursor;
1430 	struct list_head *next;
1431 	int rc;
1432 
1433 	if (ptp == NULL)
1434 		return 0;
1435 
1436 	rc = efx_ptp_disable(efx);
1437 
1438 	efx_ptp_remove_multicast_filters(efx);
1439 
1440 	/* Make sure RX packets are really delivered */
1441 	efx_ptp_deliver_rx_queue(&efx->ptp_data->rxq);
1442 	skb_queue_purge(&efx->ptp_data->txq);
1443 
1444 	/* Drop any pending receive events */
1445 	spin_lock_bh(&efx->ptp_data->evt_lock);
1446 	list_for_each_safe(cursor, next, &efx->ptp_data->evt_list) {
1447 		list_move(cursor, &efx->ptp_data->evt_free_list);
1448 	}
1449 	spin_unlock_bh(&efx->ptp_data->evt_lock);
1450 
1451 	return rc;
1452 }
1453 
efx_ptp_restart(struct efx_nic * efx)1454 static int efx_ptp_restart(struct efx_nic *efx)
1455 {
1456 	if (efx->ptp_data && efx->ptp_data->enabled)
1457 		return efx_ptp_start(efx);
1458 	return 0;
1459 }
1460 
efx_ptp_pps_worker(struct work_struct * work)1461 static void efx_ptp_pps_worker(struct work_struct *work)
1462 {
1463 	struct efx_ptp_data *ptp =
1464 		container_of(work, struct efx_ptp_data, pps_work);
1465 	struct efx_nic *efx = ptp->efx;
1466 	struct ptp_clock_event ptp_evt;
1467 
1468 	if (efx_ptp_synchronize(efx, PTP_SYNC_ATTEMPTS))
1469 		return;
1470 
1471 	ptp_evt.type = PTP_CLOCK_PPSUSR;
1472 	ptp_evt.pps_times = ptp->host_time_pps;
1473 	ptp_clock_event(ptp->phc_clock, &ptp_evt);
1474 }
1475 
efx_ptp_worker(struct work_struct * work)1476 static void efx_ptp_worker(struct work_struct *work)
1477 {
1478 	struct efx_ptp_data *ptp_data =
1479 		container_of(work, struct efx_ptp_data, work);
1480 	struct efx_nic *efx = ptp_data->efx;
1481 	struct sk_buff *skb;
1482 	struct sk_buff_head tempq;
1483 
1484 	if (ptp_data->reset_required) {
1485 		efx_ptp_stop(efx);
1486 		efx_ptp_start(efx);
1487 		return;
1488 	}
1489 
1490 	efx_ptp_drop_time_expired_events(efx);
1491 
1492 	__skb_queue_head_init(&tempq);
1493 	efx_ptp_process_events(efx, &tempq);
1494 
1495 	while ((skb = skb_dequeue(&ptp_data->txq)))
1496 		ptp_data->xmit_skb(efx, skb);
1497 
1498 	while ((skb = __skb_dequeue(&tempq)))
1499 		efx_ptp_process_rx(efx, skb);
1500 }
1501 
1502 static const struct ptp_clock_info efx_phc_clock_info = {
1503 	.owner		= THIS_MODULE,
1504 	.name		= "sfc",
1505 	.max_adj	= MAX_PPB,
1506 	.n_alarm	= 0,
1507 	.n_ext_ts	= 0,
1508 	.n_per_out	= 0,
1509 	.n_pins		= 0,
1510 	.pps		= 1,
1511 	.adjfreq	= efx_phc_adjfreq,
1512 	.adjtime	= efx_phc_adjtime,
1513 	.gettime64	= efx_phc_gettime,
1514 	.settime64	= efx_phc_settime,
1515 	.enable		= efx_phc_enable,
1516 };
1517 
1518 /* Initialise PTP state. */
efx_ptp_probe(struct efx_nic * efx,struct efx_channel * channel)1519 int efx_ptp_probe(struct efx_nic *efx, struct efx_channel *channel)
1520 {
1521 	struct efx_ptp_data *ptp;
1522 	int rc = 0;
1523 	unsigned int pos;
1524 
1525 	if (efx->ptp_data) {
1526 		efx->ptp_data->channel = channel;
1527 		return 0;
1528 	}
1529 
1530 	ptp = kzalloc(sizeof(struct efx_ptp_data), GFP_KERNEL);
1531 	efx->ptp_data = ptp;
1532 	if (!efx->ptp_data)
1533 		return -ENOMEM;
1534 
1535 	ptp->efx = efx;
1536 	ptp->channel = channel;
1537 	ptp->rx_ts_inline = efx_nic_rev(efx) >= EFX_REV_HUNT_A0;
1538 
1539 	rc = efx_nic_alloc_buffer(efx, &ptp->start, sizeof(int), GFP_KERNEL);
1540 	if (rc != 0)
1541 		goto fail1;
1542 
1543 	skb_queue_head_init(&ptp->rxq);
1544 	skb_queue_head_init(&ptp->txq);
1545 	ptp->workwq = create_singlethread_workqueue("sfc_ptp");
1546 	if (!ptp->workwq) {
1547 		rc = -ENOMEM;
1548 		goto fail2;
1549 	}
1550 
1551 	if (efx_ptp_use_mac_tx_timestamps(efx)) {
1552 		ptp->xmit_skb = efx_ptp_xmit_skb_queue;
1553 		/* Request sync events on this channel. */
1554 		channel->sync_events_state = SYNC_EVENTS_QUIESCENT;
1555 	} else {
1556 		ptp->xmit_skb = efx_ptp_xmit_skb_mc;
1557 	}
1558 
1559 	INIT_WORK(&ptp->work, efx_ptp_worker);
1560 	ptp->config.flags = 0;
1561 	ptp->config.tx_type = HWTSTAMP_TX_OFF;
1562 	ptp->config.rx_filter = HWTSTAMP_FILTER_NONE;
1563 	INIT_LIST_HEAD(&ptp->evt_list);
1564 	INIT_LIST_HEAD(&ptp->evt_free_list);
1565 	spin_lock_init(&ptp->evt_lock);
1566 	for (pos = 0; pos < MAX_RECEIVE_EVENTS; pos++)
1567 		list_add(&ptp->rx_evts[pos].link, &ptp->evt_free_list);
1568 
1569 	/* Get the NIC PTP attributes and set up time conversions */
1570 	rc = efx_ptp_get_attributes(efx);
1571 	if (rc < 0)
1572 		goto fail3;
1573 
1574 	/* Get the timestamp corrections */
1575 	rc = efx_ptp_get_timestamp_corrections(efx);
1576 	if (rc < 0)
1577 		goto fail3;
1578 
1579 	if (efx->mcdi->fn_flags &
1580 	    (1 << MC_CMD_DRV_ATTACH_EXT_OUT_FLAG_PRIMARY)) {
1581 		ptp->phc_clock_info = efx_phc_clock_info;
1582 		ptp->phc_clock = ptp_clock_register(&ptp->phc_clock_info,
1583 						    &efx->pci_dev->dev);
1584 		if (IS_ERR(ptp->phc_clock)) {
1585 			rc = PTR_ERR(ptp->phc_clock);
1586 			goto fail3;
1587 		} else if (ptp->phc_clock) {
1588 			INIT_WORK(&ptp->pps_work, efx_ptp_pps_worker);
1589 			ptp->pps_workwq = create_singlethread_workqueue("sfc_pps");
1590 			if (!ptp->pps_workwq) {
1591 				rc = -ENOMEM;
1592 				goto fail4;
1593 			}
1594 		}
1595 	}
1596 	ptp->nic_ts_enabled = false;
1597 
1598 	return 0;
1599 fail4:
1600 	ptp_clock_unregister(efx->ptp_data->phc_clock);
1601 
1602 fail3:
1603 	destroy_workqueue(efx->ptp_data->workwq);
1604 
1605 fail2:
1606 	efx_nic_free_buffer(efx, &ptp->start);
1607 
1608 fail1:
1609 	kfree(efx->ptp_data);
1610 	efx->ptp_data = NULL;
1611 
1612 	return rc;
1613 }
1614 
1615 /* Initialise PTP channel.
1616  *
1617  * Setting core_index to zero causes the queue to be initialised and doesn't
1618  * overlap with 'rxq0' because ptp.c doesn't use skb_record_rx_queue.
1619  */
efx_ptp_probe_channel(struct efx_channel * channel)1620 static int efx_ptp_probe_channel(struct efx_channel *channel)
1621 {
1622 	struct efx_nic *efx = channel->efx;
1623 	int rc;
1624 
1625 	channel->irq_moderation_us = 0;
1626 	channel->rx_queue.core_index = 0;
1627 
1628 	rc = efx_ptp_probe(efx, channel);
1629 	/* Failure to probe PTP is not fatal; this channel will just not be
1630 	 * used for anything.
1631 	 * In the case of EPERM, efx_ptp_probe will print its own message (in
1632 	 * efx_ptp_get_attributes()), so we don't need to.
1633 	 */
1634 	if (rc && rc != -EPERM)
1635 		netif_warn(efx, drv, efx->net_dev,
1636 			   "Failed to probe PTP, rc=%d\n", rc);
1637 	return 0;
1638 }
1639 
efx_ptp_remove(struct efx_nic * efx)1640 void efx_ptp_remove(struct efx_nic *efx)
1641 {
1642 	if (!efx->ptp_data)
1643 		return;
1644 
1645 	(void)efx_ptp_disable(efx);
1646 
1647 	cancel_work_sync(&efx->ptp_data->work);
1648 	if (efx->ptp_data->pps_workwq)
1649 		cancel_work_sync(&efx->ptp_data->pps_work);
1650 
1651 	skb_queue_purge(&efx->ptp_data->rxq);
1652 	skb_queue_purge(&efx->ptp_data->txq);
1653 
1654 	if (efx->ptp_data->phc_clock) {
1655 		destroy_workqueue(efx->ptp_data->pps_workwq);
1656 		ptp_clock_unregister(efx->ptp_data->phc_clock);
1657 	}
1658 
1659 	destroy_workqueue(efx->ptp_data->workwq);
1660 
1661 	efx_nic_free_buffer(efx, &efx->ptp_data->start);
1662 	kfree(efx->ptp_data);
1663 	efx->ptp_data = NULL;
1664 }
1665 
efx_ptp_remove_channel(struct efx_channel * channel)1666 static void efx_ptp_remove_channel(struct efx_channel *channel)
1667 {
1668 	efx_ptp_remove(channel->efx);
1669 }
1670 
efx_ptp_get_channel_name(struct efx_channel * channel,char * buf,size_t len)1671 static void efx_ptp_get_channel_name(struct efx_channel *channel,
1672 				     char *buf, size_t len)
1673 {
1674 	snprintf(buf, len, "%s-ptp", channel->efx->name);
1675 }
1676 
1677 /* Determine whether this packet should be processed by the PTP module
1678  * or transmitted conventionally.
1679  */
efx_ptp_is_ptp_tx(struct efx_nic * efx,struct sk_buff * skb)1680 bool efx_ptp_is_ptp_tx(struct efx_nic *efx, struct sk_buff *skb)
1681 {
1682 	return efx->ptp_data &&
1683 		efx->ptp_data->enabled &&
1684 		skb->len >= PTP_MIN_LENGTH &&
1685 		skb->len <= MC_CMD_PTP_IN_TRANSMIT_PACKET_MAXNUM &&
1686 		likely(skb->protocol == htons(ETH_P_IP)) &&
1687 		skb_transport_header_was_set(skb) &&
1688 		skb_network_header_len(skb) >= sizeof(struct iphdr) &&
1689 		ip_hdr(skb)->protocol == IPPROTO_UDP &&
1690 		skb_headlen(skb) >=
1691 		skb_transport_offset(skb) + sizeof(struct udphdr) &&
1692 		udp_hdr(skb)->dest == htons(PTP_EVENT_PORT);
1693 }
1694 
1695 /* Receive a PTP packet.  Packets are queued until the arrival of
1696  * the receive timestamp from the MC - this will probably occur after the
1697  * packet arrival because of the processing in the MC.
1698  */
efx_ptp_rx(struct efx_channel * channel,struct sk_buff * skb)1699 static bool efx_ptp_rx(struct efx_channel *channel, struct sk_buff *skb)
1700 {
1701 	struct efx_nic *efx = channel->efx;
1702 	struct efx_ptp_data *ptp = efx->ptp_data;
1703 	struct efx_ptp_match *match = (struct efx_ptp_match *)skb->cb;
1704 	u8 *match_data_012, *match_data_345;
1705 	unsigned int version;
1706 	u8 *data;
1707 
1708 	match->expiry = jiffies + msecs_to_jiffies(PKT_EVENT_LIFETIME_MS);
1709 
1710 	/* Correct version? */
1711 	if (ptp->mode == MC_CMD_PTP_MODE_V1) {
1712 		if (!pskb_may_pull(skb, PTP_V1_MIN_LENGTH)) {
1713 			return false;
1714 		}
1715 		data = skb->data;
1716 		version = ntohs(*(__be16 *)&data[PTP_V1_VERSION_OFFSET]);
1717 		if (version != PTP_VERSION_V1) {
1718 			return false;
1719 		}
1720 
1721 		/* PTP V1 uses all six bytes of the UUID to match the packet
1722 		 * to the timestamp
1723 		 */
1724 		match_data_012 = data + PTP_V1_UUID_OFFSET;
1725 		match_data_345 = data + PTP_V1_UUID_OFFSET + 3;
1726 	} else {
1727 		if (!pskb_may_pull(skb, PTP_V2_MIN_LENGTH)) {
1728 			return false;
1729 		}
1730 		data = skb->data;
1731 		version = data[PTP_V2_VERSION_OFFSET];
1732 		if ((version & PTP_VERSION_V2_MASK) != PTP_VERSION_V2) {
1733 			return false;
1734 		}
1735 
1736 		/* The original V2 implementation uses bytes 2-7 of
1737 		 * the UUID to match the packet to the timestamp. This
1738 		 * discards two of the bytes of the MAC address used
1739 		 * to create the UUID (SF bug 33070).  The PTP V2
1740 		 * enhanced mode fixes this issue and uses bytes 0-2
1741 		 * and byte 5-7 of the UUID.
1742 		 */
1743 		match_data_345 = data + PTP_V2_UUID_OFFSET + 5;
1744 		if (ptp->mode == MC_CMD_PTP_MODE_V2) {
1745 			match_data_012 = data + PTP_V2_UUID_OFFSET + 2;
1746 		} else {
1747 			match_data_012 = data + PTP_V2_UUID_OFFSET + 0;
1748 			BUG_ON(ptp->mode != MC_CMD_PTP_MODE_V2_ENHANCED);
1749 		}
1750 	}
1751 
1752 	/* Does this packet require timestamping? */
1753 	if (ntohs(*(__be16 *)&data[PTP_DPORT_OFFSET]) == PTP_EVENT_PORT) {
1754 		match->state = PTP_PACKET_STATE_UNMATCHED;
1755 
1756 		/* We expect the sequence number to be in the same position in
1757 		 * the packet for PTP V1 and V2
1758 		 */
1759 		BUILD_BUG_ON(PTP_V1_SEQUENCE_OFFSET != PTP_V2_SEQUENCE_OFFSET);
1760 		BUILD_BUG_ON(PTP_V1_SEQUENCE_LENGTH != PTP_V2_SEQUENCE_LENGTH);
1761 
1762 		/* Extract UUID/Sequence information */
1763 		match->words[0] = (match_data_012[0]         |
1764 				   (match_data_012[1] << 8)  |
1765 				   (match_data_012[2] << 16) |
1766 				   (match_data_345[0] << 24));
1767 		match->words[1] = (match_data_345[1]         |
1768 				   (match_data_345[2] << 8)  |
1769 				   (data[PTP_V1_SEQUENCE_OFFSET +
1770 					 PTP_V1_SEQUENCE_LENGTH - 1] <<
1771 				    16));
1772 	} else {
1773 		match->state = PTP_PACKET_STATE_MATCH_UNWANTED;
1774 	}
1775 
1776 	skb_queue_tail(&ptp->rxq, skb);
1777 	queue_work(ptp->workwq, &ptp->work);
1778 
1779 	return true;
1780 }
1781 
1782 /* Transmit a PTP packet.  This has to be transmitted by the MC
1783  * itself, through an MCDI call.  MCDI calls aren't permitted
1784  * in the transmit path so defer the actual transmission to a suitable worker.
1785  */
efx_ptp_tx(struct efx_nic * efx,struct sk_buff * skb)1786 int efx_ptp_tx(struct efx_nic *efx, struct sk_buff *skb)
1787 {
1788 	struct efx_ptp_data *ptp = efx->ptp_data;
1789 
1790 	skb_queue_tail(&ptp->txq, skb);
1791 
1792 	if ((udp_hdr(skb)->dest == htons(PTP_EVENT_PORT)) &&
1793 	    (skb->len <= MC_CMD_PTP_IN_TRANSMIT_PACKET_MAXNUM))
1794 		efx_xmit_hwtstamp_pending(skb);
1795 	queue_work(ptp->workwq, &ptp->work);
1796 
1797 	return NETDEV_TX_OK;
1798 }
1799 
efx_ptp_get_mode(struct efx_nic * efx)1800 int efx_ptp_get_mode(struct efx_nic *efx)
1801 {
1802 	return efx->ptp_data->mode;
1803 }
1804 
efx_ptp_change_mode(struct efx_nic * efx,bool enable_wanted,unsigned int new_mode)1805 int efx_ptp_change_mode(struct efx_nic *efx, bool enable_wanted,
1806 			unsigned int new_mode)
1807 {
1808 	if ((enable_wanted != efx->ptp_data->enabled) ||
1809 	    (enable_wanted && (efx->ptp_data->mode != new_mode))) {
1810 		int rc = 0;
1811 
1812 		if (enable_wanted) {
1813 			/* Change of mode requires disable */
1814 			if (efx->ptp_data->enabled &&
1815 			    (efx->ptp_data->mode != new_mode)) {
1816 				efx->ptp_data->enabled = false;
1817 				rc = efx_ptp_stop(efx);
1818 				if (rc != 0)
1819 					return rc;
1820 			}
1821 
1822 			/* Set new operating mode and establish
1823 			 * baseline synchronisation, which must
1824 			 * succeed.
1825 			 */
1826 			efx->ptp_data->mode = new_mode;
1827 			if (netif_running(efx->net_dev))
1828 				rc = efx_ptp_start(efx);
1829 			if (rc == 0) {
1830 				rc = efx_ptp_synchronize(efx,
1831 							 PTP_SYNC_ATTEMPTS * 2);
1832 				if (rc != 0)
1833 					efx_ptp_stop(efx);
1834 			}
1835 		} else {
1836 			rc = efx_ptp_stop(efx);
1837 		}
1838 
1839 		if (rc != 0)
1840 			return rc;
1841 
1842 		efx->ptp_data->enabled = enable_wanted;
1843 	}
1844 
1845 	return 0;
1846 }
1847 
efx_ptp_ts_init(struct efx_nic * efx,struct hwtstamp_config * init)1848 static int efx_ptp_ts_init(struct efx_nic *efx, struct hwtstamp_config *init)
1849 {
1850 	int rc;
1851 
1852 	if ((init->tx_type != HWTSTAMP_TX_OFF) &&
1853 	    (init->tx_type != HWTSTAMP_TX_ON))
1854 		return -ERANGE;
1855 
1856 	rc = efx->type->ptp_set_ts_config(efx, init);
1857 	if (rc)
1858 		return rc;
1859 
1860 	efx->ptp_data->config = *init;
1861 	return 0;
1862 }
1863 
efx_ptp_get_ts_info(struct efx_nic * efx,struct ethtool_ts_info * ts_info)1864 void efx_ptp_get_ts_info(struct efx_nic *efx, struct ethtool_ts_info *ts_info)
1865 {
1866 	struct efx_ptp_data *ptp = efx->ptp_data;
1867 	struct efx_nic *primary = efx->primary;
1868 
1869 	ASSERT_RTNL();
1870 
1871 	if (!ptp)
1872 		return;
1873 
1874 	ts_info->so_timestamping |= (SOF_TIMESTAMPING_TX_HARDWARE |
1875 				     SOF_TIMESTAMPING_RX_HARDWARE |
1876 				     SOF_TIMESTAMPING_RAW_HARDWARE);
1877 	/* Check licensed features.  If we don't have the license for TX
1878 	 * timestamps, the NIC will not support them.
1879 	 */
1880 	if (efx_ptp_use_mac_tx_timestamps(efx)) {
1881 		struct efx_ef10_nic_data *nic_data = efx->nic_data;
1882 
1883 		if (!(nic_data->licensed_features &
1884 		      (1 << LICENSED_V3_FEATURES_TX_TIMESTAMPS_LBN)))
1885 			ts_info->so_timestamping &=
1886 				~SOF_TIMESTAMPING_TX_HARDWARE;
1887 	}
1888 	if (primary && primary->ptp_data && primary->ptp_data->phc_clock)
1889 		ts_info->phc_index =
1890 			ptp_clock_index(primary->ptp_data->phc_clock);
1891 	ts_info->tx_types = 1 << HWTSTAMP_TX_OFF | 1 << HWTSTAMP_TX_ON;
1892 	ts_info->rx_filters = ptp->efx->type->hwtstamp_filters;
1893 }
1894 
efx_ptp_set_ts_config(struct efx_nic * efx,struct ifreq * ifr)1895 int efx_ptp_set_ts_config(struct efx_nic *efx, struct ifreq *ifr)
1896 {
1897 	struct hwtstamp_config config;
1898 	int rc;
1899 
1900 	/* Not a PTP enabled port */
1901 	if (!efx->ptp_data)
1902 		return -EOPNOTSUPP;
1903 
1904 	if (copy_from_user(&config, ifr->ifr_data, sizeof(config)))
1905 		return -EFAULT;
1906 
1907 	rc = efx_ptp_ts_init(efx, &config);
1908 	if (rc != 0)
1909 		return rc;
1910 
1911 	return copy_to_user(ifr->ifr_data, &config, sizeof(config))
1912 		? -EFAULT : 0;
1913 }
1914 
efx_ptp_get_ts_config(struct efx_nic * efx,struct ifreq * ifr)1915 int efx_ptp_get_ts_config(struct efx_nic *efx, struct ifreq *ifr)
1916 {
1917 	if (!efx->ptp_data)
1918 		return -EOPNOTSUPP;
1919 
1920 	return copy_to_user(ifr->ifr_data, &efx->ptp_data->config,
1921 			    sizeof(efx->ptp_data->config)) ? -EFAULT : 0;
1922 }
1923 
ptp_event_failure(struct efx_nic * efx,int expected_frag_len)1924 static void ptp_event_failure(struct efx_nic *efx, int expected_frag_len)
1925 {
1926 	struct efx_ptp_data *ptp = efx->ptp_data;
1927 
1928 	netif_err(efx, hw, efx->net_dev,
1929 		"PTP unexpected event length: got %d expected %d\n",
1930 		ptp->evt_frag_idx, expected_frag_len);
1931 	ptp->reset_required = true;
1932 	queue_work(ptp->workwq, &ptp->work);
1933 }
1934 
1935 /* Process a completed receive event.  Put it on the event queue and
1936  * start worker thread.  This is required because event and their
1937  * correspoding packets may come in either order.
1938  */
ptp_event_rx(struct efx_nic * efx,struct efx_ptp_data * ptp)1939 static void ptp_event_rx(struct efx_nic *efx, struct efx_ptp_data *ptp)
1940 {
1941 	struct efx_ptp_event_rx *evt = NULL;
1942 
1943 	if (WARN_ON_ONCE(ptp->rx_ts_inline))
1944 		return;
1945 
1946 	if (ptp->evt_frag_idx != 3) {
1947 		ptp_event_failure(efx, 3);
1948 		return;
1949 	}
1950 
1951 	spin_lock_bh(&ptp->evt_lock);
1952 	if (!list_empty(&ptp->evt_free_list)) {
1953 		evt = list_first_entry(&ptp->evt_free_list,
1954 				       struct efx_ptp_event_rx, link);
1955 		list_del(&evt->link);
1956 
1957 		evt->seq0 = EFX_QWORD_FIELD(ptp->evt_frags[2], MCDI_EVENT_DATA);
1958 		evt->seq1 = (EFX_QWORD_FIELD(ptp->evt_frags[2],
1959 					     MCDI_EVENT_SRC)        |
1960 			     (EFX_QWORD_FIELD(ptp->evt_frags[1],
1961 					      MCDI_EVENT_SRC) << 8) |
1962 			     (EFX_QWORD_FIELD(ptp->evt_frags[0],
1963 					      MCDI_EVENT_SRC) << 16));
1964 		evt->hwtimestamp = efx->ptp_data->nic_to_kernel_time(
1965 			EFX_QWORD_FIELD(ptp->evt_frags[0], MCDI_EVENT_DATA),
1966 			EFX_QWORD_FIELD(ptp->evt_frags[1], MCDI_EVENT_DATA),
1967 			ptp->ts_corrections.ptp_rx);
1968 		evt->expiry = jiffies + msecs_to_jiffies(PKT_EVENT_LIFETIME_MS);
1969 		list_add_tail(&evt->link, &ptp->evt_list);
1970 
1971 		queue_work(ptp->workwq, &ptp->work);
1972 	} else if (net_ratelimit()) {
1973 		/* Log a rate-limited warning message. */
1974 		netif_err(efx, rx_err, efx->net_dev, "PTP event queue overflow\n");
1975 	}
1976 	spin_unlock_bh(&ptp->evt_lock);
1977 }
1978 
ptp_event_fault(struct efx_nic * efx,struct efx_ptp_data * ptp)1979 static void ptp_event_fault(struct efx_nic *efx, struct efx_ptp_data *ptp)
1980 {
1981 	int code = EFX_QWORD_FIELD(ptp->evt_frags[0], MCDI_EVENT_DATA);
1982 	if (ptp->evt_frag_idx != 1) {
1983 		ptp_event_failure(efx, 1);
1984 		return;
1985 	}
1986 
1987 	netif_err(efx, hw, efx->net_dev, "PTP error %d\n", code);
1988 }
1989 
ptp_event_pps(struct efx_nic * efx,struct efx_ptp_data * ptp)1990 static void ptp_event_pps(struct efx_nic *efx, struct efx_ptp_data *ptp)
1991 {
1992 	if (ptp->nic_ts_enabled)
1993 		queue_work(ptp->pps_workwq, &ptp->pps_work);
1994 }
1995 
efx_ptp_event(struct efx_nic * efx,efx_qword_t * ev)1996 void efx_ptp_event(struct efx_nic *efx, efx_qword_t *ev)
1997 {
1998 	struct efx_ptp_data *ptp = efx->ptp_data;
1999 	int code = EFX_QWORD_FIELD(*ev, MCDI_EVENT_CODE);
2000 
2001 	if (!ptp) {
2002 		if (!efx->ptp_warned) {
2003 			netif_warn(efx, drv, efx->net_dev,
2004 				   "Received PTP event but PTP not set up\n");
2005 			efx->ptp_warned = true;
2006 		}
2007 		return;
2008 	}
2009 
2010 	if (!ptp->enabled)
2011 		return;
2012 
2013 	if (ptp->evt_frag_idx == 0) {
2014 		ptp->evt_code = code;
2015 	} else if (ptp->evt_code != code) {
2016 		netif_err(efx, hw, efx->net_dev,
2017 			  "PTP out of sequence event %d\n", code);
2018 		ptp->evt_frag_idx = 0;
2019 	}
2020 
2021 	ptp->evt_frags[ptp->evt_frag_idx++] = *ev;
2022 	if (!MCDI_EVENT_FIELD(*ev, CONT)) {
2023 		/* Process resulting event */
2024 		switch (code) {
2025 		case MCDI_EVENT_CODE_PTP_RX:
2026 			ptp_event_rx(efx, ptp);
2027 			break;
2028 		case MCDI_EVENT_CODE_PTP_FAULT:
2029 			ptp_event_fault(efx, ptp);
2030 			break;
2031 		case MCDI_EVENT_CODE_PTP_PPS:
2032 			ptp_event_pps(efx, ptp);
2033 			break;
2034 		default:
2035 			netif_err(efx, hw, efx->net_dev,
2036 				  "PTP unknown event %d\n", code);
2037 			break;
2038 		}
2039 		ptp->evt_frag_idx = 0;
2040 	} else if (MAX_EVENT_FRAGS == ptp->evt_frag_idx) {
2041 		netif_err(efx, hw, efx->net_dev,
2042 			  "PTP too many event fragments\n");
2043 		ptp->evt_frag_idx = 0;
2044 	}
2045 }
2046 
efx_time_sync_event(struct efx_channel * channel,efx_qword_t * ev)2047 void efx_time_sync_event(struct efx_channel *channel, efx_qword_t *ev)
2048 {
2049 	struct efx_nic *efx = channel->efx;
2050 	struct efx_ptp_data *ptp = efx->ptp_data;
2051 
2052 	/* When extracting the sync timestamp minor value, we should discard
2053 	 * the least significant two bits. These are not required in order
2054 	 * to reconstruct full-range timestamps and they are optionally used
2055 	 * to report status depending on the options supplied when subscribing
2056 	 * for sync events.
2057 	 */
2058 	channel->sync_timestamp_major = MCDI_EVENT_FIELD(*ev, PTP_TIME_MAJOR);
2059 	channel->sync_timestamp_minor =
2060 		(MCDI_EVENT_FIELD(*ev, PTP_TIME_MINOR_MS_8BITS) & 0xFC)
2061 			<< ptp->nic_time.sync_event_minor_shift;
2062 
2063 	/* if sync events have been disabled then we want to silently ignore
2064 	 * this event, so throw away result.
2065 	 */
2066 	(void) cmpxchg(&channel->sync_events_state, SYNC_EVENTS_REQUESTED,
2067 		       SYNC_EVENTS_VALID);
2068 }
2069 
efx_rx_buf_timestamp_minor(struct efx_nic * efx,const u8 * eh)2070 static inline u32 efx_rx_buf_timestamp_minor(struct efx_nic *efx, const u8 *eh)
2071 {
2072 #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
2073 	return __le32_to_cpup((const __le32 *)(eh + efx->rx_packet_ts_offset));
2074 #else
2075 	const u8 *data = eh + efx->rx_packet_ts_offset;
2076 	return (u32)data[0]       |
2077 	       (u32)data[1] << 8  |
2078 	       (u32)data[2] << 16 |
2079 	       (u32)data[3] << 24;
2080 #endif
2081 }
2082 
__efx_rx_skb_attach_timestamp(struct efx_channel * channel,struct sk_buff * skb)2083 void __efx_rx_skb_attach_timestamp(struct efx_channel *channel,
2084 				   struct sk_buff *skb)
2085 {
2086 	struct efx_nic *efx = channel->efx;
2087 	struct efx_ptp_data *ptp = efx->ptp_data;
2088 	u32 pkt_timestamp_major, pkt_timestamp_minor;
2089 	u32 diff, carry;
2090 	struct skb_shared_hwtstamps *timestamps;
2091 
2092 	if (channel->sync_events_state != SYNC_EVENTS_VALID)
2093 		return;
2094 
2095 	pkt_timestamp_minor = efx_rx_buf_timestamp_minor(efx, skb_mac_header(skb));
2096 
2097 	/* get the difference between the packet and sync timestamps,
2098 	 * modulo one second
2099 	 */
2100 	diff = pkt_timestamp_minor - channel->sync_timestamp_minor;
2101 	if (pkt_timestamp_minor < channel->sync_timestamp_minor)
2102 		diff += ptp->nic_time.minor_max;
2103 
2104 	/* do we roll over a second boundary and need to carry the one? */
2105 	carry = (channel->sync_timestamp_minor >= ptp->nic_time.minor_max - diff) ?
2106 		1 : 0;
2107 
2108 	if (diff <= ptp->nic_time.sync_event_diff_max) {
2109 		/* packet is ahead of the sync event by a quarter of a second or
2110 		 * less (allowing for fuzz)
2111 		 */
2112 		pkt_timestamp_major = channel->sync_timestamp_major + carry;
2113 	} else if (diff >= ptp->nic_time.sync_event_diff_min) {
2114 		/* packet is behind the sync event but within the fuzz factor.
2115 		 * This means the RX packet and sync event crossed as they were
2116 		 * placed on the event queue, which can sometimes happen.
2117 		 */
2118 		pkt_timestamp_major = channel->sync_timestamp_major - 1 + carry;
2119 	} else {
2120 		/* it's outside tolerance in both directions. this might be
2121 		 * indicative of us missing sync events for some reason, so
2122 		 * we'll call it an error rather than risk giving a bogus
2123 		 * timestamp.
2124 		 */
2125 		netif_vdbg(efx, drv, efx->net_dev,
2126 			  "packet timestamp %x too far from sync event %x:%x\n",
2127 			  pkt_timestamp_minor, channel->sync_timestamp_major,
2128 			  channel->sync_timestamp_minor);
2129 		return;
2130 	}
2131 
2132 	/* attach the timestamps to the skb */
2133 	timestamps = skb_hwtstamps(skb);
2134 	timestamps->hwtstamp =
2135 		ptp->nic_to_kernel_time(pkt_timestamp_major,
2136 					pkt_timestamp_minor,
2137 					ptp->ts_corrections.general_rx);
2138 }
2139 
efx_phc_adjfreq(struct ptp_clock_info * ptp,s32 delta)2140 static int efx_phc_adjfreq(struct ptp_clock_info *ptp, s32 delta)
2141 {
2142 	struct efx_ptp_data *ptp_data = container_of(ptp,
2143 						     struct efx_ptp_data,
2144 						     phc_clock_info);
2145 	struct efx_nic *efx = ptp_data->efx;
2146 	MCDI_DECLARE_BUF(inadj, MC_CMD_PTP_IN_ADJUST_LEN);
2147 	s64 adjustment_ns;
2148 	int rc;
2149 
2150 	if (delta > MAX_PPB)
2151 		delta = MAX_PPB;
2152 	else if (delta < -MAX_PPB)
2153 		delta = -MAX_PPB;
2154 
2155 	/* Convert ppb to fixed point ns taking care to round correctly. */
2156 	adjustment_ns = ((s64)delta * PPB_SCALE_WORD +
2157 			 (1 << (ptp_data->adjfreq_ppb_shift - 1))) >>
2158 			ptp_data->adjfreq_ppb_shift;
2159 
2160 	MCDI_SET_DWORD(inadj, PTP_IN_OP, MC_CMD_PTP_OP_ADJUST);
2161 	MCDI_SET_DWORD(inadj, PTP_IN_PERIPH_ID, 0);
2162 	MCDI_SET_QWORD(inadj, PTP_IN_ADJUST_FREQ, adjustment_ns);
2163 	MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_SECONDS, 0);
2164 	MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_NANOSECONDS, 0);
2165 	rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inadj, sizeof(inadj),
2166 			  NULL, 0, NULL);
2167 	if (rc != 0)
2168 		return rc;
2169 
2170 	ptp_data->current_adjfreq = adjustment_ns;
2171 	return 0;
2172 }
2173 
efx_phc_adjtime(struct ptp_clock_info * ptp,s64 delta)2174 static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta)
2175 {
2176 	u32 nic_major, nic_minor;
2177 	struct efx_ptp_data *ptp_data = container_of(ptp,
2178 						     struct efx_ptp_data,
2179 						     phc_clock_info);
2180 	struct efx_nic *efx = ptp_data->efx;
2181 	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_ADJUST_LEN);
2182 
2183 	efx->ptp_data->ns_to_nic_time(delta, &nic_major, &nic_minor);
2184 
2185 	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_ADJUST);
2186 	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
2187 	MCDI_SET_QWORD(inbuf, PTP_IN_ADJUST_FREQ, ptp_data->current_adjfreq);
2188 	MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_MAJOR, nic_major);
2189 	MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_MINOR, nic_minor);
2190 	return efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
2191 			    NULL, 0, NULL);
2192 }
2193 
efx_phc_gettime(struct ptp_clock_info * ptp,struct timespec64 * ts)2194 static int efx_phc_gettime(struct ptp_clock_info *ptp, struct timespec64 *ts)
2195 {
2196 	struct efx_ptp_data *ptp_data = container_of(ptp,
2197 						     struct efx_ptp_data,
2198 						     phc_clock_info);
2199 	struct efx_nic *efx = ptp_data->efx;
2200 	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_READ_NIC_TIME_LEN);
2201 	MCDI_DECLARE_BUF(outbuf, MC_CMD_PTP_OUT_READ_NIC_TIME_LEN);
2202 	int rc;
2203 	ktime_t kt;
2204 
2205 	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_READ_NIC_TIME);
2206 	MCDI_SET_DWORD(inbuf, PTP_IN_PERIPH_ID, 0);
2207 
2208 	rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
2209 			  outbuf, sizeof(outbuf), NULL);
2210 	if (rc != 0)
2211 		return rc;
2212 
2213 	kt = ptp_data->nic_to_kernel_time(
2214 		MCDI_DWORD(outbuf, PTP_OUT_READ_NIC_TIME_MAJOR),
2215 		MCDI_DWORD(outbuf, PTP_OUT_READ_NIC_TIME_MINOR), 0);
2216 	*ts = ktime_to_timespec64(kt);
2217 	return 0;
2218 }
2219 
efx_phc_settime(struct ptp_clock_info * ptp,const struct timespec64 * e_ts)2220 static int efx_phc_settime(struct ptp_clock_info *ptp,
2221 			   const struct timespec64 *e_ts)
2222 {
2223 	/* Get the current NIC time, efx_phc_gettime.
2224 	 * Subtract from the desired time to get the offset
2225 	 * call efx_phc_adjtime with the offset
2226 	 */
2227 	int rc;
2228 	struct timespec64 time_now;
2229 	struct timespec64 delta;
2230 
2231 	rc = efx_phc_gettime(ptp, &time_now);
2232 	if (rc != 0)
2233 		return rc;
2234 
2235 	delta = timespec64_sub(*e_ts, time_now);
2236 
2237 	rc = efx_phc_adjtime(ptp, timespec64_to_ns(&delta));
2238 	if (rc != 0)
2239 		return rc;
2240 
2241 	return 0;
2242 }
2243 
efx_phc_enable(struct ptp_clock_info * ptp,struct ptp_clock_request * request,int enable)2244 static int efx_phc_enable(struct ptp_clock_info *ptp,
2245 			  struct ptp_clock_request *request,
2246 			  int enable)
2247 {
2248 	struct efx_ptp_data *ptp_data = container_of(ptp,
2249 						     struct efx_ptp_data,
2250 						     phc_clock_info);
2251 	if (request->type != PTP_CLK_REQ_PPS)
2252 		return -EOPNOTSUPP;
2253 
2254 	ptp_data->nic_ts_enabled = !!enable;
2255 	return 0;
2256 }
2257 
2258 static const struct efx_channel_type efx_ptp_channel_type = {
2259 	.handle_no_channel	= efx_ptp_handle_no_channel,
2260 	.pre_probe		= efx_ptp_probe_channel,
2261 	.post_remove		= efx_ptp_remove_channel,
2262 	.get_name		= efx_ptp_get_channel_name,
2263 	.copy                   = efx_copy_channel,
2264 	.receive_skb		= efx_ptp_rx,
2265 	.want_txqs		= efx_ptp_want_txqs,
2266 	.keep_eventq		= false,
2267 };
2268 
efx_ptp_defer_probe_with_channel(struct efx_nic * efx)2269 void efx_ptp_defer_probe_with_channel(struct efx_nic *efx)
2270 {
2271 	/* Check whether PTP is implemented on this NIC.  The DISABLE
2272 	 * operation will succeed if and only if it is implemented.
2273 	 */
2274 	if (efx_ptp_disable(efx) == 0)
2275 		efx->extra_channel_type[EFX_EXTRA_CHANNEL_PTP] =
2276 			&efx_ptp_channel_type;
2277 }
2278 
efx_ptp_start_datapath(struct efx_nic * efx)2279 void efx_ptp_start_datapath(struct efx_nic *efx)
2280 {
2281 	if (efx_ptp_restart(efx))
2282 		netif_err(efx, drv, efx->net_dev, "Failed to restart PTP.\n");
2283 	/* re-enable timestamping if it was previously enabled */
2284 	if (efx->type->ptp_set_ts_sync_events)
2285 		efx->type->ptp_set_ts_sync_events(efx, true, true);
2286 }
2287 
efx_ptp_stop_datapath(struct efx_nic * efx)2288 void efx_ptp_stop_datapath(struct efx_nic *efx)
2289 {
2290 	/* temporarily disable timestamping */
2291 	if (efx->type->ptp_set_ts_sync_events)
2292 		efx->type->ptp_set_ts_sync_events(efx, false, true);
2293 	efx_ptp_stop(efx);
2294 }
2295