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