xref: /linux/drivers/net/ethernet/sfc/ptp.c (revision b889fcf63cb62e7fdb7816565e28f44dbe4a76a5)
1 /****************************************************************************
2  * Driver for Solarflare Solarstorm network controllers and boards
3  * Copyright 2011 Solarflare Communications Inc.
4  *
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  */
9 
10 /* Theory of operation:
11  *
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.
17  *
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.
26  *
27  * Work queue processing:
28  *	If work waiting, synchronise host/hardware time
29  *
30  *	Transmit: send packet through MC, which returns the transmission time
31  *	that is converted to an appropriate timestamp.
32  *
33  *	Receive: the packet's reception time is converted to an appropriate
34  *	timestamp.
35  */
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 "regs.h"
50 #include "nic.h"
51 
52 /* Maximum number of events expected to make up a PTP event */
53 #define	MAX_EVENT_FRAGS			3
54 
55 /* Maximum delay, ms, to begin synchronisation */
56 #define	MAX_SYNCHRONISE_WAIT_MS		2
57 
58 /* How long, at most, to spend synchronising */
59 #define	SYNCHRONISE_PERIOD_NS		250000
60 
61 /* How often to update the shared memory time */
62 #define	SYNCHRONISATION_GRANULARITY_NS	200
63 
64 /* Minimum permitted length of a (corrected) synchronisation time */
65 #define	MIN_SYNCHRONISATION_NS		120
66 
67 /* Maximum permitted length of a (corrected) synchronisation time */
68 #define	MAX_SYNCHRONISATION_NS		1000
69 
70 /* How many (MC) receive events that can be queued */
71 #define	MAX_RECEIVE_EVENTS		8
72 
73 /* Length of (modified) moving average. */
74 #define	AVERAGE_LENGTH			16
75 
76 /* How long an unmatched event or packet can be held */
77 #define PKT_EVENT_LIFETIME_MS		10
78 
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.
82  */
83 #define PTP_DPORT_OFFSET	22
84 
85 #define PTP_V1_VERSION_LENGTH	2
86 #define PTP_V1_VERSION_OFFSET	28
87 
88 #define PTP_V1_UUID_LENGTH	6
89 #define PTP_V1_UUID_OFFSET	50
90 
91 #define PTP_V1_SEQUENCE_LENGTH	2
92 #define PTP_V1_SEQUENCE_OFFSET	58
93 
94 /* The minimum length of a PTP V1 packet for offsets, etc. to be valid:
95  * includes IP header.
96  */
97 #define	PTP_V1_MIN_LENGTH	64
98 
99 #define PTP_V2_VERSION_LENGTH	1
100 #define PTP_V2_VERSION_OFFSET	29
101 
102 /* Although PTP V2 UUIDs are comprised a ClockIdentity (8) and PortNumber (2),
103  * the MC only captures the last six bytes of the clock identity. These values
104  * reflect those, not the ones used in the standard.  The standard permits
105  * mapping of V1 UUIDs to V2 UUIDs with these same values.
106  */
107 #define PTP_V2_MC_UUID_LENGTH	6
108 #define PTP_V2_MC_UUID_OFFSET	50
109 
110 #define PTP_V2_SEQUENCE_LENGTH	2
111 #define PTP_V2_SEQUENCE_OFFSET	58
112 
113 /* The minimum length of a PTP V2 packet for offsets, etc. to be valid:
114  * includes IP header.
115  */
116 #define	PTP_V2_MIN_LENGTH	63
117 
118 #define	PTP_MIN_LENGTH		63
119 
120 #define PTP_ADDRESS		0xe0000181	/* 224.0.1.129 */
121 #define PTP_EVENT_PORT		319
122 #define PTP_GENERAL_PORT	320
123 
124 /* Annoyingly the format of the version numbers are different between
125  * versions 1 and 2 so it isn't possible to simply look for 1 or 2.
126  */
127 #define	PTP_VERSION_V1		1
128 
129 #define	PTP_VERSION_V2		2
130 #define	PTP_VERSION_V2_MASK	0x0f
131 
132 enum ptp_packet_state {
133 	PTP_PACKET_STATE_UNMATCHED = 0,
134 	PTP_PACKET_STATE_MATCHED,
135 	PTP_PACKET_STATE_TIMED_OUT,
136 	PTP_PACKET_STATE_MATCH_UNWANTED
137 };
138 
139 /* NIC synchronised with single word of time only comprising
140  * partial seconds and full nanoseconds: 10^9 ~ 2^30 so 2 bits for seconds.
141  */
142 #define	MC_NANOSECOND_BITS	30
143 #define	MC_NANOSECOND_MASK	((1 << MC_NANOSECOND_BITS) - 1)
144 #define	MC_SECOND_MASK		((1 << (32 - MC_NANOSECOND_BITS)) - 1)
145 
146 /* Maximum parts-per-billion adjustment that is acceptable */
147 #define MAX_PPB			1000000
148 
149 /* Number of bits required to hold the above */
150 #define	MAX_PPB_BITS		20
151 
152 /* Number of extra bits allowed when calculating fractional ns.
153  * EXTRA_BITS + MC_CMD_PTP_IN_ADJUST_BITS + MAX_PPB_BITS should
154  * be less than 63.
155  */
156 #define	PPB_EXTRA_BITS		2
157 
158 /* Precalculate scale word to avoid long long division at runtime */
159 #define	PPB_SCALE_WORD	((1LL << (PPB_EXTRA_BITS + MC_CMD_PTP_IN_ADJUST_BITS +\
160 			MAX_PPB_BITS)) / 1000000000LL)
161 
162 #define PTP_SYNC_ATTEMPTS	4
163 
164 /**
165  * struct efx_ptp_match - Matching structure, stored in sk_buff's cb area.
166  * @words: UUID and (partial) sequence number
167  * @expiry: Time after which the packet should be delivered irrespective of
168  *            event arrival.
169  * @state: The state of the packet - whether it is ready for processing or
170  *         whether that is of no interest.
171  */
172 struct efx_ptp_match {
173 	u32 words[DIV_ROUND_UP(PTP_V1_UUID_LENGTH, 4)];
174 	unsigned long expiry;
175 	enum ptp_packet_state state;
176 };
177 
178 /**
179  * struct efx_ptp_event_rx - A PTP receive event (from MC)
180  * @seq0: First part of (PTP) UUID
181  * @seq1: Second part of (PTP) UUID and sequence number
182  * @hwtimestamp: Event timestamp
183  */
184 struct efx_ptp_event_rx {
185 	struct list_head link;
186 	u32 seq0;
187 	u32 seq1;
188 	ktime_t hwtimestamp;
189 	unsigned long expiry;
190 };
191 
192 /**
193  * struct efx_ptp_timeset - Synchronisation between host and MC
194  * @host_start: Host time immediately before hardware timestamp taken
195  * @seconds: Hardware timestamp, seconds
196  * @nanoseconds: Hardware timestamp, nanoseconds
197  * @host_end: Host time immediately after hardware timestamp taken
198  * @waitns: Number of nanoseconds between hardware timestamp being read and
199  *          host end time being seen
200  * @window: Difference of host_end and host_start
201  * @valid: Whether this timeset is valid
202  */
203 struct efx_ptp_timeset {
204 	u32 host_start;
205 	u32 seconds;
206 	u32 nanoseconds;
207 	u32 host_end;
208 	u32 waitns;
209 	u32 window;	/* Derived: end - start, allowing for wrap */
210 };
211 
212 /**
213  * struct efx_ptp_data - Precision Time Protocol (PTP) state
214  * @channel: The PTP channel
215  * @rxq: Receive queue (awaiting timestamps)
216  * @txq: Transmit queue
217  * @evt_list: List of MC receive events awaiting packets
218  * @evt_free_list: List of free events
219  * @evt_lock: Lock for manipulating evt_list and evt_free_list
220  * @rx_evts: Instantiated events (on evt_list and evt_free_list)
221  * @workwq: Work queue for processing pending PTP operations
222  * @work: Work task
223  * @reset_required: A serious error has occurred and the PTP task needs to be
224  *                  reset (disable, enable).
225  * @rxfilter_event: Receive filter when operating
226  * @rxfilter_general: Receive filter when operating
227  * @config: Current timestamp configuration
228  * @enabled: PTP operation enabled
229  * @mode: Mode in which PTP operating (PTP version)
230  * @evt_frags: Partly assembled PTP events
231  * @evt_frag_idx: Current fragment number
232  * @evt_code: Last event code
233  * @start: Address at which MC indicates ready for synchronisation
234  * @host_time_pps: Host time at last PPS
235  * @last_sync_ns: Last number of nanoseconds between readings when synchronising
236  * @base_sync_ns: Number of nanoseconds for last synchronisation.
237  * @base_sync_valid: Whether base_sync_time is valid.
238  * @current_adjfreq: Current ppb adjustment.
239  * @phc_clock: Pointer to registered phc device
240  * @phc_clock_info: Registration structure for phc device
241  * @pps_work: pps work task for handling pps events
242  * @pps_workwq: pps work queue
243  * @nic_ts_enabled: Flag indicating if NIC generated TS events are handled
244  * @txbuf: Buffer for use when transmitting (PTP) packets to MC (avoids
245  *         allocations in main data path).
246  * @debug_ptp_dir: PTP debugfs directory
247  * @missed_rx_sync: Number of packets received without syncrhonisation.
248  * @good_syncs: Number of successful synchronisations.
249  * @no_time_syncs: Number of synchronisations with no good times.
250  * @bad_sync_durations: Number of synchronisations with bad durations.
251  * @bad_syncs: Number of failed synchronisations.
252  * @last_sync_time: Number of nanoseconds for last synchronisation.
253  * @sync_timeouts: Number of synchronisation timeouts
254  * @fast_syncs: Number of synchronisations requiring short delay
255  * @min_sync_delta: Minimum time between event and synchronisation
256  * @max_sync_delta: Maximum time between event and synchronisation
257  * @average_sync_delta: Average time between event and synchronisation.
258  *                      Modified moving average.
259  * @last_sync_delta: Last time between event and synchronisation
260  * @mc_stats: Context value for MC statistics
261  * @timeset: Last set of synchronisation statistics.
262  */
263 struct efx_ptp_data {
264 	struct efx_channel *channel;
265 	struct sk_buff_head rxq;
266 	struct sk_buff_head txq;
267 	struct list_head evt_list;
268 	struct list_head evt_free_list;
269 	spinlock_t evt_lock;
270 	struct efx_ptp_event_rx rx_evts[MAX_RECEIVE_EVENTS];
271 	struct workqueue_struct *workwq;
272 	struct work_struct work;
273 	bool reset_required;
274 	u32 rxfilter_event;
275 	u32 rxfilter_general;
276 	bool rxfilter_installed;
277 	struct hwtstamp_config config;
278 	bool enabled;
279 	unsigned int mode;
280 	efx_qword_t evt_frags[MAX_EVENT_FRAGS];
281 	int evt_frag_idx;
282 	int evt_code;
283 	struct efx_buffer start;
284 	struct pps_event_time host_time_pps;
285 	unsigned last_sync_ns;
286 	unsigned base_sync_ns;
287 	bool base_sync_valid;
288 	s64 current_adjfreq;
289 	struct ptp_clock *phc_clock;
290 	struct ptp_clock_info phc_clock_info;
291 	struct work_struct pps_work;
292 	struct workqueue_struct *pps_workwq;
293 	bool nic_ts_enabled;
294 	u8 txbuf[ALIGN(MC_CMD_PTP_IN_TRANSMIT_LEN(
295 			       MC_CMD_PTP_IN_TRANSMIT_PACKET_MAXNUM), 4)];
296 	struct efx_ptp_timeset
297 	timeset[MC_CMD_PTP_OUT_SYNCHRONIZE_TIMESET_MAXNUM];
298 };
299 
300 static int efx_phc_adjfreq(struct ptp_clock_info *ptp, s32 delta);
301 static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta);
302 static int efx_phc_gettime(struct ptp_clock_info *ptp, struct timespec *ts);
303 static int efx_phc_settime(struct ptp_clock_info *ptp,
304 			   const struct timespec *e_ts);
305 static int efx_phc_enable(struct ptp_clock_info *ptp,
306 			  struct ptp_clock_request *request, int on);
307 
308 /* Enable MCDI PTP support. */
309 static int efx_ptp_enable(struct efx_nic *efx)
310 {
311 	u8 inbuf[MC_CMD_PTP_IN_ENABLE_LEN];
312 
313 	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_ENABLE);
314 	MCDI_SET_DWORD(inbuf, PTP_IN_ENABLE_QUEUE,
315 		       efx->ptp_data->channel->channel);
316 	MCDI_SET_DWORD(inbuf, PTP_IN_ENABLE_MODE, efx->ptp_data->mode);
317 
318 	return efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
319 			    NULL, 0, NULL);
320 }
321 
322 /* Disable MCDI PTP support.
323  *
324  * Note that this function should never rely on the presence of ptp_data -
325  * may be called before that exists.
326  */
327 static int efx_ptp_disable(struct efx_nic *efx)
328 {
329 	u8 inbuf[MC_CMD_PTP_IN_DISABLE_LEN];
330 
331 	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_DISABLE);
332 	return efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
333 			    NULL, 0, NULL);
334 }
335 
336 static void efx_ptp_deliver_rx_queue(struct sk_buff_head *q)
337 {
338 	struct sk_buff *skb;
339 
340 	while ((skb = skb_dequeue(q))) {
341 		local_bh_disable();
342 		netif_receive_skb(skb);
343 		local_bh_enable();
344 	}
345 }
346 
347 static void efx_ptp_handle_no_channel(struct efx_nic *efx)
348 {
349 	netif_err(efx, drv, efx->net_dev,
350 		  "ERROR: PTP requires MSI-X and 1 additional interrupt"
351 		  "vector. PTP disabled\n");
352 }
353 
354 /* Repeatedly send the host time to the MC which will capture the hardware
355  * time.
356  */
357 static void efx_ptp_send_times(struct efx_nic *efx,
358 			       struct pps_event_time *last_time)
359 {
360 	struct pps_event_time now;
361 	struct timespec limit;
362 	struct efx_ptp_data *ptp = efx->ptp_data;
363 	struct timespec start;
364 	int *mc_running = ptp->start.addr;
365 
366 	pps_get_ts(&now);
367 	start = now.ts_real;
368 	limit = now.ts_real;
369 	timespec_add_ns(&limit, SYNCHRONISE_PERIOD_NS);
370 
371 	/* Write host time for specified period or until MC is done */
372 	while ((timespec_compare(&now.ts_real, &limit) < 0) &&
373 	       ACCESS_ONCE(*mc_running)) {
374 		struct timespec update_time;
375 		unsigned int host_time;
376 
377 		/* Don't update continuously to avoid saturating the PCIe bus */
378 		update_time = now.ts_real;
379 		timespec_add_ns(&update_time, SYNCHRONISATION_GRANULARITY_NS);
380 		do {
381 			pps_get_ts(&now);
382 		} while ((timespec_compare(&now.ts_real, &update_time) < 0) &&
383 			 ACCESS_ONCE(*mc_running));
384 
385 		/* Synchronise NIC with single word of time only */
386 		host_time = (now.ts_real.tv_sec << MC_NANOSECOND_BITS |
387 			     now.ts_real.tv_nsec);
388 		/* Update host time in NIC memory */
389 		_efx_writed(efx, cpu_to_le32(host_time),
390 			    FR_CZ_MC_TREG_SMEM + MC_SMEM_P0_PTP_TIME_OFST);
391 	}
392 	*last_time = now;
393 }
394 
395 /* Read a timeset from the MC's results and partial process. */
396 static void efx_ptp_read_timeset(u8 *data, struct efx_ptp_timeset *timeset)
397 {
398 	unsigned start_ns, end_ns;
399 
400 	timeset->host_start = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_HOSTSTART);
401 	timeset->seconds = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_SECONDS);
402 	timeset->nanoseconds = MCDI_DWORD(data,
403 					 PTP_OUT_SYNCHRONIZE_NANOSECONDS);
404 	timeset->host_end = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_HOSTEND),
405 	timeset->waitns = MCDI_DWORD(data, PTP_OUT_SYNCHRONIZE_WAITNS);
406 
407 	/* Ignore seconds */
408 	start_ns = timeset->host_start & MC_NANOSECOND_MASK;
409 	end_ns = timeset->host_end & MC_NANOSECOND_MASK;
410 	/* Allow for rollover */
411 	if (end_ns < start_ns)
412 		end_ns += NSEC_PER_SEC;
413 	/* Determine duration of operation */
414 	timeset->window = end_ns - start_ns;
415 }
416 
417 /* Process times received from MC.
418  *
419  * Extract times from returned results, and establish the minimum value
420  * seen.  The minimum value represents the "best" possible time and events
421  * too much greater than this are rejected - the machine is, perhaps, too
422  * busy. A number of readings are taken so that, hopefully, at least one good
423  * synchronisation will be seen in the results.
424  */
425 static int efx_ptp_process_times(struct efx_nic *efx, u8 *synch_buf,
426 				 size_t response_length,
427 				 const struct pps_event_time *last_time)
428 {
429 	unsigned number_readings = (response_length /
430 			       MC_CMD_PTP_OUT_SYNCHRONIZE_TIMESET_LEN);
431 	unsigned i;
432 	unsigned min;
433 	unsigned min_set = 0;
434 	unsigned total;
435 	unsigned ngood = 0;
436 	unsigned last_good = 0;
437 	struct efx_ptp_data *ptp = efx->ptp_data;
438 	bool min_valid = false;
439 	u32 last_sec;
440 	u32 start_sec;
441 	struct timespec delta;
442 
443 	if (number_readings == 0)
444 		return -EAGAIN;
445 
446 	/* Find minimum value in this set of results, discarding clearly
447 	 * erroneous results.
448 	 */
449 	for (i = 0; i < number_readings; i++) {
450 		efx_ptp_read_timeset(synch_buf, &ptp->timeset[i]);
451 		synch_buf += MC_CMD_PTP_OUT_SYNCHRONIZE_TIMESET_LEN;
452 		if (ptp->timeset[i].window > SYNCHRONISATION_GRANULARITY_NS) {
453 			if (min_valid) {
454 				if (ptp->timeset[i].window < min_set)
455 					min_set = ptp->timeset[i].window;
456 			} else {
457 				min_valid = true;
458 				min_set = ptp->timeset[i].window;
459 			}
460 		}
461 	}
462 
463 	if (min_valid) {
464 		if (ptp->base_sync_valid && (min_set > ptp->base_sync_ns))
465 			min = ptp->base_sync_ns;
466 		else
467 			min = min_set;
468 	} else {
469 		min = SYNCHRONISATION_GRANULARITY_NS;
470 	}
471 
472 	/* Discard excessively long synchronise durations.  The MC times
473 	 * when it finishes reading the host time so the corrected window
474 	 * time should be fairly constant for a given platform.
475 	 */
476 	total = 0;
477 	for (i = 0; i < number_readings; i++)
478 		if (ptp->timeset[i].window > ptp->timeset[i].waitns) {
479 			unsigned win;
480 
481 			win = ptp->timeset[i].window - ptp->timeset[i].waitns;
482 			if (win >= MIN_SYNCHRONISATION_NS &&
483 			    win < MAX_SYNCHRONISATION_NS) {
484 				total += ptp->timeset[i].window;
485 				ngood++;
486 				last_good = i;
487 			}
488 		}
489 
490 	if (ngood == 0) {
491 		netif_warn(efx, drv, efx->net_dev,
492 			   "PTP no suitable synchronisations %dns %dns\n",
493 			   ptp->base_sync_ns, min_set);
494 		return -EAGAIN;
495 	}
496 
497 	/* Average minimum this synchronisation */
498 	ptp->last_sync_ns = DIV_ROUND_UP(total, ngood);
499 	if (!ptp->base_sync_valid || (ptp->last_sync_ns < ptp->base_sync_ns)) {
500 		ptp->base_sync_valid = true;
501 		ptp->base_sync_ns = ptp->last_sync_ns;
502 	}
503 
504 	/* Calculate delay from actual PPS to last_time */
505 	delta.tv_nsec =
506 		ptp->timeset[last_good].nanoseconds +
507 		last_time->ts_real.tv_nsec -
508 		(ptp->timeset[last_good].host_start & MC_NANOSECOND_MASK);
509 
510 	/* It is possible that the seconds rolled over between taking
511 	 * the start reading and the last value written by the host.  The
512 	 * timescales are such that a gap of more than one second is never
513 	 * expected.
514 	 */
515 	start_sec = ptp->timeset[last_good].host_start >> MC_NANOSECOND_BITS;
516 	last_sec = last_time->ts_real.tv_sec & MC_SECOND_MASK;
517 	if (start_sec != last_sec) {
518 		if (((start_sec + 1) & MC_SECOND_MASK) != last_sec) {
519 			netif_warn(efx, hw, efx->net_dev,
520 				   "PTP bad synchronisation seconds\n");
521 			return -EAGAIN;
522 		} else {
523 			delta.tv_sec = 1;
524 		}
525 	} else {
526 		delta.tv_sec = 0;
527 	}
528 
529 	ptp->host_time_pps = *last_time;
530 	pps_sub_ts(&ptp->host_time_pps, delta);
531 
532 	return 0;
533 }
534 
535 /* Synchronize times between the host and the MC */
536 static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings)
537 {
538 	struct efx_ptp_data *ptp = efx->ptp_data;
539 	u8 synch_buf[MC_CMD_PTP_OUT_SYNCHRONIZE_LENMAX];
540 	size_t response_length;
541 	int rc;
542 	unsigned long timeout;
543 	struct pps_event_time last_time = {};
544 	unsigned int loops = 0;
545 	int *start = ptp->start.addr;
546 
547 	MCDI_SET_DWORD(synch_buf, PTP_IN_OP, MC_CMD_PTP_OP_SYNCHRONIZE);
548 	MCDI_SET_DWORD(synch_buf, PTP_IN_SYNCHRONIZE_NUMTIMESETS,
549 		       num_readings);
550 	MCDI_SET_DWORD(synch_buf, PTP_IN_SYNCHRONIZE_START_ADDR_LO,
551 		       (u32)ptp->start.dma_addr);
552 	MCDI_SET_DWORD(synch_buf, PTP_IN_SYNCHRONIZE_START_ADDR_HI,
553 		       (u32)((u64)ptp->start.dma_addr >> 32));
554 
555 	/* Clear flag that signals MC ready */
556 	ACCESS_ONCE(*start) = 0;
557 	efx_mcdi_rpc_start(efx, MC_CMD_PTP, synch_buf,
558 			   MC_CMD_PTP_IN_SYNCHRONIZE_LEN);
559 
560 	/* Wait for start from MCDI (or timeout) */
561 	timeout = jiffies + msecs_to_jiffies(MAX_SYNCHRONISE_WAIT_MS);
562 	while (!ACCESS_ONCE(*start) && (time_before(jiffies, timeout))) {
563 		udelay(20);	/* Usually start MCDI execution quickly */
564 		loops++;
565 	}
566 
567 	if (ACCESS_ONCE(*start))
568 		efx_ptp_send_times(efx, &last_time);
569 
570 	/* Collect results */
571 	rc = efx_mcdi_rpc_finish(efx, MC_CMD_PTP,
572 				 MC_CMD_PTP_IN_SYNCHRONIZE_LEN,
573 				 synch_buf, sizeof(synch_buf),
574 				 &response_length);
575 	if (rc == 0)
576 		rc = efx_ptp_process_times(efx, synch_buf, response_length,
577 					   &last_time);
578 
579 	return rc;
580 }
581 
582 /* Transmit a PTP packet, via the MCDI interface, to the wire. */
583 static int efx_ptp_xmit_skb(struct efx_nic *efx, struct sk_buff *skb)
584 {
585 	u8 *txbuf = efx->ptp_data->txbuf;
586 	struct skb_shared_hwtstamps timestamps;
587 	int rc = -EIO;
588 	/* MCDI driver requires word aligned lengths */
589 	size_t len = ALIGN(MC_CMD_PTP_IN_TRANSMIT_LEN(skb->len), 4);
590 	u8 txtime[MC_CMD_PTP_OUT_TRANSMIT_LEN];
591 
592 	MCDI_SET_DWORD(txbuf, PTP_IN_OP, MC_CMD_PTP_OP_TRANSMIT);
593 	MCDI_SET_DWORD(txbuf, PTP_IN_TRANSMIT_LENGTH, skb->len);
594 	if (skb_shinfo(skb)->nr_frags != 0) {
595 		rc = skb_linearize(skb);
596 		if (rc != 0)
597 			goto fail;
598 	}
599 
600 	if (skb->ip_summed == CHECKSUM_PARTIAL) {
601 		rc = skb_checksum_help(skb);
602 		if (rc != 0)
603 			goto fail;
604 	}
605 	skb_copy_from_linear_data(skb,
606 				  &txbuf[MC_CMD_PTP_IN_TRANSMIT_PACKET_OFST],
607 				  len);
608 	rc = efx_mcdi_rpc(efx, MC_CMD_PTP, txbuf, len, txtime,
609 			  sizeof(txtime), &len);
610 	if (rc != 0)
611 		goto fail;
612 
613 	memset(&timestamps, 0, sizeof(timestamps));
614 	timestamps.hwtstamp = ktime_set(
615 		MCDI_DWORD(txtime, PTP_OUT_TRANSMIT_SECONDS),
616 		MCDI_DWORD(txtime, PTP_OUT_TRANSMIT_NANOSECONDS));
617 
618 	skb_tstamp_tx(skb, &timestamps);
619 
620 	rc = 0;
621 
622 fail:
623 	dev_kfree_skb(skb);
624 
625 	return rc;
626 }
627 
628 static void efx_ptp_drop_time_expired_events(struct efx_nic *efx)
629 {
630 	struct efx_ptp_data *ptp = efx->ptp_data;
631 	struct list_head *cursor;
632 	struct list_head *next;
633 
634 	/* Drop time-expired events */
635 	spin_lock_bh(&ptp->evt_lock);
636 	if (!list_empty(&ptp->evt_list)) {
637 		list_for_each_safe(cursor, next, &ptp->evt_list) {
638 			struct efx_ptp_event_rx *evt;
639 
640 			evt = list_entry(cursor, struct efx_ptp_event_rx,
641 					 link);
642 			if (time_after(jiffies, evt->expiry)) {
643 				list_move(&evt->link, &ptp->evt_free_list);
644 				netif_warn(efx, hw, efx->net_dev,
645 					   "PTP rx event dropped\n");
646 			}
647 		}
648 	}
649 	spin_unlock_bh(&ptp->evt_lock);
650 }
651 
652 static enum ptp_packet_state efx_ptp_match_rx(struct efx_nic *efx,
653 					      struct sk_buff *skb)
654 {
655 	struct efx_ptp_data *ptp = efx->ptp_data;
656 	bool evts_waiting;
657 	struct list_head *cursor;
658 	struct list_head *next;
659 	struct efx_ptp_match *match;
660 	enum ptp_packet_state rc = PTP_PACKET_STATE_UNMATCHED;
661 
662 	spin_lock_bh(&ptp->evt_lock);
663 	evts_waiting = !list_empty(&ptp->evt_list);
664 	spin_unlock_bh(&ptp->evt_lock);
665 
666 	if (!evts_waiting)
667 		return PTP_PACKET_STATE_UNMATCHED;
668 
669 	match = (struct efx_ptp_match *)skb->cb;
670 	/* Look for a matching timestamp in the event queue */
671 	spin_lock_bh(&ptp->evt_lock);
672 	list_for_each_safe(cursor, next, &ptp->evt_list) {
673 		struct efx_ptp_event_rx *evt;
674 
675 		evt = list_entry(cursor, struct efx_ptp_event_rx, link);
676 		if ((evt->seq0 == match->words[0]) &&
677 		    (evt->seq1 == match->words[1])) {
678 			struct skb_shared_hwtstamps *timestamps;
679 
680 			/* Match - add in hardware timestamp */
681 			timestamps = skb_hwtstamps(skb);
682 			timestamps->hwtstamp = evt->hwtimestamp;
683 
684 			match->state = PTP_PACKET_STATE_MATCHED;
685 			rc = PTP_PACKET_STATE_MATCHED;
686 			list_move(&evt->link, &ptp->evt_free_list);
687 			break;
688 		}
689 	}
690 	spin_unlock_bh(&ptp->evt_lock);
691 
692 	return rc;
693 }
694 
695 /* Process any queued receive events and corresponding packets
696  *
697  * q is returned with all the packets that are ready for delivery.
698  * true is returned if at least one of those packets requires
699  * synchronisation.
700  */
701 static bool efx_ptp_process_events(struct efx_nic *efx, struct sk_buff_head *q)
702 {
703 	struct efx_ptp_data *ptp = efx->ptp_data;
704 	bool rc = false;
705 	struct sk_buff *skb;
706 
707 	while ((skb = skb_dequeue(&ptp->rxq))) {
708 		struct efx_ptp_match *match;
709 
710 		match = (struct efx_ptp_match *)skb->cb;
711 		if (match->state == PTP_PACKET_STATE_MATCH_UNWANTED) {
712 			__skb_queue_tail(q, skb);
713 		} else if (efx_ptp_match_rx(efx, skb) ==
714 			   PTP_PACKET_STATE_MATCHED) {
715 			rc = true;
716 			__skb_queue_tail(q, skb);
717 		} else if (time_after(jiffies, match->expiry)) {
718 			match->state = PTP_PACKET_STATE_TIMED_OUT;
719 			netif_warn(efx, rx_err, efx->net_dev,
720 				   "PTP packet - no timestamp seen\n");
721 			__skb_queue_tail(q, skb);
722 		} else {
723 			/* Replace unprocessed entry and stop */
724 			skb_queue_head(&ptp->rxq, skb);
725 			break;
726 		}
727 	}
728 
729 	return rc;
730 }
731 
732 /* Complete processing of a received packet */
733 static inline void efx_ptp_process_rx(struct efx_nic *efx, struct sk_buff *skb)
734 {
735 	local_bh_disable();
736 	netif_receive_skb(skb);
737 	local_bh_enable();
738 }
739 
740 static int efx_ptp_start(struct efx_nic *efx)
741 {
742 	struct efx_ptp_data *ptp = efx->ptp_data;
743 	struct efx_filter_spec rxfilter;
744 	int rc;
745 
746 	ptp->reset_required = false;
747 
748 	/* Must filter on both event and general ports to ensure
749 	 * that there is no packet re-ordering.
750 	 */
751 	efx_filter_init_rx(&rxfilter, EFX_FILTER_PRI_REQUIRED, 0,
752 			   efx_rx_queue_index(
753 				   efx_channel_get_rx_queue(ptp->channel)));
754 	rc = efx_filter_set_ipv4_local(&rxfilter, IPPROTO_UDP,
755 				       htonl(PTP_ADDRESS),
756 				       htons(PTP_EVENT_PORT));
757 	if (rc != 0)
758 		return rc;
759 
760 	rc = efx_filter_insert_filter(efx, &rxfilter, true);
761 	if (rc < 0)
762 		return rc;
763 	ptp->rxfilter_event = rc;
764 
765 	efx_filter_init_rx(&rxfilter, EFX_FILTER_PRI_REQUIRED, 0,
766 			   efx_rx_queue_index(
767 				   efx_channel_get_rx_queue(ptp->channel)));
768 	rc = efx_filter_set_ipv4_local(&rxfilter, IPPROTO_UDP,
769 				       htonl(PTP_ADDRESS),
770 				       htons(PTP_GENERAL_PORT));
771 	if (rc != 0)
772 		goto fail;
773 
774 	rc = efx_filter_insert_filter(efx, &rxfilter, true);
775 	if (rc < 0)
776 		goto fail;
777 	ptp->rxfilter_general = rc;
778 
779 	rc = efx_ptp_enable(efx);
780 	if (rc != 0)
781 		goto fail2;
782 
783 	ptp->evt_frag_idx = 0;
784 	ptp->current_adjfreq = 0;
785 	ptp->rxfilter_installed = true;
786 
787 	return 0;
788 
789 fail2:
790 	efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
791 				  ptp->rxfilter_general);
792 fail:
793 	efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
794 				  ptp->rxfilter_event);
795 
796 	return rc;
797 }
798 
799 static int efx_ptp_stop(struct efx_nic *efx)
800 {
801 	struct efx_ptp_data *ptp = efx->ptp_data;
802 	int rc = efx_ptp_disable(efx);
803 	struct list_head *cursor;
804 	struct list_head *next;
805 
806 	if (ptp->rxfilter_installed) {
807 		efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
808 					  ptp->rxfilter_general);
809 		efx_filter_remove_id_safe(efx, EFX_FILTER_PRI_REQUIRED,
810 					  ptp->rxfilter_event);
811 		ptp->rxfilter_installed = false;
812 	}
813 
814 	/* Make sure RX packets are really delivered */
815 	efx_ptp_deliver_rx_queue(&efx->ptp_data->rxq);
816 	skb_queue_purge(&efx->ptp_data->txq);
817 
818 	/* Drop any pending receive events */
819 	spin_lock_bh(&efx->ptp_data->evt_lock);
820 	list_for_each_safe(cursor, next, &efx->ptp_data->evt_list) {
821 		list_move(cursor, &efx->ptp_data->evt_free_list);
822 	}
823 	spin_unlock_bh(&efx->ptp_data->evt_lock);
824 
825 	return rc;
826 }
827 
828 static void efx_ptp_pps_worker(struct work_struct *work)
829 {
830 	struct efx_ptp_data *ptp =
831 		container_of(work, struct efx_ptp_data, pps_work);
832 	struct efx_nic *efx = ptp->channel->efx;
833 	struct ptp_clock_event ptp_evt;
834 
835 	if (efx_ptp_synchronize(efx, PTP_SYNC_ATTEMPTS))
836 		return;
837 
838 	ptp_evt.type = PTP_CLOCK_PPSUSR;
839 	ptp_evt.pps_times = ptp->host_time_pps;
840 	ptp_clock_event(ptp->phc_clock, &ptp_evt);
841 }
842 
843 /* Process any pending transmissions and timestamp any received packets.
844  */
845 static void efx_ptp_worker(struct work_struct *work)
846 {
847 	struct efx_ptp_data *ptp_data =
848 		container_of(work, struct efx_ptp_data, work);
849 	struct efx_nic *efx = ptp_data->channel->efx;
850 	struct sk_buff *skb;
851 	struct sk_buff_head tempq;
852 
853 	if (ptp_data->reset_required) {
854 		efx_ptp_stop(efx);
855 		efx_ptp_start(efx);
856 		return;
857 	}
858 
859 	efx_ptp_drop_time_expired_events(efx);
860 
861 	__skb_queue_head_init(&tempq);
862 	if (efx_ptp_process_events(efx, &tempq) ||
863 	    !skb_queue_empty(&ptp_data->txq)) {
864 
865 		while ((skb = skb_dequeue(&ptp_data->txq)))
866 			efx_ptp_xmit_skb(efx, skb);
867 	}
868 
869 	while ((skb = __skb_dequeue(&tempq)))
870 		efx_ptp_process_rx(efx, skb);
871 }
872 
873 /* Initialise PTP channel and state.
874  *
875  * Setting core_index to zero causes the queue to be initialised and doesn't
876  * overlap with 'rxq0' because ptp.c doesn't use skb_record_rx_queue.
877  */
878 static int efx_ptp_probe_channel(struct efx_channel *channel)
879 {
880 	struct efx_nic *efx = channel->efx;
881 	struct efx_ptp_data *ptp;
882 	int rc = 0;
883 	unsigned int pos;
884 
885 	channel->irq_moderation = 0;
886 	channel->rx_queue.core_index = 0;
887 
888 	ptp = kzalloc(sizeof(struct efx_ptp_data), GFP_KERNEL);
889 	efx->ptp_data = ptp;
890 	if (!efx->ptp_data)
891 		return -ENOMEM;
892 
893 	rc = efx_nic_alloc_buffer(efx, &ptp->start, sizeof(int));
894 	if (rc != 0)
895 		goto fail1;
896 
897 	ptp->channel = channel;
898 	skb_queue_head_init(&ptp->rxq);
899 	skb_queue_head_init(&ptp->txq);
900 	ptp->workwq = create_singlethread_workqueue("sfc_ptp");
901 	if (!ptp->workwq) {
902 		rc = -ENOMEM;
903 		goto fail2;
904 	}
905 
906 	INIT_WORK(&ptp->work, efx_ptp_worker);
907 	ptp->config.flags = 0;
908 	ptp->config.tx_type = HWTSTAMP_TX_OFF;
909 	ptp->config.rx_filter = HWTSTAMP_FILTER_NONE;
910 	INIT_LIST_HEAD(&ptp->evt_list);
911 	INIT_LIST_HEAD(&ptp->evt_free_list);
912 	spin_lock_init(&ptp->evt_lock);
913 	for (pos = 0; pos < MAX_RECEIVE_EVENTS; pos++)
914 		list_add(&ptp->rx_evts[pos].link, &ptp->evt_free_list);
915 
916 	ptp->phc_clock_info.owner = THIS_MODULE;
917 	snprintf(ptp->phc_clock_info.name,
918 		 sizeof(ptp->phc_clock_info.name),
919 		 "%pm", efx->net_dev->perm_addr);
920 	ptp->phc_clock_info.max_adj = MAX_PPB;
921 	ptp->phc_clock_info.n_alarm = 0;
922 	ptp->phc_clock_info.n_ext_ts = 0;
923 	ptp->phc_clock_info.n_per_out = 0;
924 	ptp->phc_clock_info.pps = 1;
925 	ptp->phc_clock_info.adjfreq = efx_phc_adjfreq;
926 	ptp->phc_clock_info.adjtime = efx_phc_adjtime;
927 	ptp->phc_clock_info.gettime = efx_phc_gettime;
928 	ptp->phc_clock_info.settime = efx_phc_settime;
929 	ptp->phc_clock_info.enable = efx_phc_enable;
930 
931 	ptp->phc_clock = ptp_clock_register(&ptp->phc_clock_info,
932 					    &efx->pci_dev->dev);
933 	if (!ptp->phc_clock)
934 		goto fail3;
935 
936 	INIT_WORK(&ptp->pps_work, efx_ptp_pps_worker);
937 	ptp->pps_workwq = create_singlethread_workqueue("sfc_pps");
938 	if (!ptp->pps_workwq) {
939 		rc = -ENOMEM;
940 		goto fail4;
941 	}
942 	ptp->nic_ts_enabled = false;
943 
944 	return 0;
945 fail4:
946 	ptp_clock_unregister(efx->ptp_data->phc_clock);
947 
948 fail3:
949 	destroy_workqueue(efx->ptp_data->workwq);
950 
951 fail2:
952 	efx_nic_free_buffer(efx, &ptp->start);
953 
954 fail1:
955 	kfree(efx->ptp_data);
956 	efx->ptp_data = NULL;
957 
958 	return rc;
959 }
960 
961 static void efx_ptp_remove_channel(struct efx_channel *channel)
962 {
963 	struct efx_nic *efx = channel->efx;
964 
965 	if (!efx->ptp_data)
966 		return;
967 
968 	(void)efx_ptp_disable(channel->efx);
969 
970 	cancel_work_sync(&efx->ptp_data->work);
971 	cancel_work_sync(&efx->ptp_data->pps_work);
972 
973 	skb_queue_purge(&efx->ptp_data->rxq);
974 	skb_queue_purge(&efx->ptp_data->txq);
975 
976 	ptp_clock_unregister(efx->ptp_data->phc_clock);
977 
978 	destroy_workqueue(efx->ptp_data->workwq);
979 	destroy_workqueue(efx->ptp_data->pps_workwq);
980 
981 	efx_nic_free_buffer(efx, &efx->ptp_data->start);
982 	kfree(efx->ptp_data);
983 }
984 
985 static void efx_ptp_get_channel_name(struct efx_channel *channel,
986 				     char *buf, size_t len)
987 {
988 	snprintf(buf, len, "%s-ptp", channel->efx->name);
989 }
990 
991 /* Determine whether this packet should be processed by the PTP module
992  * or transmitted conventionally.
993  */
994 bool efx_ptp_is_ptp_tx(struct efx_nic *efx, struct sk_buff *skb)
995 {
996 	return efx->ptp_data &&
997 		efx->ptp_data->enabled &&
998 		skb->len >= PTP_MIN_LENGTH &&
999 		skb->len <= MC_CMD_PTP_IN_TRANSMIT_PACKET_MAXNUM &&
1000 		likely(skb->protocol == htons(ETH_P_IP)) &&
1001 		ip_hdr(skb)->protocol == IPPROTO_UDP &&
1002 		udp_hdr(skb)->dest == htons(PTP_EVENT_PORT);
1003 }
1004 
1005 /* Receive a PTP packet.  Packets are queued until the arrival of
1006  * the receive timestamp from the MC - this will probably occur after the
1007  * packet arrival because of the processing in the MC.
1008  */
1009 static void efx_ptp_rx(struct efx_channel *channel, struct sk_buff *skb)
1010 {
1011 	struct efx_nic *efx = channel->efx;
1012 	struct efx_ptp_data *ptp = efx->ptp_data;
1013 	struct efx_ptp_match *match = (struct efx_ptp_match *)skb->cb;
1014 	u8 *data;
1015 	unsigned int version;
1016 
1017 	match->expiry = jiffies + msecs_to_jiffies(PKT_EVENT_LIFETIME_MS);
1018 
1019 	/* Correct version? */
1020 	if (ptp->mode == MC_CMD_PTP_MODE_V1) {
1021 		if (skb->len < PTP_V1_MIN_LENGTH) {
1022 			netif_receive_skb(skb);
1023 			return;
1024 		}
1025 		version = ntohs(*(__be16 *)&skb->data[PTP_V1_VERSION_OFFSET]);
1026 		if (version != PTP_VERSION_V1) {
1027 			netif_receive_skb(skb);
1028 			return;
1029 		}
1030 	} else {
1031 		if (skb->len < PTP_V2_MIN_LENGTH) {
1032 			netif_receive_skb(skb);
1033 			return;
1034 		}
1035 		version = skb->data[PTP_V2_VERSION_OFFSET];
1036 
1037 		BUG_ON(ptp->mode != MC_CMD_PTP_MODE_V2);
1038 		BUILD_BUG_ON(PTP_V1_UUID_OFFSET != PTP_V2_MC_UUID_OFFSET);
1039 		BUILD_BUG_ON(PTP_V1_UUID_LENGTH != PTP_V2_MC_UUID_LENGTH);
1040 		BUILD_BUG_ON(PTP_V1_SEQUENCE_OFFSET != PTP_V2_SEQUENCE_OFFSET);
1041 		BUILD_BUG_ON(PTP_V1_SEQUENCE_LENGTH != PTP_V2_SEQUENCE_LENGTH);
1042 
1043 		if ((version & PTP_VERSION_V2_MASK) != PTP_VERSION_V2) {
1044 			netif_receive_skb(skb);
1045 			return;
1046 		}
1047 	}
1048 
1049 	/* Does this packet require timestamping? */
1050 	if (ntohs(*(__be16 *)&skb->data[PTP_DPORT_OFFSET]) == PTP_EVENT_PORT) {
1051 		struct skb_shared_hwtstamps *timestamps;
1052 
1053 		match->state = PTP_PACKET_STATE_UNMATCHED;
1054 
1055 		/* Clear all timestamps held: filled in later */
1056 		timestamps = skb_hwtstamps(skb);
1057 		memset(timestamps, 0, sizeof(*timestamps));
1058 
1059 		/* Extract UUID/Sequence information */
1060 		data = skb->data + PTP_V1_UUID_OFFSET;
1061 		match->words[0] = (data[0]         |
1062 				   (data[1] << 8)  |
1063 				   (data[2] << 16) |
1064 				   (data[3] << 24));
1065 		match->words[1] = (data[4]         |
1066 				   (data[5] << 8)  |
1067 				   (skb->data[PTP_V1_SEQUENCE_OFFSET +
1068 					      PTP_V1_SEQUENCE_LENGTH - 1] <<
1069 				    16));
1070 	} else {
1071 		match->state = PTP_PACKET_STATE_MATCH_UNWANTED;
1072 	}
1073 
1074 	skb_queue_tail(&ptp->rxq, skb);
1075 	queue_work(ptp->workwq, &ptp->work);
1076 }
1077 
1078 /* Transmit a PTP packet.  This has to be transmitted by the MC
1079  * itself, through an MCDI call.  MCDI calls aren't permitted
1080  * in the transmit path so defer the actual transmission to a suitable worker.
1081  */
1082 int efx_ptp_tx(struct efx_nic *efx, struct sk_buff *skb)
1083 {
1084 	struct efx_ptp_data *ptp = efx->ptp_data;
1085 
1086 	skb_queue_tail(&ptp->txq, skb);
1087 
1088 	if ((udp_hdr(skb)->dest == htons(PTP_EVENT_PORT)) &&
1089 	    (skb->len <= MC_CMD_PTP_IN_TRANSMIT_PACKET_MAXNUM))
1090 		efx_xmit_hwtstamp_pending(skb);
1091 	queue_work(ptp->workwq, &ptp->work);
1092 
1093 	return NETDEV_TX_OK;
1094 }
1095 
1096 static int efx_ptp_change_mode(struct efx_nic *efx, bool enable_wanted,
1097 			       unsigned int new_mode)
1098 {
1099 	if ((enable_wanted != efx->ptp_data->enabled) ||
1100 	    (enable_wanted && (efx->ptp_data->mode != new_mode))) {
1101 		int rc;
1102 
1103 		if (enable_wanted) {
1104 			/* Change of mode requires disable */
1105 			if (efx->ptp_data->enabled &&
1106 			    (efx->ptp_data->mode != new_mode)) {
1107 				efx->ptp_data->enabled = false;
1108 				rc = efx_ptp_stop(efx);
1109 				if (rc != 0)
1110 					return rc;
1111 			}
1112 
1113 			/* Set new operating mode and establish
1114 			 * baseline synchronisation, which must
1115 			 * succeed.
1116 			 */
1117 			efx->ptp_data->mode = new_mode;
1118 			rc = efx_ptp_start(efx);
1119 			if (rc == 0) {
1120 				rc = efx_ptp_synchronize(efx,
1121 							 PTP_SYNC_ATTEMPTS * 2);
1122 				if (rc != 0)
1123 					efx_ptp_stop(efx);
1124 			}
1125 		} else {
1126 			rc = efx_ptp_stop(efx);
1127 		}
1128 
1129 		if (rc != 0)
1130 			return rc;
1131 
1132 		efx->ptp_data->enabled = enable_wanted;
1133 	}
1134 
1135 	return 0;
1136 }
1137 
1138 static int efx_ptp_ts_init(struct efx_nic *efx, struct hwtstamp_config *init)
1139 {
1140 	bool enable_wanted = false;
1141 	unsigned int new_mode;
1142 	int rc;
1143 
1144 	if (init->flags)
1145 		return -EINVAL;
1146 
1147 	if ((init->tx_type != HWTSTAMP_TX_OFF) &&
1148 	    (init->tx_type != HWTSTAMP_TX_ON))
1149 		return -ERANGE;
1150 
1151 	new_mode = efx->ptp_data->mode;
1152 	/* Determine whether any PTP HW operations are required */
1153 	switch (init->rx_filter) {
1154 	case HWTSTAMP_FILTER_NONE:
1155 		break;
1156 	case HWTSTAMP_FILTER_PTP_V1_L4_EVENT:
1157 	case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
1158 	case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
1159 		init->rx_filter = HWTSTAMP_FILTER_PTP_V1_L4_EVENT;
1160 		new_mode = MC_CMD_PTP_MODE_V1;
1161 		enable_wanted = true;
1162 		break;
1163 	case HWTSTAMP_FILTER_PTP_V2_L4_EVENT:
1164 	case HWTSTAMP_FILTER_PTP_V2_L4_SYNC:
1165 	case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ:
1166 	/* Although these three are accepted only IPV4 packets will be
1167 	 * timestamped
1168 	 */
1169 		init->rx_filter = HWTSTAMP_FILTER_PTP_V2_L4_EVENT;
1170 		new_mode = MC_CMD_PTP_MODE_V2;
1171 		enable_wanted = true;
1172 		break;
1173 	case HWTSTAMP_FILTER_PTP_V2_EVENT:
1174 	case HWTSTAMP_FILTER_PTP_V2_SYNC:
1175 	case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ:
1176 	case HWTSTAMP_FILTER_PTP_V2_L2_EVENT:
1177 	case HWTSTAMP_FILTER_PTP_V2_L2_SYNC:
1178 	case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ:
1179 		/* Non-IP + IPv6 timestamping not supported */
1180 		return -ERANGE;
1181 		break;
1182 	default:
1183 		return -ERANGE;
1184 	}
1185 
1186 	if (init->tx_type != HWTSTAMP_TX_OFF)
1187 		enable_wanted = true;
1188 
1189 	rc = efx_ptp_change_mode(efx, enable_wanted, new_mode);
1190 	if (rc != 0)
1191 		return rc;
1192 
1193 	efx->ptp_data->config = *init;
1194 
1195 	return 0;
1196 }
1197 
1198 int
1199 efx_ptp_get_ts_info(struct net_device *net_dev, struct ethtool_ts_info *ts_info)
1200 {
1201 	struct efx_nic *efx = netdev_priv(net_dev);
1202 	struct efx_ptp_data *ptp = efx->ptp_data;
1203 
1204 	if (!ptp)
1205 		return -EOPNOTSUPP;
1206 
1207 	ts_info->so_timestamping = (SOF_TIMESTAMPING_TX_HARDWARE |
1208 				    SOF_TIMESTAMPING_RX_HARDWARE |
1209 				    SOF_TIMESTAMPING_RAW_HARDWARE);
1210 	ts_info->phc_index = ptp_clock_index(ptp->phc_clock);
1211 	ts_info->tx_types = 1 << HWTSTAMP_TX_OFF | 1 << HWTSTAMP_TX_ON;
1212 	ts_info->rx_filters = (1 << HWTSTAMP_FILTER_NONE |
1213 			       1 << HWTSTAMP_FILTER_PTP_V1_L4_EVENT |
1214 			       1 << HWTSTAMP_FILTER_PTP_V1_L4_SYNC |
1215 			       1 << HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ |
1216 			       1 << HWTSTAMP_FILTER_PTP_V2_L4_EVENT |
1217 			       1 << HWTSTAMP_FILTER_PTP_V2_L4_SYNC |
1218 			       1 << HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ);
1219 	return 0;
1220 }
1221 
1222 int efx_ptp_ioctl(struct efx_nic *efx, struct ifreq *ifr, int cmd)
1223 {
1224 	struct hwtstamp_config config;
1225 	int rc;
1226 
1227 	/* Not a PTP enabled port */
1228 	if (!efx->ptp_data)
1229 		return -EOPNOTSUPP;
1230 
1231 	if (copy_from_user(&config, ifr->ifr_data, sizeof(config)))
1232 		return -EFAULT;
1233 
1234 	rc = efx_ptp_ts_init(efx, &config);
1235 	if (rc != 0)
1236 		return rc;
1237 
1238 	return copy_to_user(ifr->ifr_data, &config, sizeof(config))
1239 		? -EFAULT : 0;
1240 }
1241 
1242 static void ptp_event_failure(struct efx_nic *efx, int expected_frag_len)
1243 {
1244 	struct efx_ptp_data *ptp = efx->ptp_data;
1245 
1246 	netif_err(efx, hw, efx->net_dev,
1247 		"PTP unexpected event length: got %d expected %d\n",
1248 		ptp->evt_frag_idx, expected_frag_len);
1249 	ptp->reset_required = true;
1250 	queue_work(ptp->workwq, &ptp->work);
1251 }
1252 
1253 /* Process a completed receive event.  Put it on the event queue and
1254  * start worker thread.  This is required because event and their
1255  * correspoding packets may come in either order.
1256  */
1257 static void ptp_event_rx(struct efx_nic *efx, struct efx_ptp_data *ptp)
1258 {
1259 	struct efx_ptp_event_rx *evt = NULL;
1260 
1261 	if (ptp->evt_frag_idx != 3) {
1262 		ptp_event_failure(efx, 3);
1263 		return;
1264 	}
1265 
1266 	spin_lock_bh(&ptp->evt_lock);
1267 	if (!list_empty(&ptp->evt_free_list)) {
1268 		evt = list_first_entry(&ptp->evt_free_list,
1269 				       struct efx_ptp_event_rx, link);
1270 		list_del(&evt->link);
1271 
1272 		evt->seq0 = EFX_QWORD_FIELD(ptp->evt_frags[2], MCDI_EVENT_DATA);
1273 		evt->seq1 = (EFX_QWORD_FIELD(ptp->evt_frags[2],
1274 					     MCDI_EVENT_SRC)        |
1275 			     (EFX_QWORD_FIELD(ptp->evt_frags[1],
1276 					      MCDI_EVENT_SRC) << 8) |
1277 			     (EFX_QWORD_FIELD(ptp->evt_frags[0],
1278 					      MCDI_EVENT_SRC) << 16));
1279 		evt->hwtimestamp = ktime_set(
1280 			EFX_QWORD_FIELD(ptp->evt_frags[0], MCDI_EVENT_DATA),
1281 			EFX_QWORD_FIELD(ptp->evt_frags[1], MCDI_EVENT_DATA));
1282 		evt->expiry = jiffies + msecs_to_jiffies(PKT_EVENT_LIFETIME_MS);
1283 		list_add_tail(&evt->link, &ptp->evt_list);
1284 
1285 		queue_work(ptp->workwq, &ptp->work);
1286 	} else {
1287 		netif_err(efx, rx_err, efx->net_dev, "No free PTP event");
1288 	}
1289 	spin_unlock_bh(&ptp->evt_lock);
1290 }
1291 
1292 static void ptp_event_fault(struct efx_nic *efx, struct efx_ptp_data *ptp)
1293 {
1294 	int code = EFX_QWORD_FIELD(ptp->evt_frags[0], MCDI_EVENT_DATA);
1295 	if (ptp->evt_frag_idx != 1) {
1296 		ptp_event_failure(efx, 1);
1297 		return;
1298 	}
1299 
1300 	netif_err(efx, hw, efx->net_dev, "PTP error %d\n", code);
1301 }
1302 
1303 static void ptp_event_pps(struct efx_nic *efx, struct efx_ptp_data *ptp)
1304 {
1305 	if (ptp->nic_ts_enabled)
1306 		queue_work(ptp->pps_workwq, &ptp->pps_work);
1307 }
1308 
1309 void efx_ptp_event(struct efx_nic *efx, efx_qword_t *ev)
1310 {
1311 	struct efx_ptp_data *ptp = efx->ptp_data;
1312 	int code = EFX_QWORD_FIELD(*ev, MCDI_EVENT_CODE);
1313 
1314 	if (!ptp->enabled)
1315 		return;
1316 
1317 	if (ptp->evt_frag_idx == 0) {
1318 		ptp->evt_code = code;
1319 	} else if (ptp->evt_code != code) {
1320 		netif_err(efx, hw, efx->net_dev,
1321 			  "PTP out of sequence event %d\n", code);
1322 		ptp->evt_frag_idx = 0;
1323 	}
1324 
1325 	ptp->evt_frags[ptp->evt_frag_idx++] = *ev;
1326 	if (!MCDI_EVENT_FIELD(*ev, CONT)) {
1327 		/* Process resulting event */
1328 		switch (code) {
1329 		case MCDI_EVENT_CODE_PTP_RX:
1330 			ptp_event_rx(efx, ptp);
1331 			break;
1332 		case MCDI_EVENT_CODE_PTP_FAULT:
1333 			ptp_event_fault(efx, ptp);
1334 			break;
1335 		case MCDI_EVENT_CODE_PTP_PPS:
1336 			ptp_event_pps(efx, ptp);
1337 			break;
1338 		default:
1339 			netif_err(efx, hw, efx->net_dev,
1340 				  "PTP unknown event %d\n", code);
1341 			break;
1342 		}
1343 		ptp->evt_frag_idx = 0;
1344 	} else if (MAX_EVENT_FRAGS == ptp->evt_frag_idx) {
1345 		netif_err(efx, hw, efx->net_dev,
1346 			  "PTP too many event fragments\n");
1347 		ptp->evt_frag_idx = 0;
1348 	}
1349 }
1350 
1351 static int efx_phc_adjfreq(struct ptp_clock_info *ptp, s32 delta)
1352 {
1353 	struct efx_ptp_data *ptp_data = container_of(ptp,
1354 						     struct efx_ptp_data,
1355 						     phc_clock_info);
1356 	struct efx_nic *efx = ptp_data->channel->efx;
1357 	u8 inadj[MC_CMD_PTP_IN_ADJUST_LEN];
1358 	s64 adjustment_ns;
1359 	int rc;
1360 
1361 	if (delta > MAX_PPB)
1362 		delta = MAX_PPB;
1363 	else if (delta < -MAX_PPB)
1364 		delta = -MAX_PPB;
1365 
1366 	/* Convert ppb to fixed point ns. */
1367 	adjustment_ns = (((s64)delta * PPB_SCALE_WORD) >>
1368 			 (PPB_EXTRA_BITS + MAX_PPB_BITS));
1369 
1370 	MCDI_SET_DWORD(inadj, PTP_IN_OP, MC_CMD_PTP_OP_ADJUST);
1371 	MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_FREQ_LO, (u32)adjustment_ns);
1372 	MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_FREQ_HI,
1373 		       (u32)(adjustment_ns >> 32));
1374 	MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_SECONDS, 0);
1375 	MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_NANOSECONDS, 0);
1376 	rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inadj, sizeof(inadj),
1377 			  NULL, 0, NULL);
1378 	if (rc != 0)
1379 		return rc;
1380 
1381 	ptp_data->current_adjfreq = delta;
1382 	return 0;
1383 }
1384 
1385 static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta)
1386 {
1387 	struct efx_ptp_data *ptp_data = container_of(ptp,
1388 						     struct efx_ptp_data,
1389 						     phc_clock_info);
1390 	struct efx_nic *efx = ptp_data->channel->efx;
1391 	struct timespec delta_ts = ns_to_timespec(delta);
1392 	u8 inbuf[MC_CMD_PTP_IN_ADJUST_LEN];
1393 
1394 	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_ADJUST);
1395 	MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_FREQ_LO, 0);
1396 	MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_FREQ_HI, 0);
1397 	MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_SECONDS, (u32)delta_ts.tv_sec);
1398 	MCDI_SET_DWORD(inbuf, PTP_IN_ADJUST_NANOSECONDS, (u32)delta_ts.tv_nsec);
1399 	return efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
1400 			    NULL, 0, NULL);
1401 }
1402 
1403 static int efx_phc_gettime(struct ptp_clock_info *ptp, struct timespec *ts)
1404 {
1405 	struct efx_ptp_data *ptp_data = container_of(ptp,
1406 						     struct efx_ptp_data,
1407 						     phc_clock_info);
1408 	struct efx_nic *efx = ptp_data->channel->efx;
1409 	u8 inbuf[MC_CMD_PTP_IN_READ_NIC_TIME_LEN];
1410 	u8 outbuf[MC_CMD_PTP_OUT_READ_NIC_TIME_LEN];
1411 	int rc;
1412 
1413 	MCDI_SET_DWORD(inbuf, PTP_IN_OP, MC_CMD_PTP_OP_READ_NIC_TIME);
1414 
1415 	rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inbuf, sizeof(inbuf),
1416 			  outbuf, sizeof(outbuf), NULL);
1417 	if (rc != 0)
1418 		return rc;
1419 
1420 	ts->tv_sec = MCDI_DWORD(outbuf, PTP_OUT_READ_NIC_TIME_SECONDS);
1421 	ts->tv_nsec = MCDI_DWORD(outbuf, PTP_OUT_READ_NIC_TIME_NANOSECONDS);
1422 	return 0;
1423 }
1424 
1425 static int efx_phc_settime(struct ptp_clock_info *ptp,
1426 			   const struct timespec *e_ts)
1427 {
1428 	/* Get the current NIC time, efx_phc_gettime.
1429 	 * Subtract from the desired time to get the offset
1430 	 * call efx_phc_adjtime with the offset
1431 	 */
1432 	int rc;
1433 	struct timespec time_now;
1434 	struct timespec delta;
1435 
1436 	rc = efx_phc_gettime(ptp, &time_now);
1437 	if (rc != 0)
1438 		return rc;
1439 
1440 	delta = timespec_sub(*e_ts, time_now);
1441 
1442 	efx_phc_adjtime(ptp, timespec_to_ns(&delta));
1443 	if (rc != 0)
1444 		return rc;
1445 
1446 	return 0;
1447 }
1448 
1449 static int efx_phc_enable(struct ptp_clock_info *ptp,
1450 			  struct ptp_clock_request *request,
1451 			  int enable)
1452 {
1453 	struct efx_ptp_data *ptp_data = container_of(ptp,
1454 						     struct efx_ptp_data,
1455 						     phc_clock_info);
1456 	if (request->type != PTP_CLK_REQ_PPS)
1457 		return -EOPNOTSUPP;
1458 
1459 	ptp_data->nic_ts_enabled = !!enable;
1460 	return 0;
1461 }
1462 
1463 static const struct efx_channel_type efx_ptp_channel_type = {
1464 	.handle_no_channel	= efx_ptp_handle_no_channel,
1465 	.pre_probe		= efx_ptp_probe_channel,
1466 	.post_remove		= efx_ptp_remove_channel,
1467 	.get_name		= efx_ptp_get_channel_name,
1468 	/* no copy operation; there is no need to reallocate this channel */
1469 	.receive_skb		= efx_ptp_rx,
1470 	.keep_eventq		= false,
1471 };
1472 
1473 void efx_ptp_probe(struct efx_nic *efx)
1474 {
1475 	/* Check whether PTP is implemented on this NIC.  The DISABLE
1476 	 * operation will succeed if and only if it is implemented.
1477 	 */
1478 	if (efx_ptp_disable(efx) == 0)
1479 		efx->extra_channel_type[EFX_EXTRA_CHANNEL_PTP] =
1480 			&efx_ptp_channel_type;
1481 }
1482