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