1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2018, Sensor-Technik Wiedemann GmbH
3  * Copyright (c) 2018-2019, Vladimir Oltean <olteanv@gmail.com>
4  */
5 
6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
7 
8 #include <linux/delay.h>
9 #include <linux/module.h>
10 #include <linux/printk.h>
11 #include <linux/spi/spi.h>
12 #include <linux/errno.h>
13 #include <linux/gpio/consumer.h>
14 #include <linux/phylink.h>
15 #include <linux/of.h>
16 #include <linux/of_net.h>
17 #include <linux/of_mdio.h>
18 #include <linux/of_device.h>
19 #include <linux/netdev_features.h>
20 #include <linux/netdevice.h>
21 #include <linux/if_bridge.h>
22 #include <linux/if_ether.h>
23 #include <linux/dsa/8021q.h>
24 #include "sja1105.h"
25 
26 static void sja1105_hw_reset(struct gpio_desc *gpio, unsigned int pulse_len,
27 			     unsigned int startup_delay)
28 {
29 	gpiod_set_value_cansleep(gpio, 1);
30 	/* Wait for minimum reset pulse length */
31 	msleep(pulse_len);
32 	gpiod_set_value_cansleep(gpio, 0);
33 	/* Wait until chip is ready after reset */
34 	msleep(startup_delay);
35 }
36 
37 static void
38 sja1105_port_allow_traffic(struct sja1105_l2_forwarding_entry *l2_fwd,
39 			   int from, int to, bool allow)
40 {
41 	if (allow) {
42 		l2_fwd[from].bc_domain  |= BIT(to);
43 		l2_fwd[from].reach_port |= BIT(to);
44 		l2_fwd[from].fl_domain  |= BIT(to);
45 	} else {
46 		l2_fwd[from].bc_domain  &= ~BIT(to);
47 		l2_fwd[from].reach_port &= ~BIT(to);
48 		l2_fwd[from].fl_domain  &= ~BIT(to);
49 	}
50 }
51 
52 /* Structure used to temporarily transport device tree
53  * settings into sja1105_setup
54  */
55 struct sja1105_dt_port {
56 	phy_interface_t phy_mode;
57 	sja1105_mii_role_t role;
58 };
59 
60 static int sja1105_init_mac_settings(struct sja1105_private *priv)
61 {
62 	struct sja1105_mac_config_entry default_mac = {
63 		/* Enable all 8 priority queues on egress.
64 		 * Every queue i holds top[i] - base[i] frames.
65 		 * Sum of top[i] - base[i] is 511 (max hardware limit).
66 		 */
67 		.top  = {0x3F, 0x7F, 0xBF, 0xFF, 0x13F, 0x17F, 0x1BF, 0x1FF},
68 		.base = {0x0, 0x40, 0x80, 0xC0, 0x100, 0x140, 0x180, 0x1C0},
69 		.enabled = {true, true, true, true, true, true, true, true},
70 		/* Keep standard IFG of 12 bytes on egress. */
71 		.ifg = 0,
72 		/* Always put the MAC speed in automatic mode, where it can be
73 		 * adjusted at runtime by PHYLINK.
74 		 */
75 		.speed = SJA1105_SPEED_AUTO,
76 		/* No static correction for 1-step 1588 events */
77 		.tp_delin = 0,
78 		.tp_delout = 0,
79 		/* Disable aging for critical TTEthernet traffic */
80 		.maxage = 0xFF,
81 		/* Internal VLAN (pvid) to apply to untagged ingress */
82 		.vlanprio = 0,
83 		.vlanid = 1,
84 		.ing_mirr = false,
85 		.egr_mirr = false,
86 		/* Don't drop traffic with other EtherType than ETH_P_IP */
87 		.drpnona664 = false,
88 		/* Don't drop double-tagged traffic */
89 		.drpdtag = false,
90 		/* Don't drop untagged traffic */
91 		.drpuntag = false,
92 		/* Don't retag 802.1p (VID 0) traffic with the pvid */
93 		.retag = false,
94 		/* Disable learning and I/O on user ports by default -
95 		 * STP will enable it.
96 		 */
97 		.dyn_learn = false,
98 		.egress = false,
99 		.ingress = false,
100 	};
101 	struct sja1105_mac_config_entry *mac;
102 	struct sja1105_table *table;
103 	int i;
104 
105 	table = &priv->static_config.tables[BLK_IDX_MAC_CONFIG];
106 
107 	/* Discard previous MAC Configuration Table */
108 	if (table->entry_count) {
109 		kfree(table->entries);
110 		table->entry_count = 0;
111 	}
112 
113 	table->entries = kcalloc(SJA1105_NUM_PORTS,
114 				 table->ops->unpacked_entry_size, GFP_KERNEL);
115 	if (!table->entries)
116 		return -ENOMEM;
117 
118 	table->entry_count = SJA1105_NUM_PORTS;
119 
120 	mac = table->entries;
121 
122 	for (i = 0; i < SJA1105_NUM_PORTS; i++) {
123 		mac[i] = default_mac;
124 		if (i == dsa_upstream_port(priv->ds, i)) {
125 			/* STP doesn't get called for CPU port, so we need to
126 			 * set the I/O parameters statically.
127 			 */
128 			mac[i].dyn_learn = true;
129 			mac[i].ingress = true;
130 			mac[i].egress = true;
131 		}
132 	}
133 
134 	return 0;
135 }
136 
137 static int sja1105_init_mii_settings(struct sja1105_private *priv,
138 				     struct sja1105_dt_port *ports)
139 {
140 	struct device *dev = &priv->spidev->dev;
141 	struct sja1105_xmii_params_entry *mii;
142 	struct sja1105_table *table;
143 	int i;
144 
145 	table = &priv->static_config.tables[BLK_IDX_XMII_PARAMS];
146 
147 	/* Discard previous xMII Mode Parameters Table */
148 	if (table->entry_count) {
149 		kfree(table->entries);
150 		table->entry_count = 0;
151 	}
152 
153 	table->entries = kcalloc(SJA1105_MAX_XMII_PARAMS_COUNT,
154 				 table->ops->unpacked_entry_size, GFP_KERNEL);
155 	if (!table->entries)
156 		return -ENOMEM;
157 
158 	/* Override table based on PHYLINK DT bindings */
159 	table->entry_count = SJA1105_MAX_XMII_PARAMS_COUNT;
160 
161 	mii = table->entries;
162 
163 	for (i = 0; i < SJA1105_NUM_PORTS; i++) {
164 		switch (ports[i].phy_mode) {
165 		case PHY_INTERFACE_MODE_MII:
166 			mii->xmii_mode[i] = XMII_MODE_MII;
167 			break;
168 		case PHY_INTERFACE_MODE_RMII:
169 			mii->xmii_mode[i] = XMII_MODE_RMII;
170 			break;
171 		case PHY_INTERFACE_MODE_RGMII:
172 		case PHY_INTERFACE_MODE_RGMII_ID:
173 		case PHY_INTERFACE_MODE_RGMII_RXID:
174 		case PHY_INTERFACE_MODE_RGMII_TXID:
175 			mii->xmii_mode[i] = XMII_MODE_RGMII;
176 			break;
177 		default:
178 			dev_err(dev, "Unsupported PHY mode %s!\n",
179 				phy_modes(ports[i].phy_mode));
180 		}
181 
182 		mii->phy_mac[i] = ports[i].role;
183 	}
184 	return 0;
185 }
186 
187 static int sja1105_init_static_fdb(struct sja1105_private *priv)
188 {
189 	struct sja1105_table *table;
190 
191 	table = &priv->static_config.tables[BLK_IDX_L2_LOOKUP];
192 
193 	/* We only populate the FDB table through dynamic
194 	 * L2 Address Lookup entries
195 	 */
196 	if (table->entry_count) {
197 		kfree(table->entries);
198 		table->entry_count = 0;
199 	}
200 	return 0;
201 }
202 
203 static int sja1105_init_l2_lookup_params(struct sja1105_private *priv)
204 {
205 	struct sja1105_table *table;
206 	u64 max_fdb_entries = SJA1105_MAX_L2_LOOKUP_COUNT / SJA1105_NUM_PORTS;
207 	struct sja1105_l2_lookup_params_entry default_l2_lookup_params = {
208 		/* Learned FDB entries are forgotten after 300 seconds */
209 		.maxage = SJA1105_AGEING_TIME_MS(300000),
210 		/* All entries within a FDB bin are available for learning */
211 		.dyn_tbsz = SJA1105ET_FDB_BIN_SIZE,
212 		/* And the P/Q/R/S equivalent setting: */
213 		.start_dynspc = 0,
214 		.maxaddrp = {max_fdb_entries, max_fdb_entries, max_fdb_entries,
215 			     max_fdb_entries, max_fdb_entries, },
216 		/* 2^8 + 2^5 + 2^3 + 2^2 + 2^1 + 1 in Koopman notation */
217 		.poly = 0x97,
218 		/* This selects between Independent VLAN Learning (IVL) and
219 		 * Shared VLAN Learning (SVL)
220 		 */
221 		.shared_learn = false,
222 		/* Don't discard management traffic based on ENFPORT -
223 		 * we don't perform SMAC port enforcement anyway, so
224 		 * what we are setting here doesn't matter.
225 		 */
226 		.no_enf_hostprt = false,
227 		/* Don't learn SMAC for mac_fltres1 and mac_fltres0.
228 		 * Maybe correlate with no_linklocal_learn from bridge driver?
229 		 */
230 		.no_mgmt_learn = true,
231 		/* P/Q/R/S only */
232 		.use_static = true,
233 		/* Dynamically learned FDB entries can overwrite other (older)
234 		 * dynamic FDB entries
235 		 */
236 		.owr_dyn = true,
237 		.drpnolearn = true,
238 	};
239 
240 	table = &priv->static_config.tables[BLK_IDX_L2_LOOKUP_PARAMS];
241 
242 	if (table->entry_count) {
243 		kfree(table->entries);
244 		table->entry_count = 0;
245 	}
246 
247 	table->entries = kcalloc(SJA1105_MAX_L2_LOOKUP_PARAMS_COUNT,
248 				 table->ops->unpacked_entry_size, GFP_KERNEL);
249 	if (!table->entries)
250 		return -ENOMEM;
251 
252 	table->entry_count = SJA1105_MAX_L2_LOOKUP_PARAMS_COUNT;
253 
254 	/* This table only has a single entry */
255 	((struct sja1105_l2_lookup_params_entry *)table->entries)[0] =
256 				default_l2_lookup_params;
257 
258 	return 0;
259 }
260 
261 static int sja1105_init_static_vlan(struct sja1105_private *priv)
262 {
263 	struct sja1105_table *table;
264 	struct sja1105_vlan_lookup_entry pvid = {
265 		.ving_mirr = 0,
266 		.vegr_mirr = 0,
267 		.vmemb_port = 0,
268 		.vlan_bc = 0,
269 		.tag_port = 0,
270 		.vlanid = 1,
271 	};
272 	int i;
273 
274 	table = &priv->static_config.tables[BLK_IDX_VLAN_LOOKUP];
275 
276 	/* The static VLAN table will only contain the initial pvid of 1.
277 	 * All other VLANs are to be configured through dynamic entries,
278 	 * and kept in the static configuration table as backing memory.
279 	 */
280 	if (table->entry_count) {
281 		kfree(table->entries);
282 		table->entry_count = 0;
283 	}
284 
285 	table->entries = kcalloc(1, table->ops->unpacked_entry_size,
286 				 GFP_KERNEL);
287 	if (!table->entries)
288 		return -ENOMEM;
289 
290 	table->entry_count = 1;
291 
292 	/* VLAN 1: all DT-defined ports are members; no restrictions on
293 	 * forwarding; always transmit priority-tagged frames as untagged.
294 	 */
295 	for (i = 0; i < SJA1105_NUM_PORTS; i++) {
296 		pvid.vmemb_port |= BIT(i);
297 		pvid.vlan_bc |= BIT(i);
298 		pvid.tag_port &= ~BIT(i);
299 	}
300 
301 	((struct sja1105_vlan_lookup_entry *)table->entries)[0] = pvid;
302 	return 0;
303 }
304 
305 static int sja1105_init_l2_forwarding(struct sja1105_private *priv)
306 {
307 	struct sja1105_l2_forwarding_entry *l2fwd;
308 	struct sja1105_table *table;
309 	int i, j;
310 
311 	table = &priv->static_config.tables[BLK_IDX_L2_FORWARDING];
312 
313 	if (table->entry_count) {
314 		kfree(table->entries);
315 		table->entry_count = 0;
316 	}
317 
318 	table->entries = kcalloc(SJA1105_MAX_L2_FORWARDING_COUNT,
319 				 table->ops->unpacked_entry_size, GFP_KERNEL);
320 	if (!table->entries)
321 		return -ENOMEM;
322 
323 	table->entry_count = SJA1105_MAX_L2_FORWARDING_COUNT;
324 
325 	l2fwd = table->entries;
326 
327 	/* First 5 entries define the forwarding rules */
328 	for (i = 0; i < SJA1105_NUM_PORTS; i++) {
329 		unsigned int upstream = dsa_upstream_port(priv->ds, i);
330 
331 		for (j = 0; j < SJA1105_NUM_TC; j++)
332 			l2fwd[i].vlan_pmap[j] = j;
333 
334 		if (i == upstream)
335 			continue;
336 
337 		sja1105_port_allow_traffic(l2fwd, i, upstream, true);
338 		sja1105_port_allow_traffic(l2fwd, upstream, i, true);
339 	}
340 	/* Next 8 entries define VLAN PCP mapping from ingress to egress.
341 	 * Create a one-to-one mapping.
342 	 */
343 	for (i = 0; i < SJA1105_NUM_TC; i++)
344 		for (j = 0; j < SJA1105_NUM_PORTS; j++)
345 			l2fwd[SJA1105_NUM_PORTS + i].vlan_pmap[j] = i;
346 
347 	return 0;
348 }
349 
350 static int sja1105_init_l2_forwarding_params(struct sja1105_private *priv)
351 {
352 	struct sja1105_l2_forwarding_params_entry default_l2fwd_params = {
353 		/* Disallow dynamic reconfiguration of vlan_pmap */
354 		.max_dynp = 0,
355 		/* Use a single memory partition for all ingress queues */
356 		.part_spc = { SJA1105_MAX_FRAME_MEMORY, 0, 0, 0, 0, 0, 0, 0 },
357 	};
358 	struct sja1105_table *table;
359 
360 	table = &priv->static_config.tables[BLK_IDX_L2_FORWARDING_PARAMS];
361 
362 	if (table->entry_count) {
363 		kfree(table->entries);
364 		table->entry_count = 0;
365 	}
366 
367 	table->entries = kcalloc(SJA1105_MAX_L2_FORWARDING_PARAMS_COUNT,
368 				 table->ops->unpacked_entry_size, GFP_KERNEL);
369 	if (!table->entries)
370 		return -ENOMEM;
371 
372 	table->entry_count = SJA1105_MAX_L2_FORWARDING_PARAMS_COUNT;
373 
374 	/* This table only has a single entry */
375 	((struct sja1105_l2_forwarding_params_entry *)table->entries)[0] =
376 				default_l2fwd_params;
377 
378 	return 0;
379 }
380 
381 static int sja1105_init_general_params(struct sja1105_private *priv)
382 {
383 	struct sja1105_general_params_entry default_general_params = {
384 		/* Disallow dynamic changing of the mirror port */
385 		.mirr_ptacu = 0,
386 		.switchid = priv->ds->index,
387 		/* Priority queue for link-local frames trapped to CPU */
388 		.hostprio = 7,
389 		.mac_fltres1 = SJA1105_LINKLOCAL_FILTER_A,
390 		.mac_flt1    = SJA1105_LINKLOCAL_FILTER_A_MASK,
391 		.incl_srcpt1 = false,
392 		.send_meta1  = false,
393 		.mac_fltres0 = SJA1105_LINKLOCAL_FILTER_B,
394 		.mac_flt0    = SJA1105_LINKLOCAL_FILTER_B_MASK,
395 		.incl_srcpt0 = false,
396 		.send_meta0  = false,
397 		/* The destination for traffic matching mac_fltres1 and
398 		 * mac_fltres0 on all ports except host_port. Such traffic
399 		 * receieved on host_port itself would be dropped, except
400 		 * by installing a temporary 'management route'
401 		 */
402 		.host_port = dsa_upstream_port(priv->ds, 0),
403 		/* Same as host port */
404 		.mirr_port = dsa_upstream_port(priv->ds, 0),
405 		/* Link-local traffic received on casc_port will be forwarded
406 		 * to host_port without embedding the source port and device ID
407 		 * info in the destination MAC address (presumably because it
408 		 * is a cascaded port and a downstream SJA switch already did
409 		 * that). Default to an invalid port (to disable the feature)
410 		 * and overwrite this if we find any DSA (cascaded) ports.
411 		 */
412 		.casc_port = SJA1105_NUM_PORTS,
413 		/* No TTEthernet */
414 		.vllupformat = 0,
415 		.vlmarker = 0,
416 		.vlmask = 0,
417 		/* Only update correctionField for 1-step PTP (L2 transport) */
418 		.ignore2stf = 0,
419 		/* Forcefully disable VLAN filtering by telling
420 		 * the switch that VLAN has a different EtherType.
421 		 */
422 		.tpid = ETH_P_SJA1105,
423 		.tpid2 = ETH_P_SJA1105,
424 	};
425 	struct sja1105_table *table;
426 	int i, k = 0;
427 
428 	for (i = 0; i < SJA1105_NUM_PORTS; i++) {
429 		if (dsa_is_dsa_port(priv->ds, i))
430 			default_general_params.casc_port = i;
431 		else if (dsa_is_user_port(priv->ds, i))
432 			priv->ports[i].mgmt_slot = k++;
433 	}
434 
435 	table = &priv->static_config.tables[BLK_IDX_GENERAL_PARAMS];
436 
437 	if (table->entry_count) {
438 		kfree(table->entries);
439 		table->entry_count = 0;
440 	}
441 
442 	table->entries = kcalloc(SJA1105_MAX_GENERAL_PARAMS_COUNT,
443 				 table->ops->unpacked_entry_size, GFP_KERNEL);
444 	if (!table->entries)
445 		return -ENOMEM;
446 
447 	table->entry_count = SJA1105_MAX_GENERAL_PARAMS_COUNT;
448 
449 	/* This table only has a single entry */
450 	((struct sja1105_general_params_entry *)table->entries)[0] =
451 				default_general_params;
452 
453 	return 0;
454 }
455 
456 #define SJA1105_RATE_MBPS(speed) (((speed) * 64000) / 1000)
457 
458 static inline void
459 sja1105_setup_policer(struct sja1105_l2_policing_entry *policing,
460 		      int index)
461 {
462 	policing[index].sharindx = index;
463 	policing[index].smax = 65535; /* Burst size in bytes */
464 	policing[index].rate = SJA1105_RATE_MBPS(1000);
465 	policing[index].maxlen = ETH_FRAME_LEN + VLAN_HLEN + ETH_FCS_LEN;
466 	policing[index].partition = 0;
467 }
468 
469 static int sja1105_init_l2_policing(struct sja1105_private *priv)
470 {
471 	struct sja1105_l2_policing_entry *policing;
472 	struct sja1105_table *table;
473 	int i, j, k;
474 
475 	table = &priv->static_config.tables[BLK_IDX_L2_POLICING];
476 
477 	/* Discard previous L2 Policing Table */
478 	if (table->entry_count) {
479 		kfree(table->entries);
480 		table->entry_count = 0;
481 	}
482 
483 	table->entries = kcalloc(SJA1105_MAX_L2_POLICING_COUNT,
484 				 table->ops->unpacked_entry_size, GFP_KERNEL);
485 	if (!table->entries)
486 		return -ENOMEM;
487 
488 	table->entry_count = SJA1105_MAX_L2_POLICING_COUNT;
489 
490 	policing = table->entries;
491 
492 	/* k sweeps through all unicast policers (0-39).
493 	 * bcast sweeps through policers 40-44.
494 	 */
495 	for (i = 0, k = 0; i < SJA1105_NUM_PORTS; i++) {
496 		int bcast = (SJA1105_NUM_PORTS * SJA1105_NUM_TC) + i;
497 
498 		for (j = 0; j < SJA1105_NUM_TC; j++, k++)
499 			sja1105_setup_policer(policing, k);
500 
501 		/* Set up this port's policer for broadcast traffic */
502 		sja1105_setup_policer(policing, bcast);
503 	}
504 	return 0;
505 }
506 
507 static int sja1105_init_avb_params(struct sja1105_private *priv,
508 				   bool on)
509 {
510 	struct sja1105_avb_params_entry *avb;
511 	struct sja1105_table *table;
512 
513 	table = &priv->static_config.tables[BLK_IDX_AVB_PARAMS];
514 
515 	/* Discard previous AVB Parameters Table */
516 	if (table->entry_count) {
517 		kfree(table->entries);
518 		table->entry_count = 0;
519 	}
520 
521 	/* Configure the reception of meta frames only if requested */
522 	if (!on)
523 		return 0;
524 
525 	table->entries = kcalloc(SJA1105_MAX_AVB_PARAMS_COUNT,
526 				 table->ops->unpacked_entry_size, GFP_KERNEL);
527 	if (!table->entries)
528 		return -ENOMEM;
529 
530 	table->entry_count = SJA1105_MAX_AVB_PARAMS_COUNT;
531 
532 	avb = table->entries;
533 
534 	avb->destmeta = SJA1105_META_DMAC;
535 	avb->srcmeta  = SJA1105_META_SMAC;
536 
537 	return 0;
538 }
539 
540 static int sja1105_static_config_load(struct sja1105_private *priv,
541 				      struct sja1105_dt_port *ports)
542 {
543 	int rc;
544 
545 	sja1105_static_config_free(&priv->static_config);
546 	rc = sja1105_static_config_init(&priv->static_config,
547 					priv->info->static_ops,
548 					priv->info->device_id);
549 	if (rc)
550 		return rc;
551 
552 	/* Build static configuration */
553 	rc = sja1105_init_mac_settings(priv);
554 	if (rc < 0)
555 		return rc;
556 	rc = sja1105_init_mii_settings(priv, ports);
557 	if (rc < 0)
558 		return rc;
559 	rc = sja1105_init_static_fdb(priv);
560 	if (rc < 0)
561 		return rc;
562 	rc = sja1105_init_static_vlan(priv);
563 	if (rc < 0)
564 		return rc;
565 	rc = sja1105_init_l2_lookup_params(priv);
566 	if (rc < 0)
567 		return rc;
568 	rc = sja1105_init_l2_forwarding(priv);
569 	if (rc < 0)
570 		return rc;
571 	rc = sja1105_init_l2_forwarding_params(priv);
572 	if (rc < 0)
573 		return rc;
574 	rc = sja1105_init_l2_policing(priv);
575 	if (rc < 0)
576 		return rc;
577 	rc = sja1105_init_general_params(priv);
578 	if (rc < 0)
579 		return rc;
580 	rc = sja1105_init_avb_params(priv, false);
581 	if (rc < 0)
582 		return rc;
583 
584 	/* Send initial configuration to hardware via SPI */
585 	return sja1105_static_config_upload(priv);
586 }
587 
588 static int sja1105_parse_rgmii_delays(struct sja1105_private *priv,
589 				      const struct sja1105_dt_port *ports)
590 {
591 	int i;
592 
593 	for (i = 0; i < SJA1105_NUM_PORTS; i++) {
594 		if (ports->role == XMII_MAC)
595 			continue;
596 
597 		if (ports->phy_mode == PHY_INTERFACE_MODE_RGMII_RXID ||
598 		    ports->phy_mode == PHY_INTERFACE_MODE_RGMII_ID)
599 			priv->rgmii_rx_delay[i] = true;
600 
601 		if (ports->phy_mode == PHY_INTERFACE_MODE_RGMII_TXID ||
602 		    ports->phy_mode == PHY_INTERFACE_MODE_RGMII_ID)
603 			priv->rgmii_tx_delay[i] = true;
604 
605 		if ((priv->rgmii_rx_delay[i] || priv->rgmii_tx_delay[i]) &&
606 		     !priv->info->setup_rgmii_delay)
607 			return -EINVAL;
608 	}
609 	return 0;
610 }
611 
612 static int sja1105_parse_ports_node(struct sja1105_private *priv,
613 				    struct sja1105_dt_port *ports,
614 				    struct device_node *ports_node)
615 {
616 	struct device *dev = &priv->spidev->dev;
617 	struct device_node *child;
618 
619 	for_each_child_of_node(ports_node, child) {
620 		struct device_node *phy_node;
621 		int phy_mode;
622 		u32 index;
623 
624 		/* Get switch port number from DT */
625 		if (of_property_read_u32(child, "reg", &index) < 0) {
626 			dev_err(dev, "Port number not defined in device tree "
627 				"(property \"reg\")\n");
628 			return -ENODEV;
629 		}
630 
631 		/* Get PHY mode from DT */
632 		phy_mode = of_get_phy_mode(child);
633 		if (phy_mode < 0) {
634 			dev_err(dev, "Failed to read phy-mode or "
635 				"phy-interface-type property for port %d\n",
636 				index);
637 			return -ENODEV;
638 		}
639 		ports[index].phy_mode = phy_mode;
640 
641 		phy_node = of_parse_phandle(child, "phy-handle", 0);
642 		if (!phy_node) {
643 			if (!of_phy_is_fixed_link(child)) {
644 				dev_err(dev, "phy-handle or fixed-link "
645 					"properties missing!\n");
646 				return -ENODEV;
647 			}
648 			/* phy-handle is missing, but fixed-link isn't.
649 			 * So it's a fixed link. Default to PHY role.
650 			 */
651 			ports[index].role = XMII_PHY;
652 		} else {
653 			/* phy-handle present => put port in MAC role */
654 			ports[index].role = XMII_MAC;
655 			of_node_put(phy_node);
656 		}
657 
658 		/* The MAC/PHY role can be overridden with explicit bindings */
659 		if (of_property_read_bool(child, "sja1105,role-mac"))
660 			ports[index].role = XMII_MAC;
661 		else if (of_property_read_bool(child, "sja1105,role-phy"))
662 			ports[index].role = XMII_PHY;
663 	}
664 
665 	return 0;
666 }
667 
668 static int sja1105_parse_dt(struct sja1105_private *priv,
669 			    struct sja1105_dt_port *ports)
670 {
671 	struct device *dev = &priv->spidev->dev;
672 	struct device_node *switch_node = dev->of_node;
673 	struct device_node *ports_node;
674 	int rc;
675 
676 	ports_node = of_get_child_by_name(switch_node, "ports");
677 	if (!ports_node) {
678 		dev_err(dev, "Incorrect bindings: absent \"ports\" node\n");
679 		return -ENODEV;
680 	}
681 
682 	rc = sja1105_parse_ports_node(priv, ports, ports_node);
683 	of_node_put(ports_node);
684 
685 	return rc;
686 }
687 
688 /* Convert link speed from SJA1105 to ethtool encoding */
689 static int sja1105_speed[] = {
690 	[SJA1105_SPEED_AUTO]		= SPEED_UNKNOWN,
691 	[SJA1105_SPEED_10MBPS]		= SPEED_10,
692 	[SJA1105_SPEED_100MBPS]		= SPEED_100,
693 	[SJA1105_SPEED_1000MBPS]	= SPEED_1000,
694 };
695 
696 /* Set link speed in the MAC configuration for a specific port. */
697 static int sja1105_adjust_port_config(struct sja1105_private *priv, int port,
698 				      int speed_mbps)
699 {
700 	struct sja1105_xmii_params_entry *mii;
701 	struct sja1105_mac_config_entry *mac;
702 	struct device *dev = priv->ds->dev;
703 	sja1105_phy_interface_t phy_mode;
704 	sja1105_speed_t speed;
705 	int rc;
706 
707 	/* On P/Q/R/S, one can read from the device via the MAC reconfiguration
708 	 * tables. On E/T, MAC reconfig tables are not readable, only writable.
709 	 * We have to *know* what the MAC looks like.  For the sake of keeping
710 	 * the code common, we'll use the static configuration tables as a
711 	 * reasonable approximation for both E/T and P/Q/R/S.
712 	 */
713 	mac = priv->static_config.tables[BLK_IDX_MAC_CONFIG].entries;
714 	mii = priv->static_config.tables[BLK_IDX_XMII_PARAMS].entries;
715 
716 	switch (speed_mbps) {
717 	case SPEED_UNKNOWN:
718 		/* PHYLINK called sja1105_mac_config() to inform us about
719 		 * the state->interface, but AN has not completed and the
720 		 * speed is not yet valid. UM10944.pdf says that setting
721 		 * SJA1105_SPEED_AUTO at runtime disables the port, so that is
722 		 * ok for power consumption in case AN will never complete -
723 		 * otherwise PHYLINK should come back with a new update.
724 		 */
725 		speed = SJA1105_SPEED_AUTO;
726 		break;
727 	case SPEED_10:
728 		speed = SJA1105_SPEED_10MBPS;
729 		break;
730 	case SPEED_100:
731 		speed = SJA1105_SPEED_100MBPS;
732 		break;
733 	case SPEED_1000:
734 		speed = SJA1105_SPEED_1000MBPS;
735 		break;
736 	default:
737 		dev_err(dev, "Invalid speed %iMbps\n", speed_mbps);
738 		return -EINVAL;
739 	}
740 
741 	/* Overwrite SJA1105_SPEED_AUTO from the static MAC configuration
742 	 * table, since this will be used for the clocking setup, and we no
743 	 * longer need to store it in the static config (already told hardware
744 	 * we want auto during upload phase).
745 	 */
746 	mac[port].speed = speed;
747 
748 	/* Write to the dynamic reconfiguration tables */
749 	rc = sja1105_dynamic_config_write(priv, BLK_IDX_MAC_CONFIG, port,
750 					  &mac[port], true);
751 	if (rc < 0) {
752 		dev_err(dev, "Failed to write MAC config: %d\n", rc);
753 		return rc;
754 	}
755 
756 	/* Reconfigure the PLLs for the RGMII interfaces (required 125 MHz at
757 	 * gigabit, 25 MHz at 100 Mbps and 2.5 MHz at 10 Mbps). For MII and
758 	 * RMII no change of the clock setup is required. Actually, changing
759 	 * the clock setup does interrupt the clock signal for a certain time
760 	 * which causes trouble for all PHYs relying on this signal.
761 	 */
762 	phy_mode = mii->xmii_mode[port];
763 	if (phy_mode != XMII_MODE_RGMII)
764 		return 0;
765 
766 	return sja1105_clocking_setup_port(priv, port);
767 }
768 
769 /* The SJA1105 MAC programming model is through the static config (the xMII
770  * Mode table cannot be dynamically reconfigured), and we have to program
771  * that early (earlier than PHYLINK calls us, anyway).
772  * So just error out in case the connected PHY attempts to change the initial
773  * system interface MII protocol from what is defined in the DT, at least for
774  * now.
775  */
776 static bool sja1105_phy_mode_mismatch(struct sja1105_private *priv, int port,
777 				      phy_interface_t interface)
778 {
779 	struct sja1105_xmii_params_entry *mii;
780 	sja1105_phy_interface_t phy_mode;
781 
782 	mii = priv->static_config.tables[BLK_IDX_XMII_PARAMS].entries;
783 	phy_mode = mii->xmii_mode[port];
784 
785 	switch (interface) {
786 	case PHY_INTERFACE_MODE_MII:
787 		return (phy_mode != XMII_MODE_MII);
788 	case PHY_INTERFACE_MODE_RMII:
789 		return (phy_mode != XMII_MODE_RMII);
790 	case PHY_INTERFACE_MODE_RGMII:
791 	case PHY_INTERFACE_MODE_RGMII_ID:
792 	case PHY_INTERFACE_MODE_RGMII_RXID:
793 	case PHY_INTERFACE_MODE_RGMII_TXID:
794 		return (phy_mode != XMII_MODE_RGMII);
795 	default:
796 		return true;
797 	}
798 }
799 
800 static void sja1105_mac_config(struct dsa_switch *ds, int port,
801 			       unsigned int link_an_mode,
802 			       const struct phylink_link_state *state)
803 {
804 	struct sja1105_private *priv = ds->priv;
805 
806 	if (sja1105_phy_mode_mismatch(priv, port, state->interface))
807 		return;
808 
809 	if (link_an_mode == MLO_AN_INBAND) {
810 		dev_err(ds->dev, "In-band AN not supported!\n");
811 		return;
812 	}
813 
814 	sja1105_adjust_port_config(priv, port, state->speed);
815 }
816 
817 static void sja1105_mac_link_down(struct dsa_switch *ds, int port,
818 				  unsigned int mode,
819 				  phy_interface_t interface)
820 {
821 	sja1105_inhibit_tx(ds->priv, BIT(port), true);
822 }
823 
824 static void sja1105_mac_link_up(struct dsa_switch *ds, int port,
825 				unsigned int mode,
826 				phy_interface_t interface,
827 				struct phy_device *phydev)
828 {
829 	sja1105_inhibit_tx(ds->priv, BIT(port), false);
830 }
831 
832 static void sja1105_phylink_validate(struct dsa_switch *ds, int port,
833 				     unsigned long *supported,
834 				     struct phylink_link_state *state)
835 {
836 	/* Construct a new mask which exhaustively contains all link features
837 	 * supported by the MAC, and then apply that (logical AND) to what will
838 	 * be sent to the PHY for "marketing".
839 	 */
840 	__ETHTOOL_DECLARE_LINK_MODE_MASK(mask) = { 0, };
841 	struct sja1105_private *priv = ds->priv;
842 	struct sja1105_xmii_params_entry *mii;
843 
844 	mii = priv->static_config.tables[BLK_IDX_XMII_PARAMS].entries;
845 
846 	/* include/linux/phylink.h says:
847 	 *     When @state->interface is %PHY_INTERFACE_MODE_NA, phylink
848 	 *     expects the MAC driver to return all supported link modes.
849 	 */
850 	if (state->interface != PHY_INTERFACE_MODE_NA &&
851 	    sja1105_phy_mode_mismatch(priv, port, state->interface)) {
852 		bitmap_zero(supported, __ETHTOOL_LINK_MODE_MASK_NBITS);
853 		return;
854 	}
855 
856 	/* The MAC does not support pause frames, and also doesn't
857 	 * support half-duplex traffic modes.
858 	 */
859 	phylink_set(mask, Autoneg);
860 	phylink_set(mask, MII);
861 	phylink_set(mask, 10baseT_Full);
862 	phylink_set(mask, 100baseT_Full);
863 	if (mii->xmii_mode[port] == XMII_MODE_RGMII)
864 		phylink_set(mask, 1000baseT_Full);
865 
866 	bitmap_and(supported, supported, mask, __ETHTOOL_LINK_MODE_MASK_NBITS);
867 	bitmap_and(state->advertising, state->advertising, mask,
868 		   __ETHTOOL_LINK_MODE_MASK_NBITS);
869 }
870 
871 static int
872 sja1105_find_static_fdb_entry(struct sja1105_private *priv, int port,
873 			      const struct sja1105_l2_lookup_entry *requested)
874 {
875 	struct sja1105_l2_lookup_entry *l2_lookup;
876 	struct sja1105_table *table;
877 	int i;
878 
879 	table = &priv->static_config.tables[BLK_IDX_L2_LOOKUP];
880 	l2_lookup = table->entries;
881 
882 	for (i = 0; i < table->entry_count; i++)
883 		if (l2_lookup[i].macaddr == requested->macaddr &&
884 		    l2_lookup[i].vlanid == requested->vlanid &&
885 		    l2_lookup[i].destports & BIT(port))
886 			return i;
887 
888 	return -1;
889 }
890 
891 /* We want FDB entries added statically through the bridge command to persist
892  * across switch resets, which are a common thing during normal SJA1105
893  * operation. So we have to back them up in the static configuration tables
894  * and hence apply them on next static config upload... yay!
895  */
896 static int
897 sja1105_static_fdb_change(struct sja1105_private *priv, int port,
898 			  const struct sja1105_l2_lookup_entry *requested,
899 			  bool keep)
900 {
901 	struct sja1105_l2_lookup_entry *l2_lookup;
902 	struct sja1105_table *table;
903 	int rc, match;
904 
905 	table = &priv->static_config.tables[BLK_IDX_L2_LOOKUP];
906 
907 	match = sja1105_find_static_fdb_entry(priv, port, requested);
908 	if (match < 0) {
909 		/* Can't delete a missing entry. */
910 		if (!keep)
911 			return 0;
912 
913 		/* No match => new entry */
914 		rc = sja1105_table_resize(table, table->entry_count + 1);
915 		if (rc)
916 			return rc;
917 
918 		match = table->entry_count - 1;
919 	}
920 
921 	/* Assign pointer after the resize (it may be new memory) */
922 	l2_lookup = table->entries;
923 
924 	/* We have a match.
925 	 * If the job was to add this FDB entry, it's already done (mostly
926 	 * anyway, since the port forwarding mask may have changed, case in
927 	 * which we update it).
928 	 * Otherwise we have to delete it.
929 	 */
930 	if (keep) {
931 		l2_lookup[match] = *requested;
932 		return 0;
933 	}
934 
935 	/* To remove, the strategy is to overwrite the element with
936 	 * the last one, and then reduce the array size by 1
937 	 */
938 	l2_lookup[match] = l2_lookup[table->entry_count - 1];
939 	return sja1105_table_resize(table, table->entry_count - 1);
940 }
941 
942 /* First-generation switches have a 4-way set associative TCAM that
943  * holds the FDB entries. An FDB index spans from 0 to 1023 and is comprised of
944  * a "bin" (grouping of 4 entries) and a "way" (an entry within a bin).
945  * For the placement of a newly learnt FDB entry, the switch selects the bin
946  * based on a hash function, and the way within that bin incrementally.
947  */
948 static inline int sja1105et_fdb_index(int bin, int way)
949 {
950 	return bin * SJA1105ET_FDB_BIN_SIZE + way;
951 }
952 
953 static int sja1105et_is_fdb_entry_in_bin(struct sja1105_private *priv, int bin,
954 					 const u8 *addr, u16 vid,
955 					 struct sja1105_l2_lookup_entry *match,
956 					 int *last_unused)
957 {
958 	int way;
959 
960 	for (way = 0; way < SJA1105ET_FDB_BIN_SIZE; way++) {
961 		struct sja1105_l2_lookup_entry l2_lookup = {0};
962 		int index = sja1105et_fdb_index(bin, way);
963 
964 		/* Skip unused entries, optionally marking them
965 		 * into the return value
966 		 */
967 		if (sja1105_dynamic_config_read(priv, BLK_IDX_L2_LOOKUP,
968 						index, &l2_lookup)) {
969 			if (last_unused)
970 				*last_unused = way;
971 			continue;
972 		}
973 
974 		if (l2_lookup.macaddr == ether_addr_to_u64(addr) &&
975 		    l2_lookup.vlanid == vid) {
976 			if (match)
977 				*match = l2_lookup;
978 			return way;
979 		}
980 	}
981 	/* Return an invalid entry index if not found */
982 	return -1;
983 }
984 
985 int sja1105et_fdb_add(struct dsa_switch *ds, int port,
986 		      const unsigned char *addr, u16 vid)
987 {
988 	struct sja1105_l2_lookup_entry l2_lookup = {0};
989 	struct sja1105_private *priv = ds->priv;
990 	struct device *dev = ds->dev;
991 	int last_unused = -1;
992 	int bin, way, rc;
993 
994 	bin = sja1105et_fdb_hash(priv, addr, vid);
995 
996 	way = sja1105et_is_fdb_entry_in_bin(priv, bin, addr, vid,
997 					    &l2_lookup, &last_unused);
998 	if (way >= 0) {
999 		/* We have an FDB entry. Is our port in the destination
1000 		 * mask? If yes, we need to do nothing. If not, we need
1001 		 * to rewrite the entry by adding this port to it.
1002 		 */
1003 		if (l2_lookup.destports & BIT(port))
1004 			return 0;
1005 		l2_lookup.destports |= BIT(port);
1006 	} else {
1007 		int index = sja1105et_fdb_index(bin, way);
1008 
1009 		/* We don't have an FDB entry. We construct a new one and
1010 		 * try to find a place for it within the FDB table.
1011 		 */
1012 		l2_lookup.macaddr = ether_addr_to_u64(addr);
1013 		l2_lookup.destports = BIT(port);
1014 		l2_lookup.vlanid = vid;
1015 
1016 		if (last_unused >= 0) {
1017 			way = last_unused;
1018 		} else {
1019 			/* Bin is full, need to evict somebody.
1020 			 * Choose victim at random. If you get these messages
1021 			 * often, you may need to consider changing the
1022 			 * distribution function:
1023 			 * static_config[BLK_IDX_L2_LOOKUP_PARAMS].entries->poly
1024 			 */
1025 			get_random_bytes(&way, sizeof(u8));
1026 			way %= SJA1105ET_FDB_BIN_SIZE;
1027 			dev_warn(dev, "Warning, FDB bin %d full while adding entry for %pM. Evicting entry %u.\n",
1028 				 bin, addr, way);
1029 			/* Evict entry */
1030 			sja1105_dynamic_config_write(priv, BLK_IDX_L2_LOOKUP,
1031 						     index, NULL, false);
1032 		}
1033 	}
1034 	l2_lookup.index = sja1105et_fdb_index(bin, way);
1035 
1036 	rc = sja1105_dynamic_config_write(priv, BLK_IDX_L2_LOOKUP,
1037 					  l2_lookup.index, &l2_lookup,
1038 					  true);
1039 	if (rc < 0)
1040 		return rc;
1041 
1042 	return sja1105_static_fdb_change(priv, port, &l2_lookup, true);
1043 }
1044 
1045 int sja1105et_fdb_del(struct dsa_switch *ds, int port,
1046 		      const unsigned char *addr, u16 vid)
1047 {
1048 	struct sja1105_l2_lookup_entry l2_lookup = {0};
1049 	struct sja1105_private *priv = ds->priv;
1050 	int index, bin, way, rc;
1051 	bool keep;
1052 
1053 	bin = sja1105et_fdb_hash(priv, addr, vid);
1054 	way = sja1105et_is_fdb_entry_in_bin(priv, bin, addr, vid,
1055 					    &l2_lookup, NULL);
1056 	if (way < 0)
1057 		return 0;
1058 	index = sja1105et_fdb_index(bin, way);
1059 
1060 	/* We have an FDB entry. Is our port in the destination mask? If yes,
1061 	 * we need to remove it. If the resulting port mask becomes empty, we
1062 	 * need to completely evict the FDB entry.
1063 	 * Otherwise we just write it back.
1064 	 */
1065 	l2_lookup.destports &= ~BIT(port);
1066 
1067 	if (l2_lookup.destports)
1068 		keep = true;
1069 	else
1070 		keep = false;
1071 
1072 	rc = sja1105_dynamic_config_write(priv, BLK_IDX_L2_LOOKUP,
1073 					  index, &l2_lookup, keep);
1074 	if (rc < 0)
1075 		return rc;
1076 
1077 	return sja1105_static_fdb_change(priv, port, &l2_lookup, keep);
1078 }
1079 
1080 int sja1105pqrs_fdb_add(struct dsa_switch *ds, int port,
1081 			const unsigned char *addr, u16 vid)
1082 {
1083 	struct sja1105_l2_lookup_entry l2_lookup = {0};
1084 	struct sja1105_private *priv = ds->priv;
1085 	int rc, i;
1086 
1087 	/* Search for an existing entry in the FDB table */
1088 	l2_lookup.macaddr = ether_addr_to_u64(addr);
1089 	l2_lookup.vlanid = vid;
1090 	l2_lookup.iotag = SJA1105_S_TAG;
1091 	l2_lookup.mask_macaddr = GENMASK_ULL(ETH_ALEN * 8 - 1, 0);
1092 	l2_lookup.mask_vlanid = VLAN_VID_MASK;
1093 	l2_lookup.mask_iotag = BIT(0);
1094 	l2_lookup.destports = BIT(port);
1095 
1096 	rc = sja1105_dynamic_config_read(priv, BLK_IDX_L2_LOOKUP,
1097 					 SJA1105_SEARCH, &l2_lookup);
1098 	if (rc == 0) {
1099 		/* Found and this port is already in the entry's
1100 		 * port mask => job done
1101 		 */
1102 		if (l2_lookup.destports & BIT(port))
1103 			return 0;
1104 		/* l2_lookup.index is populated by the switch in case it
1105 		 * found something.
1106 		 */
1107 		l2_lookup.destports |= BIT(port);
1108 		goto skip_finding_an_index;
1109 	}
1110 
1111 	/* Not found, so try to find an unused spot in the FDB.
1112 	 * This is slightly inefficient because the strategy is knock-knock at
1113 	 * every possible position from 0 to 1023.
1114 	 */
1115 	for (i = 0; i < SJA1105_MAX_L2_LOOKUP_COUNT; i++) {
1116 		rc = sja1105_dynamic_config_read(priv, BLK_IDX_L2_LOOKUP,
1117 						 i, NULL);
1118 		if (rc < 0)
1119 			break;
1120 	}
1121 	if (i == SJA1105_MAX_L2_LOOKUP_COUNT) {
1122 		dev_err(ds->dev, "FDB is full, cannot add entry.\n");
1123 		return -EINVAL;
1124 	}
1125 	l2_lookup.lockeds = true;
1126 	l2_lookup.index = i;
1127 
1128 skip_finding_an_index:
1129 	rc = sja1105_dynamic_config_write(priv, BLK_IDX_L2_LOOKUP,
1130 					  l2_lookup.index, &l2_lookup,
1131 					  true);
1132 	if (rc < 0)
1133 		return rc;
1134 
1135 	return sja1105_static_fdb_change(priv, port, &l2_lookup, true);
1136 }
1137 
1138 int sja1105pqrs_fdb_del(struct dsa_switch *ds, int port,
1139 			const unsigned char *addr, u16 vid)
1140 {
1141 	struct sja1105_l2_lookup_entry l2_lookup = {0};
1142 	struct sja1105_private *priv = ds->priv;
1143 	bool keep;
1144 	int rc;
1145 
1146 	l2_lookup.macaddr = ether_addr_to_u64(addr);
1147 	l2_lookup.vlanid = vid;
1148 	l2_lookup.iotag = SJA1105_S_TAG;
1149 	l2_lookup.mask_macaddr = GENMASK_ULL(ETH_ALEN * 8 - 1, 0);
1150 	l2_lookup.mask_vlanid = VLAN_VID_MASK;
1151 	l2_lookup.mask_iotag = BIT(0);
1152 	l2_lookup.destports = BIT(port);
1153 
1154 	rc = sja1105_dynamic_config_read(priv, BLK_IDX_L2_LOOKUP,
1155 					 SJA1105_SEARCH, &l2_lookup);
1156 	if (rc < 0)
1157 		return 0;
1158 
1159 	l2_lookup.destports &= ~BIT(port);
1160 
1161 	/* Decide whether we remove just this port from the FDB entry,
1162 	 * or if we remove it completely.
1163 	 */
1164 	if (l2_lookup.destports)
1165 		keep = true;
1166 	else
1167 		keep = false;
1168 
1169 	rc = sja1105_dynamic_config_write(priv, BLK_IDX_L2_LOOKUP,
1170 					  l2_lookup.index, &l2_lookup, keep);
1171 	if (rc < 0)
1172 		return rc;
1173 
1174 	return sja1105_static_fdb_change(priv, port, &l2_lookup, keep);
1175 }
1176 
1177 static int sja1105_fdb_add(struct dsa_switch *ds, int port,
1178 			   const unsigned char *addr, u16 vid)
1179 {
1180 	struct sja1105_private *priv = ds->priv;
1181 	u16 rx_vid, tx_vid;
1182 	int rc, i;
1183 
1184 	if (dsa_port_is_vlan_filtering(&ds->ports[port]))
1185 		return priv->info->fdb_add_cmd(ds, port, addr, vid);
1186 
1187 	/* Since we make use of VLANs even when the bridge core doesn't tell us
1188 	 * to, translate these FDB entries into the correct dsa_8021q ones.
1189 	 * The basic idea (also repeats for removal below) is:
1190 	 * - Each of the other front-panel ports needs to be able to forward a
1191 	 *   pvid-tagged (aka tagged with their rx_vid) frame that matches this
1192 	 *   DMAC.
1193 	 * - The CPU port (aka the tx_vid of this port) needs to be able to
1194 	 *   send a frame matching this DMAC to the specified port.
1195 	 * For a better picture see net/dsa/tag_8021q.c.
1196 	 */
1197 	for (i = 0; i < SJA1105_NUM_PORTS; i++) {
1198 		if (i == port)
1199 			continue;
1200 		if (i == dsa_upstream_port(priv->ds, port))
1201 			continue;
1202 
1203 		rx_vid = dsa_8021q_rx_vid(ds, i);
1204 		rc = priv->info->fdb_add_cmd(ds, port, addr, rx_vid);
1205 		if (rc < 0)
1206 			return rc;
1207 	}
1208 	tx_vid = dsa_8021q_tx_vid(ds, port);
1209 	return priv->info->fdb_add_cmd(ds, port, addr, tx_vid);
1210 }
1211 
1212 static int sja1105_fdb_del(struct dsa_switch *ds, int port,
1213 			   const unsigned char *addr, u16 vid)
1214 {
1215 	struct sja1105_private *priv = ds->priv;
1216 	u16 rx_vid, tx_vid;
1217 	int rc, i;
1218 
1219 	if (dsa_port_is_vlan_filtering(&ds->ports[port]))
1220 		return priv->info->fdb_del_cmd(ds, port, addr, vid);
1221 
1222 	for (i = 0; i < SJA1105_NUM_PORTS; i++) {
1223 		if (i == port)
1224 			continue;
1225 		if (i == dsa_upstream_port(priv->ds, port))
1226 			continue;
1227 
1228 		rx_vid = dsa_8021q_rx_vid(ds, i);
1229 		rc = priv->info->fdb_del_cmd(ds, port, addr, rx_vid);
1230 		if (rc < 0)
1231 			return rc;
1232 	}
1233 	tx_vid = dsa_8021q_tx_vid(ds, port);
1234 	return priv->info->fdb_del_cmd(ds, port, addr, tx_vid);
1235 }
1236 
1237 static int sja1105_fdb_dump(struct dsa_switch *ds, int port,
1238 			    dsa_fdb_dump_cb_t *cb, void *data)
1239 {
1240 	struct sja1105_private *priv = ds->priv;
1241 	struct device *dev = ds->dev;
1242 	u16 rx_vid, tx_vid;
1243 	int i;
1244 
1245 	rx_vid = dsa_8021q_rx_vid(ds, port);
1246 	tx_vid = dsa_8021q_tx_vid(ds, port);
1247 
1248 	for (i = 0; i < SJA1105_MAX_L2_LOOKUP_COUNT; i++) {
1249 		struct sja1105_l2_lookup_entry l2_lookup = {0};
1250 		u8 macaddr[ETH_ALEN];
1251 		int rc;
1252 
1253 		rc = sja1105_dynamic_config_read(priv, BLK_IDX_L2_LOOKUP,
1254 						 i, &l2_lookup);
1255 		/* No fdb entry at i, not an issue */
1256 		if (rc == -ENOENT)
1257 			continue;
1258 		if (rc) {
1259 			dev_err(dev, "Failed to dump FDB: %d\n", rc);
1260 			return rc;
1261 		}
1262 
1263 		/* FDB dump callback is per port. This means we have to
1264 		 * disregard a valid entry if it's not for this port, even if
1265 		 * only to revisit it later. This is inefficient because the
1266 		 * 1024-sized FDB table needs to be traversed 4 times through
1267 		 * SPI during a 'bridge fdb show' command.
1268 		 */
1269 		if (!(l2_lookup.destports & BIT(port)))
1270 			continue;
1271 		u64_to_ether_addr(l2_lookup.macaddr, macaddr);
1272 
1273 		/* On SJA1105 E/T, the switch doesn't implement the LOCKEDS
1274 		 * bit, so it doesn't tell us whether a FDB entry is static
1275 		 * or not.
1276 		 * But, of course, we can find out - we're the ones who added
1277 		 * it in the first place.
1278 		 */
1279 		if (priv->info->device_id == SJA1105E_DEVICE_ID ||
1280 		    priv->info->device_id == SJA1105T_DEVICE_ID) {
1281 			int match;
1282 
1283 			match = sja1105_find_static_fdb_entry(priv, port,
1284 							      &l2_lookup);
1285 			l2_lookup.lockeds = (match >= 0);
1286 		}
1287 
1288 		/* We need to hide the dsa_8021q VLANs from the user. This
1289 		 * basically means hiding the duplicates and only showing
1290 		 * the pvid that is supposed to be active in standalone and
1291 		 * non-vlan_filtering modes (aka 1).
1292 		 * - For statically added FDB entries (bridge fdb add), we
1293 		 *   can convert the TX VID (coming from the CPU port) into the
1294 		 *   pvid and ignore the RX VIDs of the other ports.
1295 		 * - For dynamically learned FDB entries, a single entry with
1296 		 *   no duplicates is learned - that which has the real port's
1297 		 *   pvid, aka RX VID.
1298 		 */
1299 		if (!dsa_port_is_vlan_filtering(&ds->ports[port])) {
1300 			if (l2_lookup.vlanid == tx_vid ||
1301 			    l2_lookup.vlanid == rx_vid)
1302 				l2_lookup.vlanid = 1;
1303 			else
1304 				continue;
1305 		}
1306 		cb(macaddr, l2_lookup.vlanid, l2_lookup.lockeds, data);
1307 	}
1308 	return 0;
1309 }
1310 
1311 /* This callback needs to be present */
1312 static int sja1105_mdb_prepare(struct dsa_switch *ds, int port,
1313 			       const struct switchdev_obj_port_mdb *mdb)
1314 {
1315 	return 0;
1316 }
1317 
1318 static void sja1105_mdb_add(struct dsa_switch *ds, int port,
1319 			    const struct switchdev_obj_port_mdb *mdb)
1320 {
1321 	sja1105_fdb_add(ds, port, mdb->addr, mdb->vid);
1322 }
1323 
1324 static int sja1105_mdb_del(struct dsa_switch *ds, int port,
1325 			   const struct switchdev_obj_port_mdb *mdb)
1326 {
1327 	return sja1105_fdb_del(ds, port, mdb->addr, mdb->vid);
1328 }
1329 
1330 static int sja1105_bridge_member(struct dsa_switch *ds, int port,
1331 				 struct net_device *br, bool member)
1332 {
1333 	struct sja1105_l2_forwarding_entry *l2_fwd;
1334 	struct sja1105_private *priv = ds->priv;
1335 	int i, rc;
1336 
1337 	l2_fwd = priv->static_config.tables[BLK_IDX_L2_FORWARDING].entries;
1338 
1339 	for (i = 0; i < SJA1105_NUM_PORTS; i++) {
1340 		/* Add this port to the forwarding matrix of the
1341 		 * other ports in the same bridge, and viceversa.
1342 		 */
1343 		if (!dsa_is_user_port(ds, i))
1344 			continue;
1345 		/* For the ports already under the bridge, only one thing needs
1346 		 * to be done, and that is to add this port to their
1347 		 * reachability domain. So we can perform the SPI write for
1348 		 * them immediately. However, for this port itself (the one
1349 		 * that is new to the bridge), we need to add all other ports
1350 		 * to its reachability domain. So we do that incrementally in
1351 		 * this loop, and perform the SPI write only at the end, once
1352 		 * the domain contains all other bridge ports.
1353 		 */
1354 		if (i == port)
1355 			continue;
1356 		if (dsa_to_port(ds, i)->bridge_dev != br)
1357 			continue;
1358 		sja1105_port_allow_traffic(l2_fwd, i, port, member);
1359 		sja1105_port_allow_traffic(l2_fwd, port, i, member);
1360 
1361 		rc = sja1105_dynamic_config_write(priv, BLK_IDX_L2_FORWARDING,
1362 						  i, &l2_fwd[i], true);
1363 		if (rc < 0)
1364 			return rc;
1365 	}
1366 
1367 	return sja1105_dynamic_config_write(priv, BLK_IDX_L2_FORWARDING,
1368 					    port, &l2_fwd[port], true);
1369 }
1370 
1371 static void sja1105_bridge_stp_state_set(struct dsa_switch *ds, int port,
1372 					 u8 state)
1373 {
1374 	struct sja1105_private *priv = ds->priv;
1375 	struct sja1105_mac_config_entry *mac;
1376 
1377 	mac = priv->static_config.tables[BLK_IDX_MAC_CONFIG].entries;
1378 
1379 	switch (state) {
1380 	case BR_STATE_DISABLED:
1381 	case BR_STATE_BLOCKING:
1382 		/* From UM10944 description of DRPDTAG (why put this there?):
1383 		 * "Management traffic flows to the port regardless of the state
1384 		 * of the INGRESS flag". So BPDUs are still be allowed to pass.
1385 		 * At the moment no difference between DISABLED and BLOCKING.
1386 		 */
1387 		mac[port].ingress   = false;
1388 		mac[port].egress    = false;
1389 		mac[port].dyn_learn = false;
1390 		break;
1391 	case BR_STATE_LISTENING:
1392 		mac[port].ingress   = true;
1393 		mac[port].egress    = false;
1394 		mac[port].dyn_learn = false;
1395 		break;
1396 	case BR_STATE_LEARNING:
1397 		mac[port].ingress   = true;
1398 		mac[port].egress    = false;
1399 		mac[port].dyn_learn = true;
1400 		break;
1401 	case BR_STATE_FORWARDING:
1402 		mac[port].ingress   = true;
1403 		mac[port].egress    = true;
1404 		mac[port].dyn_learn = true;
1405 		break;
1406 	default:
1407 		dev_err(ds->dev, "invalid STP state: %d\n", state);
1408 		return;
1409 	}
1410 
1411 	sja1105_dynamic_config_write(priv, BLK_IDX_MAC_CONFIG, port,
1412 				     &mac[port], true);
1413 }
1414 
1415 static int sja1105_bridge_join(struct dsa_switch *ds, int port,
1416 			       struct net_device *br)
1417 {
1418 	return sja1105_bridge_member(ds, port, br, true);
1419 }
1420 
1421 static void sja1105_bridge_leave(struct dsa_switch *ds, int port,
1422 				 struct net_device *br)
1423 {
1424 	sja1105_bridge_member(ds, port, br, false);
1425 }
1426 
1427 /* For situations where we need to change a setting at runtime that is only
1428  * available through the static configuration, resetting the switch in order
1429  * to upload the new static config is unavoidable. Back up the settings we
1430  * modify at runtime (currently only MAC) and restore them after uploading,
1431  * such that this operation is relatively seamless.
1432  */
1433 static int sja1105_static_config_reload(struct sja1105_private *priv)
1434 {
1435 	struct sja1105_mac_config_entry *mac;
1436 	int speed_mbps[SJA1105_NUM_PORTS];
1437 	int rc, i;
1438 
1439 	mac = priv->static_config.tables[BLK_IDX_MAC_CONFIG].entries;
1440 
1441 	/* Back up the dynamic link speed changed by sja1105_adjust_port_config
1442 	 * in order to temporarily restore it to SJA1105_SPEED_AUTO - which the
1443 	 * switch wants to see in the static config in order to allow us to
1444 	 * change it through the dynamic interface later.
1445 	 */
1446 	for (i = 0; i < SJA1105_NUM_PORTS; i++) {
1447 		speed_mbps[i] = sja1105_speed[mac[i].speed];
1448 		mac[i].speed = SJA1105_SPEED_AUTO;
1449 	}
1450 
1451 	/* Reset switch and send updated static configuration */
1452 	rc = sja1105_static_config_upload(priv);
1453 	if (rc < 0)
1454 		goto out;
1455 
1456 	/* Configure the CGU (PLLs) for MII and RMII PHYs.
1457 	 * For these interfaces there is no dynamic configuration
1458 	 * needed, since PLLs have same settings at all speeds.
1459 	 */
1460 	rc = sja1105_clocking_setup(priv);
1461 	if (rc < 0)
1462 		goto out;
1463 
1464 	for (i = 0; i < SJA1105_NUM_PORTS; i++) {
1465 		rc = sja1105_adjust_port_config(priv, i, speed_mbps[i]);
1466 		if (rc < 0)
1467 			goto out;
1468 	}
1469 out:
1470 	return rc;
1471 }
1472 
1473 static int sja1105_pvid_apply(struct sja1105_private *priv, int port, u16 pvid)
1474 {
1475 	struct sja1105_mac_config_entry *mac;
1476 
1477 	mac = priv->static_config.tables[BLK_IDX_MAC_CONFIG].entries;
1478 
1479 	mac[port].vlanid = pvid;
1480 
1481 	return sja1105_dynamic_config_write(priv, BLK_IDX_MAC_CONFIG, port,
1482 					   &mac[port], true);
1483 }
1484 
1485 static int sja1105_is_vlan_configured(struct sja1105_private *priv, u16 vid)
1486 {
1487 	struct sja1105_vlan_lookup_entry *vlan;
1488 	int count, i;
1489 
1490 	vlan = priv->static_config.tables[BLK_IDX_VLAN_LOOKUP].entries;
1491 	count = priv->static_config.tables[BLK_IDX_VLAN_LOOKUP].entry_count;
1492 
1493 	for (i = 0; i < count; i++)
1494 		if (vlan[i].vlanid == vid)
1495 			return i;
1496 
1497 	/* Return an invalid entry index if not found */
1498 	return -1;
1499 }
1500 
1501 static int sja1105_vlan_apply(struct sja1105_private *priv, int port, u16 vid,
1502 			      bool enabled, bool untagged)
1503 {
1504 	struct sja1105_vlan_lookup_entry *vlan;
1505 	struct sja1105_table *table;
1506 	bool keep = true;
1507 	int match, rc;
1508 
1509 	table = &priv->static_config.tables[BLK_IDX_VLAN_LOOKUP];
1510 
1511 	match = sja1105_is_vlan_configured(priv, vid);
1512 	if (match < 0) {
1513 		/* Can't delete a missing entry. */
1514 		if (!enabled)
1515 			return 0;
1516 		rc = sja1105_table_resize(table, table->entry_count + 1);
1517 		if (rc)
1518 			return rc;
1519 		match = table->entry_count - 1;
1520 	}
1521 	/* Assign pointer after the resize (it's new memory) */
1522 	vlan = table->entries;
1523 	vlan[match].vlanid = vid;
1524 	if (enabled) {
1525 		vlan[match].vlan_bc |= BIT(port);
1526 		vlan[match].vmemb_port |= BIT(port);
1527 	} else {
1528 		vlan[match].vlan_bc &= ~BIT(port);
1529 		vlan[match].vmemb_port &= ~BIT(port);
1530 	}
1531 	/* Also unset tag_port if removing this VLAN was requested,
1532 	 * just so we don't have a confusing bitmap (no practical purpose).
1533 	 */
1534 	if (untagged || !enabled)
1535 		vlan[match].tag_port &= ~BIT(port);
1536 	else
1537 		vlan[match].tag_port |= BIT(port);
1538 	/* If there's no port left as member of this VLAN,
1539 	 * it's time for it to go.
1540 	 */
1541 	if (!vlan[match].vmemb_port)
1542 		keep = false;
1543 
1544 	dev_dbg(priv->ds->dev,
1545 		"%s: port %d, vid %llu, broadcast domain 0x%llx, "
1546 		"port members 0x%llx, tagged ports 0x%llx, keep %d\n",
1547 		__func__, port, vlan[match].vlanid, vlan[match].vlan_bc,
1548 		vlan[match].vmemb_port, vlan[match].tag_port, keep);
1549 
1550 	rc = sja1105_dynamic_config_write(priv, BLK_IDX_VLAN_LOOKUP, vid,
1551 					  &vlan[match], keep);
1552 	if (rc < 0)
1553 		return rc;
1554 
1555 	if (!keep)
1556 		return sja1105_table_delete_entry(table, match);
1557 
1558 	return 0;
1559 }
1560 
1561 static int sja1105_setup_8021q_tagging(struct dsa_switch *ds, bool enabled)
1562 {
1563 	int rc, i;
1564 
1565 	for (i = 0; i < SJA1105_NUM_PORTS; i++) {
1566 		rc = dsa_port_setup_8021q_tagging(ds, i, enabled);
1567 		if (rc < 0) {
1568 			dev_err(ds->dev, "Failed to setup VLAN tagging for port %d: %d\n",
1569 				i, rc);
1570 			return rc;
1571 		}
1572 	}
1573 	dev_info(ds->dev, "%s switch tagging\n",
1574 		 enabled ? "Enabled" : "Disabled");
1575 	return 0;
1576 }
1577 
1578 static enum dsa_tag_protocol
1579 sja1105_get_tag_protocol(struct dsa_switch *ds, int port)
1580 {
1581 	return DSA_TAG_PROTO_SJA1105;
1582 }
1583 
1584 /* This callback needs to be present */
1585 static int sja1105_vlan_prepare(struct dsa_switch *ds, int port,
1586 				const struct switchdev_obj_port_vlan *vlan)
1587 {
1588 	return 0;
1589 }
1590 
1591 /* The TPID setting belongs to the General Parameters table,
1592  * which can only be partially reconfigured at runtime (and not the TPID).
1593  * So a switch reset is required.
1594  */
1595 static int sja1105_vlan_filtering(struct dsa_switch *ds, int port, bool enabled)
1596 {
1597 	struct sja1105_general_params_entry *general_params;
1598 	struct sja1105_private *priv = ds->priv;
1599 	struct sja1105_table *table;
1600 	u16 tpid, tpid2;
1601 	int rc;
1602 
1603 	if (enabled) {
1604 		/* Enable VLAN filtering. */
1605 		tpid  = ETH_P_8021AD;
1606 		tpid2 = ETH_P_8021Q;
1607 	} else {
1608 		/* Disable VLAN filtering. */
1609 		tpid  = ETH_P_SJA1105;
1610 		tpid2 = ETH_P_SJA1105;
1611 	}
1612 
1613 	table = &priv->static_config.tables[BLK_IDX_GENERAL_PARAMS];
1614 	general_params = table->entries;
1615 	/* EtherType used to identify outer tagged (S-tag) VLAN traffic */
1616 	general_params->tpid = tpid;
1617 	/* EtherType used to identify inner tagged (C-tag) VLAN traffic */
1618 	general_params->tpid2 = tpid2;
1619 	/* When VLAN filtering is on, we need to at least be able to
1620 	 * decode management traffic through the "backup plan".
1621 	 */
1622 	general_params->incl_srcpt1 = enabled;
1623 	general_params->incl_srcpt0 = enabled;
1624 
1625 	rc = sja1105_static_config_reload(priv);
1626 	if (rc)
1627 		dev_err(ds->dev, "Failed to change VLAN Ethertype\n");
1628 
1629 	/* Switch port identification based on 802.1Q is only passable
1630 	 * if we are not under a vlan_filtering bridge. So make sure
1631 	 * the two configurations are mutually exclusive.
1632 	 */
1633 	return sja1105_setup_8021q_tagging(ds, !enabled);
1634 }
1635 
1636 static void sja1105_vlan_add(struct dsa_switch *ds, int port,
1637 			     const struct switchdev_obj_port_vlan *vlan)
1638 {
1639 	struct sja1105_private *priv = ds->priv;
1640 	u16 vid;
1641 	int rc;
1642 
1643 	for (vid = vlan->vid_begin; vid <= vlan->vid_end; vid++) {
1644 		rc = sja1105_vlan_apply(priv, port, vid, true, vlan->flags &
1645 					BRIDGE_VLAN_INFO_UNTAGGED);
1646 		if (rc < 0) {
1647 			dev_err(ds->dev, "Failed to add VLAN %d to port %d: %d\n",
1648 				vid, port, rc);
1649 			return;
1650 		}
1651 		if (vlan->flags & BRIDGE_VLAN_INFO_PVID) {
1652 			rc = sja1105_pvid_apply(ds->priv, port, vid);
1653 			if (rc < 0) {
1654 				dev_err(ds->dev, "Failed to set pvid %d on port %d: %d\n",
1655 					vid, port, rc);
1656 				return;
1657 			}
1658 		}
1659 	}
1660 }
1661 
1662 static int sja1105_vlan_del(struct dsa_switch *ds, int port,
1663 			    const struct switchdev_obj_port_vlan *vlan)
1664 {
1665 	struct sja1105_private *priv = ds->priv;
1666 	u16 vid;
1667 	int rc;
1668 
1669 	for (vid = vlan->vid_begin; vid <= vlan->vid_end; vid++) {
1670 		rc = sja1105_vlan_apply(priv, port, vid, false, vlan->flags &
1671 					BRIDGE_VLAN_INFO_UNTAGGED);
1672 		if (rc < 0) {
1673 			dev_err(ds->dev, "Failed to remove VLAN %d from port %d: %d\n",
1674 				vid, port, rc);
1675 			return rc;
1676 		}
1677 	}
1678 	return 0;
1679 }
1680 
1681 /* The programming model for the SJA1105 switch is "all-at-once" via static
1682  * configuration tables. Some of these can be dynamically modified at runtime,
1683  * but not the xMII mode parameters table.
1684  * Furthermode, some PHYs may not have crystals for generating their clocks
1685  * (e.g. RMII). Instead, their 50MHz clock is supplied via the SJA1105 port's
1686  * ref_clk pin. So port clocking needs to be initialized early, before
1687  * connecting to PHYs is attempted, otherwise they won't respond through MDIO.
1688  * Setting correct PHY link speed does not matter now.
1689  * But dsa_slave_phy_setup is called later than sja1105_setup, so the PHY
1690  * bindings are not yet parsed by DSA core. We need to parse early so that we
1691  * can populate the xMII mode parameters table.
1692  */
1693 static int sja1105_setup(struct dsa_switch *ds)
1694 {
1695 	struct sja1105_dt_port ports[SJA1105_NUM_PORTS];
1696 	struct sja1105_private *priv = ds->priv;
1697 	int rc;
1698 
1699 	rc = sja1105_parse_dt(priv, ports);
1700 	if (rc < 0) {
1701 		dev_err(ds->dev, "Failed to parse DT: %d\n", rc);
1702 		return rc;
1703 	}
1704 
1705 	/* Error out early if internal delays are required through DT
1706 	 * and we can't apply them.
1707 	 */
1708 	rc = sja1105_parse_rgmii_delays(priv, ports);
1709 	if (rc < 0) {
1710 		dev_err(ds->dev, "RGMII delay not supported\n");
1711 		return rc;
1712 	}
1713 
1714 	rc = sja1105_ptp_clock_register(priv);
1715 	if (rc < 0) {
1716 		dev_err(ds->dev, "Failed to register PTP clock: %d\n", rc);
1717 		return rc;
1718 	}
1719 	/* Create and send configuration down to device */
1720 	rc = sja1105_static_config_load(priv, ports);
1721 	if (rc < 0) {
1722 		dev_err(ds->dev, "Failed to load static config: %d\n", rc);
1723 		return rc;
1724 	}
1725 	/* Configure the CGU (PHY link modes and speeds) */
1726 	rc = sja1105_clocking_setup(priv);
1727 	if (rc < 0) {
1728 		dev_err(ds->dev, "Failed to configure MII clocking: %d\n", rc);
1729 		return rc;
1730 	}
1731 	/* On SJA1105, VLAN filtering per se is always enabled in hardware.
1732 	 * The only thing we can do to disable it is lie about what the 802.1Q
1733 	 * EtherType is.
1734 	 * So it will still try to apply VLAN filtering, but all ingress
1735 	 * traffic (except frames received with EtherType of ETH_P_SJA1105)
1736 	 * will be internally tagged with a distorted VLAN header where the
1737 	 * TPID is ETH_P_SJA1105, and the VLAN ID is the port pvid.
1738 	 */
1739 	ds->vlan_filtering_is_global = true;
1740 
1741 	/* The DSA/switchdev model brings up switch ports in standalone mode by
1742 	 * default, and that means vlan_filtering is 0 since they're not under
1743 	 * a bridge, so it's safe to set up switch tagging at this time.
1744 	 */
1745 	return sja1105_setup_8021q_tagging(ds, true);
1746 }
1747 
1748 static void sja1105_teardown(struct dsa_switch *ds)
1749 {
1750 	struct sja1105_private *priv = ds->priv;
1751 
1752 	cancel_work_sync(&priv->tagger_data.rxtstamp_work);
1753 	skb_queue_purge(&priv->tagger_data.skb_rxtstamp_queue);
1754 }
1755 
1756 static int sja1105_mgmt_xmit(struct dsa_switch *ds, int port, int slot,
1757 			     struct sk_buff *skb, bool takets)
1758 {
1759 	struct sja1105_mgmt_entry mgmt_route = {0};
1760 	struct sja1105_private *priv = ds->priv;
1761 	struct ethhdr *hdr;
1762 	int timeout = 10;
1763 	int rc;
1764 
1765 	hdr = eth_hdr(skb);
1766 
1767 	mgmt_route.macaddr = ether_addr_to_u64(hdr->h_dest);
1768 	mgmt_route.destports = BIT(port);
1769 	mgmt_route.enfport = 1;
1770 	mgmt_route.tsreg = 0;
1771 	mgmt_route.takets = takets;
1772 
1773 	rc = sja1105_dynamic_config_write(priv, BLK_IDX_MGMT_ROUTE,
1774 					  slot, &mgmt_route, true);
1775 	if (rc < 0) {
1776 		kfree_skb(skb);
1777 		return rc;
1778 	}
1779 
1780 	/* Transfer skb to the host port. */
1781 	dsa_enqueue_skb(skb, ds->ports[port].slave);
1782 
1783 	/* Wait until the switch has processed the frame */
1784 	do {
1785 		rc = sja1105_dynamic_config_read(priv, BLK_IDX_MGMT_ROUTE,
1786 						 slot, &mgmt_route);
1787 		if (rc < 0) {
1788 			dev_err_ratelimited(priv->ds->dev,
1789 					    "failed to poll for mgmt route\n");
1790 			continue;
1791 		}
1792 
1793 		/* UM10944: The ENFPORT flag of the respective entry is
1794 		 * cleared when a match is found. The host can use this
1795 		 * flag as an acknowledgment.
1796 		 */
1797 		cpu_relax();
1798 	} while (mgmt_route.enfport && --timeout);
1799 
1800 	if (!timeout) {
1801 		/* Clean up the management route so that a follow-up
1802 		 * frame may not match on it by mistake.
1803 		 * This is only hardware supported on P/Q/R/S - on E/T it is
1804 		 * a no-op and we are silently discarding the -EOPNOTSUPP.
1805 		 */
1806 		sja1105_dynamic_config_write(priv, BLK_IDX_MGMT_ROUTE,
1807 					     slot, &mgmt_route, false);
1808 		dev_err_ratelimited(priv->ds->dev, "xmit timed out\n");
1809 	}
1810 
1811 	return NETDEV_TX_OK;
1812 }
1813 
1814 /* Deferred work is unfortunately necessary because setting up the management
1815  * route cannot be done from atomit context (SPI transfer takes a sleepable
1816  * lock on the bus)
1817  */
1818 static netdev_tx_t sja1105_port_deferred_xmit(struct dsa_switch *ds, int port,
1819 					      struct sk_buff *skb)
1820 {
1821 	struct sja1105_private *priv = ds->priv;
1822 	struct sja1105_port *sp = &priv->ports[port];
1823 	struct skb_shared_hwtstamps shwt = {0};
1824 	int slot = sp->mgmt_slot;
1825 	struct sk_buff *clone;
1826 	u64 now, ts;
1827 	int rc;
1828 
1829 	/* The tragic fact about the switch having 4x2 slots for installing
1830 	 * management routes is that all of them except one are actually
1831 	 * useless.
1832 	 * If 2 slots are simultaneously configured for two BPDUs sent to the
1833 	 * same (multicast) DMAC but on different egress ports, the switch
1834 	 * would confuse them and redirect first frame it receives on the CPU
1835 	 * port towards the port configured on the numerically first slot
1836 	 * (therefore wrong port), then second received frame on second slot
1837 	 * (also wrong port).
1838 	 * So for all practical purposes, there needs to be a lock that
1839 	 * prevents that from happening. The slot used here is utterly useless
1840 	 * (could have simply been 0 just as fine), but we are doing it
1841 	 * nonetheless, in case a smarter idea ever comes up in the future.
1842 	 */
1843 	mutex_lock(&priv->mgmt_lock);
1844 
1845 	/* The clone, if there, was made by dsa_skb_tx_timestamp */
1846 	clone = DSA_SKB_CB(skb)->clone;
1847 
1848 	sja1105_mgmt_xmit(ds, port, slot, skb, !!clone);
1849 
1850 	if (!clone)
1851 		goto out;
1852 
1853 	skb_shinfo(clone)->tx_flags |= SKBTX_IN_PROGRESS;
1854 
1855 	mutex_lock(&priv->ptp_lock);
1856 
1857 	now = priv->tstamp_cc.read(&priv->tstamp_cc);
1858 
1859 	rc = sja1105_ptpegr_ts_poll(priv, slot, &ts);
1860 	if (rc < 0) {
1861 		dev_err(ds->dev, "xmit: timed out polling for tstamp\n");
1862 		kfree_skb(clone);
1863 		goto out_unlock_ptp;
1864 	}
1865 
1866 	ts = sja1105_tstamp_reconstruct(priv, now, ts);
1867 	ts = timecounter_cyc2time(&priv->tstamp_tc, ts);
1868 
1869 	shwt.hwtstamp = ns_to_ktime(ts);
1870 	skb_complete_tx_timestamp(clone, &shwt);
1871 
1872 out_unlock_ptp:
1873 	mutex_unlock(&priv->ptp_lock);
1874 out:
1875 	mutex_unlock(&priv->mgmt_lock);
1876 	return NETDEV_TX_OK;
1877 }
1878 
1879 /* The MAXAGE setting belongs to the L2 Forwarding Parameters table,
1880  * which cannot be reconfigured at runtime. So a switch reset is required.
1881  */
1882 static int sja1105_set_ageing_time(struct dsa_switch *ds,
1883 				   unsigned int ageing_time)
1884 {
1885 	struct sja1105_l2_lookup_params_entry *l2_lookup_params;
1886 	struct sja1105_private *priv = ds->priv;
1887 	struct sja1105_table *table;
1888 	unsigned int maxage;
1889 
1890 	table = &priv->static_config.tables[BLK_IDX_L2_LOOKUP_PARAMS];
1891 	l2_lookup_params = table->entries;
1892 
1893 	maxage = SJA1105_AGEING_TIME_MS(ageing_time);
1894 
1895 	if (l2_lookup_params->maxage == maxage)
1896 		return 0;
1897 
1898 	l2_lookup_params->maxage = maxage;
1899 
1900 	return sja1105_static_config_reload(priv);
1901 }
1902 
1903 /* Caller must hold priv->tagger_data.meta_lock */
1904 static int sja1105_change_rxtstamping(struct sja1105_private *priv,
1905 				      bool on)
1906 {
1907 	struct sja1105_general_params_entry *general_params;
1908 	struct sja1105_table *table;
1909 	int rc;
1910 
1911 	table = &priv->static_config.tables[BLK_IDX_GENERAL_PARAMS];
1912 	general_params = table->entries;
1913 	general_params->send_meta1 = on;
1914 	general_params->send_meta0 = on;
1915 
1916 	rc = sja1105_init_avb_params(priv, on);
1917 	if (rc < 0)
1918 		return rc;
1919 
1920 	/* Initialize the meta state machine to a known state */
1921 	if (priv->tagger_data.stampable_skb) {
1922 		kfree_skb(priv->tagger_data.stampable_skb);
1923 		priv->tagger_data.stampable_skb = NULL;
1924 	}
1925 
1926 	return sja1105_static_config_reload(priv);
1927 }
1928 
1929 static int sja1105_hwtstamp_set(struct dsa_switch *ds, int port,
1930 				struct ifreq *ifr)
1931 {
1932 	struct sja1105_private *priv = ds->priv;
1933 	struct hwtstamp_config config;
1934 	bool rx_on;
1935 	int rc;
1936 
1937 	if (copy_from_user(&config, ifr->ifr_data, sizeof(config)))
1938 		return -EFAULT;
1939 
1940 	switch (config.tx_type) {
1941 	case HWTSTAMP_TX_OFF:
1942 		priv->ports[port].hwts_tx_en = false;
1943 		break;
1944 	case HWTSTAMP_TX_ON:
1945 		priv->ports[port].hwts_tx_en = true;
1946 		break;
1947 	default:
1948 		return -ERANGE;
1949 	}
1950 
1951 	switch (config.rx_filter) {
1952 	case HWTSTAMP_FILTER_NONE:
1953 		rx_on = false;
1954 		break;
1955 	default:
1956 		rx_on = true;
1957 		break;
1958 	}
1959 
1960 	if (rx_on != priv->tagger_data.hwts_rx_en) {
1961 		spin_lock(&priv->tagger_data.meta_lock);
1962 		rc = sja1105_change_rxtstamping(priv, rx_on);
1963 		spin_unlock(&priv->tagger_data.meta_lock);
1964 		if (rc < 0) {
1965 			dev_err(ds->dev,
1966 				"Failed to change RX timestamping: %d\n", rc);
1967 			return -EFAULT;
1968 		}
1969 		priv->tagger_data.hwts_rx_en = rx_on;
1970 	}
1971 
1972 	if (copy_to_user(ifr->ifr_data, &config, sizeof(config)))
1973 		return -EFAULT;
1974 	return 0;
1975 }
1976 
1977 static int sja1105_hwtstamp_get(struct dsa_switch *ds, int port,
1978 				struct ifreq *ifr)
1979 {
1980 	struct sja1105_private *priv = ds->priv;
1981 	struct hwtstamp_config config;
1982 
1983 	config.flags = 0;
1984 	if (priv->ports[port].hwts_tx_en)
1985 		config.tx_type = HWTSTAMP_TX_ON;
1986 	else
1987 		config.tx_type = HWTSTAMP_TX_OFF;
1988 	if (priv->tagger_data.hwts_rx_en)
1989 		config.rx_filter = HWTSTAMP_FILTER_PTP_V2_L2_EVENT;
1990 	else
1991 		config.rx_filter = HWTSTAMP_FILTER_NONE;
1992 
1993 	return copy_to_user(ifr->ifr_data, &config, sizeof(config)) ?
1994 		-EFAULT : 0;
1995 }
1996 
1997 #define to_tagger(d) \
1998 	container_of((d), struct sja1105_tagger_data, rxtstamp_work)
1999 #define to_sja1105(d) \
2000 	container_of((d), struct sja1105_private, tagger_data)
2001 
2002 static void sja1105_rxtstamp_work(struct work_struct *work)
2003 {
2004 	struct sja1105_tagger_data *data = to_tagger(work);
2005 	struct sja1105_private *priv = to_sja1105(data);
2006 	struct sk_buff *skb;
2007 	u64 now;
2008 
2009 	mutex_lock(&priv->ptp_lock);
2010 
2011 	now = priv->tstamp_cc.read(&priv->tstamp_cc);
2012 
2013 	while ((skb = skb_dequeue(&data->skb_rxtstamp_queue)) != NULL) {
2014 		struct skb_shared_hwtstamps *shwt = skb_hwtstamps(skb);
2015 		u64 ts;
2016 
2017 		*shwt = (struct skb_shared_hwtstamps) {0};
2018 
2019 		ts = SJA1105_SKB_CB(skb)->meta_tstamp;
2020 		ts = sja1105_tstamp_reconstruct(priv, now, ts);
2021 		ts = timecounter_cyc2time(&priv->tstamp_tc, ts);
2022 
2023 		shwt->hwtstamp = ns_to_ktime(ts);
2024 		netif_rx_ni(skb);
2025 	}
2026 
2027 	mutex_unlock(&priv->ptp_lock);
2028 }
2029 
2030 /* Called from dsa_skb_defer_rx_timestamp */
2031 static bool sja1105_port_rxtstamp(struct dsa_switch *ds, int port,
2032 				  struct sk_buff *skb, unsigned int type)
2033 {
2034 	struct sja1105_private *priv = ds->priv;
2035 	struct sja1105_tagger_data *data = &priv->tagger_data;
2036 
2037 	if (!data->hwts_rx_en)
2038 		return false;
2039 
2040 	/* We need to read the full PTP clock to reconstruct the Rx
2041 	 * timestamp. For that we need a sleepable context.
2042 	 */
2043 	skb_queue_tail(&data->skb_rxtstamp_queue, skb);
2044 	schedule_work(&data->rxtstamp_work);
2045 	return true;
2046 }
2047 
2048 /* Called from dsa_skb_tx_timestamp. This callback is just to make DSA clone
2049  * the skb and have it available in DSA_SKB_CB in the .port_deferred_xmit
2050  * callback, where we will timestamp it synchronously.
2051  */
2052 static bool sja1105_port_txtstamp(struct dsa_switch *ds, int port,
2053 				  struct sk_buff *skb, unsigned int type)
2054 {
2055 	struct sja1105_private *priv = ds->priv;
2056 	struct sja1105_port *sp = &priv->ports[port];
2057 
2058 	if (!sp->hwts_tx_en)
2059 		return false;
2060 
2061 	return true;
2062 }
2063 
2064 static const struct dsa_switch_ops sja1105_switch_ops = {
2065 	.get_tag_protocol	= sja1105_get_tag_protocol,
2066 	.setup			= sja1105_setup,
2067 	.teardown		= sja1105_teardown,
2068 	.set_ageing_time	= sja1105_set_ageing_time,
2069 	.phylink_validate	= sja1105_phylink_validate,
2070 	.phylink_mac_config	= sja1105_mac_config,
2071 	.phylink_mac_link_up	= sja1105_mac_link_up,
2072 	.phylink_mac_link_down	= sja1105_mac_link_down,
2073 	.get_strings		= sja1105_get_strings,
2074 	.get_ethtool_stats	= sja1105_get_ethtool_stats,
2075 	.get_sset_count		= sja1105_get_sset_count,
2076 	.get_ts_info		= sja1105_get_ts_info,
2077 	.port_fdb_dump		= sja1105_fdb_dump,
2078 	.port_fdb_add		= sja1105_fdb_add,
2079 	.port_fdb_del		= sja1105_fdb_del,
2080 	.port_bridge_join	= sja1105_bridge_join,
2081 	.port_bridge_leave	= sja1105_bridge_leave,
2082 	.port_stp_state_set	= sja1105_bridge_stp_state_set,
2083 	.port_vlan_prepare	= sja1105_vlan_prepare,
2084 	.port_vlan_filtering	= sja1105_vlan_filtering,
2085 	.port_vlan_add		= sja1105_vlan_add,
2086 	.port_vlan_del		= sja1105_vlan_del,
2087 	.port_mdb_prepare	= sja1105_mdb_prepare,
2088 	.port_mdb_add		= sja1105_mdb_add,
2089 	.port_mdb_del		= sja1105_mdb_del,
2090 	.port_deferred_xmit	= sja1105_port_deferred_xmit,
2091 	.port_hwtstamp_get	= sja1105_hwtstamp_get,
2092 	.port_hwtstamp_set	= sja1105_hwtstamp_set,
2093 	.port_rxtstamp		= sja1105_port_rxtstamp,
2094 	.port_txtstamp		= sja1105_port_txtstamp,
2095 };
2096 
2097 static int sja1105_check_device_id(struct sja1105_private *priv)
2098 {
2099 	const struct sja1105_regs *regs = priv->info->regs;
2100 	u8 prod_id[SJA1105_SIZE_DEVICE_ID] = {0};
2101 	struct device *dev = &priv->spidev->dev;
2102 	u64 device_id;
2103 	u64 part_no;
2104 	int rc;
2105 
2106 	rc = sja1105_spi_send_int(priv, SPI_READ, regs->device_id,
2107 				  &device_id, SJA1105_SIZE_DEVICE_ID);
2108 	if (rc < 0)
2109 		return rc;
2110 
2111 	if (device_id != priv->info->device_id) {
2112 		dev_err(dev, "Expected device ID 0x%llx but read 0x%llx\n",
2113 			priv->info->device_id, device_id);
2114 		return -ENODEV;
2115 	}
2116 
2117 	rc = sja1105_spi_send_packed_buf(priv, SPI_READ, regs->prod_id,
2118 					 prod_id, SJA1105_SIZE_DEVICE_ID);
2119 	if (rc < 0)
2120 		return rc;
2121 
2122 	sja1105_unpack(prod_id, &part_no, 19, 4, SJA1105_SIZE_DEVICE_ID);
2123 
2124 	if (part_no != priv->info->part_no) {
2125 		dev_err(dev, "Expected part number 0x%llx but read 0x%llx\n",
2126 			priv->info->part_no, part_no);
2127 		return -ENODEV;
2128 	}
2129 
2130 	return 0;
2131 }
2132 
2133 static int sja1105_probe(struct spi_device *spi)
2134 {
2135 	struct sja1105_tagger_data *tagger_data;
2136 	struct device *dev = &spi->dev;
2137 	struct sja1105_private *priv;
2138 	struct dsa_switch *ds;
2139 	int rc, i;
2140 
2141 	if (!dev->of_node) {
2142 		dev_err(dev, "No DTS bindings for SJA1105 driver\n");
2143 		return -EINVAL;
2144 	}
2145 
2146 	priv = devm_kzalloc(dev, sizeof(struct sja1105_private), GFP_KERNEL);
2147 	if (!priv)
2148 		return -ENOMEM;
2149 
2150 	/* Configure the optional reset pin and bring up switch */
2151 	priv->reset_gpio = devm_gpiod_get(dev, "reset", GPIOD_OUT_HIGH);
2152 	if (IS_ERR(priv->reset_gpio))
2153 		dev_dbg(dev, "reset-gpios not defined, ignoring\n");
2154 	else
2155 		sja1105_hw_reset(priv->reset_gpio, 1, 1);
2156 
2157 	/* Populate our driver private structure (priv) based on
2158 	 * the device tree node that was probed (spi)
2159 	 */
2160 	priv->spidev = spi;
2161 	spi_set_drvdata(spi, priv);
2162 
2163 	/* Configure the SPI bus */
2164 	spi->bits_per_word = 8;
2165 	rc = spi_setup(spi);
2166 	if (rc < 0) {
2167 		dev_err(dev, "Could not init SPI\n");
2168 		return rc;
2169 	}
2170 
2171 	priv->info = of_device_get_match_data(dev);
2172 
2173 	/* Detect hardware device */
2174 	rc = sja1105_check_device_id(priv);
2175 	if (rc < 0) {
2176 		dev_err(dev, "Device ID check failed: %d\n", rc);
2177 		return rc;
2178 	}
2179 
2180 	dev_info(dev, "Probed switch chip: %s\n", priv->info->name);
2181 
2182 	ds = dsa_switch_alloc(dev, SJA1105_NUM_PORTS);
2183 	if (!ds)
2184 		return -ENOMEM;
2185 
2186 	ds->ops = &sja1105_switch_ops;
2187 	ds->priv = priv;
2188 	priv->ds = ds;
2189 
2190 	tagger_data = &priv->tagger_data;
2191 	skb_queue_head_init(&tagger_data->skb_rxtstamp_queue);
2192 	INIT_WORK(&tagger_data->rxtstamp_work, sja1105_rxtstamp_work);
2193 
2194 	/* Connections between dsa_port and sja1105_port */
2195 	for (i = 0; i < SJA1105_NUM_PORTS; i++) {
2196 		struct sja1105_port *sp = &priv->ports[i];
2197 
2198 		ds->ports[i].priv = sp;
2199 		sp->dp = &ds->ports[i];
2200 		sp->data = tagger_data;
2201 	}
2202 	mutex_init(&priv->mgmt_lock);
2203 
2204 	return dsa_register_switch(priv->ds);
2205 }
2206 
2207 static int sja1105_remove(struct spi_device *spi)
2208 {
2209 	struct sja1105_private *priv = spi_get_drvdata(spi);
2210 
2211 	sja1105_ptp_clock_unregister(priv);
2212 	dsa_unregister_switch(priv->ds);
2213 	sja1105_static_config_free(&priv->static_config);
2214 	return 0;
2215 }
2216 
2217 static const struct of_device_id sja1105_dt_ids[] = {
2218 	{ .compatible = "nxp,sja1105e", .data = &sja1105e_info },
2219 	{ .compatible = "nxp,sja1105t", .data = &sja1105t_info },
2220 	{ .compatible = "nxp,sja1105p", .data = &sja1105p_info },
2221 	{ .compatible = "nxp,sja1105q", .data = &sja1105q_info },
2222 	{ .compatible = "nxp,sja1105r", .data = &sja1105r_info },
2223 	{ .compatible = "nxp,sja1105s", .data = &sja1105s_info },
2224 	{ /* sentinel */ },
2225 };
2226 MODULE_DEVICE_TABLE(of, sja1105_dt_ids);
2227 
2228 static struct spi_driver sja1105_driver = {
2229 	.driver = {
2230 		.name  = "sja1105",
2231 		.owner = THIS_MODULE,
2232 		.of_match_table = of_match_ptr(sja1105_dt_ids),
2233 	},
2234 	.probe  = sja1105_probe,
2235 	.remove = sja1105_remove,
2236 };
2237 
2238 module_spi_driver(sja1105_driver);
2239 
2240 MODULE_AUTHOR("Vladimir Oltean <olteanv@gmail.com>");
2241 MODULE_AUTHOR("Georg Waibel <georg.waibel@sensor-technik.de>");
2242 MODULE_DESCRIPTION("SJA1105 Driver");
2243 MODULE_LICENSE("GPL v2");
2244