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 	int err;
24 
25 	/*
26 	 * find the sandbox parent mdio and write a register on the PHY there
27 	 * so the mux test can verify selection.
28 	 */
29 	err = uclass_get_device_by_name(UCLASS_MDIO, "mdio-test", &mdio);
30 	if (err)
31 		return err;
32 	return dm_mdio_write(mdio, SANDBOX_PHY_ADDR, MDIO_DEVAD_NONE,
33 			     SANDBOX_PHY_REG_CNT - 1, (u16)sel);
34 }
35 
mdio_mux_sandbox_select(struct udevice * dev,int cur,int sel)36 static int mdio_mux_sandbox_select(struct udevice *dev, int cur, int sel)
37 {
38 	struct mdio_mux_sandbox_priv *priv = dev_get_priv(dev);
39 
40 	if (!priv->enabled)
41 		return -ENODEV;
42 
43 	if (cur != priv->sel)
44 		return -EINVAL;
45 
46 	priv->sel = sel;
47 	mdio_mux_sandbox_mark_selection(dev, priv->sel);
48 
49 	return 0;
50 }
51 
mdio_mux_sandbox_deselect(struct udevice * dev,int sel)52 static int mdio_mux_sandbox_deselect(struct udevice *dev, int sel)
53 {
54 	struct mdio_mux_sandbox_priv *priv = dev_get_priv(dev);
55 
56 	if (!priv->enabled)
57 		return -ENODEV;
58 
59 	if (sel != priv->sel)
60 		return -EINVAL;
61 
62 	priv->sel = -1;
63 	mdio_mux_sandbox_mark_selection(dev, priv->sel);
64 
65 	return 0;
66 }
67 
68 static const struct mdio_mux_ops mdio_mux_sandbox_ops = {
69 	.select = mdio_mux_sandbox_select,
70 	.deselect = mdio_mux_sandbox_deselect,
71 };
72 
mdio_mux_sandbox_probe(struct udevice * dev)73 static int mdio_mux_sandbox_probe(struct udevice *dev)
74 {
75 	struct mdio_mux_sandbox_priv *priv = dev_get_priv(dev);
76 
77 	priv->enabled = 1;
78 	priv->sel = -1;
79 
80 	return 0;
81 }
82 
83 static const struct udevice_id mdio_mux_sandbox_ids[] = {
84 	{ .compatible = "sandbox,mdio-mux" },
85 	{ }
86 };
87 
88 U_BOOT_DRIVER(mdio_mux_sandbox) = {
89 	.name		= "mdio_mux_sandbox",
90 	.id		= UCLASS_MDIO_MUX,
91 	.of_match	= mdio_mux_sandbox_ids,
92 	.probe		= mdio_mux_sandbox_probe,
93 	.ops		= &mdio_mux_sandbox_ops,
94 	.priv_auto	= sizeof(struct mdio_mux_sandbox_priv),
95 };
96