1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2011 Google, Inc.
4  *
5  * This software is licensed under the terms of the GNU General Public
6  * License version 2, as published by the Free Software Foundation, and
7  * may be copied, distributed, and modified under those terms.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  */
15 
16 #include <linux/export.h>
17 #include <linux/kernel.h>
18 #include <linux/usb.h>
19 #include <linux/io.h>
20 #include <linux/usb/otg.h>
21 #include <linux/usb/ulpi.h>
22 
23 #define ULPI_VIEW_WAKEUP	(1 << 31)
24 #define ULPI_VIEW_RUN		(1 << 30)
25 #define ULPI_VIEW_WRITE		(1 << 29)
26 #define ULPI_VIEW_READ		(0 << 29)
27 #define ULPI_VIEW_ADDR(x)	(((x) & 0xff) << 16)
28 #define ULPI_VIEW_DATA_READ(x)	(((x) >> 8) & 0xff)
29 #define ULPI_VIEW_DATA_WRITE(x)	((x) & 0xff)
30 
31 static int ulpi_viewport_wait(void __iomem *view, u32 mask)
32 {
33 	unsigned long usec = 2000;
34 
35 	while (usec--) {
36 		if (!(readl(view) & mask))
37 			return 0;
38 
39 		udelay(1);
40 	}
41 
42 	return -ETIMEDOUT;
43 }
44 
45 static int ulpi_viewport_read(struct usb_phy *otg, u32 reg)
46 {
47 	int ret;
48 	void __iomem *view = otg->io_priv;
49 
50 	writel(ULPI_VIEW_WAKEUP | ULPI_VIEW_WRITE, view);
51 	ret = ulpi_viewport_wait(view, ULPI_VIEW_WAKEUP);
52 	if (ret)
53 		return ret;
54 
55 	writel(ULPI_VIEW_RUN | ULPI_VIEW_READ | ULPI_VIEW_ADDR(reg), view);
56 	ret = ulpi_viewport_wait(view, ULPI_VIEW_RUN);
57 	if (ret)
58 		return ret;
59 
60 	return ULPI_VIEW_DATA_READ(readl(view));
61 }
62 
63 static int ulpi_viewport_write(struct usb_phy *otg, u32 val, u32 reg)
64 {
65 	int ret;
66 	void __iomem *view = otg->io_priv;
67 
68 	writel(ULPI_VIEW_WAKEUP | ULPI_VIEW_WRITE, view);
69 	ret = ulpi_viewport_wait(view, ULPI_VIEW_WAKEUP);
70 	if (ret)
71 		return ret;
72 
73 	writel(ULPI_VIEW_RUN | ULPI_VIEW_WRITE | ULPI_VIEW_DATA_WRITE(val) |
74 						 ULPI_VIEW_ADDR(reg), view);
75 
76 	return ulpi_viewport_wait(view, ULPI_VIEW_RUN);
77 }
78 
79 struct usb_phy_io_ops ulpi_viewport_access_ops = {
80 	.read	= ulpi_viewport_read,
81 	.write	= ulpi_viewport_write,
82 };
83 EXPORT_SYMBOL_GPL(ulpi_viewport_access_ops);
84