1 /*
2  * Copyright (c) 2018 Alexander Graf <agraf@suse.de>
3  *
4  * SPDX-License-Identifier:	GPL-2.0+
5  */
6 
7 #include <common.h>
8 #include <dm.h>
9 #include <asm/gpio.h>
10 #include <dm/pinctrl.h>
11 #include <dm/platform_data/serial_pl01x.h>
12 #include <serial.h>
13 #include "serial_pl01x_internal.h"
14 
15 /*
16  * Check if this serial device is muxed
17  *
18  * The serial device will only work properly if it has been muxed to the serial
19  * pins by firmware. Check whether that happened here.
20  *
21  * @return true if serial device is muxed, false if not
22  */
23 static bool bcm283x_is_serial_muxed(void)
24 {
25 	int serial_gpio = 15;
26 	struct udevice *dev;
27 
28 	if (uclass_first_device(UCLASS_PINCTRL, &dev) || !dev)
29 		return false;
30 
31 	if (pinctrl_get_gpio_mux(dev, 0, serial_gpio) != BCM2835_GPIO_ALT0)
32 		return false;
33 
34 	return true;
35 }
36 
37 static int bcm283x_pl011_serial_ofdata_to_platdata(struct udevice *dev)
38 {
39 	struct pl01x_serial_platdata *plat = dev_get_platdata(dev);
40 	int ret;
41 
42 	/* Don't spawn the device if it's not muxed */
43 	if (!bcm283x_is_serial_muxed())
44 		return -ENODEV;
45 
46 	ret = pl01x_serial_ofdata_to_platdata(dev);
47 	if (ret)
48 		return ret;
49 
50 	/*
51 	 * TODO: Reinitialization doesn't always work for now, just skip
52 	 *       init always - we know we're already initialized
53 	 */
54 	plat->skip_init = true;
55 
56 	return 0;
57 }
58 
59 static int bcm283x_pl011_serial_setbrg(struct udevice *dev, int baudrate)
60 {
61 	int r;
62 
63 	r = pl01x_serial_setbrg(dev, baudrate);
64 
65 	/*
66 	 * We may have been muxed to a bogus line before. Drain the RX
67 	 * queue so we start at a clean slate.
68 	 */
69 	while (pl01x_serial_getc(dev) != -EAGAIN) ;
70 
71 	return r;
72 }
73 
74 static const struct dm_serial_ops bcm283x_pl011_serial_ops = {
75 	.putc = pl01x_serial_putc,
76 	.pending = pl01x_serial_pending,
77 	.getc = pl01x_serial_getc,
78 	.setbrg = bcm283x_pl011_serial_setbrg,
79 };
80 
81 static const struct udevice_id bcm283x_pl011_serial_id[] = {
82 	{.compatible = "brcm,bcm2835-pl011", .data = TYPE_PL011},
83 	{}
84 };
85 
86 U_BOOT_DRIVER(bcm283x_pl011_uart) = {
87 	.name	= "bcm283x_pl011",
88 	.id	= UCLASS_SERIAL,
89 	.of_match = of_match_ptr(bcm283x_pl011_serial_id),
90 	.ofdata_to_platdata = of_match_ptr(bcm283x_pl011_serial_ofdata_to_platdata),
91 	.platdata_auto_alloc_size = sizeof(struct pl01x_serial_platdata),
92 	.probe	= pl01x_serial_probe,
93 	.ops	= &bcm283x_pl011_serial_ops,
94 	.flags	= DM_FLAG_PRE_RELOC,
95 	.priv_auto_alloc_size = sizeof(struct pl01x_priv),
96 };
97