1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 1999 - 2018 Intel Corporation. */
3 
4 #include "ixgbe.h"
5 #include <linux/ptp_classify.h>
6 #include <linux/clocksource.h>
7 
8 /*
9  * The 82599 and the X540 do not have true 64bit nanosecond scale
10  * counter registers. Instead, SYSTIME is defined by a fixed point
11  * system which allows the user to define the scale counter increment
12  * value at every level change of the oscillator driving the SYSTIME
13  * value. For both devices the TIMINCA:IV field defines this
14  * increment. On the X540 device, 31 bits are provided. However on the
15  * 82599 only provides 24 bits. The time unit is determined by the
16  * clock frequency of the oscillator in combination with the TIMINCA
17  * register. When these devices link at 10Gb the oscillator has a
18  * period of 6.4ns. In order to convert the scale counter into
19  * nanoseconds the cyclecounter and timecounter structures are
20  * used. The SYSTIME registers need to be converted to ns values by use
21  * of only a right shift (division by power of 2). The following math
22  * determines the largest incvalue that will fit into the available
23  * bits in the TIMINCA register.
24  *
25  * PeriodWidth: Number of bits to store the clock period
26  * MaxWidth: The maximum width value of the TIMINCA register
27  * Period: The clock period for the oscillator
28  * round(): discard the fractional portion of the calculation
29  *
30  * Period * [ 2 ^ ( MaxWidth - PeriodWidth ) ]
31  *
32  * For the X540, MaxWidth is 31 bits, and the base period is 6.4 ns
33  * For the 82599, MaxWidth is 24 bits, and the base period is 6.4 ns
34  *
35  * The period also changes based on the link speed:
36  * At 10Gb link or no link, the period remains the same.
37  * At 1Gb link, the period is multiplied by 10. (64ns)
38  * At 100Mb link, the period is multiplied by 100. (640ns)
39  *
40  * The calculated value allows us to right shift the SYSTIME register
41  * value in order to quickly convert it into a nanosecond clock,
42  * while allowing for the maximum possible adjustment value.
43  *
44  * These diagrams are only for the 10Gb link period
45  *
46  *           SYSTIMEH            SYSTIMEL
47  *       +--------------+  +--------------+
48  * X540  |      32      |  | 1 | 3 |  28  |
49  *       *--------------+  +--------------+
50  *        \________ 36 bits ______/  fract
51  *
52  *       +--------------+  +--------------+
53  * 82599 |      32      |  | 8 | 3 |  21  |
54  *       *--------------+  +--------------+
55  *        \________ 43 bits ______/  fract
56  *
57  * The 36 bit X540 SYSTIME overflows every
58  *   2^36 * 10^-9 / 60 = 1.14 minutes or 69 seconds
59  *
60  * The 43 bit 82599 SYSTIME overflows every
61  *   2^43 * 10^-9 / 3600 = 2.4 hours
62  */
63 #define IXGBE_INCVAL_10GB 0x66666666
64 #define IXGBE_INCVAL_1GB  0x40000000
65 #define IXGBE_INCVAL_100  0x50000000
66 
67 #define IXGBE_INCVAL_SHIFT_10GB  28
68 #define IXGBE_INCVAL_SHIFT_1GB   24
69 #define IXGBE_INCVAL_SHIFT_100   21
70 
71 #define IXGBE_INCVAL_SHIFT_82599 7
72 #define IXGBE_INCPER_SHIFT_82599 24
73 
74 #define IXGBE_OVERFLOW_PERIOD    (HZ * 30)
75 #define IXGBE_PTP_TX_TIMEOUT     (HZ)
76 
77 /* We use our own definitions instead of NSEC_PER_SEC because we want to mark
78  * the value as a ULL to force precision when bit shifting.
79  */
80 #define NS_PER_SEC      1000000000ULL
81 #define NS_PER_HALF_SEC  500000000ULL
82 
83 /* In contrast, the X550 controller has two registers, SYSTIMEH and SYSTIMEL
84  * which contain measurements of seconds and nanoseconds respectively. This
85  * matches the standard linux representation of time in the kernel. In addition,
86  * the X550 also has a SYSTIMER register which represents residue, or
87  * subnanosecond overflow adjustments. To control clock adjustment, the TIMINCA
88  * register is used, but it is unlike the X540 and 82599 devices. TIMINCA
89  * represents units of 2^-32 nanoseconds, and uses 31 bits for this, with the
90  * high bit representing whether the adjustent is positive or negative. Every
91  * clock cycle, the X550 will add 12.5 ns + TIMINCA which can result in a range
92  * of 12 to 13 nanoseconds adjustment. Unlike the 82599 and X540 devices, the
93  * X550's clock for purposes of SYSTIME generation is constant and not dependent
94  * on the link speed.
95  *
96  *           SYSTIMEH           SYSTIMEL        SYSTIMER
97  *       +--------------+  +--------------+  +-------------+
98  * X550  |      32      |  |      32      |  |     32      |
99  *       *--------------+  +--------------+  +-------------+
100  *       \____seconds___/   \_nanoseconds_/  \__2^-32 ns__/
101  *
102  * This results in a full 96 bits to represent the clock, with 32 bits for
103  * seconds, 32 bits for nanoseconds (largest value is 0d999999999 or just under
104  * 1 second) and an additional 32 bits to measure sub nanosecond adjustments for
105  * underflow of adjustments.
106  *
107  * The 32 bits of seconds for the X550 overflows every
108  *   2^32 / ( 365.25 * 24 * 60 * 60 ) = ~136 years.
109  *
110  * In order to adjust the clock frequency for the X550, the TIMINCA register is
111  * provided. This register represents a + or minus nearly 0.5 ns adjustment to
112  * the base frequency. It is measured in 2^-32 ns units, with the high bit being
113  * the sign bit. This register enables software to calculate frequency
114  * adjustments and apply them directly to the clock rate.
115  *
116  * The math for converting ppb into TIMINCA values is fairly straightforward.
117  *   TIMINCA value = ( Base_Frequency * ppb ) / 1000000000ULL
118  *
119  * This assumes that ppb is never high enough to create a value bigger than
120  * TIMINCA's 31 bits can store. This is ensured by the stack. Calculating this
121  * value is also simple.
122  *   Max ppb = ( Max Adjustment / Base Frequency ) / 1000000000ULL
123  *
124  * For the X550, the Max adjustment is +/- 0.5 ns, and the base frequency is
125  * 12.5 nanoseconds. This means that the Max ppb is 39999999
126  *   Note: We subtract one in order to ensure no overflow, because the TIMINCA
127  *         register can only hold slightly under 0.5 nanoseconds.
128  *
129  * Because TIMINCA is measured in 2^-32 ns units, we have to convert 12.5 ns
130  * into 2^-32 units, which is
131  *
132  *  12.5 * 2^32 = C80000000
133  *
134  * Some revisions of hardware have a faster base frequency than the registers
135  * were defined for. To fix this, we use a timecounter structure with the
136  * proper mult and shift to convert the cycles into nanoseconds of time.
137  */
138 #define IXGBE_X550_BASE_PERIOD 0xC80000000ULL
139 #define INCVALUE_MASK	0x7FFFFFFF
140 #define ISGN		0x80000000
141 
142 /**
143  * ixgbe_ptp_setup_sdp_X540
144  * @adapter: private adapter structure
145  *
146  * this function enables or disables the clock out feature on SDP0 for
147  * the X540 device. It will create a 1 second periodic output that can
148  * be used as the PPS (via an interrupt).
149  *
150  * It calculates when the system time will be on an exact second, and then
151  * aligns the start of the PPS signal to that value.
152  *
153  * This works by using the cycle counter shift and mult values in reverse, and
154  * assumes that the values we're shifting will not overflow.
155  */
156 static void ixgbe_ptp_setup_sdp_X540(struct ixgbe_adapter *adapter)
157 {
158 	struct cyclecounter *cc = &adapter->hw_cc;
159 	struct ixgbe_hw *hw = &adapter->hw;
160 	u32 esdp, tsauxc, clktiml, clktimh, trgttiml, trgttimh, rem;
161 	u64 ns = 0, clock_edge = 0, clock_period;
162 	unsigned long flags;
163 
164 	/* disable the pin first */
165 	IXGBE_WRITE_REG(hw, IXGBE_TSAUXC, 0x0);
166 	IXGBE_WRITE_FLUSH(hw);
167 
168 	if (!(adapter->flags2 & IXGBE_FLAG2_PTP_PPS_ENABLED))
169 		return;
170 
171 	esdp = IXGBE_READ_REG(hw, IXGBE_ESDP);
172 
173 	/* enable the SDP0 pin as output, and connected to the
174 	 * native function for Timesync (ClockOut)
175 	 */
176 	esdp |= IXGBE_ESDP_SDP0_DIR |
177 		IXGBE_ESDP_SDP0_NATIVE;
178 
179 	/* enable the Clock Out feature on SDP0, and allow
180 	 * interrupts to occur when the pin changes
181 	 */
182 	tsauxc = (IXGBE_TSAUXC_EN_CLK |
183 		  IXGBE_TSAUXC_SYNCLK |
184 		  IXGBE_TSAUXC_SDP0_INT);
185 
186 	/* Determine the clock time period to use. This assumes that the
187 	 * cycle counter shift is small enough to avoid overflow.
188 	 */
189 	clock_period = div_u64((NS_PER_HALF_SEC << cc->shift), cc->mult);
190 	clktiml = (u32)(clock_period);
191 	clktimh = (u32)(clock_period >> 32);
192 
193 	/* Read the current clock time, and save the cycle counter value */
194 	spin_lock_irqsave(&adapter->tmreg_lock, flags);
195 	ns = timecounter_read(&adapter->hw_tc);
196 	clock_edge = adapter->hw_tc.cycle_last;
197 	spin_unlock_irqrestore(&adapter->tmreg_lock, flags);
198 
199 	/* Figure out how many seconds to add in order to round up */
200 	div_u64_rem(ns, NS_PER_SEC, &rem);
201 
202 	/* Figure out how many nanoseconds to add to round the clock edge up
203 	 * to the next full second
204 	 */
205 	rem = (NS_PER_SEC - rem);
206 
207 	/* Adjust the clock edge to align with the next full second. */
208 	clock_edge += div_u64(((u64)rem << cc->shift), cc->mult);
209 	trgttiml = (u32)clock_edge;
210 	trgttimh = (u32)(clock_edge >> 32);
211 
212 	IXGBE_WRITE_REG(hw, IXGBE_CLKTIML, clktiml);
213 	IXGBE_WRITE_REG(hw, IXGBE_CLKTIMH, clktimh);
214 	IXGBE_WRITE_REG(hw, IXGBE_TRGTTIML0, trgttiml);
215 	IXGBE_WRITE_REG(hw, IXGBE_TRGTTIMH0, trgttimh);
216 
217 	IXGBE_WRITE_REG(hw, IXGBE_ESDP, esdp);
218 	IXGBE_WRITE_REG(hw, IXGBE_TSAUXC, tsauxc);
219 
220 	IXGBE_WRITE_FLUSH(hw);
221 }
222 
223 /**
224  * ixgbe_ptp_setup_sdp_X550
225  * @adapter: private adapter structure
226  *
227  * Enable or disable a clock output signal on SDP 0 for X550 hardware.
228  *
229  * Use the target time feature to align the output signal on the next full
230  * second.
231  *
232  * This works by using the cycle counter shift and mult values in reverse, and
233  * assumes that the values we're shifting will not overflow.
234  */
235 static void ixgbe_ptp_setup_sdp_X550(struct ixgbe_adapter *adapter)
236 {
237 	u32 esdp, tsauxc, freqout, trgttiml, trgttimh, rem, tssdp;
238 	struct cyclecounter *cc = &adapter->hw_cc;
239 	struct ixgbe_hw *hw = &adapter->hw;
240 	u64 ns = 0, clock_edge = 0;
241 	struct timespec64 ts;
242 	unsigned long flags;
243 
244 	/* disable the pin first */
245 	IXGBE_WRITE_REG(hw, IXGBE_TSAUXC, 0x0);
246 	IXGBE_WRITE_FLUSH(hw);
247 
248 	if (!(adapter->flags2 & IXGBE_FLAG2_PTP_PPS_ENABLED))
249 		return;
250 
251 	esdp = IXGBE_READ_REG(hw, IXGBE_ESDP);
252 
253 	/* enable the SDP0 pin as output, and connected to the
254 	 * native function for Timesync (ClockOut)
255 	 */
256 	esdp |= IXGBE_ESDP_SDP0_DIR |
257 		IXGBE_ESDP_SDP0_NATIVE;
258 
259 	/* enable the Clock Out feature on SDP0, and use Target Time 0 to
260 	 * enable generation of interrupts on the clock change.
261 	 */
262 #define IXGBE_TSAUXC_DIS_TS_CLEAR 0x40000000
263 	tsauxc = (IXGBE_TSAUXC_EN_CLK | IXGBE_TSAUXC_ST0 |
264 		  IXGBE_TSAUXC_EN_TT0 | IXGBE_TSAUXC_SDP0_INT |
265 		  IXGBE_TSAUXC_DIS_TS_CLEAR);
266 
267 	tssdp = (IXGBE_TSSDP_TS_SDP0_EN |
268 		 IXGBE_TSSDP_TS_SDP0_CLK0);
269 
270 	/* Determine the clock time period to use. This assumes that the
271 	 * cycle counter shift is small enough to avoid overflowing a 32bit
272 	 * value.
273 	 */
274 	freqout = div_u64(NS_PER_HALF_SEC << cc->shift,  cc->mult);
275 
276 	/* Read the current clock time, and save the cycle counter value */
277 	spin_lock_irqsave(&adapter->tmreg_lock, flags);
278 	ns = timecounter_read(&adapter->hw_tc);
279 	clock_edge = adapter->hw_tc.cycle_last;
280 	spin_unlock_irqrestore(&adapter->tmreg_lock, flags);
281 
282 	/* Figure out how far past the next second we are */
283 	div_u64_rem(ns, NS_PER_SEC, &rem);
284 
285 	/* Figure out how many nanoseconds to add to round the clock edge up
286 	 * to the next full second
287 	 */
288 	rem = (NS_PER_SEC - rem);
289 
290 	/* Adjust the clock edge to align with the next full second. */
291 	clock_edge += div_u64(((u64)rem << cc->shift), cc->mult);
292 
293 	/* X550 hardware stores the time in 32bits of 'billions of cycles' and
294 	 * 32bits of 'cycles'. There's no guarantee that cycles represents
295 	 * nanoseconds. However, we can use the math from a timespec64 to
296 	 * convert into the hardware representation.
297 	 *
298 	 * See ixgbe_ptp_read_X550() for more details.
299 	 */
300 	ts = ns_to_timespec64(clock_edge);
301 	trgttiml = (u32)ts.tv_nsec;
302 	trgttimh = (u32)ts.tv_sec;
303 
304 	IXGBE_WRITE_REG(hw, IXGBE_FREQOUT0, freqout);
305 	IXGBE_WRITE_REG(hw, IXGBE_TRGTTIML0, trgttiml);
306 	IXGBE_WRITE_REG(hw, IXGBE_TRGTTIMH0, trgttimh);
307 
308 	IXGBE_WRITE_REG(hw, IXGBE_ESDP, esdp);
309 	IXGBE_WRITE_REG(hw, IXGBE_TSSDP, tssdp);
310 	IXGBE_WRITE_REG(hw, IXGBE_TSAUXC, tsauxc);
311 
312 	IXGBE_WRITE_FLUSH(hw);
313 }
314 
315 /**
316  * ixgbe_ptp_read_X550 - read cycle counter value
317  * @cc: cyclecounter structure
318  *
319  * This function reads SYSTIME registers. It is called by the cyclecounter
320  * structure to convert from internal representation into nanoseconds. We need
321  * this for X550 since some skews do not have expected clock frequency and
322  * result of SYSTIME is 32bits of "billions of cycles" and 32 bits of
323  * "cycles", rather than seconds and nanoseconds.
324  */
325 static u64 ixgbe_ptp_read_X550(const struct cyclecounter *cc)
326 {
327 	struct ixgbe_adapter *adapter =
328 		container_of(cc, struct ixgbe_adapter, hw_cc);
329 	struct ixgbe_hw *hw = &adapter->hw;
330 	struct timespec64 ts;
331 
332 	/* storage is 32 bits of 'billions of cycles' and 32 bits of 'cycles'.
333 	 * Some revisions of hardware run at a higher frequency and so the
334 	 * cycles are not guaranteed to be nanoseconds. The timespec64 created
335 	 * here is used for its math/conversions but does not necessarily
336 	 * represent nominal time.
337 	 *
338 	 * It should be noted that this cyclecounter will overflow at a
339 	 * non-bitmask field since we have to convert our billions of cycles
340 	 * into an actual cycles count. This results in some possible weird
341 	 * situations at high cycle counter stamps. However given that 32 bits
342 	 * of "seconds" is ~138 years this isn't a problem. Even at the
343 	 * increased frequency of some revisions, this is still ~103 years.
344 	 * Since the SYSTIME values start at 0 and we never write them, it is
345 	 * highly unlikely for the cyclecounter to overflow in practice.
346 	 */
347 	IXGBE_READ_REG(hw, IXGBE_SYSTIMR);
348 	ts.tv_nsec = IXGBE_READ_REG(hw, IXGBE_SYSTIML);
349 	ts.tv_sec = IXGBE_READ_REG(hw, IXGBE_SYSTIMH);
350 
351 	return (u64)timespec64_to_ns(&ts);
352 }
353 
354 /**
355  * ixgbe_ptp_read_82599 - read raw cycle counter (to be used by time counter)
356  * @cc: the cyclecounter structure
357  *
358  * this function reads the cyclecounter registers and is called by the
359  * cyclecounter structure used to construct a ns counter from the
360  * arbitrary fixed point registers
361  */
362 static u64 ixgbe_ptp_read_82599(const struct cyclecounter *cc)
363 {
364 	struct ixgbe_adapter *adapter =
365 		container_of(cc, struct ixgbe_adapter, hw_cc);
366 	struct ixgbe_hw *hw = &adapter->hw;
367 	u64 stamp = 0;
368 
369 	stamp |= (u64)IXGBE_READ_REG(hw, IXGBE_SYSTIML);
370 	stamp |= (u64)IXGBE_READ_REG(hw, IXGBE_SYSTIMH) << 32;
371 
372 	return stamp;
373 }
374 
375 /**
376  * ixgbe_ptp_convert_to_hwtstamp - convert register value to hw timestamp
377  * @adapter: private adapter structure
378  * @hwtstamp: stack timestamp structure
379  * @timestamp: unsigned 64bit system time value
380  *
381  * We need to convert the adapter's RX/TXSTMP registers into a hwtstamp value
382  * which can be used by the stack's ptp functions.
383  *
384  * The lock is used to protect consistency of the cyclecounter and the SYSTIME
385  * registers. However, it does not need to protect against the Rx or Tx
386  * timestamp registers, as there can't be a new timestamp until the old one is
387  * unlatched by reading.
388  *
389  * In addition to the timestamp in hardware, some controllers need a software
390  * overflow cyclecounter, and this function takes this into account as well.
391  **/
392 static void ixgbe_ptp_convert_to_hwtstamp(struct ixgbe_adapter *adapter,
393 					  struct skb_shared_hwtstamps *hwtstamp,
394 					  u64 timestamp)
395 {
396 	unsigned long flags;
397 	struct timespec64 systime;
398 	u64 ns;
399 
400 	memset(hwtstamp, 0, sizeof(*hwtstamp));
401 
402 	switch (adapter->hw.mac.type) {
403 	/* X550 and later hardware supposedly represent time using a seconds
404 	 * and nanoseconds counter, instead of raw 64bits nanoseconds. We need
405 	 * to convert the timestamp into cycles before it can be fed to the
406 	 * cyclecounter. We need an actual cyclecounter because some revisions
407 	 * of hardware run at a higher frequency and thus the counter does
408 	 * not represent seconds/nanoseconds. Instead it can be thought of as
409 	 * cycles and billions of cycles.
410 	 */
411 	case ixgbe_mac_X550:
412 	case ixgbe_mac_X550EM_x:
413 	case ixgbe_mac_x550em_a:
414 		/* Upper 32 bits represent billions of cycles, lower 32 bits
415 		 * represent cycles. However, we use timespec64_to_ns for the
416 		 * correct math even though the units haven't been corrected
417 		 * yet.
418 		 */
419 		systime.tv_sec = timestamp >> 32;
420 		systime.tv_nsec = timestamp & 0xFFFFFFFF;
421 
422 		timestamp = timespec64_to_ns(&systime);
423 		break;
424 	default:
425 		break;
426 	}
427 
428 	spin_lock_irqsave(&adapter->tmreg_lock, flags);
429 	ns = timecounter_cyc2time(&adapter->hw_tc, timestamp);
430 	spin_unlock_irqrestore(&adapter->tmreg_lock, flags);
431 
432 	hwtstamp->hwtstamp = ns_to_ktime(ns);
433 }
434 
435 /**
436  * ixgbe_ptp_adjfreq_82599
437  * @ptp: the ptp clock structure
438  * @ppb: parts per billion adjustment from base
439  *
440  * adjust the frequency of the ptp cycle counter by the
441  * indicated ppb from the base frequency.
442  */
443 static int ixgbe_ptp_adjfreq_82599(struct ptp_clock_info *ptp, s32 ppb)
444 {
445 	struct ixgbe_adapter *adapter =
446 		container_of(ptp, struct ixgbe_adapter, ptp_caps);
447 	struct ixgbe_hw *hw = &adapter->hw;
448 	u64 freq, incval;
449 	u32 diff;
450 	int neg_adj = 0;
451 
452 	if (ppb < 0) {
453 		neg_adj = 1;
454 		ppb = -ppb;
455 	}
456 
457 	smp_mb();
458 	incval = READ_ONCE(adapter->base_incval);
459 
460 	freq = incval;
461 	freq *= ppb;
462 	diff = div_u64(freq, 1000000000ULL);
463 
464 	incval = neg_adj ? (incval - diff) : (incval + diff);
465 
466 	switch (hw->mac.type) {
467 	case ixgbe_mac_X540:
468 		if (incval > 0xFFFFFFFFULL)
469 			e_dev_warn("PTP ppb adjusted SYSTIME rate overflowed!\n");
470 		IXGBE_WRITE_REG(hw, IXGBE_TIMINCA, (u32)incval);
471 		break;
472 	case ixgbe_mac_82599EB:
473 		if (incval > 0x00FFFFFFULL)
474 			e_dev_warn("PTP ppb adjusted SYSTIME rate overflowed!\n");
475 		IXGBE_WRITE_REG(hw, IXGBE_TIMINCA,
476 				BIT(IXGBE_INCPER_SHIFT_82599) |
477 				((u32)incval & 0x00FFFFFFUL));
478 		break;
479 	default:
480 		break;
481 	}
482 
483 	return 0;
484 }
485 
486 /**
487  * ixgbe_ptp_adjfreq_X550
488  * @ptp: the ptp clock structure
489  * @ppb: parts per billion adjustment from base
490  *
491  * adjust the frequency of the SYSTIME registers by the indicated ppb from base
492  * frequency
493  */
494 static int ixgbe_ptp_adjfreq_X550(struct ptp_clock_info *ptp, s32 ppb)
495 {
496 	struct ixgbe_adapter *adapter =
497 			container_of(ptp, struct ixgbe_adapter, ptp_caps);
498 	struct ixgbe_hw *hw = &adapter->hw;
499 	int neg_adj = 0;
500 	u64 rate = IXGBE_X550_BASE_PERIOD;
501 	u32 inca;
502 
503 	if (ppb < 0) {
504 		neg_adj = 1;
505 		ppb = -ppb;
506 	}
507 	rate *= ppb;
508 	rate = div_u64(rate, 1000000000ULL);
509 
510 	/* warn if rate is too large */
511 	if (rate >= INCVALUE_MASK)
512 		e_dev_warn("PTP ppb adjusted SYSTIME rate overflowed!\n");
513 
514 	inca = rate & INCVALUE_MASK;
515 	if (neg_adj)
516 		inca |= ISGN;
517 
518 	IXGBE_WRITE_REG(hw, IXGBE_TIMINCA, inca);
519 
520 	return 0;
521 }
522 
523 /**
524  * ixgbe_ptp_adjtime
525  * @ptp: the ptp clock structure
526  * @delta: offset to adjust the cycle counter by
527  *
528  * adjust the timer by resetting the timecounter structure.
529  */
530 static int ixgbe_ptp_adjtime(struct ptp_clock_info *ptp, s64 delta)
531 {
532 	struct ixgbe_adapter *adapter =
533 		container_of(ptp, struct ixgbe_adapter, ptp_caps);
534 	unsigned long flags;
535 
536 	spin_lock_irqsave(&adapter->tmreg_lock, flags);
537 	timecounter_adjtime(&adapter->hw_tc, delta);
538 	spin_unlock_irqrestore(&adapter->tmreg_lock, flags);
539 
540 	if (adapter->ptp_setup_sdp)
541 		adapter->ptp_setup_sdp(adapter);
542 
543 	return 0;
544 }
545 
546 /**
547  * ixgbe_ptp_gettimex
548  * @ptp: the ptp clock structure
549  * @ts: timespec to hold the PHC timestamp
550  * @sts: structure to hold the system time before and after reading the PHC
551  *
552  * read the timecounter and return the correct value on ns,
553  * after converting it into a struct timespec.
554  */
555 static int ixgbe_ptp_gettimex(struct ptp_clock_info *ptp,
556 			      struct timespec64 *ts,
557 			      struct ptp_system_timestamp *sts)
558 {
559 	struct ixgbe_adapter *adapter =
560 		container_of(ptp, struct ixgbe_adapter, ptp_caps);
561 	struct ixgbe_hw *hw = &adapter->hw;
562 	unsigned long flags;
563 	u64 ns, stamp;
564 
565 	spin_lock_irqsave(&adapter->tmreg_lock, flags);
566 
567 	switch (adapter->hw.mac.type) {
568 	case ixgbe_mac_X550:
569 	case ixgbe_mac_X550EM_x:
570 	case ixgbe_mac_x550em_a:
571 		/* Upper 32 bits represent billions of cycles, lower 32 bits
572 		 * represent cycles. However, we use timespec64_to_ns for the
573 		 * correct math even though the units haven't been corrected
574 		 * yet.
575 		 */
576 		ptp_read_system_prets(sts);
577 		IXGBE_READ_REG(hw, IXGBE_SYSTIMR);
578 		ptp_read_system_postts(sts);
579 		ts->tv_nsec = IXGBE_READ_REG(hw, IXGBE_SYSTIML);
580 		ts->tv_sec = IXGBE_READ_REG(hw, IXGBE_SYSTIMH);
581 		stamp = timespec64_to_ns(ts);
582 		break;
583 	default:
584 		ptp_read_system_prets(sts);
585 		stamp = IXGBE_READ_REG(hw, IXGBE_SYSTIML);
586 		ptp_read_system_postts(sts);
587 		stamp |= (u64)IXGBE_READ_REG(hw, IXGBE_SYSTIMH) << 32;
588 		break;
589 	}
590 
591 	ns = timecounter_cyc2time(&adapter->hw_tc, stamp);
592 
593 	spin_unlock_irqrestore(&adapter->tmreg_lock, flags);
594 
595 	*ts = ns_to_timespec64(ns);
596 
597 	return 0;
598 }
599 
600 /**
601  * ixgbe_ptp_settime
602  * @ptp: the ptp clock structure
603  * @ts: the timespec containing the new time for the cycle counter
604  *
605  * reset the timecounter to use a new base value instead of the kernel
606  * wall timer value.
607  */
608 static int ixgbe_ptp_settime(struct ptp_clock_info *ptp,
609 			     const struct timespec64 *ts)
610 {
611 	struct ixgbe_adapter *adapter =
612 		container_of(ptp, struct ixgbe_adapter, ptp_caps);
613 	unsigned long flags;
614 	u64 ns = timespec64_to_ns(ts);
615 
616 	/* reset the timecounter */
617 	spin_lock_irqsave(&adapter->tmreg_lock, flags);
618 	timecounter_init(&adapter->hw_tc, &adapter->hw_cc, ns);
619 	spin_unlock_irqrestore(&adapter->tmreg_lock, flags);
620 
621 	if (adapter->ptp_setup_sdp)
622 		adapter->ptp_setup_sdp(adapter);
623 	return 0;
624 }
625 
626 /**
627  * ixgbe_ptp_feature_enable
628  * @ptp: the ptp clock structure
629  * @rq: the requested feature to change
630  * @on: whether to enable or disable the feature
631  *
632  * enable (or disable) ancillary features of the phc subsystem.
633  * our driver only supports the PPS feature on the X540
634  */
635 static int ixgbe_ptp_feature_enable(struct ptp_clock_info *ptp,
636 				    struct ptp_clock_request *rq, int on)
637 {
638 	struct ixgbe_adapter *adapter =
639 		container_of(ptp, struct ixgbe_adapter, ptp_caps);
640 
641 	/**
642 	 * When PPS is enabled, unmask the interrupt for the ClockOut
643 	 * feature, so that the interrupt handler can send the PPS
644 	 * event when the clock SDP triggers. Clear mask when PPS is
645 	 * disabled
646 	 */
647 	if (rq->type != PTP_CLK_REQ_PPS || !adapter->ptp_setup_sdp)
648 		return -ENOTSUPP;
649 
650 	if (on)
651 		adapter->flags2 |= IXGBE_FLAG2_PTP_PPS_ENABLED;
652 	else
653 		adapter->flags2 &= ~IXGBE_FLAG2_PTP_PPS_ENABLED;
654 
655 	adapter->ptp_setup_sdp(adapter);
656 	return 0;
657 }
658 
659 /**
660  * ixgbe_ptp_check_pps_event
661  * @adapter: the private adapter structure
662  *
663  * This function is called by the interrupt routine when checking for
664  * interrupts. It will check and handle a pps event.
665  */
666 void ixgbe_ptp_check_pps_event(struct ixgbe_adapter *adapter)
667 {
668 	struct ixgbe_hw *hw = &adapter->hw;
669 	struct ptp_clock_event event;
670 
671 	event.type = PTP_CLOCK_PPS;
672 
673 	/* this check is necessary in case the interrupt was enabled via some
674 	 * alternative means (ex. debug_fs). Better to check here than
675 	 * everywhere that calls this function.
676 	 */
677 	if (!adapter->ptp_clock)
678 		return;
679 
680 	switch (hw->mac.type) {
681 	case ixgbe_mac_X540:
682 		ptp_clock_event(adapter->ptp_clock, &event);
683 		break;
684 	default:
685 		break;
686 	}
687 }
688 
689 /**
690  * ixgbe_ptp_overflow_check - watchdog task to detect SYSTIME overflow
691  * @adapter: private adapter struct
692  *
693  * this watchdog task periodically reads the timecounter
694  * in order to prevent missing when the system time registers wrap
695  * around. This needs to be run approximately twice a minute.
696  */
697 void ixgbe_ptp_overflow_check(struct ixgbe_adapter *adapter)
698 {
699 	bool timeout = time_is_before_jiffies(adapter->last_overflow_check +
700 					     IXGBE_OVERFLOW_PERIOD);
701 	unsigned long flags;
702 
703 	if (timeout) {
704 		/* Update the timecounter */
705 		spin_lock_irqsave(&adapter->tmreg_lock, flags);
706 		timecounter_read(&adapter->hw_tc);
707 		spin_unlock_irqrestore(&adapter->tmreg_lock, flags);
708 
709 		adapter->last_overflow_check = jiffies;
710 	}
711 }
712 
713 /**
714  * ixgbe_ptp_rx_hang - detect error case when Rx timestamp registers latched
715  * @adapter: private network adapter structure
716  *
717  * this watchdog task is scheduled to detect error case where hardware has
718  * dropped an Rx packet that was timestamped when the ring is full. The
719  * particular error is rare but leaves the device in a state unable to timestamp
720  * any future packets.
721  */
722 void ixgbe_ptp_rx_hang(struct ixgbe_adapter *adapter)
723 {
724 	struct ixgbe_hw *hw = &adapter->hw;
725 	u32 tsyncrxctl = IXGBE_READ_REG(hw, IXGBE_TSYNCRXCTL);
726 	struct ixgbe_ring *rx_ring;
727 	unsigned long rx_event;
728 	int n;
729 
730 	/* if we don't have a valid timestamp in the registers, just update the
731 	 * timeout counter and exit
732 	 */
733 	if (!(tsyncrxctl & IXGBE_TSYNCRXCTL_VALID)) {
734 		adapter->last_rx_ptp_check = jiffies;
735 		return;
736 	}
737 
738 	/* determine the most recent watchdog or rx_timestamp event */
739 	rx_event = adapter->last_rx_ptp_check;
740 	for (n = 0; n < adapter->num_rx_queues; n++) {
741 		rx_ring = adapter->rx_ring[n];
742 		if (time_after(rx_ring->last_rx_timestamp, rx_event))
743 			rx_event = rx_ring->last_rx_timestamp;
744 	}
745 
746 	/* only need to read the high RXSTMP register to clear the lock */
747 	if (time_is_before_jiffies(rx_event + 5 * HZ)) {
748 		IXGBE_READ_REG(hw, IXGBE_RXSTMPH);
749 		adapter->last_rx_ptp_check = jiffies;
750 
751 		adapter->rx_hwtstamp_cleared++;
752 		e_warn(drv, "clearing RX Timestamp hang\n");
753 	}
754 }
755 
756 /**
757  * ixgbe_ptp_clear_tx_timestamp - utility function to clear Tx timestamp state
758  * @adapter: the private adapter structure
759  *
760  * This function should be called whenever the state related to a Tx timestamp
761  * needs to be cleared. This helps ensure that all related bits are reset for
762  * the next Tx timestamp event.
763  */
764 static void ixgbe_ptp_clear_tx_timestamp(struct ixgbe_adapter *adapter)
765 {
766 	struct ixgbe_hw *hw = &adapter->hw;
767 
768 	IXGBE_READ_REG(hw, IXGBE_TXSTMPH);
769 	if (adapter->ptp_tx_skb) {
770 		dev_kfree_skb_any(adapter->ptp_tx_skb);
771 		adapter->ptp_tx_skb = NULL;
772 	}
773 	clear_bit_unlock(__IXGBE_PTP_TX_IN_PROGRESS, &adapter->state);
774 }
775 
776 /**
777  * ixgbe_ptp_tx_hang - detect error case where Tx timestamp never finishes
778  * @adapter: private network adapter structure
779  */
780 void ixgbe_ptp_tx_hang(struct ixgbe_adapter *adapter)
781 {
782 	bool timeout = time_is_before_jiffies(adapter->ptp_tx_start +
783 					      IXGBE_PTP_TX_TIMEOUT);
784 
785 	if (!adapter->ptp_tx_skb)
786 		return;
787 
788 	if (!test_bit(__IXGBE_PTP_TX_IN_PROGRESS, &adapter->state))
789 		return;
790 
791 	/* If we haven't received a timestamp within the timeout, it is
792 	 * reasonable to assume that it will never occur, so we can unlock the
793 	 * timestamp bit when this occurs.
794 	 */
795 	if (timeout) {
796 		cancel_work_sync(&adapter->ptp_tx_work);
797 		ixgbe_ptp_clear_tx_timestamp(adapter);
798 		adapter->tx_hwtstamp_timeouts++;
799 		e_warn(drv, "clearing Tx timestamp hang\n");
800 	}
801 }
802 
803 /**
804  * ixgbe_ptp_tx_hwtstamp - utility function which checks for TX time stamp
805  * @adapter: the private adapter struct
806  *
807  * if the timestamp is valid, we convert it into the timecounter ns
808  * value, then store that result into the shhwtstamps structure which
809  * is passed up the network stack
810  */
811 static void ixgbe_ptp_tx_hwtstamp(struct ixgbe_adapter *adapter)
812 {
813 	struct sk_buff *skb = adapter->ptp_tx_skb;
814 	struct ixgbe_hw *hw = &adapter->hw;
815 	struct skb_shared_hwtstamps shhwtstamps;
816 	u64 regval = 0;
817 
818 	regval |= (u64)IXGBE_READ_REG(hw, IXGBE_TXSTMPL);
819 	regval |= (u64)IXGBE_READ_REG(hw, IXGBE_TXSTMPH) << 32;
820 	ixgbe_ptp_convert_to_hwtstamp(adapter, &shhwtstamps, regval);
821 
822 	/* Handle cleanup of the ptp_tx_skb ourselves, and unlock the state
823 	 * bit prior to notifying the stack via skb_tstamp_tx(). This prevents
824 	 * well behaved applications from attempting to timestamp again prior
825 	 * to the lock bit being clear.
826 	 */
827 	adapter->ptp_tx_skb = NULL;
828 	clear_bit_unlock(__IXGBE_PTP_TX_IN_PROGRESS, &adapter->state);
829 
830 	/* Notify the stack and then free the skb after we've unlocked */
831 	skb_tstamp_tx(skb, &shhwtstamps);
832 	dev_kfree_skb_any(skb);
833 }
834 
835 /**
836  * ixgbe_ptp_tx_hwtstamp_work
837  * @work: pointer to the work struct
838  *
839  * This work item polls TSYNCTXCTL valid bit to determine when a Tx hardware
840  * timestamp has been taken for the current skb. It is necessary, because the
841  * descriptor's "done" bit does not correlate with the timestamp event.
842  */
843 static void ixgbe_ptp_tx_hwtstamp_work(struct work_struct *work)
844 {
845 	struct ixgbe_adapter *adapter = container_of(work, struct ixgbe_adapter,
846 						     ptp_tx_work);
847 	struct ixgbe_hw *hw = &adapter->hw;
848 	bool timeout = time_is_before_jiffies(adapter->ptp_tx_start +
849 					      IXGBE_PTP_TX_TIMEOUT);
850 	u32 tsynctxctl;
851 
852 	/* we have to have a valid skb to poll for a timestamp */
853 	if (!adapter->ptp_tx_skb) {
854 		ixgbe_ptp_clear_tx_timestamp(adapter);
855 		return;
856 	}
857 
858 	/* stop polling once we have a valid timestamp */
859 	tsynctxctl = IXGBE_READ_REG(hw, IXGBE_TSYNCTXCTL);
860 	if (tsynctxctl & IXGBE_TSYNCTXCTL_VALID) {
861 		ixgbe_ptp_tx_hwtstamp(adapter);
862 		return;
863 	}
864 
865 	if (timeout) {
866 		ixgbe_ptp_clear_tx_timestamp(adapter);
867 		adapter->tx_hwtstamp_timeouts++;
868 		e_warn(drv, "clearing Tx Timestamp hang\n");
869 	} else {
870 		/* reschedule to keep checking if it's not available yet */
871 		schedule_work(&adapter->ptp_tx_work);
872 	}
873 }
874 
875 /**
876  * ixgbe_ptp_rx_pktstamp - utility function to get RX time stamp from buffer
877  * @q_vector: structure containing interrupt and ring information
878  * @skb: the packet
879  *
880  * This function will be called by the Rx routine of the timestamp for this
881  * packet is stored in the buffer. The value is stored in little endian format
882  * starting at the end of the packet data.
883  */
884 void ixgbe_ptp_rx_pktstamp(struct ixgbe_q_vector *q_vector,
885 			   struct sk_buff *skb)
886 {
887 	__le64 regval;
888 
889 	/* copy the bits out of the skb, and then trim the skb length */
890 	skb_copy_bits(skb, skb->len - IXGBE_TS_HDR_LEN, &regval,
891 		      IXGBE_TS_HDR_LEN);
892 	__pskb_trim(skb, skb->len - IXGBE_TS_HDR_LEN);
893 
894 	/* The timestamp is recorded in little endian format, and is stored at
895 	 * the end of the packet.
896 	 *
897 	 * DWORD: N              N + 1      N + 2
898 	 * Field: End of Packet  SYSTIMH    SYSTIML
899 	 */
900 	ixgbe_ptp_convert_to_hwtstamp(q_vector->adapter, skb_hwtstamps(skb),
901 				      le64_to_cpu(regval));
902 }
903 
904 /**
905  * ixgbe_ptp_rx_rgtstamp - utility function which checks for RX time stamp
906  * @q_vector: structure containing interrupt and ring information
907  * @skb: particular skb to send timestamp with
908  *
909  * if the timestamp is valid, we convert it into the timecounter ns
910  * value, then store that result into the shhwtstamps structure which
911  * is passed up the network stack
912  */
913 void ixgbe_ptp_rx_rgtstamp(struct ixgbe_q_vector *q_vector,
914 			   struct sk_buff *skb)
915 {
916 	struct ixgbe_adapter *adapter;
917 	struct ixgbe_hw *hw;
918 	u64 regval = 0;
919 	u32 tsyncrxctl;
920 
921 	/* we cannot process timestamps on a ring without a q_vector */
922 	if (!q_vector || !q_vector->adapter)
923 		return;
924 
925 	adapter = q_vector->adapter;
926 	hw = &adapter->hw;
927 
928 	/* Read the tsyncrxctl register afterwards in order to prevent taking an
929 	 * I/O hit on every packet.
930 	 */
931 
932 	tsyncrxctl = IXGBE_READ_REG(hw, IXGBE_TSYNCRXCTL);
933 	if (!(tsyncrxctl & IXGBE_TSYNCRXCTL_VALID))
934 		return;
935 
936 	regval |= (u64)IXGBE_READ_REG(hw, IXGBE_RXSTMPL);
937 	regval |= (u64)IXGBE_READ_REG(hw, IXGBE_RXSTMPH) << 32;
938 
939 	ixgbe_ptp_convert_to_hwtstamp(adapter, skb_hwtstamps(skb), regval);
940 }
941 
942 /**
943  * ixgbe_ptp_get_ts_config - get current hardware timestamping configuration
944  * @adapter: pointer to adapter structure
945  * @ifr: ioctl data
946  *
947  * This function returns the current timestamping settings. Rather than
948  * attempt to deconstruct registers to fill in the values, simply keep a copy
949  * of the old settings around, and return a copy when requested.
950  */
951 int ixgbe_ptp_get_ts_config(struct ixgbe_adapter *adapter, struct ifreq *ifr)
952 {
953 	struct hwtstamp_config *config = &adapter->tstamp_config;
954 
955 	return copy_to_user(ifr->ifr_data, config,
956 			    sizeof(*config)) ? -EFAULT : 0;
957 }
958 
959 /**
960  * ixgbe_ptp_set_timestamp_mode - setup the hardware for the requested mode
961  * @adapter: the private ixgbe adapter structure
962  * @config: the hwtstamp configuration requested
963  *
964  * Outgoing time stamping can be enabled and disabled. Play nice and
965  * disable it when requested, although it shouldn't cause any overhead
966  * when no packet needs it. At most one packet in the queue may be
967  * marked for time stamping, otherwise it would be impossible to tell
968  * for sure to which packet the hardware time stamp belongs.
969  *
970  * Incoming time stamping has to be configured via the hardware
971  * filters. Not all combinations are supported, in particular event
972  * type has to be specified. Matching the kind of event packet is
973  * not supported, with the exception of "all V2 events regardless of
974  * level 2 or 4".
975  *
976  * Since hardware always timestamps Path delay packets when timestamping V2
977  * packets, regardless of the type specified in the register, only use V2
978  * Event mode. This more accurately tells the user what the hardware is going
979  * to do anyways.
980  *
981  * Note: this may modify the hwtstamp configuration towards a more general
982  * mode, if required to support the specifically requested mode.
983  */
984 static int ixgbe_ptp_set_timestamp_mode(struct ixgbe_adapter *adapter,
985 				 struct hwtstamp_config *config)
986 {
987 	struct ixgbe_hw *hw = &adapter->hw;
988 	u32 tsync_tx_ctl = IXGBE_TSYNCTXCTL_ENABLED;
989 	u32 tsync_rx_ctl = IXGBE_TSYNCRXCTL_ENABLED;
990 	u32 tsync_rx_mtrl = PTP_EV_PORT << 16;
991 	bool is_l2 = false;
992 	u32 regval;
993 
994 	switch (config->tx_type) {
995 	case HWTSTAMP_TX_OFF:
996 		tsync_tx_ctl = 0;
997 		break;
998 	case HWTSTAMP_TX_ON:
999 		break;
1000 	default:
1001 		return -ERANGE;
1002 	}
1003 
1004 	switch (config->rx_filter) {
1005 	case HWTSTAMP_FILTER_NONE:
1006 		tsync_rx_ctl = 0;
1007 		tsync_rx_mtrl = 0;
1008 		adapter->flags &= ~(IXGBE_FLAG_RX_HWTSTAMP_ENABLED |
1009 				    IXGBE_FLAG_RX_HWTSTAMP_IN_REGISTER);
1010 		break;
1011 	case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
1012 		tsync_rx_ctl |= IXGBE_TSYNCRXCTL_TYPE_L4_V1;
1013 		tsync_rx_mtrl |= IXGBE_RXMTRL_V1_SYNC_MSG;
1014 		adapter->flags |= (IXGBE_FLAG_RX_HWTSTAMP_ENABLED |
1015 				   IXGBE_FLAG_RX_HWTSTAMP_IN_REGISTER);
1016 		break;
1017 	case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
1018 		tsync_rx_ctl |= IXGBE_TSYNCRXCTL_TYPE_L4_V1;
1019 		tsync_rx_mtrl |= IXGBE_RXMTRL_V1_DELAY_REQ_MSG;
1020 		adapter->flags |= (IXGBE_FLAG_RX_HWTSTAMP_ENABLED |
1021 				   IXGBE_FLAG_RX_HWTSTAMP_IN_REGISTER);
1022 		break;
1023 	case HWTSTAMP_FILTER_PTP_V2_EVENT:
1024 	case HWTSTAMP_FILTER_PTP_V2_L2_EVENT:
1025 	case HWTSTAMP_FILTER_PTP_V2_L4_EVENT:
1026 	case HWTSTAMP_FILTER_PTP_V2_SYNC:
1027 	case HWTSTAMP_FILTER_PTP_V2_L2_SYNC:
1028 	case HWTSTAMP_FILTER_PTP_V2_L4_SYNC:
1029 	case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ:
1030 	case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ:
1031 	case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ:
1032 		tsync_rx_ctl |= IXGBE_TSYNCRXCTL_TYPE_EVENT_V2;
1033 		is_l2 = true;
1034 		config->rx_filter = HWTSTAMP_FILTER_PTP_V2_EVENT;
1035 		adapter->flags |= (IXGBE_FLAG_RX_HWTSTAMP_ENABLED |
1036 				   IXGBE_FLAG_RX_HWTSTAMP_IN_REGISTER);
1037 		break;
1038 	case HWTSTAMP_FILTER_PTP_V1_L4_EVENT:
1039 	case HWTSTAMP_FILTER_NTP_ALL:
1040 	case HWTSTAMP_FILTER_ALL:
1041 		/* The X550 controller is capable of timestamping all packets,
1042 		 * which allows it to accept any filter.
1043 		 */
1044 		if (hw->mac.type >= ixgbe_mac_X550) {
1045 			tsync_rx_ctl |= IXGBE_TSYNCRXCTL_TYPE_ALL;
1046 			config->rx_filter = HWTSTAMP_FILTER_ALL;
1047 			adapter->flags |= IXGBE_FLAG_RX_HWTSTAMP_ENABLED;
1048 			break;
1049 		}
1050 		fallthrough;
1051 	default:
1052 		/*
1053 		 * register RXMTRL must be set in order to do V1 packets,
1054 		 * therefore it is not possible to time stamp both V1 Sync and
1055 		 * Delay_Req messages and hardware does not support
1056 		 * timestamping all packets => return error
1057 		 */
1058 		adapter->flags &= ~(IXGBE_FLAG_RX_HWTSTAMP_ENABLED |
1059 				    IXGBE_FLAG_RX_HWTSTAMP_IN_REGISTER);
1060 		config->rx_filter = HWTSTAMP_FILTER_NONE;
1061 		return -ERANGE;
1062 	}
1063 
1064 	if (hw->mac.type == ixgbe_mac_82598EB) {
1065 		adapter->flags &= ~(IXGBE_FLAG_RX_HWTSTAMP_ENABLED |
1066 				    IXGBE_FLAG_RX_HWTSTAMP_IN_REGISTER);
1067 		if (tsync_rx_ctl | tsync_tx_ctl)
1068 			return -ERANGE;
1069 		return 0;
1070 	}
1071 
1072 	/* Per-packet timestamping only works if the filter is set to all
1073 	 * packets. Since this is desired, always timestamp all packets as long
1074 	 * as any Rx filter was configured.
1075 	 */
1076 	switch (hw->mac.type) {
1077 	case ixgbe_mac_X550:
1078 	case ixgbe_mac_X550EM_x:
1079 	case ixgbe_mac_x550em_a:
1080 		/* enable timestamping all packets only if at least some
1081 		 * packets were requested. Otherwise, play nice and disable
1082 		 * timestamping
1083 		 */
1084 		if (config->rx_filter == HWTSTAMP_FILTER_NONE)
1085 			break;
1086 
1087 		tsync_rx_ctl = IXGBE_TSYNCRXCTL_ENABLED |
1088 			       IXGBE_TSYNCRXCTL_TYPE_ALL |
1089 			       IXGBE_TSYNCRXCTL_TSIP_UT_EN;
1090 		config->rx_filter = HWTSTAMP_FILTER_ALL;
1091 		adapter->flags |= IXGBE_FLAG_RX_HWTSTAMP_ENABLED;
1092 		adapter->flags &= ~IXGBE_FLAG_RX_HWTSTAMP_IN_REGISTER;
1093 		is_l2 = true;
1094 		break;
1095 	default:
1096 		break;
1097 	}
1098 
1099 	/* define ethertype filter for timestamping L2 packets */
1100 	if (is_l2)
1101 		IXGBE_WRITE_REG(hw, IXGBE_ETQF(IXGBE_ETQF_FILTER_1588),
1102 				(IXGBE_ETQF_FILTER_EN | /* enable filter */
1103 				 IXGBE_ETQF_1588 | /* enable timestamping */
1104 				 ETH_P_1588));     /* 1588 eth protocol type */
1105 	else
1106 		IXGBE_WRITE_REG(hw, IXGBE_ETQF(IXGBE_ETQF_FILTER_1588), 0);
1107 
1108 	/* enable/disable TX */
1109 	regval = IXGBE_READ_REG(hw, IXGBE_TSYNCTXCTL);
1110 	regval &= ~IXGBE_TSYNCTXCTL_ENABLED;
1111 	regval |= tsync_tx_ctl;
1112 	IXGBE_WRITE_REG(hw, IXGBE_TSYNCTXCTL, regval);
1113 
1114 	/* enable/disable RX */
1115 	regval = IXGBE_READ_REG(hw, IXGBE_TSYNCRXCTL);
1116 	regval &= ~(IXGBE_TSYNCRXCTL_ENABLED | IXGBE_TSYNCRXCTL_TYPE_MASK);
1117 	regval |= tsync_rx_ctl;
1118 	IXGBE_WRITE_REG(hw, IXGBE_TSYNCRXCTL, regval);
1119 
1120 	/* define which PTP packets are time stamped */
1121 	IXGBE_WRITE_REG(hw, IXGBE_RXMTRL, tsync_rx_mtrl);
1122 
1123 	IXGBE_WRITE_FLUSH(hw);
1124 
1125 	/* clear TX/RX time stamp registers, just to be sure */
1126 	ixgbe_ptp_clear_tx_timestamp(adapter);
1127 	IXGBE_READ_REG(hw, IXGBE_RXSTMPH);
1128 
1129 	return 0;
1130 }
1131 
1132 /**
1133  * ixgbe_ptp_set_ts_config - user entry point for timestamp mode
1134  * @adapter: pointer to adapter struct
1135  * @ifr: ioctl data
1136  *
1137  * Set hardware to requested mode. If unsupported, return an error with no
1138  * changes. Otherwise, store the mode for future reference.
1139  */
1140 int ixgbe_ptp_set_ts_config(struct ixgbe_adapter *adapter, struct ifreq *ifr)
1141 {
1142 	struct hwtstamp_config config;
1143 	int err;
1144 
1145 	if (copy_from_user(&config, ifr->ifr_data, sizeof(config)))
1146 		return -EFAULT;
1147 
1148 	err = ixgbe_ptp_set_timestamp_mode(adapter, &config);
1149 	if (err)
1150 		return err;
1151 
1152 	/* save these settings for future reference */
1153 	memcpy(&adapter->tstamp_config, &config,
1154 	       sizeof(adapter->tstamp_config));
1155 
1156 	return copy_to_user(ifr->ifr_data, &config, sizeof(config)) ?
1157 		-EFAULT : 0;
1158 }
1159 
1160 static void ixgbe_ptp_link_speed_adjust(struct ixgbe_adapter *adapter,
1161 					u32 *shift, u32 *incval)
1162 {
1163 	/**
1164 	 * Scale the NIC cycle counter by a large factor so that
1165 	 * relatively small corrections to the frequency can be added
1166 	 * or subtracted. The drawbacks of a large factor include
1167 	 * (a) the clock register overflows more quickly, (b) the cycle
1168 	 * counter structure must be able to convert the systime value
1169 	 * to nanoseconds using only a multiplier and a right-shift,
1170 	 * and (c) the value must fit within the timinca register space
1171 	 * => math based on internal DMA clock rate and available bits
1172 	 *
1173 	 * Note that when there is no link, internal DMA clock is same as when
1174 	 * link speed is 10Gb. Set the registers correctly even when link is
1175 	 * down to preserve the clock setting
1176 	 */
1177 	switch (adapter->link_speed) {
1178 	case IXGBE_LINK_SPEED_100_FULL:
1179 		*shift = IXGBE_INCVAL_SHIFT_100;
1180 		*incval = IXGBE_INCVAL_100;
1181 		break;
1182 	case IXGBE_LINK_SPEED_1GB_FULL:
1183 		*shift = IXGBE_INCVAL_SHIFT_1GB;
1184 		*incval = IXGBE_INCVAL_1GB;
1185 		break;
1186 	case IXGBE_LINK_SPEED_10GB_FULL:
1187 	default:
1188 		*shift = IXGBE_INCVAL_SHIFT_10GB;
1189 		*incval = IXGBE_INCVAL_10GB;
1190 		break;
1191 	}
1192 }
1193 
1194 /**
1195  * ixgbe_ptp_start_cyclecounter - create the cycle counter from hw
1196  * @adapter: pointer to the adapter structure
1197  *
1198  * This function should be called to set the proper values for the TIMINCA
1199  * register and tell the cyclecounter structure what the tick rate of SYSTIME
1200  * is. It does not directly modify SYSTIME registers or the timecounter
1201  * structure. It should be called whenever a new TIMINCA value is necessary,
1202  * such as during initialization or when the link speed changes.
1203  */
1204 void ixgbe_ptp_start_cyclecounter(struct ixgbe_adapter *adapter)
1205 {
1206 	struct ixgbe_hw *hw = &adapter->hw;
1207 	struct cyclecounter cc;
1208 	unsigned long flags;
1209 	u32 incval = 0;
1210 	u32 tsauxc = 0;
1211 	u32 fuse0 = 0;
1212 
1213 	/* For some of the boards below this mask is technically incorrect.
1214 	 * The timestamp mask overflows at approximately 61bits. However the
1215 	 * particular hardware does not overflow on an even bitmask value.
1216 	 * Instead, it overflows due to conversion of upper 32bits billions of
1217 	 * cycles. Timecounters are not really intended for this purpose so
1218 	 * they do not properly function if the overflow point isn't 2^N-1.
1219 	 * However, the actual SYSTIME values in question take ~138 years to
1220 	 * overflow. In practice this means they won't actually overflow. A
1221 	 * proper fix to this problem would require modification of the
1222 	 * timecounter delta calculations.
1223 	 */
1224 	cc.mask = CLOCKSOURCE_MASK(64);
1225 	cc.mult = 1;
1226 	cc.shift = 0;
1227 
1228 	switch (hw->mac.type) {
1229 	case ixgbe_mac_X550EM_x:
1230 		/* SYSTIME assumes X550EM_x board frequency is 300Mhz, and is
1231 		 * designed to represent seconds and nanoseconds when this is
1232 		 * the case. However, some revisions of hardware have a 400Mhz
1233 		 * clock and we have to compensate for this frequency
1234 		 * variation using corrected mult and shift values.
1235 		 */
1236 		fuse0 = IXGBE_READ_REG(hw, IXGBE_FUSES0_GROUP(0));
1237 		if (!(fuse0 & IXGBE_FUSES0_300MHZ)) {
1238 			cc.mult = 3;
1239 			cc.shift = 2;
1240 		}
1241 		fallthrough;
1242 	case ixgbe_mac_x550em_a:
1243 	case ixgbe_mac_X550:
1244 		cc.read = ixgbe_ptp_read_X550;
1245 
1246 		/* enable SYSTIME counter */
1247 		IXGBE_WRITE_REG(hw, IXGBE_SYSTIMR, 0);
1248 		IXGBE_WRITE_REG(hw, IXGBE_SYSTIML, 0);
1249 		IXGBE_WRITE_REG(hw, IXGBE_SYSTIMH, 0);
1250 		tsauxc = IXGBE_READ_REG(hw, IXGBE_TSAUXC);
1251 		IXGBE_WRITE_REG(hw, IXGBE_TSAUXC,
1252 				tsauxc & ~IXGBE_TSAUXC_DISABLE_SYSTIME);
1253 		IXGBE_WRITE_REG(hw, IXGBE_TSIM, IXGBE_TSIM_TXTS);
1254 		IXGBE_WRITE_REG(hw, IXGBE_EIMS, IXGBE_EIMS_TIMESYNC);
1255 
1256 		IXGBE_WRITE_FLUSH(hw);
1257 		break;
1258 	case ixgbe_mac_X540:
1259 		cc.read = ixgbe_ptp_read_82599;
1260 
1261 		ixgbe_ptp_link_speed_adjust(adapter, &cc.shift, &incval);
1262 		IXGBE_WRITE_REG(hw, IXGBE_TIMINCA, incval);
1263 		break;
1264 	case ixgbe_mac_82599EB:
1265 		cc.read = ixgbe_ptp_read_82599;
1266 
1267 		ixgbe_ptp_link_speed_adjust(adapter, &cc.shift, &incval);
1268 		incval >>= IXGBE_INCVAL_SHIFT_82599;
1269 		cc.shift -= IXGBE_INCVAL_SHIFT_82599;
1270 		IXGBE_WRITE_REG(hw, IXGBE_TIMINCA,
1271 				BIT(IXGBE_INCPER_SHIFT_82599) | incval);
1272 		break;
1273 	default:
1274 		/* other devices aren't supported */
1275 		return;
1276 	}
1277 
1278 	/* update the base incval used to calculate frequency adjustment */
1279 	WRITE_ONCE(adapter->base_incval, incval);
1280 	smp_mb();
1281 
1282 	/* need lock to prevent incorrect read while modifying cyclecounter */
1283 	spin_lock_irqsave(&adapter->tmreg_lock, flags);
1284 	memcpy(&adapter->hw_cc, &cc, sizeof(adapter->hw_cc));
1285 	spin_unlock_irqrestore(&adapter->tmreg_lock, flags);
1286 }
1287 
1288 /**
1289  * ixgbe_ptp_reset
1290  * @adapter: the ixgbe private board structure
1291  *
1292  * When the MAC resets, all the hardware bits for timesync are reset. This
1293  * function is used to re-enable the device for PTP based on current settings.
1294  * We do lose the current clock time, so just reset the cyclecounter to the
1295  * system real clock time.
1296  *
1297  * This function will maintain hwtstamp_config settings, and resets the SDP
1298  * output if it was enabled.
1299  */
1300 void ixgbe_ptp_reset(struct ixgbe_adapter *adapter)
1301 {
1302 	struct ixgbe_hw *hw = &adapter->hw;
1303 	unsigned long flags;
1304 
1305 	/* reset the hardware timestamping mode */
1306 	ixgbe_ptp_set_timestamp_mode(adapter, &adapter->tstamp_config);
1307 
1308 	/* 82598 does not support PTP */
1309 	if (hw->mac.type == ixgbe_mac_82598EB)
1310 		return;
1311 
1312 	ixgbe_ptp_start_cyclecounter(adapter);
1313 
1314 	spin_lock_irqsave(&adapter->tmreg_lock, flags);
1315 	timecounter_init(&adapter->hw_tc, &adapter->hw_cc,
1316 			 ktime_to_ns(ktime_get_real()));
1317 	spin_unlock_irqrestore(&adapter->tmreg_lock, flags);
1318 
1319 	adapter->last_overflow_check = jiffies;
1320 
1321 	/* Now that the shift has been calculated and the systime
1322 	 * registers reset, (re-)enable the Clock out feature
1323 	 */
1324 	if (adapter->ptp_setup_sdp)
1325 		adapter->ptp_setup_sdp(adapter);
1326 }
1327 
1328 /**
1329  * ixgbe_ptp_create_clock
1330  * @adapter: the ixgbe private adapter structure
1331  *
1332  * This function performs setup of the user entry point function table and
1333  * initializes the PTP clock device, which is used to access the clock-like
1334  * features of the PTP core. It will be called by ixgbe_ptp_init, and may
1335  * reuse a previously initialized clock (such as during a suspend/resume
1336  * cycle).
1337  */
1338 static long ixgbe_ptp_create_clock(struct ixgbe_adapter *adapter)
1339 {
1340 	struct net_device *netdev = adapter->netdev;
1341 	long err;
1342 
1343 	/* do nothing if we already have a clock device */
1344 	if (!IS_ERR_OR_NULL(adapter->ptp_clock))
1345 		return 0;
1346 
1347 	switch (adapter->hw.mac.type) {
1348 	case ixgbe_mac_X540:
1349 		snprintf(adapter->ptp_caps.name,
1350 			 sizeof(adapter->ptp_caps.name),
1351 			 "%s", netdev->name);
1352 		adapter->ptp_caps.owner = THIS_MODULE;
1353 		adapter->ptp_caps.max_adj = 250000000;
1354 		adapter->ptp_caps.n_alarm = 0;
1355 		adapter->ptp_caps.n_ext_ts = 0;
1356 		adapter->ptp_caps.n_per_out = 0;
1357 		adapter->ptp_caps.pps = 1;
1358 		adapter->ptp_caps.adjfreq = ixgbe_ptp_adjfreq_82599;
1359 		adapter->ptp_caps.adjtime = ixgbe_ptp_adjtime;
1360 		adapter->ptp_caps.gettimex64 = ixgbe_ptp_gettimex;
1361 		adapter->ptp_caps.settime64 = ixgbe_ptp_settime;
1362 		adapter->ptp_caps.enable = ixgbe_ptp_feature_enable;
1363 		adapter->ptp_setup_sdp = ixgbe_ptp_setup_sdp_X540;
1364 		break;
1365 	case ixgbe_mac_82599EB:
1366 		snprintf(adapter->ptp_caps.name,
1367 			 sizeof(adapter->ptp_caps.name),
1368 			 "%s", netdev->name);
1369 		adapter->ptp_caps.owner = THIS_MODULE;
1370 		adapter->ptp_caps.max_adj = 250000000;
1371 		adapter->ptp_caps.n_alarm = 0;
1372 		adapter->ptp_caps.n_ext_ts = 0;
1373 		adapter->ptp_caps.n_per_out = 0;
1374 		adapter->ptp_caps.pps = 0;
1375 		adapter->ptp_caps.adjfreq = ixgbe_ptp_adjfreq_82599;
1376 		adapter->ptp_caps.adjtime = ixgbe_ptp_adjtime;
1377 		adapter->ptp_caps.gettimex64 = ixgbe_ptp_gettimex;
1378 		adapter->ptp_caps.settime64 = ixgbe_ptp_settime;
1379 		adapter->ptp_caps.enable = ixgbe_ptp_feature_enable;
1380 		break;
1381 	case ixgbe_mac_X550:
1382 	case ixgbe_mac_X550EM_x:
1383 	case ixgbe_mac_x550em_a:
1384 		snprintf(adapter->ptp_caps.name, 16, "%s", netdev->name);
1385 		adapter->ptp_caps.owner = THIS_MODULE;
1386 		adapter->ptp_caps.max_adj = 30000000;
1387 		adapter->ptp_caps.n_alarm = 0;
1388 		adapter->ptp_caps.n_ext_ts = 0;
1389 		adapter->ptp_caps.n_per_out = 0;
1390 		adapter->ptp_caps.pps = 1;
1391 		adapter->ptp_caps.adjfreq = ixgbe_ptp_adjfreq_X550;
1392 		adapter->ptp_caps.adjtime = ixgbe_ptp_adjtime;
1393 		adapter->ptp_caps.gettimex64 = ixgbe_ptp_gettimex;
1394 		adapter->ptp_caps.settime64 = ixgbe_ptp_settime;
1395 		adapter->ptp_caps.enable = ixgbe_ptp_feature_enable;
1396 		adapter->ptp_setup_sdp = ixgbe_ptp_setup_sdp_X550;
1397 		break;
1398 	default:
1399 		adapter->ptp_clock = NULL;
1400 		adapter->ptp_setup_sdp = NULL;
1401 		return -EOPNOTSUPP;
1402 	}
1403 
1404 	adapter->ptp_clock = ptp_clock_register(&adapter->ptp_caps,
1405 						&adapter->pdev->dev);
1406 	if (IS_ERR(adapter->ptp_clock)) {
1407 		err = PTR_ERR(adapter->ptp_clock);
1408 		adapter->ptp_clock = NULL;
1409 		e_dev_err("ptp_clock_register failed\n");
1410 		return err;
1411 	} else if (adapter->ptp_clock)
1412 		e_dev_info("registered PHC device on %s\n", netdev->name);
1413 
1414 	/* set default timestamp mode to disabled here. We do this in
1415 	 * create_clock instead of init, because we don't want to override the
1416 	 * previous settings during a resume cycle.
1417 	 */
1418 	adapter->tstamp_config.rx_filter = HWTSTAMP_FILTER_NONE;
1419 	adapter->tstamp_config.tx_type = HWTSTAMP_TX_OFF;
1420 
1421 	return 0;
1422 }
1423 
1424 /**
1425  * ixgbe_ptp_init
1426  * @adapter: the ixgbe private adapter structure
1427  *
1428  * This function performs the required steps for enabling PTP
1429  * support. If PTP support has already been loaded it simply calls the
1430  * cyclecounter init routine and exits.
1431  */
1432 void ixgbe_ptp_init(struct ixgbe_adapter *adapter)
1433 {
1434 	/* initialize the spin lock first since we can't control when a user
1435 	 * will call the entry functions once we have initialized the clock
1436 	 * device
1437 	 */
1438 	spin_lock_init(&adapter->tmreg_lock);
1439 
1440 	/* obtain a PTP device, or re-use an existing device */
1441 	if (ixgbe_ptp_create_clock(adapter))
1442 		return;
1443 
1444 	/* we have a clock so we can initialize work now */
1445 	INIT_WORK(&adapter->ptp_tx_work, ixgbe_ptp_tx_hwtstamp_work);
1446 
1447 	/* reset the PTP related hardware bits */
1448 	ixgbe_ptp_reset(adapter);
1449 
1450 	/* enter the IXGBE_PTP_RUNNING state */
1451 	set_bit(__IXGBE_PTP_RUNNING, &adapter->state);
1452 
1453 	return;
1454 }
1455 
1456 /**
1457  * ixgbe_ptp_suspend - stop PTP work items
1458  * @adapter: pointer to adapter struct
1459  *
1460  * this function suspends PTP activity, and prevents more PTP work from being
1461  * generated, but does not destroy the PTP clock device.
1462  */
1463 void ixgbe_ptp_suspend(struct ixgbe_adapter *adapter)
1464 {
1465 	/* Leave the IXGBE_PTP_RUNNING state. */
1466 	if (!test_and_clear_bit(__IXGBE_PTP_RUNNING, &adapter->state))
1467 		return;
1468 
1469 	adapter->flags2 &= ~IXGBE_FLAG2_PTP_PPS_ENABLED;
1470 	if (adapter->ptp_setup_sdp)
1471 		adapter->ptp_setup_sdp(adapter);
1472 
1473 	/* ensure that we cancel any pending PTP Tx work item in progress */
1474 	cancel_work_sync(&adapter->ptp_tx_work);
1475 	ixgbe_ptp_clear_tx_timestamp(adapter);
1476 }
1477 
1478 /**
1479  * ixgbe_ptp_stop - close the PTP device
1480  * @adapter: pointer to adapter struct
1481  *
1482  * completely destroy the PTP device, should only be called when the device is
1483  * being fully closed.
1484  */
1485 void ixgbe_ptp_stop(struct ixgbe_adapter *adapter)
1486 {
1487 	/* first, suspend PTP activity */
1488 	ixgbe_ptp_suspend(adapter);
1489 
1490 	/* disable the PTP clock device */
1491 	if (adapter->ptp_clock) {
1492 		ptp_clock_unregister(adapter->ptp_clock);
1493 		adapter->ptp_clock = NULL;
1494 		e_dev_info("removed PHC on %s\n",
1495 			   adapter->netdev->name);
1496 	}
1497 }
1498