1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2019
4  * Alex Marginean, NXP
5  */
6 
7 #include <dm.h>
8 #include <errno.h>
9 #include <miiphy.h>
10 
11 /* macros copied over from mdio_sandbox.c */
12 #define SANDBOX_PHY_ADDR	5
13 #define SANDBOX_PHY_REG_CNT	2
14 
15 struct mdio_mux_sandbox_priv {
16 	int enabled;
17 	int sel;
18 };
19 
mdio_mux_sandbox_mark_selection(struct udevice * dev,int sel)20 static int mdio_mux_sandbox_mark_selection(struct udevice *dev, int sel)
21 {
22 	struct udevice *mdio;
23 	struct mdio_ops *ops;
24 	int err;
25 
26 	/*
27 	 * find the sandbox parent mdio and write a register on the PHY there
28 	 * so the mux test can verify selection.
29 	 */
30 	err = uclass_get_device_by_name(UCLASS_MDIO, "mdio-test", &mdio);
31 	if (err)
32 		return err;
33 	ops = mdio_get_ops(mdio);
34 	return ops->write(mdio, SANDBOX_PHY_ADDR, MDIO_DEVAD_NONE,
35 			  SANDBOX_PHY_REG_CNT - 1, (u16)sel);
36 }
37 
mdio_mux_sandbox_select(struct udevice * dev,int cur,int sel)38 static int mdio_mux_sandbox_select(struct udevice *dev, int cur, int sel)
39 {
40 	struct mdio_mux_sandbox_priv *priv = dev_get_priv(dev);
41 
42 	if (!priv->enabled)
43 		return -ENODEV;
44 
45 	if (cur != priv->sel)
46 		return -EINVAL;
47 
48 	priv->sel = sel;
49 	mdio_mux_sandbox_mark_selection(dev, priv->sel);
50 
51 	return 0;
52 }
53 
mdio_mux_sandbox_deselect(struct udevice * dev,int sel)54 static int mdio_mux_sandbox_deselect(struct udevice *dev, int sel)
55 {
56 	struct mdio_mux_sandbox_priv *priv = dev_get_priv(dev);
57 
58 	if (!priv->enabled)
59 		return -ENODEV;
60 
61 	if (sel != priv->sel)
62 		return -EINVAL;
63 
64 	priv->sel = -1;
65 	mdio_mux_sandbox_mark_selection(dev, priv->sel);
66 
67 	return 0;
68 }
69 
70 static const struct mdio_mux_ops mdio_mux_sandbox_ops = {
71 	.select = mdio_mux_sandbox_select,
72 	.deselect = mdio_mux_sandbox_deselect,
73 };
74 
mdio_mux_sandbox_probe(struct udevice * dev)75 static int mdio_mux_sandbox_probe(struct udevice *dev)
76 {
77 	struct mdio_mux_sandbox_priv *priv = dev_get_priv(dev);
78 
79 	priv->enabled = 1;
80 	priv->sel = -1;
81 
82 	return 0;
83 }
84 
85 static const struct udevice_id mdio_mux_sandbox_ids[] = {
86 	{ .compatible = "sandbox,mdio-mux" },
87 	{ }
88 };
89 
90 U_BOOT_DRIVER(mdio_mux_sandbox) = {
91 	.name		= "mdio_mux_sandbox",
92 	.id		= UCLASS_MDIO_MUX,
93 	.of_match	= mdio_mux_sandbox_ids,
94 	.probe		= mdio_mux_sandbox_probe,
95 	.ops		= &mdio_mux_sandbox_ops,
96 	.priv_auto	= sizeof(struct mdio_mux_sandbox_priv),
97 };
98