1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2019, Vladimir Oltean <olteanv@gmail.com>
3  */
4 #include <linux/spi/spi.h>
5 #include "sja1105.h"
6 
7 /* The adjfine API clamps ppb between [-32,768,000, 32,768,000], and
8  * therefore scaled_ppm between [-2,147,483,648, 2,147,483,647].
9  * Set the maximum supported ppb to a round value smaller than the maximum.
10  *
11  * Percentually speaking, this is a +/- 0.032x adjustment of the
12  * free-running counter (0.968x to 1.032x).
13  */
14 #define SJA1105_MAX_ADJ_PPB		32000000
15 #define SJA1105_SIZE_PTP_CMD		4
16 
17 /* PTPSYNCTS has no interrupt or update mechanism, because the intended
18  * hardware use case is for the timestamp to be collected synchronously,
19  * immediately after the CAS_MASTER SJA1105 switch has performed a CASSYNC
20  * one-shot toggle (no return to level) on the PTP_CLK pin. When used as a
21  * generic extts source, the PTPSYNCTS register needs polling and a comparison
22  * with the old value. The polling interval is configured as the Nyquist rate
23  * of a signal with 50% duty cycle and 1Hz frequency, which is sadly all that
24  * this hardware can do (but may be enough for some setups). Anything of higher
25  * frequency than 1 Hz will be lost, since there is no timestamp FIFO.
26  */
27 #define SJA1105_EXTTS_INTERVAL		(HZ / 6)
28 
29 /*            This range is actually +/- SJA1105_MAX_ADJ_PPB
30  *            divided by 1000 (ppb -> ppm) and with a 16-bit
31  *            "fractional" part (actually fixed point).
32  *                                    |
33  *                                    v
34  * Convert scaled_ppm from the +/- ((10^6) << 16) range
35  * into the +/- (1 << 31) range.
36  *
37  * This forgoes a "ppb" numeric representation (up to NSEC_PER_SEC)
38  * and defines the scaling factor between scaled_ppm and the actual
39  * frequency adjustments of the PHC.
40  *
41  *   ptpclkrate = scaled_ppm * 2^31 / (10^6 * 2^16)
42  *   simplifies to
43  *   ptpclkrate = scaled_ppm * 2^9 / 5^6
44  */
45 #define SJA1105_CC_MULT_NUM		(1 << 9)
46 #define SJA1105_CC_MULT_DEM		15625
47 #define SJA1105_CC_MULT			0x80000000
48 
49 enum sja1105_ptp_clk_mode {
50 	PTP_ADD_MODE = 1,
51 	PTP_SET_MODE = 0,
52 };
53 
54 #define extts_to_data(t) \
55 		container_of((t), struct sja1105_ptp_data, extts_timer)
56 #define ptp_caps_to_data(d) \
57 		container_of((d), struct sja1105_ptp_data, caps)
58 #define ptp_data_to_sja1105(d) \
59 		container_of((d), struct sja1105_private, ptp_data)
60 
61 /* Must be called only with priv->tagger_data.state bit
62  * SJA1105_HWTS_RX_EN cleared
63  */
64 static int sja1105_change_rxtstamping(struct sja1105_private *priv,
65 				      bool on)
66 {
67 	struct sja1105_ptp_data *ptp_data = &priv->ptp_data;
68 	struct sja1105_general_params_entry *general_params;
69 	struct sja1105_table *table;
70 
71 	table = &priv->static_config.tables[BLK_IDX_GENERAL_PARAMS];
72 	general_params = table->entries;
73 	general_params->send_meta1 = on;
74 	general_params->send_meta0 = on;
75 
76 	/* Initialize the meta state machine to a known state */
77 	if (priv->tagger_data.stampable_skb) {
78 		kfree_skb(priv->tagger_data.stampable_skb);
79 		priv->tagger_data.stampable_skb = NULL;
80 	}
81 	ptp_cancel_worker_sync(ptp_data->clock);
82 	skb_queue_purge(&ptp_data->skb_rxtstamp_queue);
83 
84 	return sja1105_static_config_reload(priv, SJA1105_RX_HWTSTAMPING);
85 }
86 
87 int sja1105_hwtstamp_set(struct dsa_switch *ds, int port, struct ifreq *ifr)
88 {
89 	struct sja1105_private *priv = ds->priv;
90 	struct hwtstamp_config config;
91 	bool rx_on;
92 	int rc;
93 
94 	if (copy_from_user(&config, ifr->ifr_data, sizeof(config)))
95 		return -EFAULT;
96 
97 	switch (config.tx_type) {
98 	case HWTSTAMP_TX_OFF:
99 		priv->ports[port].hwts_tx_en = false;
100 		break;
101 	case HWTSTAMP_TX_ON:
102 		priv->ports[port].hwts_tx_en = true;
103 		break;
104 	default:
105 		return -ERANGE;
106 	}
107 
108 	switch (config.rx_filter) {
109 	case HWTSTAMP_FILTER_NONE:
110 		rx_on = false;
111 		break;
112 	default:
113 		rx_on = true;
114 		break;
115 	}
116 
117 	if (rx_on != test_bit(SJA1105_HWTS_RX_EN, &priv->tagger_data.state)) {
118 		clear_bit(SJA1105_HWTS_RX_EN, &priv->tagger_data.state);
119 
120 		rc = sja1105_change_rxtstamping(priv, rx_on);
121 		if (rc < 0) {
122 			dev_err(ds->dev,
123 				"Failed to change RX timestamping: %d\n", rc);
124 			return rc;
125 		}
126 		if (rx_on)
127 			set_bit(SJA1105_HWTS_RX_EN, &priv->tagger_data.state);
128 	}
129 
130 	if (copy_to_user(ifr->ifr_data, &config, sizeof(config)))
131 		return -EFAULT;
132 	return 0;
133 }
134 
135 int sja1105_hwtstamp_get(struct dsa_switch *ds, int port, struct ifreq *ifr)
136 {
137 	struct sja1105_private *priv = ds->priv;
138 	struct hwtstamp_config config;
139 
140 	config.flags = 0;
141 	if (priv->ports[port].hwts_tx_en)
142 		config.tx_type = HWTSTAMP_TX_ON;
143 	else
144 		config.tx_type = HWTSTAMP_TX_OFF;
145 	if (test_bit(SJA1105_HWTS_RX_EN, &priv->tagger_data.state))
146 		config.rx_filter = HWTSTAMP_FILTER_PTP_V2_L2_EVENT;
147 	else
148 		config.rx_filter = HWTSTAMP_FILTER_NONE;
149 
150 	return copy_to_user(ifr->ifr_data, &config, sizeof(config)) ?
151 		-EFAULT : 0;
152 }
153 
154 int sja1105_get_ts_info(struct dsa_switch *ds, int port,
155 			struct ethtool_ts_info *info)
156 {
157 	struct sja1105_private *priv = ds->priv;
158 	struct sja1105_ptp_data *ptp_data = &priv->ptp_data;
159 
160 	/* Called during cleanup */
161 	if (!ptp_data->clock)
162 		return -ENODEV;
163 
164 	info->so_timestamping = SOF_TIMESTAMPING_TX_HARDWARE |
165 				SOF_TIMESTAMPING_RX_HARDWARE |
166 				SOF_TIMESTAMPING_RAW_HARDWARE;
167 	info->tx_types = (1 << HWTSTAMP_TX_OFF) |
168 			 (1 << HWTSTAMP_TX_ON);
169 	info->rx_filters = (1 << HWTSTAMP_FILTER_NONE) |
170 			   (1 << HWTSTAMP_FILTER_PTP_V2_L2_EVENT);
171 	info->phc_index = ptp_clock_index(ptp_data->clock);
172 	return 0;
173 }
174 
175 void sja1105et_ptp_cmd_packing(u8 *buf, struct sja1105_ptp_cmd *cmd,
176 			       enum packing_op op)
177 {
178 	const int size = SJA1105_SIZE_PTP_CMD;
179 	/* No need to keep this as part of the structure */
180 	u64 valid = 1;
181 
182 	sja1105_packing(buf, &valid,           31, 31, size, op);
183 	sja1105_packing(buf, &cmd->ptpstrtsch, 30, 30, size, op);
184 	sja1105_packing(buf, &cmd->ptpstopsch, 29, 29, size, op);
185 	sja1105_packing(buf, &cmd->startptpcp, 28, 28, size, op);
186 	sja1105_packing(buf, &cmd->stopptpcp,  27, 27, size, op);
187 	sja1105_packing(buf, &cmd->resptp,      2,  2, size, op);
188 	sja1105_packing(buf, &cmd->corrclk4ts,  1,  1, size, op);
189 	sja1105_packing(buf, &cmd->ptpclkadd,   0,  0, size, op);
190 }
191 
192 void sja1105pqrs_ptp_cmd_packing(u8 *buf, struct sja1105_ptp_cmd *cmd,
193 				 enum packing_op op)
194 {
195 	const int size = SJA1105_SIZE_PTP_CMD;
196 	/* No need to keep this as part of the structure */
197 	u64 valid = 1;
198 
199 	sja1105_packing(buf, &valid,           31, 31, size, op);
200 	sja1105_packing(buf, &cmd->ptpstrtsch, 30, 30, size, op);
201 	sja1105_packing(buf, &cmd->ptpstopsch, 29, 29, size, op);
202 	sja1105_packing(buf, &cmd->startptpcp, 28, 28, size, op);
203 	sja1105_packing(buf, &cmd->stopptpcp,  27, 27, size, op);
204 	sja1105_packing(buf, &cmd->resptp,      3,  3, size, op);
205 	sja1105_packing(buf, &cmd->corrclk4ts,  2,  2, size, op);
206 	sja1105_packing(buf, &cmd->ptpclkadd,   0,  0, size, op);
207 }
208 
209 int sja1105_ptp_commit(struct dsa_switch *ds, struct sja1105_ptp_cmd *cmd,
210 		       sja1105_spi_rw_mode_t rw)
211 {
212 	const struct sja1105_private *priv = ds->priv;
213 	const struct sja1105_regs *regs = priv->info->regs;
214 	u8 buf[SJA1105_SIZE_PTP_CMD] = {0};
215 	int rc;
216 
217 	if (rw == SPI_WRITE)
218 		priv->info->ptp_cmd_packing(buf, cmd, PACK);
219 
220 	rc = sja1105_xfer_buf(priv, rw, regs->ptp_control, buf,
221 			      SJA1105_SIZE_PTP_CMD);
222 
223 	if (rw == SPI_READ)
224 		priv->info->ptp_cmd_packing(buf, cmd, UNPACK);
225 
226 	return rc;
227 }
228 
229 /* The switch returns partial timestamps (24 bits for SJA1105 E/T, which wrap
230  * around in 0.135 seconds, and 32 bits for P/Q/R/S, wrapping around in 34.35
231  * seconds).
232  *
233  * This receives the RX or TX MAC timestamps, provided by hardware as
234  * the lower bits of the cycle counter, sampled at the time the timestamp was
235  * collected.
236  *
237  * To reconstruct into a full 64-bit-wide timestamp, the cycle counter is
238  * read and the high-order bits are filled in.
239  *
240  * Must be called within one wraparound period of the partial timestamp since
241  * it was generated by the MAC.
242  */
243 static u64 sja1105_tstamp_reconstruct(struct dsa_switch *ds, u64 now,
244 				      u64 ts_partial)
245 {
246 	struct sja1105_private *priv = ds->priv;
247 	u64 partial_tstamp_mask = CYCLECOUNTER_MASK(priv->info->ptp_ts_bits);
248 	u64 ts_reconstructed;
249 
250 	ts_reconstructed = (now & ~partial_tstamp_mask) | ts_partial;
251 
252 	/* Check lower bits of current cycle counter against the timestamp.
253 	 * If the current cycle counter is lower than the partial timestamp,
254 	 * then wraparound surely occurred and must be accounted for.
255 	 */
256 	if ((now & partial_tstamp_mask) <= ts_partial)
257 		ts_reconstructed -= (partial_tstamp_mask + 1);
258 
259 	return ts_reconstructed;
260 }
261 
262 /* Reads the SPI interface for an egress timestamp generated by the switch
263  * for frames sent using management routes.
264  *
265  * SJA1105 E/T layout of the 4-byte SPI payload:
266  *
267  * 31    23    15    7     0
268  * |     |     |     |     |
269  * +-----+-----+-----+     ^
270  *          ^              |
271  *          |              |
272  *  24-bit timestamp   Update bit
273  *
274  *
275  * SJA1105 P/Q/R/S layout of the 8-byte SPI payload:
276  *
277  * 31    23    15    7     0     63    55    47    39    32
278  * |     |     |     |     |     |     |     |     |     |
279  *                         ^     +-----+-----+-----+-----+
280  *                         |                 ^
281  *                         |                 |
282  *                    Update bit    32-bit timestamp
283  *
284  * Notice that the update bit is in the same place.
285  * To have common code for E/T and P/Q/R/S for reading the timestamp,
286  * we need to juggle with the offset and the bit indices.
287  */
288 static int sja1105_ptpegr_ts_poll(struct dsa_switch *ds, int port, u64 *ts)
289 {
290 	struct sja1105_private *priv = ds->priv;
291 	const struct sja1105_regs *regs = priv->info->regs;
292 	int tstamp_bit_start, tstamp_bit_end;
293 	int timeout = 10;
294 	u8 packed_buf[8];
295 	u64 update;
296 	int rc;
297 
298 	do {
299 		rc = sja1105_xfer_buf(priv, SPI_READ, regs->ptpegr_ts[port],
300 				      packed_buf, priv->info->ptpegr_ts_bytes);
301 		if (rc < 0)
302 			return rc;
303 
304 		sja1105_unpack(packed_buf, &update, 0, 0,
305 			       priv->info->ptpegr_ts_bytes);
306 		if (update)
307 			break;
308 
309 		usleep_range(10, 50);
310 	} while (--timeout);
311 
312 	if (!timeout)
313 		return -ETIMEDOUT;
314 
315 	/* Point the end bit to the second 32-bit word on P/Q/R/S,
316 	 * no-op on E/T.
317 	 */
318 	tstamp_bit_end = (priv->info->ptpegr_ts_bytes - 4) * 8;
319 	/* Shift the 24-bit timestamp on E/T to be collected from 31:8.
320 	 * No-op on P/Q/R/S.
321 	 */
322 	tstamp_bit_end += 32 - priv->info->ptp_ts_bits;
323 	tstamp_bit_start = tstamp_bit_end + priv->info->ptp_ts_bits - 1;
324 
325 	*ts = 0;
326 
327 	sja1105_unpack(packed_buf, ts, tstamp_bit_start, tstamp_bit_end,
328 		       priv->info->ptpegr_ts_bytes);
329 
330 	return 0;
331 }
332 
333 /* Caller must hold ptp_data->lock */
334 static int sja1105_ptpclkval_read(struct sja1105_private *priv, u64 *ticks,
335 				  struct ptp_system_timestamp *ptp_sts)
336 {
337 	const struct sja1105_regs *regs = priv->info->regs;
338 
339 	return sja1105_xfer_u64(priv, SPI_READ, regs->ptpclkval, ticks,
340 				ptp_sts);
341 }
342 
343 /* Caller must hold ptp_data->lock */
344 static int sja1105_ptpclkval_write(struct sja1105_private *priv, u64 ticks,
345 				   struct ptp_system_timestamp *ptp_sts)
346 {
347 	const struct sja1105_regs *regs = priv->info->regs;
348 
349 	return sja1105_xfer_u64(priv, SPI_WRITE, regs->ptpclkval, &ticks,
350 				ptp_sts);
351 }
352 
353 static void sja1105_extts_poll(struct sja1105_private *priv)
354 {
355 	struct sja1105_ptp_data *ptp_data = &priv->ptp_data;
356 	const struct sja1105_regs *regs = priv->info->regs;
357 	struct ptp_clock_event event;
358 	u64 ptpsyncts = 0;
359 	int rc;
360 
361 	rc = sja1105_xfer_u64(priv, SPI_READ, regs->ptpsyncts, &ptpsyncts,
362 			      NULL);
363 	if (rc < 0)
364 		dev_err_ratelimited(priv->ds->dev,
365 				    "Failed to read PTPSYNCTS: %d\n", rc);
366 
367 	if (ptpsyncts && ptp_data->ptpsyncts != ptpsyncts) {
368 		event.index = 0;
369 		event.type = PTP_CLOCK_EXTTS;
370 		event.timestamp = ns_to_ktime(sja1105_ticks_to_ns(ptpsyncts));
371 		ptp_clock_event(ptp_data->clock, &event);
372 
373 		ptp_data->ptpsyncts = ptpsyncts;
374 	}
375 }
376 
377 static long sja1105_rxtstamp_work(struct ptp_clock_info *ptp)
378 {
379 	struct sja1105_ptp_data *ptp_data = ptp_caps_to_data(ptp);
380 	struct sja1105_private *priv = ptp_data_to_sja1105(ptp_data);
381 	struct dsa_switch *ds = priv->ds;
382 	struct sk_buff *skb;
383 
384 	mutex_lock(&ptp_data->lock);
385 
386 	while ((skb = skb_dequeue(&ptp_data->skb_rxtstamp_queue)) != NULL) {
387 		struct skb_shared_hwtstamps *shwt = skb_hwtstamps(skb);
388 		u64 ticks, ts;
389 		int rc;
390 
391 		rc = sja1105_ptpclkval_read(priv, &ticks, NULL);
392 		if (rc < 0) {
393 			dev_err(ds->dev, "Failed to read PTP clock: %d\n", rc);
394 			kfree_skb(skb);
395 			continue;
396 		}
397 
398 		*shwt = (struct skb_shared_hwtstamps) {0};
399 
400 		ts = SJA1105_SKB_CB(skb)->meta_tstamp;
401 		ts = sja1105_tstamp_reconstruct(ds, ticks, ts);
402 
403 		shwt->hwtstamp = ns_to_ktime(sja1105_ticks_to_ns(ts));
404 		netif_rx_ni(skb);
405 	}
406 
407 	if (ptp_data->extts_enabled)
408 		sja1105_extts_poll(priv);
409 
410 	mutex_unlock(&ptp_data->lock);
411 
412 	/* Don't restart */
413 	return -1;
414 }
415 
416 /* Called from dsa_skb_defer_rx_timestamp */
417 bool sja1105_port_rxtstamp(struct dsa_switch *ds, int port,
418 			   struct sk_buff *skb, unsigned int type)
419 {
420 	struct sja1105_private *priv = ds->priv;
421 	struct sja1105_ptp_data *ptp_data = &priv->ptp_data;
422 
423 	if (!test_bit(SJA1105_HWTS_RX_EN, &priv->tagger_data.state))
424 		return false;
425 
426 	/* We need to read the full PTP clock to reconstruct the Rx
427 	 * timestamp. For that we need a sleepable context.
428 	 */
429 	skb_queue_tail(&ptp_data->skb_rxtstamp_queue, skb);
430 	ptp_schedule_worker(ptp_data->clock, 0);
431 	return true;
432 }
433 
434 /* Called from dsa_skb_tx_timestamp. This callback is just to clone
435  * the skb and have it available in SJA1105_SKB_CB in the .port_deferred_xmit
436  * callback, where we will timestamp it synchronously.
437  */
438 void sja1105_port_txtstamp(struct dsa_switch *ds, int port, struct sk_buff *skb)
439 {
440 	struct sja1105_private *priv = ds->priv;
441 	struct sja1105_port *sp = &priv->ports[port];
442 	struct sk_buff *clone;
443 
444 	if (!sp->hwts_tx_en)
445 		return;
446 
447 	clone = skb_clone_sk(skb);
448 	if (!clone)
449 		return;
450 
451 	SJA1105_SKB_CB(skb)->clone = clone;
452 }
453 
454 static int sja1105_ptp_reset(struct dsa_switch *ds)
455 {
456 	struct sja1105_private *priv = ds->priv;
457 	struct sja1105_ptp_data *ptp_data = &priv->ptp_data;
458 	struct sja1105_ptp_cmd cmd = ptp_data->cmd;
459 	int rc;
460 
461 	mutex_lock(&ptp_data->lock);
462 
463 	cmd.resptp = 1;
464 
465 	dev_dbg(ds->dev, "Resetting PTP clock\n");
466 	rc = sja1105_ptp_commit(ds, &cmd, SPI_WRITE);
467 
468 	sja1105_tas_clockstep(priv->ds);
469 
470 	mutex_unlock(&ptp_data->lock);
471 
472 	return rc;
473 }
474 
475 /* Caller must hold ptp_data->lock */
476 int __sja1105_ptp_gettimex(struct dsa_switch *ds, u64 *ns,
477 			   struct ptp_system_timestamp *ptp_sts)
478 {
479 	struct sja1105_private *priv = ds->priv;
480 	u64 ticks;
481 	int rc;
482 
483 	rc = sja1105_ptpclkval_read(priv, &ticks, ptp_sts);
484 	if (rc < 0) {
485 		dev_err(ds->dev, "Failed to read PTP clock: %d\n", rc);
486 		return rc;
487 	}
488 
489 	*ns = sja1105_ticks_to_ns(ticks);
490 
491 	return 0;
492 }
493 
494 static int sja1105_ptp_gettimex(struct ptp_clock_info *ptp,
495 				struct timespec64 *ts,
496 				struct ptp_system_timestamp *ptp_sts)
497 {
498 	struct sja1105_ptp_data *ptp_data = ptp_caps_to_data(ptp);
499 	struct sja1105_private *priv = ptp_data_to_sja1105(ptp_data);
500 	u64 now = 0;
501 	int rc;
502 
503 	mutex_lock(&ptp_data->lock);
504 
505 	rc = __sja1105_ptp_gettimex(priv->ds, &now, ptp_sts);
506 	*ts = ns_to_timespec64(now);
507 
508 	mutex_unlock(&ptp_data->lock);
509 
510 	return rc;
511 }
512 
513 /* Caller must hold ptp_data->lock */
514 static int sja1105_ptp_mode_set(struct sja1105_private *priv,
515 				enum sja1105_ptp_clk_mode mode)
516 {
517 	struct sja1105_ptp_data *ptp_data = &priv->ptp_data;
518 
519 	if (ptp_data->cmd.ptpclkadd == mode)
520 		return 0;
521 
522 	ptp_data->cmd.ptpclkadd = mode;
523 
524 	return sja1105_ptp_commit(priv->ds, &ptp_data->cmd, SPI_WRITE);
525 }
526 
527 /* Write to PTPCLKVAL while PTPCLKADD is 0 */
528 int __sja1105_ptp_settime(struct dsa_switch *ds, u64 ns,
529 			  struct ptp_system_timestamp *ptp_sts)
530 {
531 	struct sja1105_private *priv = ds->priv;
532 	u64 ticks = ns_to_sja1105_ticks(ns);
533 	int rc;
534 
535 	rc = sja1105_ptp_mode_set(priv, PTP_SET_MODE);
536 	if (rc < 0) {
537 		dev_err(priv->ds->dev, "Failed to put PTPCLK in set mode\n");
538 		return rc;
539 	}
540 
541 	rc = sja1105_ptpclkval_write(priv, ticks, ptp_sts);
542 
543 	sja1105_tas_clockstep(priv->ds);
544 
545 	return rc;
546 }
547 
548 static int sja1105_ptp_settime(struct ptp_clock_info *ptp,
549 			       const struct timespec64 *ts)
550 {
551 	struct sja1105_ptp_data *ptp_data = ptp_caps_to_data(ptp);
552 	struct sja1105_private *priv = ptp_data_to_sja1105(ptp_data);
553 	u64 ns = timespec64_to_ns(ts);
554 	int rc;
555 
556 	mutex_lock(&ptp_data->lock);
557 
558 	rc = __sja1105_ptp_settime(priv->ds, ns, NULL);
559 
560 	mutex_unlock(&ptp_data->lock);
561 
562 	return rc;
563 }
564 
565 static int sja1105_ptp_adjfine(struct ptp_clock_info *ptp, long scaled_ppm)
566 {
567 	struct sja1105_ptp_data *ptp_data = ptp_caps_to_data(ptp);
568 	struct sja1105_private *priv = ptp_data_to_sja1105(ptp_data);
569 	const struct sja1105_regs *regs = priv->info->regs;
570 	u32 clkrate32;
571 	s64 clkrate;
572 	int rc;
573 
574 	clkrate = (s64)scaled_ppm * SJA1105_CC_MULT_NUM;
575 	clkrate = div_s64(clkrate, SJA1105_CC_MULT_DEM);
576 
577 	/* Take a +/- value and re-center it around 2^31. */
578 	clkrate = SJA1105_CC_MULT + clkrate;
579 	WARN_ON(abs(clkrate) >= GENMASK_ULL(31, 0));
580 	clkrate32 = clkrate;
581 
582 	mutex_lock(&ptp_data->lock);
583 
584 	rc = sja1105_xfer_u32(priv, SPI_WRITE, regs->ptpclkrate, &clkrate32,
585 			      NULL);
586 
587 	sja1105_tas_adjfreq(priv->ds);
588 
589 	mutex_unlock(&ptp_data->lock);
590 
591 	return rc;
592 }
593 
594 /* Write to PTPCLKVAL while PTPCLKADD is 1 */
595 int __sja1105_ptp_adjtime(struct dsa_switch *ds, s64 delta)
596 {
597 	struct sja1105_private *priv = ds->priv;
598 	s64 ticks = ns_to_sja1105_ticks(delta);
599 	int rc;
600 
601 	rc = sja1105_ptp_mode_set(priv, PTP_ADD_MODE);
602 	if (rc < 0) {
603 		dev_err(priv->ds->dev, "Failed to put PTPCLK in add mode\n");
604 		return rc;
605 	}
606 
607 	rc = sja1105_ptpclkval_write(priv, ticks, NULL);
608 
609 	sja1105_tas_clockstep(priv->ds);
610 
611 	return rc;
612 }
613 
614 static int sja1105_ptp_adjtime(struct ptp_clock_info *ptp, s64 delta)
615 {
616 	struct sja1105_ptp_data *ptp_data = ptp_caps_to_data(ptp);
617 	struct sja1105_private *priv = ptp_data_to_sja1105(ptp_data);
618 	int rc;
619 
620 	mutex_lock(&ptp_data->lock);
621 
622 	rc = __sja1105_ptp_adjtime(priv->ds, delta);
623 
624 	mutex_unlock(&ptp_data->lock);
625 
626 	return rc;
627 }
628 
629 static void sja1105_ptp_extts_setup_timer(struct sja1105_ptp_data *ptp_data)
630 {
631 	unsigned long expires = ((jiffies / SJA1105_EXTTS_INTERVAL) + 1) *
632 				SJA1105_EXTTS_INTERVAL;
633 
634 	mod_timer(&ptp_data->extts_timer, expires);
635 }
636 
637 static void sja1105_ptp_extts_timer(struct timer_list *t)
638 {
639 	struct sja1105_ptp_data *ptp_data = extts_to_data(t);
640 
641 	ptp_schedule_worker(ptp_data->clock, 0);
642 
643 	sja1105_ptp_extts_setup_timer(ptp_data);
644 }
645 
646 static int sja1105_change_ptp_clk_pin_func(struct sja1105_private *priv,
647 					   enum ptp_pin_function func)
648 {
649 	struct sja1105_avb_params_entry *avb;
650 	enum ptp_pin_function old_func;
651 
652 	avb = priv->static_config.tables[BLK_IDX_AVB_PARAMS].entries;
653 
654 	if (priv->info->device_id == SJA1105E_DEVICE_ID ||
655 	    priv->info->device_id == SJA1105T_DEVICE_ID ||
656 	    avb->cas_master)
657 		old_func = PTP_PF_PEROUT;
658 	else
659 		old_func = PTP_PF_EXTTS;
660 
661 	if (func == old_func)
662 		return 0;
663 
664 	avb->cas_master = (func == PTP_PF_PEROUT);
665 
666 	return sja1105_dynamic_config_write(priv, BLK_IDX_AVB_PARAMS, 0, avb,
667 					    true);
668 }
669 
670 /* The PTP_CLK pin may be configured to toggle with a 50% duty cycle and a
671  * frequency f:
672  *
673  *           NSEC_PER_SEC
674  * f = ----------------------
675  *     (PTPPINDUR * 8 ns) * 2
676  */
677 static int sja1105_per_out_enable(struct sja1105_private *priv,
678 				  struct ptp_perout_request *perout,
679 				  bool on)
680 {
681 	struct sja1105_ptp_data *ptp_data = &priv->ptp_data;
682 	const struct sja1105_regs *regs = priv->info->regs;
683 	struct sja1105_ptp_cmd cmd = ptp_data->cmd;
684 	int rc;
685 
686 	/* We only support one channel */
687 	if (perout->index != 0)
688 		return -EOPNOTSUPP;
689 
690 	/* Reject requests with unsupported flags */
691 	if (perout->flags)
692 		return -EOPNOTSUPP;
693 
694 	mutex_lock(&ptp_data->lock);
695 
696 	rc = sja1105_change_ptp_clk_pin_func(priv, PTP_PF_PEROUT);
697 	if (rc)
698 		goto out;
699 
700 	if (on) {
701 		struct timespec64 pin_duration_ts = {
702 			.tv_sec = perout->period.sec,
703 			.tv_nsec = perout->period.nsec,
704 		};
705 		struct timespec64 pin_start_ts = {
706 			.tv_sec = perout->start.sec,
707 			.tv_nsec = perout->start.nsec,
708 		};
709 		u64 pin_duration = timespec64_to_ns(&pin_duration_ts);
710 		u64 pin_start = timespec64_to_ns(&pin_start_ts);
711 		u32 pin_duration32;
712 		u64 now;
713 
714 		/* ptppindur: 32 bit register which holds the interval between
715 		 * 2 edges on PTP_CLK. So check for truncation which happens
716 		 * at periods larger than around 68.7 seconds.
717 		 */
718 		pin_duration = ns_to_sja1105_ticks(pin_duration / 2);
719 		if (pin_duration > U32_MAX) {
720 			rc = -ERANGE;
721 			goto out;
722 		}
723 		pin_duration32 = pin_duration;
724 
725 		/* ptppins: 64 bit register which needs to hold a PTP time
726 		 * larger than the current time, otherwise the startptpcp
727 		 * command won't do anything. So advance the current time
728 		 * by a number of periods in a way that won't alter the
729 		 * phase offset.
730 		 */
731 		rc = __sja1105_ptp_gettimex(priv->ds, &now, NULL);
732 		if (rc < 0)
733 			goto out;
734 
735 		pin_start = future_base_time(pin_start, pin_duration,
736 					     now + 1ull * NSEC_PER_SEC);
737 		pin_start = ns_to_sja1105_ticks(pin_start);
738 
739 		rc = sja1105_xfer_u64(priv, SPI_WRITE, regs->ptppinst,
740 				      &pin_start, NULL);
741 		if (rc < 0)
742 			goto out;
743 
744 		rc = sja1105_xfer_u32(priv, SPI_WRITE, regs->ptppindur,
745 				      &pin_duration32, NULL);
746 		if (rc < 0)
747 			goto out;
748 	}
749 
750 	if (on)
751 		cmd.startptpcp = true;
752 	else
753 		cmd.stopptpcp = true;
754 
755 	rc = sja1105_ptp_commit(priv->ds, &cmd, SPI_WRITE);
756 
757 out:
758 	mutex_unlock(&ptp_data->lock);
759 
760 	return rc;
761 }
762 
763 static int sja1105_extts_enable(struct sja1105_private *priv,
764 				struct ptp_extts_request *extts,
765 				bool on)
766 {
767 	int rc;
768 
769 	/* We only support one channel */
770 	if (extts->index != 0)
771 		return -EOPNOTSUPP;
772 
773 	/* Reject requests with unsupported flags */
774 	if (extts->flags & ~(PTP_ENABLE_FEATURE |
775 			     PTP_RISING_EDGE |
776 			     PTP_FALLING_EDGE |
777 			     PTP_STRICT_FLAGS))
778 		return -EOPNOTSUPP;
779 
780 	/* We can only enable time stamping on both edges, sadly. */
781 	if ((extts->flags & PTP_STRICT_FLAGS) &&
782 	    (extts->flags & PTP_ENABLE_FEATURE) &&
783 	    (extts->flags & PTP_EXTTS_EDGES) != PTP_EXTTS_EDGES)
784 		return -EOPNOTSUPP;
785 
786 	rc = sja1105_change_ptp_clk_pin_func(priv, PTP_PF_EXTTS);
787 	if (rc)
788 		return rc;
789 
790 	priv->ptp_data.extts_enabled = on;
791 
792 	if (on)
793 		sja1105_ptp_extts_setup_timer(&priv->ptp_data);
794 	else
795 		del_timer_sync(&priv->ptp_data.extts_timer);
796 
797 	return 0;
798 }
799 
800 static int sja1105_ptp_enable(struct ptp_clock_info *ptp,
801 			      struct ptp_clock_request *req, int on)
802 {
803 	struct sja1105_ptp_data *ptp_data = ptp_caps_to_data(ptp);
804 	struct sja1105_private *priv = ptp_data_to_sja1105(ptp_data);
805 	int rc = -EOPNOTSUPP;
806 
807 	if (req->type == PTP_CLK_REQ_PEROUT)
808 		rc = sja1105_per_out_enable(priv, &req->perout, on);
809 	else if (req->type == PTP_CLK_REQ_EXTTS)
810 		rc = sja1105_extts_enable(priv, &req->extts, on);
811 
812 	return rc;
813 }
814 
815 static int sja1105_ptp_verify_pin(struct ptp_clock_info *ptp, unsigned int pin,
816 				  enum ptp_pin_function func, unsigned int chan)
817 {
818 	struct sja1105_ptp_data *ptp_data = ptp_caps_to_data(ptp);
819 	struct sja1105_private *priv = ptp_data_to_sja1105(ptp_data);
820 
821 	if (chan != 0 || pin != 0)
822 		return -1;
823 
824 	switch (func) {
825 	case PTP_PF_NONE:
826 	case PTP_PF_PEROUT:
827 		break;
828 	case PTP_PF_EXTTS:
829 		if (priv->info->device_id == SJA1105E_DEVICE_ID ||
830 		    priv->info->device_id == SJA1105T_DEVICE_ID)
831 			return -1;
832 		break;
833 	default:
834 		return -1;
835 	}
836 	return 0;
837 }
838 
839 static struct ptp_pin_desc sja1105_ptp_pin = {
840 	.name = "ptp_clk",
841 	.index = 0,
842 	.func = PTP_PF_NONE,
843 };
844 
845 int sja1105_ptp_clock_register(struct dsa_switch *ds)
846 {
847 	struct sja1105_private *priv = ds->priv;
848 	struct sja1105_tagger_data *tagger_data = &priv->tagger_data;
849 	struct sja1105_ptp_data *ptp_data = &priv->ptp_data;
850 
851 	ptp_data->caps = (struct ptp_clock_info) {
852 		.owner		= THIS_MODULE,
853 		.name		= "SJA1105 PHC",
854 		.adjfine	= sja1105_ptp_adjfine,
855 		.adjtime	= sja1105_ptp_adjtime,
856 		.gettimex64	= sja1105_ptp_gettimex,
857 		.settime64	= sja1105_ptp_settime,
858 		.enable		= sja1105_ptp_enable,
859 		.verify		= sja1105_ptp_verify_pin,
860 		.do_aux_work	= sja1105_rxtstamp_work,
861 		.max_adj	= SJA1105_MAX_ADJ_PPB,
862 		.pin_config	= &sja1105_ptp_pin,
863 		.n_pins		= 1,
864 		.n_ext_ts	= 1,
865 		.n_per_out	= 1,
866 	};
867 
868 	skb_queue_head_init(&ptp_data->skb_rxtstamp_queue);
869 	spin_lock_init(&tagger_data->meta_lock);
870 
871 	ptp_data->clock = ptp_clock_register(&ptp_data->caps, ds->dev);
872 	if (IS_ERR_OR_NULL(ptp_data->clock))
873 		return PTR_ERR(ptp_data->clock);
874 
875 	ptp_data->cmd.corrclk4ts = true;
876 	ptp_data->cmd.ptpclkadd = PTP_SET_MODE;
877 
878 	timer_setup(&ptp_data->extts_timer, sja1105_ptp_extts_timer, 0);
879 
880 	return sja1105_ptp_reset(ds);
881 }
882 
883 void sja1105_ptp_clock_unregister(struct dsa_switch *ds)
884 {
885 	struct sja1105_private *priv = ds->priv;
886 	struct sja1105_ptp_data *ptp_data = &priv->ptp_data;
887 
888 	if (IS_ERR_OR_NULL(ptp_data->clock))
889 		return;
890 
891 	del_timer_sync(&ptp_data->extts_timer);
892 	ptp_cancel_worker_sync(ptp_data->clock);
893 	skb_queue_purge(&ptp_data->skb_rxtstamp_queue);
894 	ptp_clock_unregister(ptp_data->clock);
895 	ptp_data->clock = NULL;
896 }
897 
898 void sja1105_ptp_txtstamp_skb(struct dsa_switch *ds, int port,
899 			      struct sk_buff *skb)
900 {
901 	struct sja1105_private *priv = ds->priv;
902 	struct sja1105_ptp_data *ptp_data = &priv->ptp_data;
903 	struct skb_shared_hwtstamps shwt = {0};
904 	u64 ticks, ts;
905 	int rc;
906 
907 	skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
908 
909 	mutex_lock(&ptp_data->lock);
910 
911 	rc = sja1105_ptpegr_ts_poll(ds, port, &ts);
912 	if (rc < 0) {
913 		dev_err(ds->dev, "timed out polling for tstamp\n");
914 		kfree_skb(skb);
915 		goto out;
916 	}
917 
918 	rc = sja1105_ptpclkval_read(priv, &ticks, NULL);
919 	if (rc < 0) {
920 		dev_err(ds->dev, "Failed to read PTP clock: %d\n", rc);
921 		kfree_skb(skb);
922 		goto out;
923 	}
924 
925 	ts = sja1105_tstamp_reconstruct(ds, ticks, ts);
926 
927 	shwt.hwtstamp = ns_to_ktime(sja1105_ticks_to_ns(ts));
928 	skb_complete_tx_timestamp(skb, &shwt);
929 
930 out:
931 	mutex_unlock(&ptp_data->lock);
932 }
933