aboutsummaryrefslogtreecommitdiff
path: root/drivers
diff options
context:
space:
mode:
Diffstat (limited to 'drivers')
-rw-r--r--drivers/Makefile1
-rw-r--r--drivers/clk/Makefile1
-rw-r--r--drivers/clk/clk_pic32.c433
-rw-r--r--drivers/core/device.c9
-rw-r--r--drivers/ddr/fsl/fsl_ddr_gen4.c28
-rw-r--r--drivers/ddr/fsl/main.c1
-rw-r--r--drivers/ddr/microchip/Makefile6
-rw-r--r--drivers/ddr/microchip/ddr2.c278
-rw-r--r--drivers/ddr/microchip/ddr2_regs.h148
-rw-r--r--drivers/ddr/microchip/ddr2_timing.h65
-rw-r--r--drivers/fpga/xilinx.c4
-rw-r--r--drivers/gpio/Kconfig7
-rw-r--r--drivers/gpio/Makefile2
-rw-r--r--drivers/gpio/pic32_gpio.c174
-rw-r--r--drivers/hwmon/adt7460.c2
-rw-r--r--drivers/misc/Kconfig8
-rw-r--r--drivers/misc/Makefile1
-rw-r--r--drivers/misc/winbond_w83627.c41
-rw-r--r--drivers/mmc/Kconfig6
-rw-r--r--drivers/mmc/Makefile2
-rw-r--r--drivers/mmc/fsl_esdhc.c14
-rw-r--r--drivers/mmc/pic32_sdhci.c58
-rw-r--r--drivers/mmc/sdhci.c11
-rw-r--r--drivers/mmc/zynq_sdhci.c12
-rw-r--r--drivers/net/Kconfig24
-rw-r--r--drivers/net/Makefile1
-rw-r--r--drivers/net/designware.c16
-rw-r--r--drivers/net/designware.h1
-rw-r--r--drivers/net/fsl-mc/dpio/qbman_portal.c4
-rw-r--r--drivers/net/fsl-mc/dpni.c81
-rw-r--r--drivers/net/fsl-mc/mc.c70
-rw-r--r--drivers/net/fsl_mdio.c4
-rw-r--r--drivers/net/ldpaa_eth/ldpaa_eth.c122
-rw-r--r--drivers/net/ldpaa_eth/ldpaa_eth.h2
-rw-r--r--drivers/net/phy/cortina.c7
-rw-r--r--drivers/net/phy/micrel.c25
-rw-r--r--drivers/net/phy/phy.c102
-rw-r--r--drivers/net/phy/smsc.c10
-rw-r--r--drivers/net/phy/ti.c3
-rw-r--r--drivers/net/pic32_eth.c605
-rw-r--r--drivers/net/pic32_eth.h164
-rw-r--r--drivers/net/pic32_mdio.c121
-rw-r--r--drivers/net/tsec.c536
-rw-r--r--drivers/net/vsc9953.c354
-rw-r--r--drivers/net/xilinx_axi_emac.c280
-rw-r--r--drivers/net/xilinx_emaclite.c610
-rw-r--r--drivers/net/xilinx_ll_temac.c3
-rw-r--r--drivers/net/zynq_gem.c4
-rw-r--r--drivers/pci/pci-uclass.c15
-rw-r--r--drivers/pci/pci_tegra.c6
-rw-r--r--drivers/pinctrl/Kconfig10
-rw-r--r--drivers/pinctrl/Makefile1
-rw-r--r--drivers/pinctrl/pinctrl_pic32.c363
-rw-r--r--drivers/serial/Kconfig29
-rw-r--r--drivers/serial/Makefile1
-rw-r--r--drivers/serial/serial_pic32.c198
-rw-r--r--drivers/serial/serial_xuartlite.c194
-rw-r--r--drivers/serial/serial_zynq.c8
-rw-r--r--drivers/spi/fsl_qspi.c20
-rw-r--r--drivers/tpm/Kconfig20
-rw-r--r--drivers/tpm/Makefile2
-rw-r--r--drivers/tpm/tpm_tis.h (renamed from drivers/tpm/tpm_tis_infineon.h)17
-rw-r--r--drivers/tpm/tpm_tis_infineon.c17
-rw-r--r--drivers/tpm/tpm_tis_st33zp24_i2c.c543
-rw-r--r--drivers/tpm/tpm_tis_st33zp24_spi.c672
-rw-r--r--drivers/video/Kconfig36
-rw-r--r--drivers/video/Makefile6
-rw-r--r--drivers/video/console_normal.c24
-rw-r--r--drivers/video/console_rotate.c65
-rw-r--r--drivers/video/console_truetype.c550
-rw-r--r--drivers/video/fonts/Kconfig51
-rw-r--r--drivers/video/fonts/Makefile11
-rw-r--r--drivers/video/fonts/ankacoder_c75_r.ttfbin0 -> 65596 bytes
-rw-r--r--drivers/video/fonts/cantoraone_regular.ttfbin0 -> 163116 bytes
-rw-r--r--drivers/video/fonts/nimbus_sans_l_regular.ttfbin0 -> 61660 bytes
-rw-r--r--drivers/video/fonts/rufscript010.ttfbin0 -> 23080 bytes
-rw-r--r--drivers/video/sandbox_sdl.c2
-rw-r--r--drivers/video/stb_truetype.h3240
-rw-r--r--drivers/video/vidconsole-uclass.c84
-rw-r--r--drivers/video/video-uclass.c29
80 files changed, 9951 insertions, 724 deletions
diff --git a/drivers/Makefile b/drivers/Makefile
index 6294048f261..e7eab6603e0 100644
--- a/drivers/Makefile
+++ b/drivers/Makefile
@@ -69,4 +69,5 @@ obj-y += soc/
obj-$(CONFIG_REMOTEPROC) += remoteproc/
obj-y += thermal/
+obj-$(CONFIG_MACH_PIC32) += ddr/microchip/
endif
diff --git a/drivers/clk/Makefile b/drivers/clk/Makefile
index 8aa81f49f4f..c9144e3e1d4 100644
--- a/drivers/clk/Makefile
+++ b/drivers/clk/Makefile
@@ -9,3 +9,4 @@ obj-$(CONFIG_CLK) += clk-uclass.o clk_fixed_rate.o
obj-$(CONFIG_ROCKCHIP_RK3036) += clk_rk3036.o
obj-$(CONFIG_ROCKCHIP_RK3288) += clk_rk3288.o
obj-$(CONFIG_SANDBOX) += clk_sandbox.o
+obj-$(CONFIG_MACH_PIC32) += clk_pic32.o
diff --git a/drivers/clk/clk_pic32.c b/drivers/clk/clk_pic32.c
new file mode 100644
index 00000000000..5d883544d51
--- /dev/null
+++ b/drivers/clk/clk_pic32.c
@@ -0,0 +1,433 @@
+/*
+ * Copyright (C) 2015 Purna Chandra Mandal <purna.mandal@microchip.com>
+ *
+ * SPDX-License-Identifier: GPL-2.0+
+ *
+ */
+
+#include <common.h>
+#include <clk.h>
+#include <dm.h>
+#include <div64.h>
+#include <wait_bit.h>
+#include <dm/lists.h>
+#include <asm/io.h>
+#include <mach/pic32.h>
+#include <dt-bindings/clock/microchip,clock.h>
+
+DECLARE_GLOBAL_DATA_PTR;
+
+/* Primary oscillator */
+#define SYS_POSC_CLK_HZ 24000000
+
+/* FRC clk rate */
+#define SYS_FRC_CLK_HZ 8000000
+
+/* Clock Registers */
+#define OSCCON 0x0000
+#define OSCTUNE 0x0010
+#define SPLLCON 0x0020
+#define REFO1CON 0x0080
+#define REFO1TRIM 0x0090
+#define PB1DIV 0x0140
+
+/* SPLL */
+#define ICLK_MASK 0x00000080
+#define PLLIDIV_MASK 0x00000007
+#define PLLODIV_MASK 0x00000007
+#define CUROSC_MASK 0x00000007
+#define PLLMUL_MASK 0x0000007F
+#define FRCDIV_MASK 0x00000007
+
+/* PBCLK */
+#define PBDIV_MASK 0x00000007
+
+/* SYSCLK MUX */
+#define SCLK_SRC_FRC1 0
+#define SCLK_SRC_SPLL 1
+#define SCLK_SRC_POSC 2
+#define SCLK_SRC_FRC2 7
+
+/* Reference Oscillator Control Reg fields */
+#define REFO_SEL_MASK 0x0f
+#define REFO_SEL_SHIFT 0
+#define REFO_ACTIVE BIT(8)
+#define REFO_DIVSW_EN BIT(9)
+#define REFO_OE BIT(12)
+#define REFO_ON BIT(15)
+#define REFO_DIV_SHIFT 16
+#define REFO_DIV_MASK 0x7fff
+
+/* Reference Oscillator Trim Register Fields */
+#define REFO_TRIM_REG 0x10
+#define REFO_TRIM_MASK 0x1ff
+#define REFO_TRIM_SHIFT 23
+#define REFO_TRIM_MAX 511
+
+#define ROCLK_SRC_SCLK 0x0
+#define ROCLK_SRC_SPLL 0x7
+#define ROCLK_SRC_ROCLKI 0x8
+
+/* Memory PLL */
+#define MPLL_IDIV 0x3f
+#define MPLL_MULT 0xff
+#define MPLL_ODIV1 0x7
+#define MPLL_ODIV2 0x7
+#define MPLL_VREG_RDY BIT(23)
+#define MPLL_RDY BIT(31)
+#define MPLL_IDIV_SHIFT 0
+#define MPLL_MULT_SHIFT 8
+#define MPLL_ODIV1_SHIFT 24
+#define MPLL_ODIV2_SHIFT 27
+#define MPLL_IDIV_INIT 0x03
+#define MPLL_MULT_INIT 0x32
+#define MPLL_ODIV1_INIT 0x02
+#define MPLL_ODIV2_INIT 0x01
+
+struct pic32_clk_priv {
+ void __iomem *iobase;
+ void __iomem *syscfg_base;
+};
+
+static ulong pic32_get_pll_rate(struct pic32_clk_priv *priv)
+{
+ u32 iclk, idiv, odiv, mult;
+ ulong plliclk, v;
+
+ v = readl(priv->iobase + SPLLCON);
+ iclk = (v & ICLK_MASK);
+ idiv = ((v >> 8) & PLLIDIV_MASK) + 1;
+ odiv = ((v >> 24) & PLLODIV_MASK);
+ mult = ((v >> 16) & PLLMUL_MASK) + 1;
+
+ plliclk = iclk ? SYS_FRC_CLK_HZ : SYS_POSC_CLK_HZ;
+
+ if (odiv < 2)
+ odiv = 2;
+ else if (odiv < 5)
+ odiv = (1 << odiv);
+ else
+ odiv = 32;
+
+ return ((plliclk / idiv) * mult) / odiv;
+}
+
+static ulong pic32_get_sysclk(struct pic32_clk_priv *priv)
+{
+ ulong v;
+ ulong hz;
+ ulong div, frcdiv;
+ ulong curr_osc;
+
+ /* get clk source */
+ v = readl(priv->iobase + OSCCON);
+ curr_osc = (v >> 12) & CUROSC_MASK;
+ switch (curr_osc) {
+ case SCLK_SRC_FRC1:
+ case SCLK_SRC_FRC2:
+ frcdiv = ((v >> 24) & FRCDIV_MASK);
+ div = ((1 << frcdiv) + 1) + (128 * (frcdiv == 7));
+ hz = SYS_FRC_CLK_HZ / div;
+ break;
+
+ case SCLK_SRC_SPLL:
+ hz = pic32_get_pll_rate(priv);
+ break;
+
+ case SCLK_SRC_POSC:
+ hz = SYS_POSC_CLK_HZ;
+ break;
+
+ default:
+ hz = 0;
+ printf("clk: unknown sclk_src.\n");
+ break;
+ }
+
+ return hz;
+}
+
+static ulong pic32_get_pbclk(struct pic32_clk_priv *priv, int periph)
+{
+ void __iomem *reg;
+ ulong div, clk_freq;
+
+ WARN_ON((periph < PB1CLK) || (periph > PB7CLK));
+
+ clk_freq = pic32_get_sysclk(priv);
+
+ reg = priv->iobase + PB1DIV + (periph - PB1CLK) * 0x10;
+ div = (readl(reg) & PBDIV_MASK) + 1;
+
+ return clk_freq / div;
+}
+
+static ulong pic32_get_cpuclk(struct pic32_clk_priv *priv)
+{
+ return pic32_get_pbclk(priv, PB7CLK);
+}
+
+static ulong pic32_set_refclk(struct pic32_clk_priv *priv, int periph,
+ int parent_rate, int rate, int parent_id)
+{
+ void __iomem *reg;
+ u32 div, trim, v;
+ u64 frac;
+
+ WARN_ON((periph < REF1CLK) || (periph > REF5CLK));
+
+ /* calculate dividers,
+ * rate = parent_rate / [2 * (div + (trim / 512))]
+ */
+ if (parent_rate <= rate) {
+ div = 0;
+ trim = 0;
+ } else {
+ div = parent_rate / (rate << 1);
+ frac = parent_rate;
+ frac <<= 8;
+ do_div(frac, rate);
+ frac -= (u64)(div << 9);
+ trim = (frac >= REFO_TRIM_MAX) ? REFO_TRIM_MAX : (u32)frac;
+ }
+
+ reg = priv->iobase + REFO1CON + (periph - REF1CLK) * 0x20;
+
+ /* disable clk */
+ writel(REFO_ON | REFO_OE, reg + _CLR_OFFSET);
+
+ /* wait till previous src change is active */
+ wait_for_bit(__func__, reg, REFO_DIVSW_EN | REFO_ACTIVE,
+ false, CONFIG_SYS_HZ, false);
+
+ /* parent_id */
+ v = readl(reg);
+ v &= ~(REFO_SEL_MASK << REFO_SEL_SHIFT);
+ v |= (parent_id << REFO_SEL_SHIFT);
+
+ /* apply rodiv */
+ v &= ~(REFO_DIV_MASK << REFO_DIV_SHIFT);
+ v |= (div << REFO_DIV_SHIFT);
+ writel(v, reg);
+
+ /* apply trim */
+ v = readl(reg + REFO_TRIM_REG);
+ v &= ~(REFO_TRIM_MASK << REFO_TRIM_SHIFT);
+ v |= (trim << REFO_TRIM_SHIFT);
+ writel(v, reg + REFO_TRIM_REG);
+
+ /* enable clk */
+ writel(REFO_ON | REFO_OE, reg + _SET_OFFSET);
+
+ /* switch divider */
+ writel(REFO_DIVSW_EN, reg + _SET_OFFSET);
+
+ /* wait for divider switching to complete */
+ return wait_for_bit(__func__, reg, REFO_DIVSW_EN, false,
+ CONFIG_SYS_HZ, false);
+}
+
+static ulong pic32_get_refclk(struct pic32_clk_priv *priv, int periph)
+{
+ u32 rodiv, rotrim, rosel, v, parent_rate;
+ void __iomem *reg;
+ u64 rate64;
+
+ WARN_ON((periph < REF1CLK) || (periph > REF5CLK));
+
+ reg = priv->iobase + REFO1CON + (periph - REF1CLK) * 0x20;
+ v = readl(reg);
+ /* get rosel */
+ rosel = (v >> REFO_SEL_SHIFT) & REFO_SEL_MASK;
+ /* get div */
+ rodiv = (v >> REFO_DIV_SHIFT) & REFO_DIV_MASK;
+
+ /* get trim */
+ v = readl(reg + REFO_TRIM_REG);
+ rotrim = (v >> REFO_TRIM_SHIFT) & REFO_TRIM_MASK;
+
+ if (!rodiv)
+ return 0;
+
+ /* get parent rate */
+ switch (rosel) {
+ case ROCLK_SRC_SCLK:
+ parent_rate = pic32_get_cpuclk(priv);
+ break;
+ case ROCLK_SRC_SPLL:
+ parent_rate = pic32_get_pll_rate(priv);
+ break;
+ default:
+ parent_rate = 0;
+ break;
+ }
+
+ /* Calculation
+ * rate = parent_rate / [2 * (div + (trim / 512))]
+ */
+ if (rotrim) {
+ rodiv <<= 9;
+ rodiv += rotrim;
+ rate64 = parent_rate;
+ rate64 <<= 8;
+ do_div(rate64, rodiv);
+ v = (u32)rate64;
+ } else {
+ v = parent_rate / (rodiv << 1);
+ }
+ return v;
+}
+
+static ulong pic32_get_mpll_rate(struct pic32_clk_priv *priv)
+{
+ u32 v, idiv, mul;
+ u32 odiv1, odiv2;
+ u64 rate;
+
+ v = readl(priv->syscfg_base + CFGMPLL);
+ idiv = v & MPLL_IDIV;
+ mul = (v >> MPLL_MULT_SHIFT) & MPLL_MULT;
+ odiv1 = (v >> MPLL_ODIV1_SHIFT) & MPLL_ODIV1;
+ odiv2 = (v >> MPLL_ODIV2_SHIFT) & MPLL_ODIV2;
+
+ rate = (SYS_POSC_CLK_HZ / idiv) * mul;
+ do_div(rate, odiv1);
+ do_div(rate, odiv2);
+
+ return (ulong)rate;
+}
+
+static int pic32_mpll_init(struct pic32_clk_priv *priv)
+{
+ u32 v, mask;
+
+ /* initialize */
+ v = (MPLL_IDIV_INIT << MPLL_IDIV_SHIFT) |
+ (MPLL_MULT_INIT << MPLL_MULT_SHIFT) |
+ (MPLL_ODIV1_INIT << MPLL_ODIV1_SHIFT) |
+ (MPLL_ODIV2_INIT << MPLL_ODIV2_SHIFT);
+
+ writel(v, priv->syscfg_base + CFGMPLL);
+
+ /* Wait for ready */
+ mask = MPLL_RDY | MPLL_VREG_RDY;
+ return wait_for_bit(__func__, priv->syscfg_base + CFGMPLL, mask,
+ true, get_tbclk(), false);
+}
+
+static void pic32_clk_init(struct udevice *dev)
+{
+ const void *blob = gd->fdt_blob;
+ struct pic32_clk_priv *priv;
+ ulong rate, pll_hz;
+ char propname[50];
+ int i;
+
+ priv = dev_get_priv(dev);
+ pll_hz = pic32_get_pll_rate(priv);
+
+ /* Initialize REFOs as not initialized and enabled on reset. */
+ for (i = REF1CLK; i <= REF5CLK; i++) {
+ snprintf(propname, sizeof(propname),
+ "microchip,refo%d-frequency", i - REF1CLK + 1);
+ rate = fdtdec_get_int(blob, dev->of_offset, propname, 0);
+ if (rate)
+ pic32_set_refclk(priv, i, pll_hz, rate, ROCLK_SRC_SPLL);
+ }
+
+ /* Memory PLL */
+ pic32_mpll_init(priv);
+}
+
+static ulong pic32_clk_get_rate(struct udevice *dev)
+{
+ struct pic32_clk_priv *priv = dev_get_priv(dev);
+
+ return pic32_get_cpuclk(priv);
+}
+
+static ulong pic32_get_periph_rate(struct udevice *dev, int periph)
+{
+ struct pic32_clk_priv *priv = dev_get_priv(dev);
+ ulong rate;
+
+ switch (periph) {
+ case PB1CLK ... PB7CLK:
+ rate = pic32_get_pbclk(priv, periph);
+ break;
+ case REF1CLK ... REF5CLK:
+ rate = pic32_get_refclk(priv, periph);
+ break;
+ case PLLCLK:
+ rate = pic32_get_pll_rate(priv);
+ break;
+ case MPLL:
+ rate = pic32_get_mpll_rate(priv);
+ break;
+ default:
+ rate = 0;
+ break;
+ }
+
+ return rate;
+}
+
+static ulong pic32_set_periph_rate(struct udevice *dev, int periph, ulong rate)
+{
+ struct pic32_clk_priv *priv = dev_get_priv(dev);
+ ulong pll_hz;
+
+ switch (periph) {
+ case REF1CLK ... REF5CLK:
+ pll_hz = pic32_get_pll_rate(priv);
+ pic32_set_refclk(priv, periph, pll_hz, rate, ROCLK_SRC_SPLL);
+ break;
+ default:
+ break;
+ }
+
+ return rate;
+}
+
+static struct clk_ops pic32_pic32_clk_ops = {
+ .get_rate = pic32_clk_get_rate,
+ .set_periph_rate = pic32_set_periph_rate,
+ .get_periph_rate = pic32_get_periph_rate,
+};
+
+static int pic32_clk_probe(struct udevice *dev)
+{
+ struct pic32_clk_priv *priv = dev_get_priv(dev);
+ fdt_addr_t addr;
+ fdt_size_t size;
+
+ addr = fdtdec_get_addr_size(gd->fdt_blob, dev->of_offset, "reg", &size);
+ if (addr == FDT_ADDR_T_NONE)
+ return -EINVAL;
+
+ priv->iobase = ioremap(addr, size);
+ if (!priv->iobase)
+ return -EINVAL;
+
+ priv->syscfg_base = pic32_get_syscfg_base();
+
+ /* initialize clocks */
+ pic32_clk_init(dev);
+
+ return 0;
+}
+
+static const struct udevice_id pic32_clk_ids[] = {
+ { .compatible = "microchip,pic32mzda-clk"},
+ {}
+};
+
+U_BOOT_DRIVER(pic32_clk) = {
+ .name = "pic32_clk",
+ .id = UCLASS_CLK,
+ .of_match = pic32_clk_ids,
+ .flags = DM_FLAG_PRE_RELOC,
+ .ops = &pic32_pic32_clk_ops,
+ .probe = pic32_clk_probe,
+ .priv_auto_alloc_size = sizeof(struct pic32_clk_priv),
+};
diff --git a/drivers/core/device.c b/drivers/core/device.c
index f5def35b5b6..cb24a617cee 100644
--- a/drivers/core/device.c
+++ b/drivers/core/device.c
@@ -223,7 +223,7 @@ static void *alloc_priv(int size, uint flags)
return priv;
}
-int device_probe_child(struct udevice *dev, void *parent_priv)
+int device_probe(struct udevice *dev)
{
const struct driver *drv;
int size = 0;
@@ -270,8 +270,6 @@ int device_probe_child(struct udevice *dev, void *parent_priv)
ret = -ENOMEM;
goto fail;
}
- if (parent_priv)
- memcpy(dev->parent_priv, parent_priv, size);
}
ret = device_probe(dev->parent);
@@ -349,11 +347,6 @@ fail:
return ret;
}
-int device_probe(struct udevice *dev)
-{
- return device_probe_child(dev, NULL);
-}
-
void *dev_get_platdata(struct udevice *dev)
{
if (!dev) {
diff --git a/drivers/ddr/fsl/fsl_ddr_gen4.c b/drivers/ddr/fsl/fsl_ddr_gen4.c
index 3fca5c2684b..6f76980d319 100644
--- a/drivers/ddr/fsl/fsl_ddr_gen4.c
+++ b/drivers/ddr/fsl/fsl_ddr_gen4.c
@@ -55,6 +55,10 @@ void fsl_ddr_set_memctl_regs(const fsl_ddr_cfg_regs_t *regs,
u32 vref_seq2[3] = {0xc0, 0xf0, 0x70}; /* for range 2 */
u32 *vref_seq = vref_seq1;
#endif
+#ifdef CONFIG_SYS_FSL_ERRATUM_A009942
+ ulong ddr_freq;
+ u32 tmp;
+#endif
#ifdef CONFIG_FSL_DDR_BIST
u32 mtcr, err_detect, err_sbe;
u32 cs0_bnds, cs1_bnds, cs2_bnds, cs3_bnds, cs0_config;
@@ -151,7 +155,12 @@ void fsl_ddr_set_memctl_regs(const fsl_ddr_cfg_regs_t *regs,
ddr_out32(&ddr->sdram_mode_15, regs->ddr_sdram_mode_15);
ddr_out32(&ddr->sdram_mode_16, regs->ddr_sdram_mode_16);
ddr_out32(&ddr->sdram_md_cntl, regs->ddr_sdram_md_cntl);
+#ifdef CONFIG_SYS_FSL_ERRATUM_A009663
+ ddr_out32(&ddr->sdram_interval,
+ regs->ddr_sdram_interval & ~SDRAM_INTERVAL_BSTOPRE);
+#else
ddr_out32(&ddr->sdram_interval, regs->ddr_sdram_interval);
+#endif
ddr_out32(&ddr->sdram_data_init, regs->ddr_data_init);
ddr_out32(&ddr->ddr_wrlvl_cntl, regs->ddr_wrlvl_cntl);
#ifndef CONFIG_SYS_FSL_DDR_EMU
@@ -227,6 +236,20 @@ void fsl_ddr_set_memctl_regs(const fsl_ddr_cfg_regs_t *regs,
ddr_out32(&ddr->debug[25], 0x9000);
}
#endif
+
+#ifdef CONFIG_SYS_FSL_ERRATUM_A009942
+ ddr_freq = get_ddr_freq(ctrl_num) / 1000000;
+ tmp = ddr_in32(&ddr->debug[28]);
+ if (ddr_freq <= 1333)
+ ddr_out32(&ddr->debug[28], tmp | 0x0080006a);
+ else if (ddr_freq <= 1600)
+ ddr_out32(&ddr->debug[28], tmp | 0x0070006f);
+ else if (ddr_freq <= 1867)
+ ddr_out32(&ddr->debug[28], tmp | 0x00700076);
+ else if (ddr_freq <= 2133)
+ ddr_out32(&ddr->debug[28], tmp | 0x0060007b);
+#endif
+
/*
* For RDIMMs, JEDEC spec requires clocks to be stable before reset is
* deasserted. Clocks start when any chip select is enabled and clock
@@ -379,6 +402,11 @@ step2:
if (timeout <= 0)
printf("Waiting for D_INIT timeout. Memory may not work.\n");
+
+#ifdef CONFIG_SYS_FSL_ERRATUM_A009663
+ ddr_out32(&ddr->sdram_interval, regs->ddr_sdram_interval);
+#endif
+
#ifdef CONFIG_DEEP_SLEEP
if (is_warm_boot()) {
/* exit self-refresh */
diff --git a/drivers/ddr/fsl/main.c b/drivers/ddr/fsl/main.c
index 139a3a7f5ad..479184f4ed7 100644
--- a/drivers/ddr/fsl/main.c
+++ b/drivers/ddr/fsl/main.c
@@ -857,6 +857,7 @@ fsl_ddr_sdram_size(void)
info.num_ctrls = CONFIG_SYS_FSL_DDR_MAIN_NUM_CTRLS;
info.dimm_slots_per_ctrl = CONFIG_DIMM_SLOTS_PER_CTLR;
info.board_need_mem_reset = NULL;
+ remove_unused_controllers(&info);
/* Compute it once normally. */
total_memory = fsl_ddr_compute(&info, STEP_GET_SPD, 1);
diff --git a/drivers/ddr/microchip/Makefile b/drivers/ddr/microchip/Makefile
new file mode 100644
index 00000000000..305c48b164b
--- /dev/null
+++ b/drivers/ddr/microchip/Makefile
@@ -0,0 +1,6 @@
+#
+# Copyright (C) 2015 Microchip Technology Inc.
+#
+# SPDX-License-Identifier: GPL-2.0+
+#
+obj-$(CONFIG_MACH_PIC32) += ddr2.o
diff --git a/drivers/ddr/microchip/ddr2.c b/drivers/ddr/microchip/ddr2.c
new file mode 100644
index 00000000000..6056418588c
--- /dev/null
+++ b/drivers/ddr/microchip/ddr2.c
@@ -0,0 +1,278 @@
+/*
+ * (c) 2015 Paul Thacker <paul.thacker@microchip.com>
+ *
+ * SPDX-License-Identifier: GPL-2.0+
+ *
+ */
+#include <common.h>
+#include <wait_bit.h>
+#include <linux/kernel.h>
+#include <linux/bitops.h>
+#include <mach/pic32.h>
+#include <mach/ddr.h>
+
+#include "ddr2_regs.h"
+#include "ddr2_timing.h"
+
+/* init DDR2 Phy */
+void ddr2_phy_init(void)
+{
+ struct ddr2_phy_regs *ddr2_phy;
+ u32 pad_ctl;
+
+ ddr2_phy = ioremap(PIC32_DDR2P_BASE, sizeof(*ddr2_phy));
+
+ /* PHY_DLL_RECALIB */
+ writel(DELAY_START_VAL(3) | DISABLE_RECALIB(0) |
+ RECALIB_CNT(0x10), &ddr2_phy->dll_recalib);
+
+ /* PHY_PAD_CTRL */
+ pad_ctl = ODT_SEL | ODT_EN | DRIVE_SEL(0) |
+ ODT_PULLDOWN(2) | ODT_PULLUP(3) |
+ EXTRA_OEN_CLK(0) | NOEXT_DLL |
+ DLR_DFT_WRCMD | HALF_RATE |
+ DRVSTR_PFET(0xe) | DRVSTR_NFET(0xe) |
+ RCVR_EN | PREAMBLE_DLY(2);
+ writel(pad_ctl, &ddr2_phy->pad_ctrl);
+
+ /* SCL_CONFIG_0 */
+ writel(SCL_BURST8 | SCL_DDR_CONNECTED | SCL_RCAS_LAT(RL) |
+ SCL_ODTCSWW, &ddr2_phy->scl_config_1);
+
+ /* SCL_CONFIG_1 */
+ writel(SCL_CSEN | SCL_WCAS_LAT(WL), &ddr2_phy->scl_config_2);
+
+ /* SCL_LAT */
+ writel(SCL_CAPCLKDLY(3) | SCL_DDRCLKDLY(4), &ddr2_phy->scl_latency);
+}
+
+/* start phy self calibration logic */
+static int ddr2_phy_calib_start(void)
+{
+ struct ddr2_phy_regs *ddr2_phy;
+
+ ddr2_phy = ioremap(PIC32_DDR2P_BASE, sizeof(*ddr2_phy));
+
+ /* DDR Phy SCL Start */
+ writel(SCL_START | SCL_EN, &ddr2_phy->scl_start);
+
+ /* Wait for SCL for data byte to pass */
+ return wait_for_bit(__func__, &ddr2_phy->scl_start, SCL_LUBPASS,
+ true, CONFIG_SYS_HZ, false);
+}
+
+/* DDR2 Controller initialization */
+
+/* Target Agent Arbiter */
+static void ddr_set_arbiter(struct ddr2_ctrl_regs *ctrl,
+ const struct ddr2_arbiter_params *const param)
+{
+ int i;
+
+ for (i = 0; i < NUM_AGENTS; i++) {
+ /* set min burst size */
+ writel(i * MIN_LIM_WIDTH, &ctrl->tsel);
+ writel(param->min_limit, &ctrl->minlim);
+
+ /* set request period (4 * req_period clocks) */
+ writel(i * RQST_PERIOD_WIDTH, &ctrl->tsel);
+ writel(param->req_period, &ctrl->reqprd);
+
+ /* set number of burst accepted */
+ writel(i * MIN_CMDACPT_WIDTH, &ctrl->tsel);
+ writel(param->min_cmd_acpt, &ctrl->mincmd);
+ }
+}
+
+const struct ddr2_arbiter_params *__weak board_get_ddr_arbiter_params(void)
+{
+ /* default arbiter parameters */
+ static const struct ddr2_arbiter_params arb_params[] = {
+ { .min_limit = 0x1f, .req_period = 0xff, .min_cmd_acpt = 0x04,},
+ { .min_limit = 0x1f, .req_period = 0xff, .min_cmd_acpt = 0x10,},
+ { .min_limit = 0x1f, .req_period = 0xff, .min_cmd_acpt = 0x10,},
+ { .min_limit = 0x04, .req_period = 0xff, .min_cmd_acpt = 0x04,},
+ { .min_limit = 0x04, .req_period = 0xff, .min_cmd_acpt = 0x04,},
+ };
+
+ return &arb_params[0];
+}
+
+static void host_load_cmd(struct ddr2_ctrl_regs *ctrl, u32 cmd_idx,
+ u32 hostcmd2, u32 hostcmd1, u32 delay)
+{
+ u32 hc_delay;
+
+ hc_delay = max_t(u32, DIV_ROUND_UP(delay, T_CK), 2) - 2;
+ writel(hostcmd1, &ctrl->cmd10[cmd_idx]);
+ writel((hostcmd2 & 0x7ff) | (hc_delay << 11), &ctrl->cmd20[cmd_idx]);
+}
+
+/* init DDR2 Controller */
+void ddr2_ctrl_init(void)
+{
+ u32 wr2prech, rd2prech, wr2rd, wr2rd_cs;
+ u32 ras2ras, ras2cas, prech2ras, temp;
+ const struct ddr2_arbiter_params *arb_params;
+ struct ddr2_ctrl_regs *ctrl;
+
+ ctrl = ioremap(PIC32_DDR2C_BASE, sizeof(*ctrl));
+
+ /* PIC32 DDR2 controller always work in HALF_RATE */
+ writel(HALF_RATE_MODE, &ctrl->memwidth);
+
+ /* Set arbiter configuration per target */
+ arb_params = board_get_ddr_arbiter_params();
+ ddr_set_arbiter(ctrl, arb_params);
+
+ /* Address Configuration, model {CS, ROW, BA, COL} */
+ writel((ROW_ADDR_RSHIFT | (BA_RSHFT << 8) | (CS_ADDR_RSHIFT << 16) |
+ (COL_HI_RSHFT << 24) | (SB_PRI << 29) |
+ (EN_AUTO_PRECH << 30)), &ctrl->memcfg0);
+
+ writel(ROW_ADDR_MASK, &ctrl->memcfg1);
+ writel(COL_HI_MASK, &ctrl->memcfg2);
+ writel(COL_LO_MASK, &ctrl->memcfg3);
+ writel(BA_MASK | (CS_ADDR_MASK << 8), &ctrl->memcfg4);
+
+ /* Refresh Config */
+ writel(REFCNT_CLK(DIV_ROUND_UP(T_RFI, T_CK_CTRL) - 2) |
+ REFDLY_CLK(DIV_ROUND_UP(T_RFC_MIN, T_CK_CTRL) - 2) |
+ MAX_PEND_REF(7),
+ &ctrl->refcfg);
+
+ /* Power Config */
+ writel(ECC_EN(0) | ERR_CORR_EN(0) | EN_AUTO_PWR_DN(0) |
+ EN_AUTO_SELF_REF(3) | PWR_DN_DLY(8) |
+ SELF_REF_DLY(17) | PRECH_PWR_DN_ONLY(0),
+ &ctrl->pwrcfg);
+
+ /* Delay Config */
+ wr2rd = max_t(u32, DIV_ROUND_UP(T_WTR, T_CK_CTRL),
+ DIV_ROUND_UP(T_WTR_TCK, 2)) + WL + BL;
+ wr2rd_cs = max_t(u32, wr2rd - 1, 3);
+ wr2prech = DIV_ROUND_UP(T_WR, T_CK_CTRL) + WL + BL;
+ rd2prech = max_t(u32, DIV_ROUND_UP(T_RTP, T_CK_CTRL),
+ DIV_ROUND_UP(T_RTP_TCK, 2)) + BL - 2;
+ ras2ras = max_t(u32, DIV_ROUND_UP(T_RRD, T_CK_CTRL),
+ DIV_ROUND_UP(T_RRD_TCK, 2)) - 1;
+ ras2cas = DIV_ROUND_UP(T_RCD, T_CK_CTRL) - 1;
+ prech2ras = DIV_ROUND_UP(T_RP, T_CK_CTRL) - 1;
+
+ writel(((wr2rd & 0x0f) |
+ ((wr2rd_cs & 0x0f) << 4) |
+ ((BL - 1) << 8) |
+ (BL << 12) |
+ ((BL - 1) << 16) |
+ ((BL - 1) << 20) |
+ ((BL + 2) << 24) |
+ ((RL - WL + 3) << 28)), &ctrl->dlycfg0);
+
+ writel(((T_CKE_TCK - 1) |
+ (((DIV_ROUND_UP(T_DLLK, 2) - 2) & 0xff) << 8) |
+ ((T_CKE_TCK - 1) << 16) |
+ ((max_t(u32, T_XP_TCK, T_CKE_TCK) - 1) << 20) |
+ ((wr2prech >> 4) << 26) |
+ ((wr2rd >> 4) << 27) |
+ ((wr2rd_cs >> 4) << 28) |
+ (((RL + 5) >> 4) << 29) |
+ ((DIV_ROUND_UP(T_DLLK, 2) >> 8) << 30)), &ctrl->dlycfg1);
+
+ writel((DIV_ROUND_UP(T_RP, T_CK_CTRL) |
+ (rd2prech << 8) |
+ ((wr2prech & 0x0f) << 12) |
+ (ras2ras << 16) |
+ (ras2cas << 20) |
+ (prech2ras << 24) |
+ ((RL + 3) << 28)), &ctrl->dlycfg2);
+
+ writel(((DIV_ROUND_UP(T_RAS_MIN, T_CK_CTRL) - 1) |
+ ((DIV_ROUND_UP(T_RC, T_CK_CTRL) - 1) << 8) |
+ ((DIV_ROUND_UP(T_FAW, T_CK_CTRL) - 1) << 16)),
+ &ctrl->dlycfg3);
+
+ /* ODT Config */
+ writel(0x0, &ctrl->odtcfg);
+ writel(BIT(16), &ctrl->odtencfg);
+ writel(ODTRDLY(RL - 3) | ODTWDLY(WL - 3) | ODTRLEN(2) | ODTWLEN(3),
+ &ctrl->odtcfg);
+
+ /* Transfer Configuration */
+ writel(NXTDATRQDLY(2) | NXDATAVDLY(4) | RDATENDLY(2) |
+ MAX_BURST(3) | (7 << 28) | BIG_ENDIAN(0),
+ &ctrl->xfercfg);
+
+ /* DRAM Initialization */
+ /* CKE high after reset and wait 400 nsec */
+ host_load_cmd(ctrl, 0, 0, IDLE_NOP, 400000);
+
+ /* issue precharge all command */
+ host_load_cmd(ctrl, 1, 0x04, PRECH_ALL_CMD, T_RP + T_CK);
+
+ /* initialize EMR2 */
+ host_load_cmd(ctrl, 2, 0x200, LOAD_MODE_CMD, T_MRD_TCK * T_CK);
+
+ /* initialize EMR3 */
+ host_load_cmd(ctrl, 3, 0x300, LOAD_MODE_CMD, T_MRD_TCK * T_CK);
+
+ /*
+ * RDQS disable, DQSB enable, OCD exit, 150 ohm termination,
+ * AL=0, DLL enable
+ */
+ host_load_cmd(ctrl, 4, 0x100,
+ LOAD_MODE_CMD | (0x40 << 24), T_MRD_TCK * T_CK);
+ /*
+ * PD fast exit, WR REC = T_WR in clocks -1,
+ * DLL reset, CAS = RL, burst = 4
+ */
+ temp = ((DIV_ROUND_UP(T_WR, T_CK) - 1) << 1) | 1;
+ host_load_cmd(ctrl, 5, temp, LOAD_MODE_CMD | (RL << 28) | (2 << 24),
+ T_MRD_TCK * T_CK);
+
+ /* issue precharge all command */
+ host_load_cmd(ctrl, 6, 4, PRECH_ALL_CMD, T_RP + T_CK);
+
+ /* issue refresh command */
+ host_load_cmd(ctrl, 7, 0, REF_CMD, T_RFC_MIN);
+
+ /* issue refresh command */
+ host_load_cmd(ctrl, 8, 0, REF_CMD, T_RFC_MIN);
+
+ /* Mode register programming as before without DLL reset */
+ host_load_cmd(ctrl, 9, temp, LOAD_MODE_CMD | (RL << 28) | (3 << 24),
+ T_MRD_TCK * T_CK);
+
+ /* extended mode register same as before with OCD default */
+ host_load_cmd(ctrl, 10, 0x103, LOAD_MODE_CMD | (0xc << 24),
+ T_MRD_TCK * T_CK);
+
+ /* extended mode register same as before with OCD exit */
+ host_load_cmd(ctrl, 11, 0x100, LOAD_MODE_CMD | (0x4 << 28),
+ 140 * T_CK);
+
+ writel(CMD_VALID | NUMHOSTCMD(11), &ctrl->cmdissue);
+
+ /* start memory initialization */
+ writel(INIT_START, &ctrl->memcon);
+
+ /* wait for all host cmds to be transmitted */
+ wait_for_bit(__func__, &ctrl->cmdissue, CMD_VALID, false,
+ CONFIG_SYS_HZ, false);
+
+ /* inform all cmds issued, ready for normal operation */
+ writel(INIT_START | INIT_DONE, &ctrl->memcon);
+
+ /* perform phy caliberation */
+ if (ddr2_phy_calib_start())
+ printf("ddr2: phy calib failed\n");
+}
+
+phys_size_t ddr2_calculate_size(void)
+{
+ u32 temp;
+
+ temp = 1 << (COL_BITS + BA_BITS + ROW_BITS);
+ /* 16-bit data width between controller and DIMM */
+ temp = temp * CS_BITS * (16 / 8);
+ return (phys_size_t)temp;
+}
diff --git a/drivers/ddr/microchip/ddr2_regs.h b/drivers/ddr/microchip/ddr2_regs.h
new file mode 100644
index 00000000000..0f4b159048c
--- /dev/null
+++ b/drivers/ddr/microchip/ddr2_regs.h
@@ -0,0 +1,148 @@
+/*
+ * (c) 2015 Purna Chandra Mandal <purna.mandal@microchip.com>
+ *
+ * SPDX-License-Identifier: GPL-2.0+
+ *
+ */
+
+#ifndef __MICROCHIP_DDR2_REGS_H
+#define __MICROCHIP_DDR2_REGS_H
+
+#include <linux/bitops.h>
+
+/* DDR2 Controller */
+struct ddr2_ctrl_regs {
+ u32 tsel;
+ u32 minlim;
+ u32 reqprd;
+ u32 mincmd;
+ u32 memcon;
+ u32 memcfg0;
+ u32 memcfg1;
+ u32 memcfg2;
+ u32 memcfg3;
+ u32 memcfg4;
+ u32 refcfg;
+ u32 pwrcfg;
+ u32 dlycfg0;
+ u32 dlycfg1;
+ u32 dlycfg2;
+ u32 dlycfg3;
+ u32 odtcfg;
+ u32 xfercfg;
+ u32 cmdissue;
+ u32 odtencfg;
+ u32 memwidth;
+ u32 unused[11];
+ u32 cmd10[16];
+ u32 cmd20[16];
+};
+
+/* Arbiter Config */
+#define MIN_LIM_WIDTH 5
+#define RQST_PERIOD_WIDTH 8
+#define MIN_CMDACPT_WIDTH 8
+
+/* Refresh Config */
+#define REFCNT_CLK(x) (x)
+#define REFDLY_CLK(x) ((x) << 16)
+#define MAX_PEND_REF(x) ((x) << 24)
+
+/* Power Config */
+#define PRECH_PWR_DN_ONLY(x) ((x) << 22)
+#define SELF_REF_DLY(x) ((x) << 12)
+#define PWR_DN_DLY(x) ((x) << 4)
+#define EN_AUTO_SELF_REF(x) ((x) << 3)
+#define EN_AUTO_PWR_DN(x) ((x) << 2)
+#define ERR_CORR_EN(x) ((x) << 1)
+#define ECC_EN(x) (x)
+
+/* Memory Width */
+#define HALF_RATE_MODE BIT(3)
+
+/* Delay Config */
+#define ODTWLEN(x) ((x) << 20)
+#define ODTRLEN(x) ((x) << 16)
+#define ODTWDLY(x) ((x) << 12)
+#define ODTRDLY(x) ((x) << 8)
+
+/* Xfer Config */
+#define BIG_ENDIAN(x) ((x) << 31)
+#define MAX_BURST(x) ((x) << 24)
+#define RDATENDLY(x) ((x) << 16)
+#define NXDATAVDLY(x) ((x) << 4)
+#define NXTDATRQDLY(x) ((x) << 0)
+
+/* Host Commands */
+#define IDLE_NOP 0x00ffffff
+#define PRECH_ALL_CMD 0x00fff401
+#define REF_CMD 0x00fff801
+#define LOAD_MODE_CMD 0x00fff001
+#define CKE_LOW 0x00ffeffe
+
+#define NUM_HOST_CMDS 12
+
+/* Host CMD Issue */
+#define CMD_VALID BIT(4)
+#define NUMHOSTCMD(x) (x)
+
+/* Memory Control */
+#define INIT_DONE BIT(1)
+#define INIT_START BIT(0)
+
+/* Address Control */
+#define EN_AUTO_PRECH 0
+#define SB_PRI 1
+
+/* DDR2 Phy Register */
+struct ddr2_phy_regs {
+ u32 scl_start;
+ u32 unused1[2];
+ u32 scl_latency;
+ u32 unused2[2];
+ u32 scl_config_1;
+ u32 scl_config_2;
+ u32 pad_ctrl;
+ u32 dll_recalib;
+};
+
+/* PHY PAD CONTROL */
+#define ODT_SEL BIT(0)
+#define ODT_EN BIT(1)
+#define DRIVE_SEL(x) ((x) << 2)
+#define ODT_PULLDOWN(x) ((x) << 4)
+#define ODT_PULLUP(x) ((x) << 6)
+#define EXTRA_OEN_CLK(x) ((x) << 8)
+#define NOEXT_DLL BIT(9)
+#define DLR_DFT_WRCMD BIT(13)
+#define HALF_RATE BIT(14)
+#define DRVSTR_PFET(x) ((x) << 16)
+#define DRVSTR_NFET(x) ((x) << 20)
+#define RCVR_EN BIT(28)
+#define PREAMBLE_DLY(x) ((x) << 29)
+
+/* PHY DLL RECALIBRATE */
+#define RECALIB_CNT(x) ((x) << 8)
+#define DISABLE_RECALIB(x) ((x) << 26)
+#define DELAY_START_VAL(x) ((x) << 28)
+
+/* PHY SCL CONFIG1 */
+#define SCL_BURST8 BIT(0)
+#define SCL_DDR_CONNECTED BIT(1)
+#define SCL_RCAS_LAT(x) ((x) << 4)
+#define SCL_ODTCSWW BIT(24)
+
+/* PHY SCL CONFIG2 */
+#define SCL_CSEN BIT(0)
+#define SCL_WCAS_LAT(x) ((x) << 8)
+
+/* PHY SCL Latency */
+#define SCL_CAPCLKDLY(x) ((x) << 0)
+#define SCL_DDRCLKDLY(x) ((x) << 4)
+
+/* PHY SCL START */
+#define SCL_START BIT(28)
+#define SCL_EN BIT(26)
+#define SCL_LUBPASS (BIT(1) | BIT(0))
+
+#endif /* __MICROCHIP_DDR2_REGS_H */
diff --git a/drivers/ddr/microchip/ddr2_timing.h b/drivers/ddr/microchip/ddr2_timing.h
new file mode 100644
index 00000000000..5895f9d5928
--- /dev/null
+++ b/drivers/ddr/microchip/ddr2_timing.h
@@ -0,0 +1,65 @@
+/*
+ * (c) 2015 Purna Chandra Mandal <purna.mandal@microchip.com>
+ *
+ * SPDX-License-Identifier: GPL-2.0+
+ *
+ */
+
+#ifndef __MICROCHIP_DDR2_TIMING_H
+#define __MICROCHIP_DDR2_TIMING_H
+
+/* MPLL freq is 400MHz */
+#define T_CK 2500 /* 2500 psec */
+#define T_CK_CTRL (T_CK * 2)
+
+/* Burst length in cycles */
+#define BL 2
+/* default CAS latency for all speed grades */
+#define RL 5
+/* default write latency for all speed grades = CL-1 */
+#define WL 4
+
+/* From Micron MT47H64M16HR-3 data sheet */
+#define T_RFC_MIN 127500 /* psec */
+#define T_WR 15000 /* psec */
+#define T_RP 12500 /* psec */
+#define T_RCD 12500 /* psec */
+#define T_RRD 7500 /* psec */
+/* T_RRD_TCK is minimum of 2 clk periods, regardless of freq */
+#define T_RRD_TCK 2
+#define T_WTR 7500 /* psec */
+/* T_WTR_TCK is minimum of 2 clk periods, regardless of freq */
+#define T_WTR_TCK 2
+#define T_RTP 7500 /* psec */
+#define T_RTP_TCK (BL / 2)
+#define T_XP_TCK 2 /* clocks */
+#define T_CKE_TCK 3 /* clocks */
+#define T_XSNR (T_RFC_MIN + 10000) /* psec */
+#define T_DLLK 200 /* clocks */
+#define T_RAS_MIN 45000 /* psec */
+#define T_RC 57500 /* psec */
+#define T_FAW 35000 /* psec */
+#define T_MRD_TCK 2 /* clocks */
+#define T_RFI 7800000 /* psec */
+
+/* DDR Addressing */
+#define COL_BITS 10
+#define BA_BITS 3
+#define ROW_BITS 13
+#define CS_BITS 1
+
+/* DDR Addressing scheme: {CS, ROW, BA, COL} */
+#define COL_HI_RSHFT 0
+#define COL_HI_MASK 0
+#define COL_LO_MASK ((1 << COL_BITS) - 1)
+
+#define BA_RSHFT COL_BITS
+#define BA_MASK ((1 << BA_BITS) - 1)
+
+#define ROW_ADDR_RSHIFT (BA_RSHFT + BA_BITS)
+#define ROW_ADDR_MASK ((1 << ROW_BITS) - 1)
+
+#define CS_ADDR_RSHIFT 0
+#define CS_ADDR_MASK 0
+
+#endif /* __MICROCHIP_DDR2_TIMING_H */
diff --git a/drivers/fpga/xilinx.c b/drivers/fpga/xilinx.c
index c765a74a25e..d459a2f7a57 100644
--- a/drivers/fpga/xilinx.c
+++ b/drivers/fpga/xilinx.c
@@ -75,8 +75,8 @@ int fpga_loadbitstream(int devnum, char *fpgadata, size_t size,
buffer[i] = *dataptr++;
if (xdesc->name) {
- i = strncmp(buffer, xdesc->name, strlen(xdesc->name));
- if (i) {
+ i = (ulong)strstr(buffer, xdesc->name);
+ if (!i) {
printf("%s: Wrong bitstream ID for this device\n",
__func__);
printf("%s: Bitstream ID %s, current device ID %d/%s\n",
diff --git a/drivers/gpio/Kconfig b/drivers/gpio/Kconfig
index e60e9fd86c3..845dc725c54 100644
--- a/drivers/gpio/Kconfig
+++ b/drivers/gpio/Kconfig
@@ -83,4 +83,11 @@ config VYBRID_GPIO
help
Say yes here to support Vybrid vf610 GPIOs.
+config PIC32_GPIO
+ bool "Microchip PIC32 GPIO driver"
+ depends on DM_GPIO && MACH_PIC32
+ default y
+ help
+ Say yes here to support Microchip PIC32 GPIOs.
+
endmenu
diff --git a/drivers/gpio/Makefile b/drivers/gpio/Makefile
index fb4fd255df3..845a6d4493b 100644
--- a/drivers/gpio/Makefile
+++ b/drivers/gpio/Makefile
@@ -46,4 +46,4 @@ obj-$(CONFIG_STM32_GPIO) += stm32_gpio.o
obj-$(CONFIG_ZYNQ_GPIO) += zynq_gpio.o
obj-$(CONFIG_VYBRID_GPIO) += vybrid_gpio.o
obj-$(CONFIG_HIKEY_GPIO) += hi6220_gpio.o
-
+obj-$(CONFIG_PIC32_GPIO) += pic32_gpio.o
diff --git a/drivers/gpio/pic32_gpio.c b/drivers/gpio/pic32_gpio.c
new file mode 100644
index 00000000000..499b4fa5ad1
--- /dev/null
+++ b/drivers/gpio/pic32_gpio.c
@@ -0,0 +1,174 @@
+/*
+ * Copyright (c) 2015 Microchip Technology Inc
+ * Purna Chandra Mandal <purna.mandal@microchip.com>
+ *
+ * SPDX-License-Identifier: GPL-2.0+
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <errno.h>
+#include <malloc.h>
+#include <asm/io.h>
+#include <asm/gpio.h>
+#include <linux/compat.h>
+#include <dt-bindings/gpio/gpio.h>
+#include <mach/pic32.h>
+
+DECLARE_GLOBAL_DATA_PTR;
+
+/* Peripheral Pin Control */
+struct pic32_reg_port {
+ struct pic32_reg_atomic ansel;
+ struct pic32_reg_atomic tris;
+ struct pic32_reg_atomic port;
+ struct pic32_reg_atomic lat;
+ struct pic32_reg_atomic open_drain;
+ struct pic32_reg_atomic cnpu;
+ struct pic32_reg_atomic cnpd;
+ struct pic32_reg_atomic cncon;
+};
+
+enum {
+ MICROCHIP_GPIO_DIR_OUT,
+ MICROCHIP_GPIO_DIR_IN,
+ MICROCHIP_GPIOS_PER_BANK = 16,
+};
+
+struct pic32_gpio_priv {
+ struct pic32_reg_port *regs;
+ char name[2];
+};
+
+static int pic32_gpio_get_value(struct udevice *dev, unsigned offset)
+{
+ struct pic32_gpio_priv *priv = dev_get_priv(dev);
+
+ return !!(readl(&priv->regs->port.raw) & BIT(offset));
+}
+
+static int pic32_gpio_set_value(struct udevice *dev, unsigned offset,
+ int value)
+{
+ struct pic32_gpio_priv *priv = dev_get_priv(dev);
+ int mask = BIT(offset);
+
+ if (value)
+ writel(mask, &priv->regs->port.set);
+ else
+ writel(mask, &priv->regs->port.clr);
+
+ return 0;
+}
+
+static int pic32_gpio_direction(struct udevice *dev, unsigned offset)
+{
+ struct pic32_gpio_priv *priv = dev_get_priv(dev);
+
+ /* pin in analog mode ? */
+ if (readl(&priv->regs->ansel.raw) & BIT(offset))
+ return -EPERM;
+
+ if (readl(&priv->regs->tris.raw) & BIT(offset))
+ return MICROCHIP_GPIO_DIR_IN;
+ else
+ return MICROCHIP_GPIO_DIR_OUT;
+}
+
+static int pic32_gpio_direction_input(struct udevice *dev, unsigned offset)
+{
+ struct pic32_gpio_priv *priv = dev_get_priv(dev);
+ int mask = BIT(offset);
+
+ writel(mask, &priv->regs->ansel.clr);
+ writel(mask, &priv->regs->tris.set);
+
+ return 0;
+}
+
+static int pic32_gpio_direction_output(struct udevice *dev,
+ unsigned offset, int value)
+{
+ struct pic32_gpio_priv *priv = dev_get_priv(dev);
+ int mask = BIT(offset);
+
+ writel(mask, &priv->regs->ansel.clr);
+ writel(mask, &priv->regs->tris.clr);
+
+ pic32_gpio_set_value(dev, offset, value);
+ return 0;
+}
+
+static int pic32_gpio_xlate(struct udevice *dev, struct gpio_desc *desc,
+ struct fdtdec_phandle_args *args)
+{
+ desc->flags = args->args[1] & GPIO_ACTIVE_LOW ? GPIOD_ACTIVE_LOW : 0;
+
+ return 0;
+}
+
+static int pic32_gpio_get_function(struct udevice *dev, unsigned offset)
+{
+ int ret = GPIOF_UNUSED;
+
+ switch (pic32_gpio_direction(dev, offset)) {
+ case MICROCHIP_GPIO_DIR_OUT:
+ ret = GPIOF_OUTPUT;
+ break;
+ case MICROCHIP_GPIO_DIR_IN:
+ ret = GPIOF_INPUT;
+ break;
+ default:
+ ret = GPIOF_UNUSED;
+ break;
+ }
+ return ret;
+}
+
+static const struct dm_gpio_ops gpio_pic32_ops = {
+ .direction_input = pic32_gpio_direction_input,
+ .direction_output = pic32_gpio_direction_output,
+ .get_value = pic32_gpio_get_value,
+ .set_value = pic32_gpio_set_value,
+ .get_function = pic32_gpio_get_function,
+ .xlate = pic32_gpio_xlate,
+};
+
+static int pic32_gpio_probe(struct udevice *dev)
+{
+ struct gpio_dev_priv *uc_priv = dev_get_uclass_priv(dev);
+ struct pic32_gpio_priv *priv = dev_get_priv(dev);
+ fdt_addr_t addr;
+ fdt_size_t size;
+ char *end;
+ int bank;
+
+ addr = fdtdec_get_addr_size(gd->fdt_blob, dev->of_offset, "reg", &size);
+ if (addr == FDT_ADDR_T_NONE)
+ return -EINVAL;
+
+ priv->regs = ioremap(addr, size);
+
+ uc_priv->gpio_count = MICROCHIP_GPIOS_PER_BANK;
+ /* extract bank name */
+ end = strrchr(dev->name, '@');
+ bank = trailing_strtoln(dev->name, end);
+ priv->name[0] = 'A' + bank;
+ uc_priv->bank_name = priv->name;
+
+ return 0;
+}
+
+static const struct udevice_id pic32_gpio_ids[] = {
+ { .compatible = "microchip,pic32mzda-gpio" },
+ { }
+};
+
+U_BOOT_DRIVER(gpio_pic32) = {
+ .name = "gpio_pic32",
+ .id = UCLASS_GPIO,
+ .of_match = pic32_gpio_ids,
+ .ops = &gpio_pic32_ops,
+ .probe = pic32_gpio_probe,
+ .priv_auto_alloc_size = sizeof(struct pic32_gpio_priv),
+};
diff --git a/drivers/hwmon/adt7460.c b/drivers/hwmon/adt7460.c
index fd05c177948..9b2c5b69ce5 100644
--- a/drivers/hwmon/adt7460.c
+++ b/drivers/hwmon/adt7460.c
@@ -1,6 +1,6 @@
/*
* (C) Copyright 2008
- * Ricado Ribalda-Universidad Autonoma de Madrid, ricardo.ribalda@uam.es
+ * Ricado Ribalda-Universidad Autonoma de Madrid, ricardo.ribalda@gmail.com
* This work has been supported by: QTechnology http://qtec.com/
* SPDX-License-Identifier: GPL-2.0+
*/
diff --git a/drivers/misc/Kconfig b/drivers/misc/Kconfig
index cba236334c0..af8667f030c 100644
--- a/drivers/misc/Kconfig
+++ b/drivers/misc/Kconfig
@@ -130,4 +130,12 @@ config RESET
effect a reset. The uclass will try all available drivers when
reset_walk() is called.
+config WINBOND_W83627
+ bool "Enable Winbond Super I/O driver"
+ help
+ If you say Y here, you will get support for the Winbond
+ W83627 Super I/O driver. This can be used to enable the
+ legacy UART or other devices in the Winbond Super IO chips
+ on X86 platforms.
+
endmenu
diff --git a/drivers/misc/Makefile b/drivers/misc/Makefile
index cd4846b4a8e..e1e3c6b70fc 100644
--- a/drivers/misc/Makefile
+++ b/drivers/misc/Makefile
@@ -41,3 +41,4 @@ obj-$(CONFIG_FSL_SEC_MON) += fsl_sec_mon.o
obj-$(CONFIG_PCA9551_LED) += pca9551_led.o
obj-$(CONFIG_RESET) += reset-uclass.o
obj-$(CONFIG_FSL_DEVICE_DISABLE) += fsl_devdis.o
+obj-$(CONFIG_WINBOND_W83627) += winbond_w83627.o
diff --git a/drivers/misc/winbond_w83627.c b/drivers/misc/winbond_w83627.c
new file mode 100644
index 00000000000..59db7d971ca
--- /dev/null
+++ b/drivers/misc/winbond_w83627.c
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2016 Stefan Roese <sr@denx.de>
+ *
+ * SPDX-License-Identifier: GPL-2.0+
+ */
+
+#include <common.h>
+#include <asm/io.h>
+#include <asm/pnp_def.h>
+
+#define WINBOND_ENTRY_KEY 0x87
+#define WINBOND_EXIT_KEY 0xaa
+
+/* Enable configuration: pass entry key '0x87' into index port dev twice */
+static void pnp_enter_conf_state(u16 dev)
+{
+ u16 port = dev >> 8;
+
+ outb(WINBOND_ENTRY_KEY, port);
+ outb(WINBOND_ENTRY_KEY, port);
+}
+
+/* Disable configuration: pass exit key '0xAA' into index port dev */
+static void pnp_exit_conf_state(u16 dev)
+{
+ u16 port = dev >> 8;
+
+ outb(WINBOND_EXIT_KEY, port);
+}
+
+/* Bring up early serial debugging output before the RAM is initialized */
+void winbond_enable_serial(uint dev, uint iobase, uint irq)
+{
+ pnp_enter_conf_state(dev);
+ pnp_set_logical_device(dev);
+ pnp_set_enable(dev, 0);
+ pnp_set_iobase(dev, PNP_IDX_IO0, iobase);
+ pnp_set_irq(dev, PNP_IDX_IRQ0, irq);
+ pnp_set_enable(dev, 1);
+ pnp_exit_conf_state(dev);
+}
diff --git a/drivers/mmc/Kconfig b/drivers/mmc/Kconfig
index ceae7bcaec6..9f4b766f7a4 100644
--- a/drivers/mmc/Kconfig
+++ b/drivers/mmc/Kconfig
@@ -31,4 +31,10 @@ config SH_SDHI
help
Support for the on-chip SDHI host controller on SuperH/Renesas ARM SoCs platform
+config PIC32_SDHCI
+ bool "Microchip PIC32 on-chip SDHCI support"
+ depends on DM_MMC && MACH_PIC32
+ help
+ Support for Microchip PIC32 SDHCI controller.
+
endmenu
diff --git a/drivers/mmc/Makefile b/drivers/mmc/Makefile
index 5d357056ddd..c9c3e3e9381 100644
--- a/drivers/mmc/Makefile
+++ b/drivers/mmc/Makefile
@@ -48,4 +48,4 @@ obj-$(CONFIG_SPL_MMC_BOOT) += fsl_esdhc_spl.o
else
obj-$(CONFIG_GENERIC_MMC) += mmc_write.o
endif
-
+obj-$(CONFIG_PIC32_SDHCI) += pic32_sdhci.o
diff --git a/drivers/mmc/fsl_esdhc.c b/drivers/mmc/fsl_esdhc.c
index 1ccc576c347..ea5f4bf6c0e 100644
--- a/drivers/mmc/fsl_esdhc.c
+++ b/drivers/mmc/fsl_esdhc.c
@@ -105,12 +105,9 @@ static uint esdhc_xfertyp(struct mmc_cmd *cmd, struct mmc_data *data)
else if (cmd->resp_type & MMC_RSP_PRESENT)
xfertyp |= XFERTYP_RSPTYP_48;
-#if defined(CONFIG_MX53) || defined(CONFIG_PPC_T4240) || \
- defined(CONFIG_LS102XA) || defined(CONFIG_FSL_LAYERSCAPE) || \
- defined(CONFIG_PPC_T4160)
if (cmd->cmdidx == MMC_CMD_STOP_TRANSMISSION)
xfertyp |= XFERTYP_CMDTYP_ABORT;
-#endif
+
return XFERTYP_CMD(cmd->cmdidx) | xfertyp;
}
@@ -252,8 +249,15 @@ static int esdhc_setup_data(struct mmc *mmc, struct mmc_data *data)
* Rounding up to next power of 2
* => timeout + 13 = log2(mmc->clock/4) + 1
* => timeout + 13 = fls(mmc->clock/4)
+ *
+ * However, the MMC spec "It is strongly recommended for hosts to
+ * implement more than 500ms timeout value even if the card
+ * indicates the 250ms maximum busy length." Even the previous
+ * value of 300ms is known to be insufficient for some cards.
+ * So, we use
+ * => timeout + 13 = fls(mmc->clock/2)
*/
- timeout = fls(mmc->clock/4);
+ timeout = fls(mmc->clock/2);
timeout -= 13;
if (timeout > 14)
diff --git a/drivers/mmc/pic32_sdhci.c b/drivers/mmc/pic32_sdhci.c
new file mode 100644
index 00000000000..28da55d2db5
--- /dev/null
+++ b/drivers/mmc/pic32_sdhci.c
@@ -0,0 +1,58 @@
+/*
+ * Support of SDHCI for Microchip PIC32 SoC.
+ *
+ * Copyright (C) 2015 Microchip Technology Inc.
+ * Andrei Pistirica <andrei.pistirica@microchip.com>
+ *
+ * SPDX-License-Identifier: GPL-2.0+
+ */
+
+#include <dm.h>
+#include <common.h>
+#include <sdhci.h>
+#include <asm/errno.h>
+#include <mach/pic32.h>
+
+DECLARE_GLOBAL_DATA_PTR;
+
+static int pic32_sdhci_probe(struct udevice *dev)
+{
+ struct sdhci_host *host = dev_get_priv(dev);
+ const void *fdt = gd->fdt_blob;
+ u32 f_min_max[2];
+ fdt_addr_t addr;
+ fdt_size_t size;
+ int ret;
+
+ addr = fdtdec_get_addr_size(fdt, dev->of_offset, "reg", &size);
+ if (addr == FDT_ADDR_T_NONE)
+ return -EINVAL;
+
+ host->ioaddr = ioremap(addr, size);
+ host->name = (char *)dev->name;
+ host->quirks = SDHCI_QUIRK_NO_HISPD_BIT | SDHCI_QUIRK_NO_CD;
+ host->bus_width = fdtdec_get_int(gd->fdt_blob, dev->of_offset,
+ "bus-width", 4);
+
+ ret = fdtdec_get_int_array(gd->fdt_blob, dev->of_offset,
+ "clock-freq-min-max", f_min_max, 2);
+ if (ret) {
+ printf("sdhci: clock-freq-min-max not found\n");
+ return ret;
+ }
+
+ return add_sdhci(host, f_min_max[1], f_min_max[0]);
+}
+
+static const struct udevice_id pic32_sdhci_ids[] = {
+ { .compatible = "microchip,pic32mzda-sdhci" },
+ { }
+};
+
+U_BOOT_DRIVER(pic32_sdhci_drv) = {
+ .name = "pic32_sdhci",
+ .id = UCLASS_MMC,
+ .of_match = pic32_sdhci_ids,
+ .probe = pic32_sdhci_probe,
+ .priv_auto_alloc_size = sizeof(struct sdhci_host),
+};
diff --git a/drivers/mmc/sdhci.c b/drivers/mmc/sdhci.c
index 02d71b93440..8586d898fdd 100644
--- a/drivers/mmc/sdhci.c
+++ b/drivers/mmc/sdhci.c
@@ -443,6 +443,12 @@ static int sdhci_init(struct mmc *mmc)
sdhci_set_power(host, fls(mmc->cfg->voltages) - 1);
if (host->quirks & SDHCI_QUIRK_NO_CD) {
+#if defined(CONFIG_PIC32_SDHCI)
+ /* PIC32 SDHCI CD errata:
+ * - set CD_TEST and clear CD_TEST_INS bit
+ */
+ sdhci_writeb(host, SDHCI_CTRL_CD_TEST, SDHCI_HOST_CONTROL);
+#else
unsigned int status;
sdhci_writeb(host, SDHCI_CTRL_CD_TEST_INS | SDHCI_CTRL_CD_TEST,
@@ -453,6 +459,7 @@ static int sdhci_init(struct mmc *mmc)
(!(status & SDHCI_CARD_STATE_STABLE)) ||
(!(status & SDHCI_CARD_DETECT_PIN_LEVEL)))
status = sdhci_readl(host, SDHCI_PRESENT_STATE);
+#endif
}
/* Enable only interrupts served by the SD controller */
@@ -530,6 +537,10 @@ int add_sdhci(struct sdhci_host *host, u32 max_clk, u32 min_clk)
if (caps & SDHCI_CAN_DO_8BIT)
host->cfg.host_caps |= MMC_MODE_8BIT;
}
+
+ if (host->quirks & SDHCI_QUIRK_NO_HISPD_BIT)
+ host->cfg.host_caps &= ~(MMC_MODE_HS | MMC_MODE_HS_52MHz);
+
if (host->host_caps)
host->cfg.host_caps |= host->host_caps;
diff --git a/drivers/mmc/zynq_sdhci.c b/drivers/mmc/zynq_sdhci.c
index 4fe3da93b20..039ec16e91f 100644
--- a/drivers/mmc/zynq_sdhci.c
+++ b/drivers/mmc/zynq_sdhci.c
@@ -13,6 +13,10 @@
#include <malloc.h>
#include <sdhci.h>
+#ifndef CONFIG_ZYNQ_SDHCI_MIN_FREQ
+# define CONFIG_ZYNQ_SDHCI_MIN_FREQ 0
+#endif
+
static int arasan_sdhci_probe(struct udevice *dev)
{
struct mmc_uclass_priv *upriv = dev_get_uclass_priv(dev);
@@ -20,9 +24,15 @@ static int arasan_sdhci_probe(struct udevice *dev)
host->quirks = SDHCI_QUIRK_WAIT_SEND_CMD |
SDHCI_QUIRK_BROKEN_R1B;
+
+#ifdef CONFIG_ZYNQ_HISPD_BROKEN
+ host->quirks |= SDHCI_QUIRK_NO_HISPD_BIT;
+#endif
+
host->version = sdhci_readw(host, SDHCI_HOST_VERSION);
- add_sdhci(host, CONFIG_ZYNQ_SDHCI_MAX_FREQ, 0);
+ add_sdhci(host, CONFIG_ZYNQ_SDHCI_MAX_FREQ,
+ CONFIG_ZYNQ_SDHCI_MIN_FREQ);
upriv->mmc = host->mmc;
diff --git a/drivers/net/Kconfig b/drivers/net/Kconfig
index de54ca8014c..bc2f51d9588 100644
--- a/drivers/net/Kconfig
+++ b/drivers/net/Kconfig
@@ -102,6 +102,22 @@ config PCH_GBE
This MAC is present in Intel Platform Controller Hub EG20T. It
supports 10/100/1000 Mbps operation.
+config XILINX_AXIEMAC
+ depends on DM_ETH && (MICROBLAZE || ARCH_ZYNQ || ARCH_ZYNQMP)
+ select PHYLIB
+ select MII
+ bool "Xilinx AXI Ethernet"
+ help
+ This MAC is present in Xilinx Microblaze, Zynq and ZynqMP SoCs.
+
+config XILINX_EMACLITE
+ depends on DM_ETH && (MICROBLAZE || ARCH_ZYNQ || ARCH_ZYNQMP)
+ select PHYLIB
+ select MII
+ bool "Xilinx Ethernetlite"
+ help
+ This MAC is present in Xilinx Microblaze, Zynq and ZynqMP SoCs.
+
config ZYNQ_GEM
depends on DM_ETH && (ARCH_ZYNQ || ARCH_ZYNQMP)
select PHYLIB
@@ -109,4 +125,12 @@ config ZYNQ_GEM
help
This MAC is present in Xilinx Zynq and ZynqMP SoCs.
+config PIC32_ETH
+ bool "Microchip PIC32 Ethernet Support"
+ depends on DM_ETH && MACH_PIC32
+ select PHYLIB
+ help
+ This driver implements 10/100 Mbps Ethernet and MAC layer for
+ Microchip PIC32 microcontrollers.
+
endif # NETDEVICES
diff --git a/drivers/net/Makefile b/drivers/net/Makefile
index 150470c24b0..33a81ee5470 100644
--- a/drivers/net/Makefile
+++ b/drivers/net/Makefile
@@ -72,3 +72,4 @@ obj-$(CONFIG_FSL_MC_ENET) += fsl-mc/
obj-$(CONFIG_FSL_MC_ENET) += ldpaa_eth/
obj-$(CONFIG_FSL_MEMAC) += fm/memac_phy.o
obj-$(CONFIG_VSC9953) += vsc9953.o
+obj-$(CONFIG_PIC32_ETH) += pic32_mdio.o pic32_eth.o
diff --git a/drivers/net/designware.c b/drivers/net/designware.c
index 68b6548309e..77b98c94c04 100644
--- a/drivers/net/designware.c
+++ b/drivers/net/designware.c
@@ -196,6 +196,8 @@ static void dw_adjust_link(struct eth_mac_regs *mac_p,
if (phydev->speed != 1000)
conf |= MII_PORTSELECT;
+ else
+ conf &= ~MII_PORTSELECT;
if (phydev->speed == 100)
conf |= FES_100;
@@ -404,7 +406,7 @@ static int _dw_free_pkt(struct dw_eth_dev *priv)
static int dw_phy_init(struct dw_eth_dev *priv, void *dev)
{
struct phy_device *phydev;
- int mask = 0xffffffff;
+ int mask = 0xffffffff, ret;
#ifdef CONFIG_PHY_ADDR
mask = 1 << CONFIG_PHY_ADDR;
@@ -417,6 +419,11 @@ static int dw_phy_init(struct dw_eth_dev *priv, void *dev)
phy_connect_dev(phydev, dev);
phydev->supported &= PHY_GBIT_FEATURES;
+ if (priv->max_speed) {
+ ret = phy_set_supported(phydev, priv->max_speed);
+ if (ret)
+ return ret;
+ }
phydev->advertising = phydev->supported;
priv->phydev = phydev;
@@ -599,6 +606,7 @@ static int designware_eth_probe(struct udevice *dev)
priv->mac_regs_p = (struct eth_mac_regs *)iobase;
priv->dma_regs_p = (struct eth_dma_regs *)(iobase + DW_DMA_BASE_OFFSET);
priv->interface = pdata->phy_interface;
+ priv->max_speed = pdata->max_speed;
dw_mdio_init(dev->name, priv->mac_regs_p);
priv->bus = miiphy_get_dev_by_name(dev->name);
@@ -633,6 +641,7 @@ static int designware_eth_ofdata_to_platdata(struct udevice *dev)
{
struct eth_pdata *pdata = dev_get_platdata(dev);
const char *phy_mode;
+ const fdt32_t *cell;
pdata->iobase = dev_get_addr(dev);
pdata->phy_interface = -1;
@@ -644,6 +653,11 @@ static int designware_eth_ofdata_to_platdata(struct udevice *dev)
return -EINVAL;
}
+ pdata->max_speed = 0;
+ cell = fdt_getprop(gd->fdt_blob, dev->of_offset, "max-speed", NULL);
+ if (cell)
+ pdata->max_speed = fdt32_to_cpu(*cell);
+
return 0;
}
diff --git a/drivers/net/designware.h b/drivers/net/designware.h
index 4b9ec39cc82..ed6344cc28f 100644
--- a/drivers/net/designware.h
+++ b/drivers/net/designware.h
@@ -223,6 +223,7 @@ struct dw_eth_dev {
char rxbuffs[RX_TOTAL_BUFSIZE] __aligned(ARCH_DMA_MINALIGN);
u32 interface;
+ u32 max_speed;
u32 tx_currdescnum;
u32 rx_currdescnum;
diff --git a/drivers/net/fsl-mc/dpio/qbman_portal.c b/drivers/net/fsl-mc/dpio/qbman_portal.c
index 449ff8a8ba3..4b64c8ae73f 100644
--- a/drivers/net/fsl-mc/dpio/qbman_portal.c
+++ b/drivers/net/fsl-mc/dpio/qbman_portal.c
@@ -102,12 +102,14 @@ struct qbman_swp *qbman_swp_init(const struct qbman_swp_desc *d)
void *qbman_swp_mc_start(struct qbman_swp *p)
{
void *ret;
+ int *return_val;
#ifdef QBMAN_CHECKING
BUG_ON(p->mc.check != swp_mc_can_start);
#endif
ret = qbman_cena_write_start(&p->sys, QBMAN_CENA_SWP_CR);
#ifdef QBMAN_CHECKING
- if (!ret)
+ return_val = (int *)ret;
+ if (!(*return_val))
p->mc.check = swp_mc_can_submit;
#endif
return ret;
diff --git a/drivers/net/fsl-mc/dpni.c b/drivers/net/fsl-mc/dpni.c
index eacb3c8bb2f..41bf56abf5b 100644
--- a/drivers/net/fsl-mc/dpni.c
+++ b/drivers/net/fsl-mc/dpni.c
@@ -8,6 +8,26 @@
#include <fsl-mc/fsl_mc_cmd.h>
#include <fsl-mc/fsl_dpni.h>
+int dpni_prepare_extended_cfg(const struct dpni_extended_cfg *cfg,
+ uint8_t *ext_cfg_buf)
+{
+ uint64_t *ext_params = (uint64_t *)ext_cfg_buf;
+
+ DPNI_PREP_EXTENDED_CFG(ext_params, cfg);
+
+ return 0;
+}
+
+int dpni_extract_extended_cfg(struct dpni_extended_cfg *cfg,
+ const uint8_t *ext_cfg_buf)
+{
+ uint64_t *ext_params = (uint64_t *)ext_cfg_buf;
+
+ DPNI_EXT_EXTENDED_CFG(ext_params, cfg);
+
+ return 0;
+}
+
int dpni_open(struct fsl_mc_io *mc_io,
uint32_t cmd_flags,
int dpni_id,
@@ -162,6 +182,7 @@ int dpni_get_attributes(struct fsl_mc_io *mc_io,
cmd.header = mc_encode_cmd_header(DPNI_CMDID_GET_ATTR,
cmd_flags,
token);
+ DPNI_CMD_GET_ATTR(cmd, attr);
/* send command to mc*/
err = mc_send_command(mc_io, &cmd);
@@ -174,6 +195,23 @@ int dpni_get_attributes(struct fsl_mc_io *mc_io,
return 0;
}
+int dpni_set_errors_behavior(struct fsl_mc_io *mc_io,
+ uint32_t cmd_flags,
+ uint16_t token,
+ struct dpni_error_cfg *cfg)
+{
+ struct mc_command cmd = { 0 };
+
+ /* prepare command */
+ cmd.header = mc_encode_cmd_header(DPNI_CMDID_SET_ERRORS_BEHAVIOR,
+ cmd_flags,
+ token);
+ DPNI_CMD_SET_ERRORS_BEHAVIOR(cmd, cfg);
+
+ /* send command to mc*/
+ return mc_send_command(mc_io, &cmd);
+}
+
int dpni_get_rx_buffer_layout(struct fsl_mc_io *mc_io,
uint32_t cmd_flags,
uint16_t token,
@@ -602,3 +640,46 @@ int dpni_get_rx_flow(struct fsl_mc_io *mc_io,
return 0;
}
+
+int dpni_set_tx_conf(struct fsl_mc_io *mc_io,
+ uint32_t cmd_flags,
+ uint16_t token,
+ uint16_t flow_id,
+ const struct dpni_tx_conf_cfg *cfg)
+{
+ struct mc_command cmd = { 0 };
+
+ /* prepare command */
+ cmd.header = mc_encode_cmd_header(DPNI_CMDID_SET_TX_CONF,
+ cmd_flags,
+ token);
+ DPNI_CMD_SET_TX_CONF(cmd, flow_id, cfg);
+
+ /* send command to mc*/
+ return mc_send_command(mc_io, &cmd);
+}
+
+int dpni_get_tx_conf(struct fsl_mc_io *mc_io,
+ uint32_t cmd_flags,
+ uint16_t token,
+ uint16_t flow_id,
+ struct dpni_tx_conf_attr *attr)
+{
+ struct mc_command cmd = { 0 };
+ int err;
+
+ /* prepare command */
+ cmd.header = mc_encode_cmd_header(DPNI_CMDID_GET_TX_CONF,
+ cmd_flags,
+ token);
+ DPNI_CMD_GET_TX_CONF(cmd, flow_id);
+
+ /* send command to mc*/
+ err = mc_send_command(mc_io, &cmd);
+ if (err)
+ return err;
+
+ DPNI_RSP_GET_TX_CONF(cmd, attr);
+
+ return 0;
+}
diff --git a/drivers/net/fsl-mc/mc.c b/drivers/net/fsl-mc/mc.c
index 4b9b3720f74..fdbd5841868 100644
--- a/drivers/net/fsl-mc/mc.c
+++ b/drivers/net/fsl-mc/mc.c
@@ -656,6 +656,26 @@ int fsl_mc_ldpaa_init(bd_t *bis)
return 0;
}
+static int dprc_version_check(struct fsl_mc_io *mc_io, uint16_t handle)
+{
+ struct dprc_attributes attr;
+ int error;
+
+ memset(&attr, 0, sizeof(struct dprc_attributes));
+ error = dprc_get_attributes(mc_io, MC_CMD_NO_FLAGS, handle, &attr);
+ if (error == 0) {
+ if ((attr.version.major != DPRC_VER_MAJOR) ||
+ (attr.version.minor != DPRC_VER_MINOR)) {
+ printf("DPRC version mismatch found %u.%u,",
+ attr.version.major,
+ attr.version.minor);
+ printf("supported version is %u.%u\n",
+ DPRC_VER_MAJOR, DPRC_VER_MINOR);
+ }
+ }
+ return error;
+}
+
static int dpio_init(void)
{
struct qbman_swp_desc p_des;
@@ -689,11 +709,18 @@ static int dpio_init(void)
goto err_get_attr;
}
+ if ((attr.version.major != DPIO_VER_MAJOR) ||
+ (attr.version.minor != DPIO_VER_MINOR)) {
+ printf("DPIO version mismatch found %u.%u,",
+ attr.version.major, attr.version.minor);
+ printf("supported version is %u.%u\n",
+ DPIO_VER_MAJOR, DPIO_VER_MINOR);
+ }
+
dflt_dpio->dpio_id = attr.id;
#ifdef DEBUG
printf("Init: DPIO id=0x%d\n", dflt_dpio->dpio_id);
#endif
-
err = dpio_enable(dflt_mc_io, MC_CMD_NO_FLAGS, dflt_dpio->dpio_handle);
if (err < 0) {
printf("dpio_enable() failed %d\n", err);
@@ -785,11 +812,18 @@ static int dprc_init(void)
goto err_root_open;
}
+ err = dprc_version_check(root_mc_io, root_dprc_handle);
+ if (err < 0) {
+ printf("dprc_version_check() failed: %d\n", err);
+ goto err_root_open;
+ }
+
+ memset(&cfg, 0, sizeof(struct dprc_cfg));
cfg.options = DPRC_CFG_OPT_TOPOLOGY_CHANGES_ALLOWED |
DPRC_CFG_OPT_OBJ_CREATE_ALLOWED |
DPRC_CFG_OPT_ALLOC_ALLOWED;
cfg.icid = DPRC_GET_ICID_FROM_POOL;
- cfg.portal_id = 250;
+ cfg.portal_id = DPRC_GET_PORTAL_ID_FROM_POOL;
err = dprc_create_container(root_mc_io, MC_CMD_NO_FLAGS,
root_dprc_handle,
&cfg,
@@ -907,6 +941,14 @@ static int dpbp_init(void)
goto err_get_attr;
}
+ if ((dpbp_attr.version.major != DPBP_VER_MAJOR) ||
+ (dpbp_attr.version.minor != DPBP_VER_MINOR)) {
+ printf("DPBP version mismatch found %u.%u,",
+ dpbp_attr.version.major, dpbp_attr.version.minor);
+ printf("supported version is %u.%u\n",
+ DPBP_VER_MAJOR, DPBP_VER_MINOR);
+ }
+
dflt_dpbp->dpbp_attr.id = dpbp_attr.id;
#ifdef DEBUG
printf("Init: DPBP id=0x%d\n", dflt_dpbp->dpbp_attr.id);
@@ -964,6 +1006,8 @@ static int dpni_init(void)
{
int err;
struct dpni_attr dpni_attr;
+ uint8_t ext_cfg_buf[256] = {0};
+ struct dpni_extended_cfg dpni_extended_cfg;
struct dpni_cfg dpni_cfg;
dflt_dpni = (struct fsl_dpni_obj *)malloc(sizeof(struct fsl_dpni_obj));
@@ -973,10 +1017,19 @@ static int dpni_init(void)
goto err_malloc;
}
+ memset(&dpni_extended_cfg, 0, sizeof(dpni_extended_cfg));
+ err = dpni_prepare_extended_cfg(&dpni_extended_cfg, &ext_cfg_buf[0]);
+ if (err < 0) {
+ err = -ENODEV;
+ printf("dpni_prepare_extended_cfg() failed: %d\n", err);
+ goto err_prepare_extended_cfg;
+ }
+
memset(&dpni_cfg, 0, sizeof(dpni_cfg));
dpni_cfg.adv.options = DPNI_OPT_UNICAST_FILTER |
DPNI_OPT_MULTICAST_FILTER;
+ dpni_cfg.adv.ext_cfg_iova = (uint64_t)&ext_cfg_buf[0];
err = dpni_create(dflt_mc_io, MC_CMD_NO_FLAGS, &dpni_cfg,
&dflt_dpni->dpni_handle);
@@ -995,6 +1048,14 @@ static int dpni_init(void)
goto err_get_attr;
}
+ if ((dpni_attr.version.major != DPNI_VER_MAJOR) ||
+ (dpni_attr.version.minor != DPNI_VER_MINOR)) {
+ printf("DPNI version mismatch found %u.%u,",
+ dpni_attr.version.major, dpni_attr.version.minor);
+ printf("supported version is %u.%u\n",
+ DPNI_VER_MAJOR, DPNI_VER_MINOR);
+ }
+
dflt_dpni->dpni_id = dpni_attr.id;
#ifdef DEBUG
printf("Init: DPNI id=0x%d\n", dflt_dpni->dpni_id);
@@ -1009,11 +1070,12 @@ static int dpni_init(void)
return 0;
err_close:
- free(dflt_dpni);
err_get_attr:
dpni_close(dflt_mc_io, MC_CMD_NO_FLAGS, dflt_dpni->dpni_handle);
dpni_destroy(dflt_mc_io, MC_CMD_NO_FLAGS, dflt_dpni->dpni_handle);
err_create:
+err_prepare_extended_cfg:
+ free(dflt_dpni);
err_malloc:
return err;
}
@@ -1099,7 +1161,7 @@ int fsl_mc_ldpaa_exit(bd_t *bd)
err = dpbp_exit();
if (err < 0) {
- printf("dpni_exit() failed: %d\n", err);
+ printf("dpbp_exit() failed: %d\n", err);
goto err;
}
diff --git a/drivers/net/fsl_mdio.c b/drivers/net/fsl_mdio.c
index f48bbc31239..77b9739a244 100644
--- a/drivers/net/fsl_mdio.c
+++ b/drivers/net/fsl_mdio.c
@@ -5,6 +5,7 @@
*
* SPDX-License-Identifier: GPL-2.0+
*/
+
#include <common.h>
#include <miiphy.h>
#include <phy.h>
@@ -32,8 +33,7 @@ int tsec_local_mdio_read(struct tsec_mii_mng __iomem *phyregs, int port_addr,
int value;
int timeout = 1000000;
- /* Put the address of the phy, and the register
- * number into MIIMADD */
+ /* Put the address of the phy, and the register number into MIIMADD */
out_be32(&phyregs->miimadd, (port_addr << 8) | (regnum & 0x1f));
/* Clear the command register, and wait */
diff --git a/drivers/net/ldpaa_eth/ldpaa_eth.c b/drivers/net/ldpaa_eth/ldpaa_eth.c
index 3857122bd05..7f96883d347 100644
--- a/drivers/net/ldpaa_eth/ldpaa_eth.c
+++ b/drivers/net/ldpaa_eth/ldpaa_eth.c
@@ -100,6 +100,83 @@ static void ldpaa_eth_get_dpni_counter(void)
}
printf("DPNI_CNT_EGR_FRAME_DISCARD =%lld\n", value);
}
+
+static void ldpaa_eth_get_dpmac_counter(struct eth_device *net_dev)
+{
+ struct ldpaa_eth_priv *priv = (struct ldpaa_eth_priv *)net_dev->priv;
+ int err = 0;
+ u64 value;
+
+ err = dpmac_get_counter(dflt_mc_io, MC_CMD_NO_FLAGS,
+ priv->dpmac_handle,
+ DPMAC_CNT_ING_BYTE,
+ &value);
+ if (err < 0) {
+ printf("dpmac_get_counter: DPMAC_CNT_ING_BYTE failed\n");
+ return;
+ }
+ printf("DPMAC_CNT_ING_BYTE=%lld\n", value);
+
+ err = dpmac_get_counter(dflt_mc_io, MC_CMD_NO_FLAGS,
+ priv->dpmac_handle,
+ DPMAC_CNT_ING_FRAME_DISCARD,
+ &value);
+ if (err < 0) {
+ printf("dpmac_get_counter: DPMAC_CNT_ING_FRAME_DISCARD failed\n");
+ return;
+ }
+ printf("DPMAC_CNT_ING_FRAME_DISCARD=%lld\n", value);
+
+ err = dpmac_get_counter(dflt_mc_io, MC_CMD_NO_FLAGS,
+ priv->dpmac_handle,
+ DPMAC_CNT_ING_ALIGN_ERR,
+ &value);
+ if (err < 0) {
+ printf("dpmac_get_counter: DPMAC_CNT_ING_ALIGN_ERR failed\n");
+ return;
+ }
+ printf("DPMAC_CNT_ING_ALIGN_ERR =%lld\n", value);
+
+ err = dpmac_get_counter(dflt_mc_io, MC_CMD_NO_FLAGS,
+ priv->dpmac_handle,
+ DPMAC_CNT_ING_BYTE,
+ &value);
+ if (err < 0) {
+ printf("dpmac_get_counter: DPMAC_CNT_ING_BYTE failed\n");
+ return;
+ }
+ printf("DPMAC_CNT_ING_BYTE=%lld\n", value);
+
+ err = dpmac_get_counter(dflt_mc_io, MC_CMD_NO_FLAGS,
+ priv->dpmac_handle,
+ DPMAC_CNT_ING_ERR_FRAME,
+ &value);
+ if (err < 0) {
+ printf("dpmac_get_counter: DPMAC_CNT_ING_ERR_FRAME failed\n");
+ return;
+ }
+ printf("DPMAC_CNT_ING_ERR_FRAME=%lld\n", value);
+
+ err = dpmac_get_counter(dflt_mc_io, MC_CMD_NO_FLAGS,
+ priv->dpmac_handle,
+ DPMAC_CNT_EGR_BYTE ,
+ &value);
+ if (err < 0) {
+ printf("dpmac_get_counter: DPMAC_CNT_EGR_BYTE failed\n");
+ return;
+ }
+ printf("DPMAC_CNT_EGR_BYTE =%lld\n", value);
+
+ err = dpmac_get_counter(dflt_mc_io, MC_CMD_NO_FLAGS,
+ priv->dpmac_handle,
+ DPMAC_CNT_EGR_ERR_FRAME ,
+ &value);
+ if (err < 0) {
+ printf("dpmac_get_counter: DPMAC_CNT_EGR_ERR_FRAME failed\n");
+ return;
+ }
+ printf("DPMAC_CNT_EGR_ERR_FRAME =%lld\n", value);
+}
#endif
static void ldpaa_eth_rx(struct ldpaa_eth_priv *priv,
@@ -436,6 +513,7 @@ static void ldpaa_eth_stop(struct eth_device *net_dev)
#ifdef DEBUG
ldpaa_eth_get_dpni_counter();
+ ldpaa_eth_get_dpmac_counter(net_dev);
#endif
err = dprc_disconnect(dflt_mc_io, MC_CMD_NO_FLAGS,
@@ -599,6 +677,29 @@ static void ldpaa_dpbp_free(void)
dpbp_close(dflt_mc_io, MC_CMD_NO_FLAGS, dflt_dpbp->dpbp_handle);
}
+static int ldpaa_dpmac_version_check(struct fsl_mc_io *mc_io,
+ struct ldpaa_eth_priv *priv)
+{
+ struct dpmac_attr attr;
+ int error;
+
+ memset(&attr, 0, sizeof(struct dpmac_attr));
+ error = dpmac_get_attributes(mc_io, MC_CMD_NO_FLAGS,
+ priv->dpmac_handle,
+ &attr);
+ if (error == 0) {
+ if ((attr.version.major != DPMAC_VER_MAJOR) ||
+ (attr.version.minor != DPMAC_VER_MINOR)) {
+ printf("DPMAC version mismatch found %u.%u,",
+ attr.version.major, attr.version.minor);
+ printf("supported version is %u.%u\n",
+ DPMAC_VER_MAJOR, DPMAC_VER_MINOR);
+ }
+ }
+
+ return error;
+}
+
static int ldpaa_dpmac_setup(struct ldpaa_eth_priv *priv)
{
int err = 0;
@@ -609,6 +710,11 @@ static int ldpaa_dpmac_setup(struct ldpaa_eth_priv *priv)
&priv->dpmac_handle);
if (err)
printf("dpmac_create() failed\n");
+
+ err = ldpaa_dpmac_version_check(dflt_mc_io, priv);
+ if (err < 0)
+ printf("ldpaa_dpmac_version_check() failed: %d\n", err);
+
return err;
}
@@ -755,6 +861,7 @@ static int ldpaa_dpni_bind(struct ldpaa_eth_priv *priv)
{
struct dpni_pools_cfg pools_params;
struct dpni_tx_flow_cfg dflt_tx_flow;
+ struct dpni_tx_conf_cfg tx_conf_cfg;
int err = 0;
pools_params.num_dpbp = 1;
@@ -770,9 +877,7 @@ static int ldpaa_dpni_bind(struct ldpaa_eth_priv *priv)
priv->tx_flow_id = DPNI_NEW_FLOW_ID;
memset(&dflt_tx_flow, 0, sizeof(dflt_tx_flow));
- dflt_tx_flow.options = DPNI_TX_FLOW_OPT_ONLY_TX_ERROR;
- dflt_tx_flow.conf_err_cfg.use_default_queue = 0;
- dflt_tx_flow.conf_err_cfg.errors_only = 1;
+ dflt_tx_flow.use_common_tx_conf_queue = 0;
err = dpni_set_tx_flow(dflt_mc_io, MC_CMD_NO_FLAGS,
dflt_dpni->dpni_handle, &priv->tx_flow_id,
&dflt_tx_flow);
@@ -781,6 +886,17 @@ static int ldpaa_dpni_bind(struct ldpaa_eth_priv *priv)
return err;
}
+ memset(&tx_conf_cfg, 0, sizeof(struct dpni_tx_conf_cfg));
+ tx_conf_cfg.errors_only = true;
+ /*Set tx-conf and error configuration*/
+ err = dpni_set_tx_conf(dflt_mc_io, MC_CMD_NO_FLAGS,
+ dflt_dpni->dpni_handle,
+ priv->tx_flow_id, &tx_conf_cfg);
+ if (err) {
+ printf("dpni_set_tx_conf() failed\n");
+ return err;
+ }
+
return 0;
}
diff --git a/drivers/net/ldpaa_eth/ldpaa_eth.h b/drivers/net/ldpaa_eth/ldpaa_eth.h
index af41b278440..3b161507359 100644
--- a/drivers/net/ldpaa_eth/ldpaa_eth.h
+++ b/drivers/net/ldpaa_eth/ldpaa_eth.h
@@ -24,7 +24,7 @@ enum ldpaa_eth_type {
};
/* Arbitrary values for now, but we'll need to tune */
-#define LDPAA_ETH_NUM_BUFS (2 * 7)
+#define LDPAA_ETH_NUM_BUFS (7 * 7)
#define LDPAA_ETH_REFILL_THRESH (LDPAA_ETH_NUM_BUFS/2)
#define LDPAA_ETH_RX_BUFFER_SIZE 2048
diff --git a/drivers/net/phy/cortina.c b/drivers/net/phy/cortina.c
index 447ecfbeb6d..f975fd82091 100644
--- a/drivers/net/phy/cortina.c
+++ b/drivers/net/phy/cortina.c
@@ -257,6 +257,12 @@ int cs4340_config(struct phy_device *phydev)
return 0;
}
+int cs4340_probe(struct phy_device *phydev)
+{
+ phydev->flags = PHY_FLAG_BROKEN_RESET;
+ return 0;
+}
+
int cs4340_startup(struct phy_device *phydev)
{
phydev->link = 1;
@@ -276,6 +282,7 @@ struct phy_driver cs4340_driver = {
MDIO_DEVS_PHYXS | MDIO_DEVS_AN |
MDIO_DEVS_VEND1 | MDIO_DEVS_VEND2),
.config = &cs4340_config,
+ .probe = &cs4340_probe,
.startup = &cs4340_startup,
.shutdown = &gen10g_shutdown,
};
diff --git a/drivers/net/phy/micrel.c b/drivers/net/phy/micrel.c
index 19b6bc74727..c3da1606dc5 100644
--- a/drivers/net/phy/micrel.c
+++ b/drivers/net/phy/micrel.c
@@ -27,12 +27,31 @@ static struct phy_driver KSZ804_driver = {
.shutdown = &genphy_shutdown,
};
+#define MII_KSZPHY_OMSO 0x16
+#define KSZPHY_OMSO_B_CAST_OFF (1 << 9)
+
+static int ksz_genconfig_bcastoff(struct phy_device *phydev)
+{
+ int ret;
+
+ ret = phy_read(phydev, MDIO_DEVAD_NONE, MII_KSZPHY_OMSO);
+ if (ret < 0)
+ return ret;
+
+ ret = phy_write(phydev, MDIO_DEVAD_NONE, MII_KSZPHY_OMSO,
+ ret | KSZPHY_OMSO_B_CAST_OFF);
+ if (ret < 0)
+ return ret;
+
+ return genphy_config(phydev);
+}
+
static struct phy_driver KSZ8031_driver = {
.name = "Micrel KSZ8021/KSZ8031",
.uid = 0x221550,
.mask = 0xfffff0,
.features = PHY_BASIC_FEATURES,
- .config = &genphy_config,
+ .config = &ksz_genconfig_bcastoff,
.startup = &genphy_startup,
.shutdown = &genphy_shutdown,
};
@@ -70,7 +89,7 @@ static struct phy_driver KSZ8081_driver = {
.uid = 0x221560,
.mask = 0xfffff0,
.features = PHY_BASIC_FEATURES,
- .config = &genphy_config,
+ .config = &ksz_genconfig_bcastoff,
.startup = &genphy_startup,
.shutdown = &genphy_shutdown,
};
@@ -211,7 +230,7 @@ static int ksz90x1_of_config_group(struct phy_device *phydev,
{
struct udevice *dev = phydev->dev;
struct phy_driver *drv = phydev->drv;
- const int ps_to_regval = 200;
+ const int ps_to_regval = 60;
int val[4];
int i, changed = 0, offset, max;
u16 regval = 0;
diff --git a/drivers/net/phy/phy.c b/drivers/net/phy/phy.c
index 51b5746a5a4..17866a244b3 100644
--- a/drivers/net/phy/phy.c
+++ b/drivers/net/phy/phy.c
@@ -38,16 +38,16 @@ DECLARE_GLOBAL_DATA_PTR;
static int genphy_config_advert(struct phy_device *phydev)
{
u32 advertise;
- int oldadv, adv;
+ int oldadv, adv, bmsr;
int err, changed = 0;
- /* Only allow advertising what
- * this PHY supports */
+ /* Only allow advertising what this PHY supports */
phydev->advertising &= phydev->supported;
advertise = phydev->advertising;
/* Setup standard advertisement */
- oldadv = adv = phy_read(phydev, MDIO_DEVAD_NONE, MII_ADVERTISE);
+ adv = phy_read(phydev, MDIO_DEVAD_NONE, MII_ADVERTISE);
+ oldadv = adv;
if (adv < 0)
return adv;
@@ -79,29 +79,40 @@ static int genphy_config_advert(struct phy_device *phydev)
changed = 1;
}
+ bmsr = phy_read(phydev, MDIO_DEVAD_NONE, MII_BMSR);
+ if (bmsr < 0)
+ return bmsr;
+
+ /* Per 802.3-2008, Section 22.2.4.2.16 Extended status all
+ * 1000Mbits/sec capable PHYs shall have the BMSR_ESTATEN bit set to a
+ * logical 1.
+ */
+ if (!(bmsr & BMSR_ESTATEN))
+ return changed;
+
/* Configure gigabit if it's supported */
- if (phydev->supported & (SUPPORTED_1000baseT_Half |
- SUPPORTED_1000baseT_Full)) {
- oldadv = adv = phy_read(phydev, MDIO_DEVAD_NONE, MII_CTRL1000);
+ adv = phy_read(phydev, MDIO_DEVAD_NONE, MII_CTRL1000);
+ oldadv = adv;
+
+ if (adv < 0)
+ return adv;
- if (adv < 0)
- return adv;
+ adv &= ~(ADVERTISE_1000FULL | ADVERTISE_1000HALF);
- adv &= ~(ADVERTISE_1000FULL | ADVERTISE_1000HALF);
+ if (phydev->supported & (SUPPORTED_1000baseT_Half |
+ SUPPORTED_1000baseT_Full)) {
if (advertise & SUPPORTED_1000baseT_Half)
adv |= ADVERTISE_1000HALF;
if (advertise & SUPPORTED_1000baseT_Full)
adv |= ADVERTISE_1000FULL;
+ }
- if (adv != oldadv) {
- err = phy_write(phydev, MDIO_DEVAD_NONE, MII_CTRL1000,
- adv);
+ if (adv != oldadv)
+ changed = 1;
- if (err < 0)
- return err;
- changed = 1;
- }
- }
+ err = phy_write(phydev, MDIO_DEVAD_NONE, MII_CTRL1000, adv);
+ if (err < 0)
+ return err;
return changed;
}
@@ -117,7 +128,7 @@ static int genphy_config_advert(struct phy_device *phydev)
static int genphy_setup_forced(struct phy_device *phydev)
{
int err;
- int ctl = 0;
+ int ctl = BMCR_ANRESTART;
phydev->pause = phydev->asym_pause = 0;
@@ -224,7 +235,8 @@ int genphy_update_link(struct phy_device *phydev)
if (phydev->link && mii_reg & BMSR_LSTATUS)
return 0;
- if ((mii_reg & BMSR_ANEGCAPABLE) && !(mii_reg & BMSR_ANEGCOMPLETE)) {
+ if ((phydev->autoneg == AUTONEG_ENABLE) &&
+ !(mii_reg & BMSR_ANEGCOMPLETE)) {
int i = 0;
printf("%s Waiting for PHY auto negotiation to complete",
@@ -280,7 +292,7 @@ int genphy_parse_link(struct phy_device *phydev)
int mii_reg = phy_read(phydev, MDIO_DEVAD_NONE, MII_BMSR);
/* We're using autonegotiation */
- if (phydev->supported & SUPPORTED_Autoneg) {
+ if (phydev->autoneg == AUTONEG_ENABLE) {
u32 lpa = 0;
int gblpa = 0;
u32 estatus = 0;
@@ -371,8 +383,6 @@ int genphy_config(struct phy_device *phydev)
int val;
u32 features;
- /* For now, I'll claim that the generic driver supports
- * all possible port types */
features = (SUPPORTED_TP | SUPPORTED_MII
| SUPPORTED_AUI | SUPPORTED_FIBRE |
SUPPORTED_BNC);
@@ -411,8 +421,8 @@ int genphy_config(struct phy_device *phydev)
features |= SUPPORTED_1000baseX_Half;
}
- phydev->supported = features;
- phydev->advertising = features;
+ phydev->supported &= features;
+ phydev->advertising &= features;
genphy_config_aneg(phydev);
@@ -436,7 +446,9 @@ static struct phy_driver genphy_driver = {
.uid = 0xffffffff,
.mask = 0xffffffff,
.name = "Generic PHY",
- .features = 0,
+ .features = PHY_GBIT_FEATURES | SUPPORTED_MII |
+ SUPPORTED_AUI | SUPPORTED_FIBRE |
+ SUPPORTED_BNC,
.config = genphy_config,
.startup = genphy_startup,
.shutdown = genphy_shutdown,
@@ -517,6 +529,30 @@ int phy_register(struct phy_driver *drv)
return 0;
}
+int phy_set_supported(struct phy_device *phydev, u32 max_speed)
+{
+ /* The default values for phydev->supported are provided by the PHY
+ * driver "features" member, we want to reset to sane defaults first
+ * before supporting higher speeds.
+ */
+ phydev->supported &= PHY_DEFAULT_FEATURES;
+
+ switch (max_speed) {
+ default:
+ return -ENOTSUPP;
+ case SPEED_1000:
+ phydev->supported |= PHY_1000BT_FEATURES;
+ /* fall through */
+ case SPEED_100:
+ phydev->supported |= PHY_100BT_FEATURES;
+ /* fall through */
+ case SPEED_10:
+ phydev->supported |= PHY_10BT_FEATURES;
+ }
+
+ return 0;
+}
+
static int phy_probe(struct phy_device *phydev)
{
int err = 0;
@@ -707,6 +743,9 @@ int phy_reset(struct phy_device *phydev)
int timeout = 500;
int devad = MDIO_DEVAD_NONE;
+ if (phydev->flags & PHY_FLAG_BROKEN_RESET)
+ return 0;
+
#ifdef CONFIG_PHYLIB_10G
/* If it's 10G, we need to issue reset through one of the MMDs */
if (is_10g_interface(phydev->interface)) {
@@ -717,15 +756,7 @@ int phy_reset(struct phy_device *phydev)
}
#endif
- reg = phy_read(phydev, devad, MII_BMCR);
- if (reg < 0) {
- debug("PHY status read failed\n");
- return -1;
- }
-
- reg |= BMCR_RESET;
-
- if (phy_write(phydev, devad, MII_BMCR, reg) < 0) {
+ if (phy_write(phydev, devad, MII_BMCR, BMCR_RESET) < 0) {
debug("PHY reset failed\n");
return -1;
}
@@ -738,6 +769,7 @@ int phy_reset(struct phy_device *phydev)
* auto-clearing). This should happen within 0.5 seconds per the
* IEEE spec.
*/
+ reg = phy_read(phydev, devad, MII_BMCR);
while ((reg & BMCR_RESET) && timeout--) {
reg = phy_read(phydev, devad, MII_BMCR);
diff --git a/drivers/net/phy/smsc.c b/drivers/net/phy/smsc.c
index bfd9815abf9..34986a29fc3 100644
--- a/drivers/net/phy/smsc.c
+++ b/drivers/net/phy/smsc.c
@@ -69,11 +69,21 @@ static struct phy_driver lan8710_driver = {
.shutdown = &genphy_shutdown,
};
+static struct phy_driver lan8740_driver = {
+ .name = "SMSC LAN8740",
+ .uid = 0x0007c110,
+ .mask = 0xffff0,
+ .features = PHY_BASIC_FEATURES,
+ .config = &genphy_config_aneg,
+ .startup = &genphy_startup,
+ .shutdown = &genphy_shutdown,
+};
int phy_smsc_init(void)
{
phy_register(&lan8710_driver);
phy_register(&lan911x_driver);
phy_register(&lan8700_driver);
+ phy_register(&lan8740_driver);
return 0;
}
diff --git a/drivers/net/phy/ti.c b/drivers/net/phy/ti.c
index 541a57f9802..c3912d52f32 100644
--- a/drivers/net/phy/ti.c
+++ b/drivers/net/phy/ti.c
@@ -41,6 +41,8 @@
/* PHY CTRL bits */
#define DP83867_PHYCR_FIFO_DEPTH_SHIFT 14
+#define DP83867_MDI_CROSSOVER 5
+#define DP83867_MDI_CROSSOVER_AUTO 2
/* RGMIIDCTL bits */
#define DP83867_RGMII_TX_CLK_DELAY_SHIFT 4
@@ -149,6 +151,7 @@ static int dp83867_config(struct phy_device *phydev)
if (phy_interface_is_rgmii(phydev)) {
ret = phy_write(phydev, MDIO_DEVAD_NONE, MII_DP83867_PHYCTRL,
+ (DP83867_MDI_CROSSOVER_AUTO << DP83867_MDI_CROSSOVER) |
(FIFO_DEPTH << DP83867_PHYCR_FIFO_DEPTH_SHIFT));
if (ret)
return ret;
diff --git a/drivers/net/pic32_eth.c b/drivers/net/pic32_eth.c
new file mode 100644
index 00000000000..167af8bde5b
--- /dev/null
+++ b/drivers/net/pic32_eth.c
@@ -0,0 +1,605 @@
+/*
+ * (c) 2015 Purna Chandra Mandal <purna.mandal@microchip.com>
+ *
+ * SPDX-License-Identifier: GPL-2.0+
+ *
+ */
+#include <common.h>
+#include <errno.h>
+#include <dm.h>
+#include <net.h>
+#include <miiphy.h>
+#include <console.h>
+#include <wait_bit.h>
+#include <asm/gpio.h>
+
+#include "pic32_eth.h"
+
+#define MAX_RX_BUF_SIZE 1536
+#define MAX_RX_DESCR PKTBUFSRX
+#define MAX_TX_DESCR 2
+
+DECLARE_GLOBAL_DATA_PTR;
+
+struct pic32eth_dev {
+ struct eth_dma_desc rxd_ring[MAX_RX_DESCR];
+ struct eth_dma_desc txd_ring[MAX_TX_DESCR];
+ u32 rxd_idx; /* index of RX desc to read */
+ /* regs */
+ struct pic32_ectl_regs *ectl_regs;
+ struct pic32_emac_regs *emac_regs;
+ /* Phy */
+ struct phy_device *phydev;
+ phy_interface_t phyif;
+ u32 phy_addr;
+ struct gpio_desc rst_gpio;
+};
+
+void __weak board_netphy_reset(void *dev)
+{
+ struct pic32eth_dev *priv = dev;
+
+ if (!dm_gpio_is_valid(&priv->rst_gpio))
+ return;
+
+ /* phy reset */
+ dm_gpio_set_value(&priv->rst_gpio, 0);
+ udelay(300);
+ dm_gpio_set_value(&priv->rst_gpio, 1);
+ udelay(300);
+}
+
+/* Initialize mii(MDIO) interface, discover which PHY is
+ * attached to the device, and configure it properly.
+ */
+static int pic32_mii_init(struct pic32eth_dev *priv)
+{
+ struct pic32_ectl_regs *ectl_p = priv->ectl_regs;
+ struct pic32_emac_regs *emac_p = priv->emac_regs;
+
+ /* board phy reset */
+ board_netphy_reset(priv);
+
+ /* disable RX, TX & all transactions */
+ writel(ETHCON_ON | ETHCON_TXRTS | ETHCON_RXEN, &ectl_p->con1.clr);
+
+ /* wait till busy */
+ wait_for_bit(__func__, &ectl_p->stat.raw, ETHSTAT_BUSY, false,
+ CONFIG_SYS_HZ, false);
+
+ /* turn controller ON to access PHY over MII */
+ writel(ETHCON_ON, &ectl_p->con1.set);
+
+ mdelay(10);
+
+ /* reset MAC */
+ writel(EMAC_SOFTRESET, &emac_p->cfg1.set); /* reset assert */
+ mdelay(10);
+ writel(EMAC_SOFTRESET, &emac_p->cfg1.clr); /* reset deassert */
+
+ /* initialize MDIO/MII */
+ if (priv->phyif == PHY_INTERFACE_MODE_RMII) {
+ writel(EMAC_RMII_RESET, &emac_p->supp.set);
+ mdelay(10);
+ writel(EMAC_RMII_RESET, &emac_p->supp.clr);
+ }
+
+ return pic32_mdio_init(PIC32_MDIO_NAME, (ulong)&emac_p->mii);
+}
+
+static int pic32_phy_init(struct pic32eth_dev *priv, struct udevice *dev)
+{
+ struct mii_dev *mii;
+
+ mii = miiphy_get_dev_by_name(PIC32_MDIO_NAME);
+
+ /* find & connect PHY */
+ priv->phydev = phy_connect(mii, priv->phy_addr,
+ dev, priv->phyif);
+ if (!priv->phydev) {
+ printf("%s: %s: Error, PHY connect\n", __FILE__, __func__);
+ return 0;
+ }
+
+ /* Wait for phy to complete reset */
+ mdelay(10);
+
+ /* configure supported modes */
+ priv->phydev->supported = SUPPORTED_10baseT_Half |
+ SUPPORTED_10baseT_Full |
+ SUPPORTED_100baseT_Half |
+ SUPPORTED_100baseT_Full |
+ SUPPORTED_Autoneg;
+
+ priv->phydev->advertising = ADVERTISED_10baseT_Half |
+ ADVERTISED_10baseT_Full |
+ ADVERTISED_100baseT_Half |
+ ADVERTISED_100baseT_Full |
+ ADVERTISED_Autoneg;
+
+ priv->phydev->autoneg = AUTONEG_ENABLE;
+
+ return 0;
+}
+
+/* Configure MAC based on negotiated speed and duplex
+ * reported by PHY.
+ */
+static int pic32_mac_adjust_link(struct pic32eth_dev *priv)
+{
+ struct phy_device *phydev = priv->phydev;
+ struct pic32_emac_regs *emac_p = priv->emac_regs;
+
+ if (!phydev->link) {
+ printf("%s: No link.\n", phydev->dev->name);
+ return -EINVAL;
+ }
+
+ if (phydev->duplex) {
+ writel(EMAC_FULLDUP, &emac_p->cfg2.set);
+ writel(FULLDUP_GAP_TIME, &emac_p->ipgt.raw);
+ } else {
+ writel(EMAC_FULLDUP, &emac_p->cfg2.clr);
+ writel(HALFDUP_GAP_TIME, &emac_p->ipgt.raw);
+ }
+
+ switch (phydev->speed) {
+ case SPEED_100:
+ writel(EMAC_RMII_SPD100, &emac_p->supp.set);
+ break;
+ case SPEED_10:
+ writel(EMAC_RMII_SPD100, &emac_p->supp.clr);
+ break;
+ default:
+ printf("%s: Speed was bad\n", phydev->dev->name);
+ return -EINVAL;
+ }
+
+ printf("pic32eth: PHY is %s with %dbase%s, %s\n",
+ phydev->drv->name, phydev->speed,
+ (phydev->port == PORT_TP) ? "T" : "X",
+ (phydev->duplex) ? "full" : "half");
+
+ return 0;
+}
+
+static void pic32_mac_init(struct pic32eth_dev *priv, u8 *macaddr)
+{
+ struct pic32_emac_regs *emac_p = priv->emac_regs;
+ u32 stat = 0, v;
+ u64 expire;
+
+ v = EMAC_TXPAUSE | EMAC_RXPAUSE | EMAC_RXENABLE;
+ writel(v, &emac_p->cfg1.raw);
+
+ v = EMAC_EXCESS | EMAC_AUTOPAD | EMAC_PADENABLE |
+ EMAC_CRCENABLE | EMAC_LENGTHCK | EMAC_FULLDUP;
+ writel(v, &emac_p->cfg2.raw);
+
+ /* recommended back-to-back inter-packet gap for 10 Mbps half duplex */
+ writel(HALFDUP_GAP_TIME, &emac_p->ipgt.raw);
+
+ /* recommended non-back-to-back interpacket gap is 0xc12 */
+ writel(0xc12, &emac_p->ipgr.raw);
+
+ /* recommended collision window retry limit is 0x370F */
+ writel(0x370f, &emac_p->clrt.raw);
+
+ /* set maximum frame length: allow VLAN tagged frame */
+ writel(0x600, &emac_p->maxf.raw);
+
+ /* set the mac address */
+ writel(macaddr[0] | (macaddr[1] << 8), &emac_p->sa2.raw);
+ writel(macaddr[2] | (macaddr[3] << 8), &emac_p->sa1.raw);
+ writel(macaddr[4] | (macaddr[5] << 8), &emac_p->sa0.raw);
+
+ /* default, enable 10 Mbps operation */
+ writel(EMAC_RMII_SPD100, &emac_p->supp.clr);
+
+ /* wait until link status UP or deadline elapsed */
+ expire = get_ticks() + get_tbclk() * 2;
+ for (; get_ticks() < expire;) {
+ stat = phy_read(priv->phydev, priv->phy_addr, MII_BMSR);
+ if (stat & BMSR_LSTATUS)
+ break;
+ }
+
+ if (!(stat & BMSR_LSTATUS))
+ printf("MAC: Link is DOWN!\n");
+
+ /* delay to stabilize before any tx/rx */
+ mdelay(10);
+}
+
+static void pic32_mac_reset(struct pic32eth_dev *priv)
+{
+ struct pic32_emac_regs *emac_p = priv->emac_regs;
+ struct mii_dev *mii;
+
+ /* Reset MAC */
+ writel(EMAC_SOFTRESET, &emac_p->cfg1.raw);
+ mdelay(10);
+
+ /* clear reset */
+ writel(0, &emac_p->cfg1.raw);
+
+ /* Reset MII */
+ mii = priv->phydev->bus;
+ if (mii && mii->reset)
+ mii->reset(mii);
+}
+
+/* initializes the MAC and PHY, then establishes a link */
+static void pic32_ctrl_reset(struct pic32eth_dev *priv)
+{
+ struct pic32_ectl_regs *ectl_p = priv->ectl_regs;
+ u32 v;
+
+ /* disable RX, TX & any other transactions */
+ writel(ETHCON_ON | ETHCON_TXRTS | ETHCON_RXEN, &ectl_p->con1.clr);
+
+ /* wait till busy */
+ wait_for_bit(__func__, &ectl_p->stat.raw, ETHSTAT_BUSY, false,
+ CONFIG_SYS_HZ, false);
+ /* decrement received buffcnt to zero. */
+ while (readl(&ectl_p->stat.raw) & ETHSTAT_BUFCNT)
+ writel(ETHCON_BUFCDEC, &ectl_p->con1.set);
+
+ /* clear any existing interrupt event */
+ writel(0xffffffff, &ectl_p->irq.clr);
+
+ /* clear RX/TX start address */
+ writel(0xffffffff, &ectl_p->txst.clr);
+ writel(0xffffffff, &ectl_p->rxst.clr);
+
+ /* clear the receive filters */
+ writel(0x00ff, &ectl_p->rxfc.clr);
+
+ /* set the receive filters
+ * ETH_FILT_CRC_ERR_REJECT
+ * ETH_FILT_RUNT_REJECT
+ * ETH_FILT_UCAST_ACCEPT
+ * ETH_FILT_MCAST_ACCEPT
+ * ETH_FILT_BCAST_ACCEPT
+ */
+ v = ETHRXFC_BCEN | ETHRXFC_MCEN | ETHRXFC_UCEN |
+ ETHRXFC_RUNTEN | ETHRXFC_CRCOKEN;
+ writel(v, &ectl_p->rxfc.set);
+
+ /* turn controller ON to access PHY over MII */
+ writel(ETHCON_ON, &ectl_p->con1.set);
+}
+
+static void pic32_rx_desc_init(struct pic32eth_dev *priv)
+{
+ struct pic32_ectl_regs *ectl_p = priv->ectl_regs;
+ struct eth_dma_desc *rxd;
+ u32 idx, bufsz;
+
+ priv->rxd_idx = 0;
+ for (idx = 0; idx < MAX_RX_DESCR; idx++) {
+ rxd = &priv->rxd_ring[idx];
+
+ /* hw owned */
+ rxd->hdr = EDH_NPV | EDH_EOWN | EDH_STICKY;
+
+ /* packet buffer address */
+ rxd->data_buff = virt_to_phys(net_rx_packets[idx]);
+
+ /* link to next desc */
+ rxd->next_ed = virt_to_phys(rxd + 1);
+
+ /* reset status */
+ rxd->stat1 = 0;
+ rxd->stat2 = 0;
+
+ /* decrement bufcnt */
+ writel(ETHCON_BUFCDEC, &ectl_p->con1.set);
+ }
+
+ /* link last descr to beginning of list */
+ rxd->next_ed = virt_to_phys(&priv->rxd_ring[0]);
+
+ /* flush rx ring */
+ flush_dcache_range((ulong)priv->rxd_ring,
+ (ulong)priv->rxd_ring + sizeof(priv->rxd_ring));
+
+ /* set rx desc-ring start address */
+ writel((ulong)virt_to_phys(&priv->rxd_ring[0]), &ectl_p->rxst.raw);
+
+ /* RX Buffer size */
+ bufsz = readl(&ectl_p->con2.raw);
+ bufsz &= ~(ETHCON_RXBUFSZ << ETHCON_RXBUFSZ_SHFT);
+ bufsz |= ((MAX_RX_BUF_SIZE / 16) << ETHCON_RXBUFSZ_SHFT);
+ writel(bufsz, &ectl_p->con2.raw);
+
+ /* enable the receiver in hardware which allows hardware
+ * to DMA received pkts to the descriptor pointer address.
+ */
+ writel(ETHCON_RXEN, &ectl_p->con1.set);
+}
+
+static int pic32_eth_start(struct udevice *dev)
+{
+ struct eth_pdata *pdata = dev_get_platdata(dev);
+ struct pic32eth_dev *priv = dev_get_priv(dev);
+
+ /* controller */
+ pic32_ctrl_reset(priv);
+
+ /* reset MAC */
+ pic32_mac_reset(priv);
+
+ /* configure PHY */
+ phy_config(priv->phydev);
+
+ /* initialize MAC */
+ pic32_mac_init(priv, &pdata->enetaddr[0]);
+
+ /* init RX descriptor; TX descriptors are handled in xmit */
+ pic32_rx_desc_init(priv);
+
+ /* Start up & update link status of PHY */
+ phy_startup(priv->phydev);
+
+ /* adjust mac with phy link status */
+ return pic32_mac_adjust_link(priv);
+}
+
+static void pic32_eth_stop(struct udevice *dev)
+{
+ struct pic32eth_dev *priv = dev_get_priv(dev);
+ struct pic32_ectl_regs *ectl_p = priv->ectl_regs;
+ struct pic32_emac_regs *emac_p = priv->emac_regs;
+
+ /* Reset the phy if the controller is enabled */
+ if (readl(&ectl_p->con1.raw) & ETHCON_ON)
+ phy_reset(priv->phydev);
+
+ /* Shut down the PHY */
+ phy_shutdown(priv->phydev);
+
+ /* Stop rx/tx */
+ writel(ETHCON_TXRTS | ETHCON_RXEN, &ectl_p->con1.clr);
+ mdelay(10);
+
+ /* reset MAC */
+ writel(EMAC_SOFTRESET, &emac_p->cfg1.raw);
+
+ /* clear reset */
+ writel(0, &emac_p->cfg1.raw);
+ mdelay(10);
+
+ /* disable controller */
+ writel(ETHCON_ON, &ectl_p->con1.clr);
+ mdelay(10);
+
+ /* wait until everything is down */
+ wait_for_bit(__func__, &ectl_p->stat.raw, ETHSTAT_BUSY, false,
+ 2 * CONFIG_SYS_HZ, false);
+
+ /* clear any existing interrupt event */
+ writel(0xffffffff, &ectl_p->irq.clr);
+}
+
+static int pic32_eth_send(struct udevice *dev, void *packet, int length)
+{
+ struct pic32eth_dev *priv = dev_get_priv(dev);
+ struct pic32_ectl_regs *ectl_p = priv->ectl_regs;
+ struct eth_dma_desc *txd;
+ u64 deadline;
+
+ txd = &priv->txd_ring[0];
+
+ /* set proper flags & length in descriptor header */
+ txd->hdr = EDH_SOP | EDH_EOP | EDH_EOWN | EDH_BCOUNT(length);
+
+ /* pass buffer address to hardware */
+ txd->data_buff = virt_to_phys(packet);
+
+ debug("%s: %d / .hdr %x, .data_buff %x, .stat %x, .nexted %x\n",
+ __func__, __LINE__, txd->hdr, txd->data_buff, txd->stat2,
+ txd->next_ed);
+
+ /* cache flush (packet) */
+ flush_dcache_range((ulong)packet, (ulong)packet + length);
+
+ /* cache flush (txd) */
+ flush_dcache_range((ulong)txd, (ulong)txd + sizeof(*txd));
+
+ /* pass descriptor table base to h/w */
+ writel(virt_to_phys(txd), &ectl_p->txst.raw);
+
+ /* ready to send enabled, hardware can now send the packet(s) */
+ writel(ETHCON_TXRTS | ETHCON_ON, &ectl_p->con1.set);
+
+ /* wait until tx has completed and h/w has released ownership
+ * of the tx descriptor or timeout elapsed.
+ */
+ deadline = get_ticks() + get_tbclk();
+ for (;;) {
+ /* check timeout */
+ if (get_ticks() > deadline)
+ return -ETIMEDOUT;
+
+ if (ctrlc())
+ return -EINTR;
+
+ /* tx completed ? */
+ if (readl(&ectl_p->con1.raw) & ETHCON_TXRTS) {
+ udelay(1);
+ continue;
+ }
+
+ /* h/w not released ownership yet? */
+ invalidate_dcache_range((ulong)txd, (ulong)txd + sizeof(*txd));
+ if (!(txd->hdr & EDH_EOWN))
+ break;
+ }
+
+ return 0;
+}
+
+static int pic32_eth_recv(struct udevice *dev, int flags, uchar **packetp)
+{
+ struct pic32eth_dev *priv = dev_get_priv(dev);
+ struct eth_dma_desc *rxd;
+ u32 idx = priv->rxd_idx;
+ u32 rx_count;
+
+ /* find the next ready to receive */
+ rxd = &priv->rxd_ring[idx];
+
+ invalidate_dcache_range((ulong)rxd, (ulong)rxd + sizeof(*rxd));
+ /* check if owned by MAC */
+ if (rxd->hdr & EDH_EOWN)
+ return -EAGAIN;
+
+ /* Sanity check on header: SOP and EOP */
+ if ((rxd->hdr & (EDH_SOP | EDH_EOP)) != (EDH_SOP | EDH_EOP)) {
+ printf("%s: %s, rx pkt across multiple descr\n",
+ __FILE__, __func__);
+ return 0;
+ }
+
+ debug("%s: %d /idx %i, hdr=%x, data_buff %x, stat %x, nexted %x\n",
+ __func__, __LINE__, idx, rxd->hdr,
+ rxd->data_buff, rxd->stat2, rxd->next_ed);
+
+ /* Sanity check on rx_stat: OK, CRC */
+ if (!RSV_RX_OK(rxd->stat2) || RSV_CRC_ERR(rxd->stat2)) {
+ debug("%s: %s: Error, rx problem detected\n",
+ __FILE__, __func__);
+ return 0;
+ }
+
+ /* invalidate dcache */
+ rx_count = RSV_RX_COUNT(rxd->stat2);
+ invalidate_dcache_range((ulong)net_rx_packets[idx],
+ (ulong)net_rx_packets[idx] + rx_count);
+
+ /* Pass the packet to protocol layer */
+ *packetp = net_rx_packets[idx];
+
+ /* increment number of bytes rcvd (ignore CRC) */
+ return rx_count - 4;
+}
+
+static int pic32_eth_free_pkt(struct udevice *dev, uchar *packet, int length)
+{
+ struct pic32eth_dev *priv = dev_get_priv(dev);
+ struct pic32_ectl_regs *ectl_p = priv->ectl_regs;
+ struct eth_dma_desc *rxd;
+ int idx = priv->rxd_idx;
+
+ /* sanity check */
+ if (packet != net_rx_packets[idx]) {
+ printf("rxd_id %d: packet is not matched,\n", idx);
+ return -EAGAIN;
+ }
+
+ /* prepare for receive */
+ rxd = &priv->rxd_ring[idx];
+ rxd->hdr = EDH_STICKY | EDH_NPV | EDH_EOWN;
+
+ flush_dcache_range((ulong)rxd, (ulong)rxd + sizeof(*rxd));
+
+ /* decrement rx pkt count */
+ writel(ETHCON_BUFCDEC, &ectl_p->con1.set);
+
+ debug("%s: %d / idx %i, hdr %x, data_buff %x, stat %x, nexted %x\n",
+ __func__, __LINE__, idx, rxd->hdr, rxd->data_buff,
+ rxd->stat2, rxd->next_ed);
+
+ priv->rxd_idx = (priv->rxd_idx + 1) % MAX_RX_DESCR;
+
+ return 0;
+}
+
+static const struct eth_ops pic32_eth_ops = {
+ .start = pic32_eth_start,
+ .send = pic32_eth_send,
+ .recv = pic32_eth_recv,
+ .free_pkt = pic32_eth_free_pkt,
+ .stop = pic32_eth_stop,
+};
+
+static int pic32_eth_probe(struct udevice *dev)
+{
+ struct eth_pdata *pdata = dev_get_platdata(dev);
+ struct pic32eth_dev *priv = dev_get_priv(dev);
+ const char *phy_mode;
+ void __iomem *iobase;
+ fdt_addr_t addr;
+ fdt_size_t size;
+ int offset = 0;
+ int phy_addr = -1;
+
+ addr = fdtdec_get_addr_size(gd->fdt_blob, dev->of_offset, "reg", &size);
+ if (addr == FDT_ADDR_T_NONE)
+ return -EINVAL;
+
+ iobase = ioremap(addr, size);
+ pdata->iobase = (phys_addr_t)addr;
+
+ /* get phy mode */
+ pdata->phy_interface = -1;
+ phy_mode = fdt_getprop(gd->fdt_blob, dev->of_offset, "phy-mode", NULL);
+ if (phy_mode)
+ pdata->phy_interface = phy_get_interface_by_name(phy_mode);
+ if (pdata->phy_interface == -1) {
+ debug("%s: Invalid PHY interface '%s'\n", __func__, phy_mode);
+ return -EINVAL;
+ }
+
+ /* get phy addr */
+ offset = fdtdec_lookup_phandle(gd->fdt_blob, dev->of_offset,
+ "phy-handle");
+ if (offset > 0)
+ phy_addr = fdtdec_get_int(gd->fdt_blob, offset, "reg", -1);
+
+ /* phy reset gpio */
+ gpio_request_by_name_nodev(gd->fdt_blob, dev->of_offset,
+ "reset-gpios", 0,
+ &priv->rst_gpio, GPIOD_IS_OUT);
+
+ priv->phyif = pdata->phy_interface;
+ priv->phy_addr = phy_addr;
+ priv->ectl_regs = iobase;
+ priv->emac_regs = iobase + PIC32_EMAC1CFG1;
+
+ pic32_mii_init(priv);
+
+ return pic32_phy_init(priv, dev);
+}
+
+static int pic32_eth_remove(struct udevice *dev)
+{
+ struct pic32eth_dev *priv = dev_get_priv(dev);
+ struct mii_dev *bus;
+
+ dm_gpio_free(dev, &priv->rst_gpio);
+ phy_shutdown(priv->phydev);
+ free(priv->phydev);
+ bus = miiphy_get_dev_by_name(PIC32_MDIO_NAME);
+ mdio_unregister(bus);
+ mdio_free(bus);
+ iounmap(priv->ectl_regs);
+ return 0;
+}
+
+static const struct udevice_id pic32_eth_ids[] = {
+ { .compatible = "microchip,pic32mzda-eth" },
+ { }
+};
+
+U_BOOT_DRIVER(pic32_ethernet) = {
+ .name = "pic32_ethernet",
+ .id = UCLASS_ETH,
+ .of_match = pic32_eth_ids,
+ .probe = pic32_eth_probe,
+ .remove = pic32_eth_remove,
+ .ops = &pic32_eth_ops,
+ .priv_auto_alloc_size = sizeof(struct pic32eth_dev),
+ .platdata_auto_alloc_size = sizeof(struct eth_pdata),
+};
diff --git a/drivers/net/pic32_eth.h b/drivers/net/pic32_eth.h
new file mode 100644
index 00000000000..be2a1872d86
--- /dev/null
+++ b/drivers/net/pic32_eth.h
@@ -0,0 +1,164 @@
+/*
+ * (c) 2015 Purna Chandra Mandal <purna.mandal@microchip.com>
+ *
+ * SPDX-License-Identifier: GPL-2.0+
+ *
+ */
+
+#ifndef __MICROCHIP_PIC32_ETH_H_
+#define __MICROCHIP_PIC32_ETH_H_
+
+#include <mach/pic32.h>
+
+/* Ethernet */
+struct pic32_ectl_regs {
+ struct pic32_reg_atomic con1; /* 0x00 */
+ struct pic32_reg_atomic con2; /* 0x10 */
+ struct pic32_reg_atomic txst; /* 0x20 */
+ struct pic32_reg_atomic rxst; /* 0x30 */
+ struct pic32_reg_atomic ht0; /* 0x40 */
+ struct pic32_reg_atomic ht1; /* 0x50 */
+ struct pic32_reg_atomic pmm0; /* 0x60 */
+ struct pic32_reg_atomic pmm1; /* 0x70 */
+ struct pic32_reg_atomic pmcs; /* 0x80 */
+ struct pic32_reg_atomic pmo; /* 0x90 */
+ struct pic32_reg_atomic rxfc; /* 0xa0 */
+ struct pic32_reg_atomic rxwm; /* 0xb0 */
+ struct pic32_reg_atomic ien; /* 0xc0 */
+ struct pic32_reg_atomic irq; /* 0xd0 */
+ struct pic32_reg_atomic stat; /* 0xe0 */
+};
+
+struct pic32_mii_regs {
+ struct pic32_reg_atomic mcfg; /* 0x280 */
+ struct pic32_reg_atomic mcmd; /* 0x290 */
+ struct pic32_reg_atomic madr; /* 0x2a0 */
+ struct pic32_reg_atomic mwtd; /* 0x2b0 */
+ struct pic32_reg_atomic mrdd; /* 0x2c0 */
+ struct pic32_reg_atomic mind; /* 0x2d0 */
+};
+
+struct pic32_emac_regs {
+ struct pic32_reg_atomic cfg1; /* 0x200*/
+ struct pic32_reg_atomic cfg2; /* 0x210*/
+ struct pic32_reg_atomic ipgt; /* 0x220*/
+ struct pic32_reg_atomic ipgr; /* 0x230*/
+ struct pic32_reg_atomic clrt; /* 0x240*/
+ struct pic32_reg_atomic maxf; /* 0x250*/
+ struct pic32_reg_atomic supp; /* 0x260*/
+ struct pic32_reg_atomic test; /* 0x270*/
+ struct pic32_mii_regs mii; /* 0x280 - 0x2d0 */
+ struct pic32_reg_atomic res1; /* 0x2e0 */
+ struct pic32_reg_atomic res2; /* 0x2f0 */
+ struct pic32_reg_atomic sa0; /* 0x300 */
+ struct pic32_reg_atomic sa1; /* 0x310 */
+ struct pic32_reg_atomic sa2; /* 0x320 */
+};
+
+/* ETHCON1 Reg field */
+#define ETHCON_BUFCDEC BIT(0)
+#define ETHCON_RXEN BIT(8)
+#define ETHCON_TXRTS BIT(9)
+#define ETHCON_ON BIT(15)
+
+/* ETHCON2 Reg field */
+#define ETHCON_RXBUFSZ 0x7f
+#define ETHCON_RXBUFSZ_SHFT 0x4
+
+/* ETHSTAT Reg field */
+#define ETHSTAT_BUSY BIT(7)
+#define ETHSTAT_BUFCNT 0x00ff0000
+
+/* ETHRXFC Register fields */
+#define ETHRXFC_BCEN BIT(0)
+#define ETHRXFC_MCEN BIT(1)
+#define ETHRXFC_UCEN BIT(3)
+#define ETHRXFC_RUNTEN BIT(4)
+#define ETHRXFC_CRCOKEN BIT(5)
+
+/* EMAC1CFG1 register offset */
+#define PIC32_EMAC1CFG1 0x0200
+
+/* EMAC1CFG1 register fields */
+#define EMAC_RXENABLE BIT(0)
+#define EMAC_RXPAUSE BIT(2)
+#define EMAC_TXPAUSE BIT(3)
+#define EMAC_SOFTRESET BIT(15)
+
+/* EMAC1CFG2 register fields */
+#define EMAC_FULLDUP BIT(0)
+#define EMAC_LENGTHCK BIT(1)
+#define EMAC_CRCENABLE BIT(4)
+#define EMAC_PADENABLE BIT(5)
+#define EMAC_AUTOPAD BIT(7)
+#define EMAC_EXCESS BIT(14)
+
+/* EMAC1IPGT register magic */
+#define FULLDUP_GAP_TIME 0x15
+#define HALFDUP_GAP_TIME 0x12
+
+/* EMAC1SUPP register fields */
+#define EMAC_RMII_SPD100 BIT(8)
+#define EMAC_RMII_RESET BIT(11)
+
+/* MII Management Configuration Register */
+#define MIIMCFG_RSTMGMT BIT(15)
+#define MIIMCFG_CLKSEL_DIV40 0x0020 /* 100Mhz / 40 */
+
+/* MII Management Command Register */
+#define MIIMCMD_READ BIT(0)
+#define MIIMCMD_SCAN BIT(1)
+
+/* MII Management Address Register */
+#define MIIMADD_REGADDR 0x1f
+#define MIIMADD_REGADDR_SHIFT 0
+#define MIIMADD_PHYADDR_SHIFT 8
+
+/* MII Management Indicator Register */
+#define MIIMIND_BUSY BIT(0)
+#define MIIMIND_NOTVALID BIT(2)
+#define MIIMIND_LINKFAIL BIT(3)
+
+/* Packet Descriptor */
+/* Received Packet Status */
+#define _RSV1_PKT_CSUM 0xffff
+#define _RSV2_CRC_ERR BIT(20)
+#define _RSV2_LEN_ERR BIT(21)
+#define _RSV2_RX_OK BIT(23)
+#define _RSV2_RX_COUNT 0xffff
+
+#define RSV_RX_CSUM(__rsv1) ((__rsv1) & _RSV1_PKT_CSUM)
+#define RSV_RX_COUNT(__rsv2) ((__rsv2) & _RSV2_RX_COUNT)
+#define RSV_RX_OK(__rsv2) ((__rsv2) & _RSV2_RX_OK)
+#define RSV_CRC_ERR(__rsv2) ((__rsv2) & _RSV2_CRC_ERR)
+
+/* Ethernet Hardware Descriptor Header bits */
+#define EDH_EOWN BIT(7)
+#define EDH_NPV BIT(8)
+#define EDH_STICKY BIT(9)
+#define _EDH_BCOUNT 0x07ff0000
+#define EDH_EOP BIT(30)
+#define EDH_SOP BIT(31)
+#define EDH_BCOUNT_SHIFT 16
+#define EDH_BCOUNT(len) ((len) << EDH_BCOUNT_SHIFT)
+
+/* Ethernet Hardware Descriptors
+ * ref: PIC32 Family Reference Manual Table 35-7
+ * This structure represents the layout of the DMA
+ * memory shared between the CPU and the Ethernet
+ * controller.
+ */
+/* TX/RX DMA descriptor */
+struct eth_dma_desc {
+ u32 hdr; /* header */
+ u32 data_buff; /* data buffer address */
+ u32 stat1; /* transmit/receive packet status */
+ u32 stat2; /* transmit/receive packet status */
+ u32 next_ed; /* next descriptor */
+};
+
+#define PIC32_MDIO_NAME "PIC32_EMAC"
+
+int pic32_mdio_init(const char *name, ulong ioaddr);
+
+#endif /* __MICROCHIP_PIC32_ETH_H_*/
diff --git a/drivers/net/pic32_mdio.c b/drivers/net/pic32_mdio.c
new file mode 100644
index 00000000000..578fc969051
--- /dev/null
+++ b/drivers/net/pic32_mdio.c
@@ -0,0 +1,121 @@
+/*
+ * pic32_mdio.c: PIC32 MDIO/MII driver, part of pic32_eth.c.
+ *
+ * Copyright 2015 Microchip Inc.
+ * Purna Chandra Mandal <purna.mandal@microchip.com>
+ *
+ * SPDX-License-Identifier: GPL-2.0+
+ */
+#include <common.h>
+#include <phy.h>
+#include <miiphy.h>
+#include <errno.h>
+#include <wait_bit.h>
+#include <asm/io.h>
+#include "pic32_eth.h"
+
+static int pic32_mdio_write(struct mii_dev *bus,
+ int addr, int dev_addr,
+ int reg, u16 value)
+{
+ u32 v;
+ struct pic32_mii_regs *mii_regs = bus->priv;
+
+ /* Wait for the previous operation to finish */
+ wait_for_bit(__func__, &mii_regs->mind.raw, MIIMIND_BUSY,
+ false, CONFIG_SYS_HZ, true);
+
+ /* Put phyaddr and regaddr into MIIMADD */
+ v = (addr << MIIMADD_PHYADDR_SHIFT) | (reg & MIIMADD_REGADDR);
+ writel(v, &mii_regs->madr.raw);
+
+ /* Initiate a write command */
+ writel(value, &mii_regs->mwtd.raw);
+
+ /* Wait 30 clock cycles for busy flag to be set */
+ udelay(12);
+
+ /* Wait for write to complete */
+ wait_for_bit(__func__, &mii_regs->mind.raw, MIIMIND_BUSY,
+ false, CONFIG_SYS_HZ, true);
+
+ return 0;
+}
+
+static int pic32_mdio_read(struct mii_dev *bus, int addr, int devaddr, int reg)
+{
+ u32 v;
+ struct pic32_mii_regs *mii_regs = bus->priv;
+
+ /* Wait for the previous operation to finish */
+ wait_for_bit(__func__, &mii_regs->mind.raw, MIIMIND_BUSY,
+ false, CONFIG_SYS_HZ, true);
+
+ /* Put phyaddr and regaddr into MIIMADD */
+ v = (addr << MIIMADD_PHYADDR_SHIFT) | (reg & MIIMADD_REGADDR);
+ writel(v, &mii_regs->madr.raw);
+
+ /* Initiate a read command */
+ writel(MIIMCMD_READ, &mii_regs->mcmd.raw);
+
+ /* Wait 30 clock cycles for busy flag to be set */
+ udelay(12);
+
+ /* Wait for read to complete */
+ wait_for_bit(__func__, &mii_regs->mind.raw,
+ MIIMIND_NOTVALID | MIIMIND_BUSY,
+ false, CONFIG_SYS_HZ, false);
+
+ /* Clear the command register */
+ writel(0, &mii_regs->mcmd.raw);
+
+ /* Grab the value read from the PHY */
+ v = readl(&mii_regs->mrdd.raw);
+ return v;
+}
+
+static int pic32_mdio_reset(struct mii_dev *bus)
+{
+ struct pic32_mii_regs *mii_regs = bus->priv;
+
+ /* Reset MII (due to new addresses) */
+ writel(MIIMCFG_RSTMGMT, &mii_regs->mcfg.raw);
+
+ /* Wait for the operation to finish */
+ wait_for_bit(__func__, &mii_regs->mind.raw, MIIMIND_BUSY,
+ false, CONFIG_SYS_HZ, true);
+
+ /* Clear reset bit */
+ writel(0, &mii_regs->mcfg);
+
+ /* Wait for the operation to finish */
+ wait_for_bit(__func__, &mii_regs->mind.raw, MIIMIND_BUSY,
+ false, CONFIG_SYS_HZ, true);
+
+ /* Set the MII Management Clock (MDC) - no faster than 2.5 MHz */
+ writel(MIIMCFG_CLKSEL_DIV40, &mii_regs->mcfg.raw);
+
+ /* Wait for the operation to finish */
+ wait_for_bit(__func__, &mii_regs->mind.raw, MIIMIND_BUSY,
+ false, CONFIG_SYS_HZ, true);
+ return 0;
+}
+
+int pic32_mdio_init(const char *name, ulong ioaddr)
+{
+ struct mii_dev *bus;
+
+ bus = mdio_alloc();
+ if (!bus) {
+ printf("Failed to allocate PIC32-MDIO bus\n");
+ return -ENOMEM;
+ }
+
+ bus->read = pic32_mdio_read;
+ bus->write = pic32_mdio_write;
+ bus->reset = pic32_mdio_reset;
+ strncpy(bus->name, name, sizeof(bus->name));
+ bus->priv = (void *)ioaddr;
+
+ return mdio_register(bus);
+}
diff --git a/drivers/net/tsec.c b/drivers/net/tsec.c
index 9b09caf8c83..be0f38288f3 100644
--- a/drivers/net/tsec.c
+++ b/drivers/net/tsec.c
@@ -1,18 +1,16 @@
/*
* Freescale Three Speed Ethernet Controller driver
*
- * This software may be used and distributed according to the
- * terms of the GNU Public License, Version 2, incorporated
- * herein by reference.
- *
* Copyright 2004-2011, 2013 Freescale Semiconductor, Inc.
* (C) Copyright 2003, Motorola, Inc.
* author Andy Fleming
*
+ * SPDX-License-Identifier: GPL-2.0+
*/
#include <config.h>
#include <common.h>
+#include <dm.h>
#include <malloc.h>
#include <net.h>
#include <command.h>
@@ -24,21 +22,7 @@
DECLARE_GLOBAL_DATA_PTR;
-#define TX_BUF_CNT 2
-
-static uint rx_idx; /* index of the current RX buffer */
-static uint tx_idx; /* index of the current TX buffer */
-
-#ifdef __GNUC__
-static struct txbd8 __iomem txbd[TX_BUF_CNT] __aligned(8);
-static struct rxbd8 __iomem rxbd[PKTBUFSRX] __aligned(8);
-
-#else
-#error "rtx must be 64-bit aligned"
-#endif
-
-static int tsec_send(struct eth_device *dev, void *packet, int length);
-
+#ifndef CONFIG_DM_ETH
/* Default initializations for TSEC controllers. */
static struct tsec_info_struct tsec_info[] = {
@@ -64,6 +48,7 @@ static struct tsec_info_struct tsec_info[] = {
STD_TSEC_INFO(4), /* TSEC4 */
#endif
};
+#endif /* CONFIG_DM_ETH */
#define TBIANA_SETTINGS ( \
TBIANA_ASYMMETRIC_PAUSE \
@@ -84,8 +69,10 @@ static struct tsec_info_struct tsec_info[] = {
/* Configure the TBI for SGMII operation */
static void tsec_configure_serdes(struct tsec_private *priv)
{
- /* Access TBI PHY registers at given TSEC register offset as opposed
- * to the register offset used for external PHY accesses */
+ /*
+ * Access TBI PHY registers at given TSEC register offset as opposed
+ * to the register offset used for external PHY accesses
+ */
tsec_local_mdio_write(priv->phyregs_sgmii, in_be32(&priv->regs->tbipa),
0, TBI_ANA, TBIANA_SETTINGS);
tsec_local_mdio_write(priv->phyregs_sgmii, in_be32(&priv->regs->tbipa),
@@ -100,7 +87,8 @@ static void tsec_configure_serdes(struct tsec_private *priv)
/* Set the appropriate hash bit for the given addr */
-/* The algorithm works like so:
+/*
+ * The algorithm works like so:
* 1) Take the Destination Address (ie the multicast address), and
* do a CRC on it (little endian), and reverse the bits of the
* result.
@@ -111,9 +99,13 @@ static void tsec_configure_serdes(struct tsec_private *priv)
* hash index which gaddr register to use, and the 5 other bits
* indicate which bit (assuming an IBM numbering scheme, which
* for PowerPC (tm) is usually the case) in the register holds
- * the entry. */
-static int
-tsec_mcast_addr(struct eth_device *dev, const u8 *mcast_mac, u8 set)
+ * the entry.
+ */
+#ifndef CONFIG_DM_ETH
+static int tsec_mcast_addr(struct eth_device *dev, const u8 *mcast_mac, u8 set)
+#else
+static int tsec_mcast_addr(struct udevice *dev, const u8 *mcast_mac, int set)
+#endif
{
struct tsec_private *priv = (struct tsec_private *)dev->priv;
struct tsec __iomem *regs = priv->regs;
@@ -135,7 +127,8 @@ tsec_mcast_addr(struct eth_device *dev, const u8 *mcast_mac, u8 set)
}
#endif /* Multicast TFTP ? */
-/* Initialized required registers to appropriate values, zeroing
+/*
+ * Initialized required registers to appropriate values, zeroing
* those we don't care about (unless zero is bad, in which case,
* choose a more appropriate value)
*/
@@ -181,7 +174,8 @@ static void init_registers(struct tsec __iomem *regs)
}
-/* Configure maccfg2 based on negotiated speed and duplex
+/*
+ * Configure maccfg2 based on negotiated speed and duplex
* reported by PHY handling code
*/
static void adjust_link(struct tsec_private *priv, struct phy_device *phydev)
@@ -212,7 +206,8 @@ static void adjust_link(struct tsec_private *priv, struct phy_device *phydev)
case 10:
maccfg2 |= MACCFG2_MII;
- /* Set R100 bit in all modes although
+ /*
+ * Set R100 bit in all modes although
* it is only used in RGMII mode
*/
if (phydev->speed == 100)
@@ -231,15 +226,174 @@ static void adjust_link(struct tsec_private *priv, struct phy_device *phydev)
(phydev->port == PORT_FIBRE) ? ", fiber mode" : "");
}
+/*
+ * This returns the status bits of the device. The return value
+ * is never checked, and this is what the 8260 driver did, so we
+ * do the same. Presumably, this would be zero if there were no
+ * errors
+ */
+#ifndef CONFIG_DM_ETH
+static int tsec_send(struct eth_device *dev, void *packet, int length)
+#else
+static int tsec_send(struct udevice *dev, void *packet, int length)
+#endif
+{
+ struct tsec_private *priv = (struct tsec_private *)dev->priv;
+ struct tsec __iomem *regs = priv->regs;
+ uint16_t status;
+ int result = 0;
+ int i;
+
+ /* Find an empty buffer descriptor */
+ for (i = 0;
+ in_be16(&priv->txbd[priv->tx_idx].status) & TXBD_READY;
+ i++) {
+ if (i >= TOUT_LOOP) {
+ debug("%s: tsec: tx buffers full\n", dev->name);
+ return result;
+ }
+ }
+
+ out_be32(&priv->txbd[priv->tx_idx].bufptr, (u32)packet);
+ out_be16(&priv->txbd[priv->tx_idx].length, length);
+ status = in_be16(&priv->txbd[priv->tx_idx].status);
+ out_be16(&priv->txbd[priv->tx_idx].status, status |
+ (TXBD_READY | TXBD_LAST | TXBD_CRC | TXBD_INTERRUPT));
+
+ /* Tell the DMA to go */
+ out_be32(&regs->tstat, TSTAT_CLEAR_THALT);
+
+ /* Wait for buffer to be transmitted */
+ for (i = 0;
+ in_be16(&priv->txbd[priv->tx_idx].status) & TXBD_READY;
+ i++) {
+ if (i >= TOUT_LOOP) {
+ debug("%s: tsec: tx error\n", dev->name);
+ return result;
+ }
+ }
+
+ priv->tx_idx = (priv->tx_idx + 1) % TX_BUF_CNT;
+ result = in_be16(&priv->txbd[priv->tx_idx].status) & TXBD_STATS;
+
+ return result;
+}
+
+#ifndef CONFIG_DM_ETH
+static int tsec_recv(struct eth_device *dev)
+{
+ struct tsec_private *priv = (struct tsec_private *)dev->priv;
+ struct tsec __iomem *regs = priv->regs;
+
+ while (!(in_be16(&priv->rxbd[priv->rx_idx].status) & RXBD_EMPTY)) {
+ int length = in_be16(&priv->rxbd[priv->rx_idx].length);
+ uint16_t status = in_be16(&priv->rxbd[priv->rx_idx].status);
+ uchar *packet = net_rx_packets[priv->rx_idx];
+
+ /* Send the packet up if there were no errors */
+ if (!(status & RXBD_STATS))
+ net_process_received_packet(packet, length - 4);
+ else
+ printf("Got error %x\n", (status & RXBD_STATS));
+
+ out_be16(&priv->rxbd[priv->rx_idx].length, 0);
+
+ status = RXBD_EMPTY;
+ /* Set the wrap bit if this is the last element in the list */
+ if ((priv->rx_idx + 1) == PKTBUFSRX)
+ status |= RXBD_WRAP;
+ out_be16(&priv->rxbd[priv->rx_idx].status, status);
+
+ priv->rx_idx = (priv->rx_idx + 1) % PKTBUFSRX;
+ }
+
+ if (in_be32(&regs->ievent) & IEVENT_BSY) {
+ out_be32(&regs->ievent, IEVENT_BSY);
+ out_be32(&regs->rstat, RSTAT_CLEAR_RHALT);
+ }
+
+ return -1;
+}
+#else
+static int tsec_recv(struct udevice *dev, int flags, uchar **packetp)
+{
+ struct tsec_private *priv = (struct tsec_private *)dev->priv;
+ struct tsec __iomem *regs = priv->regs;
+ int ret = -1;
+
+ if (!(in_be16(&priv->rxbd[priv->rx_idx].status) & RXBD_EMPTY)) {
+ int length = in_be16(&priv->rxbd[priv->rx_idx].length);
+ uint16_t status = in_be16(&priv->rxbd[priv->rx_idx].status);
+ uint32_t buf;
+
+ /* Send the packet up if there were no errors */
+ if (!(status & RXBD_STATS)) {
+ buf = in_be32(&priv->rxbd[priv->rx_idx].bufptr);
+ *packetp = (uchar *)buf;
+ ret = length - 4;
+ } else {
+ printf("Got error %x\n", (status & RXBD_STATS));
+ }
+ }
+
+ if (in_be32(&regs->ievent) & IEVENT_BSY) {
+ out_be32(&regs->ievent, IEVENT_BSY);
+ out_be32(&regs->rstat, RSTAT_CLEAR_RHALT);
+ }
+
+ return ret;
+}
+
+static int tsec_free_pkt(struct udevice *dev, uchar *packet, int length)
+{
+ struct tsec_private *priv = (struct tsec_private *)dev->priv;
+ uint16_t status;
+
+ out_be16(&priv->rxbd[priv->rx_idx].length, 0);
+
+ status = RXBD_EMPTY;
+ /* Set the wrap bit if this is the last element in the list */
+ if ((priv->rx_idx + 1) == PKTBUFSRX)
+ status |= RXBD_WRAP;
+ out_be16(&priv->rxbd[priv->rx_idx].status, status);
+
+ priv->rx_idx = (priv->rx_idx + 1) % PKTBUFSRX;
+
+ return 0;
+}
+#endif
+
+/* Stop the interface */
+#ifndef CONFIG_DM_ETH
+static void tsec_halt(struct eth_device *dev)
+#else
+static void tsec_halt(struct udevice *dev)
+#endif
+{
+ struct tsec_private *priv = (struct tsec_private *)dev->priv;
+ struct tsec __iomem *regs = priv->regs;
+
+ clrbits_be32(&regs->dmactrl, DMACTRL_GRS | DMACTRL_GTS);
+ setbits_be32(&regs->dmactrl, DMACTRL_GRS | DMACTRL_GTS);
+
+ while ((in_be32(&regs->ievent) & (IEVENT_GRSC | IEVENT_GTSC))
+ != (IEVENT_GRSC | IEVENT_GTSC))
+ ;
+
+ clrbits_be32(&regs->maccfg1, MACCFG1_TX_EN | MACCFG1_RX_EN);
+
+ /* Shut down the PHY, as needed */
+ phy_shutdown(priv->phydev);
+}
+
#ifdef CONFIG_SYS_FSL_ERRATUM_NMG_ETSEC129
/*
* When MACCFG1[Rx_EN] is enabled during system boot as part
* of the eTSEC port initialization sequence,
* the eTSEC Rx logic may not be properly initialized.
*/
-void redundant_init(struct eth_device *dev)
+void redundant_init(struct tsec_private *priv)
{
- struct tsec_private *priv = dev->priv;
struct tsec __iomem *regs = priv->regs;
uint t, count = 0;
int fail = 1;
@@ -274,25 +428,27 @@ void redundant_init(struct eth_device *dev)
do {
uint16_t status;
- tsec_send(dev, (void *)pkt, sizeof(pkt));
+ tsec_send(priv->dev, (void *)pkt, sizeof(pkt));
/* Wait for buffer to be received */
- for (t = 0; in_be16(&rxbd[rx_idx].status) & RXBD_EMPTY; t++) {
+ for (t = 0;
+ in_be16(&priv->rxbd[priv->rx_idx].status) & RXBD_EMPTY;
+ t++) {
if (t >= 10 * TOUT_LOOP) {
- printf("%s: tsec: rx error\n", dev->name);
+ printf("%s: tsec: rx error\n", priv->dev->name);
break;
}
}
- if (!memcmp(pkt, (void *)net_rx_packets[rx_idx], sizeof(pkt)))
+ if (!memcmp(pkt, net_rx_packets[priv->rx_idx], sizeof(pkt)))
fail = 0;
- out_be16(&rxbd[rx_idx].length, 0);
+ out_be16(&priv->rxbd[priv->rx_idx].length, 0);
status = RXBD_EMPTY;
- if ((rx_idx + 1) == PKTBUFSRX)
+ if ((priv->rx_idx + 1) == PKTBUFSRX)
status |= RXBD_WRAP;
- out_be16(&rxbd[rx_idx].status, status);
- rx_idx = (rx_idx + 1) % PKTBUFSRX;
+ out_be16(&priv->rxbd[priv->rx_idx].status, status);
+ priv->rx_idx = (priv->rx_idx + 1) % PKTBUFSRX;
if (in_be32(&regs->ievent) & IEVENT_BSY) {
out_be32(&regs->ievent, IEVENT_BSY);
@@ -315,49 +471,49 @@ void redundant_init(struct eth_device *dev)
}
#endif
-/* Set up the buffers and their descriptors, and bring up the
+/*
+ * Set up the buffers and their descriptors, and bring up the
* interface
*/
-static void startup_tsec(struct eth_device *dev)
+static void startup_tsec(struct tsec_private *priv)
{
- struct tsec_private *priv = (struct tsec_private *)dev->priv;
struct tsec __iomem *regs = priv->regs;
uint16_t status;
int i;
/* reset the indices to zero */
- rx_idx = 0;
- tx_idx = 0;
+ priv->rx_idx = 0;
+ priv->tx_idx = 0;
#ifdef CONFIG_SYS_FSL_ERRATUM_NMG_ETSEC129
uint svr;
#endif
/* Point to the buffer descriptors */
- out_be32(&regs->tbase, (u32)&txbd[0]);
- out_be32(&regs->rbase, (u32)&rxbd[0]);
+ out_be32(&regs->tbase, (u32)&priv->txbd[0]);
+ out_be32(&regs->rbase, (u32)&priv->rxbd[0]);
/* Initialize the Rx Buffer descriptors */
for (i = 0; i < PKTBUFSRX; i++) {
- out_be16(&rxbd[i].status, RXBD_EMPTY);
- out_be16(&rxbd[i].length, 0);
- out_be32(&rxbd[i].bufptr, (u32)net_rx_packets[i]);
+ out_be16(&priv->rxbd[i].status, RXBD_EMPTY);
+ out_be16(&priv->rxbd[i].length, 0);
+ out_be32(&priv->rxbd[i].bufptr, (u32)net_rx_packets[i]);
}
- status = in_be16(&rxbd[PKTBUFSRX - 1].status);
- out_be16(&rxbd[PKTBUFSRX - 1].status, status | RXBD_WRAP);
+ status = in_be16(&priv->rxbd[PKTBUFSRX - 1].status);
+ out_be16(&priv->rxbd[PKTBUFSRX - 1].status, status | RXBD_WRAP);
/* Initialize the TX Buffer Descriptors */
for (i = 0; i < TX_BUF_CNT; i++) {
- out_be16(&txbd[i].status, 0);
- out_be16(&txbd[i].length, 0);
- out_be32(&txbd[i].bufptr, 0);
+ out_be16(&priv->txbd[i].status, 0);
+ out_be16(&priv->txbd[i].length, 0);
+ out_be32(&priv->txbd[i].bufptr, 0);
}
- status = in_be16(&txbd[TX_BUF_CNT - 1].status);
- out_be16(&txbd[TX_BUF_CNT - 1].status, status | TXBD_WRAP);
+ status = in_be16(&priv->txbd[TX_BUF_CNT - 1].status);
+ out_be16(&priv->txbd[TX_BUF_CNT - 1].status, status | TXBD_WRAP);
#ifdef CONFIG_SYS_FSL_ERRATUM_NMG_ETSEC129
svr = get_svr();
if ((SVR_MAJ(svr) == 1) || IS_SVR_REV(svr, 2, 0))
- redundant_init(dev);
+ redundant_init(priv);
#endif
/* Enable Transmit and Receive */
setbits_be32(&regs->maccfg1, MACCFG1_RX_EN | MACCFG1_TX_EN);
@@ -369,113 +525,22 @@ static void startup_tsec(struct eth_device *dev)
clrbits_be32(&regs->dmactrl, DMACTRL_GRS | DMACTRL_GTS);
}
-/* This returns the status bits of the device. The return value
- * is never checked, and this is what the 8260 driver did, so we
- * do the same. Presumably, this would be zero if there were no
- * errors
- */
-static int tsec_send(struct eth_device *dev, void *packet, int length)
-{
- struct tsec_private *priv = (struct tsec_private *)dev->priv;
- struct tsec __iomem *regs = priv->regs;
- uint16_t status;
- int result = 0;
- int i;
-
- /* Find an empty buffer descriptor */
- for (i = 0; in_be16(&txbd[tx_idx].status) & TXBD_READY; i++) {
- if (i >= TOUT_LOOP) {
- debug("%s: tsec: tx buffers full\n", dev->name);
- return result;
- }
- }
-
- out_be32(&txbd[tx_idx].bufptr, (u32)packet);
- out_be16(&txbd[tx_idx].length, length);
- status = in_be16(&txbd[tx_idx].status);
- out_be16(&txbd[tx_idx].status, status |
- (TXBD_READY | TXBD_LAST | TXBD_CRC | TXBD_INTERRUPT));
-
- /* Tell the DMA to go */
- out_be32(&regs->tstat, TSTAT_CLEAR_THALT);
-
- /* Wait for buffer to be transmitted */
- for (i = 0; in_be16(&txbd[tx_idx].status) & TXBD_READY; i++) {
- if (i >= TOUT_LOOP) {
- debug("%s: tsec: tx error\n", dev->name);
- return result;
- }
- }
-
- tx_idx = (tx_idx + 1) % TX_BUF_CNT;
- result = in_be16(&txbd[tx_idx].status) & TXBD_STATS;
-
- return result;
-}
-
-static int tsec_recv(struct eth_device *dev)
-{
- struct tsec_private *priv = (struct tsec_private *)dev->priv;
- struct tsec __iomem *regs = priv->regs;
-
- while (!(in_be16(&rxbd[rx_idx].status) & RXBD_EMPTY)) {
- int length = in_be16(&rxbd[rx_idx].length);
- uint16_t status = in_be16(&rxbd[rx_idx].status);
-
- /* Send the packet up if there were no errors */
- if (!(status & RXBD_STATS))
- net_process_received_packet(net_rx_packets[rx_idx],
- length - 4);
- else
- printf("Got error %x\n", (status & RXBD_STATS));
-
- out_be16(&rxbd[rx_idx].length, 0);
-
- status = RXBD_EMPTY;
- /* Set the wrap bit if this is the last element in the list */
- if ((rx_idx + 1) == PKTBUFSRX)
- status |= RXBD_WRAP;
- out_be16(&rxbd[rx_idx].status, status);
-
- rx_idx = (rx_idx + 1) % PKTBUFSRX;
- }
-
- if (in_be32(&regs->ievent) & IEVENT_BSY) {
- out_be32(&regs->ievent, IEVENT_BSY);
- out_be32(&regs->rstat, RSTAT_CLEAR_RHALT);
- }
-
- return -1;
-
-}
-
-/* Stop the interface */
-static void tsec_halt(struct eth_device *dev)
-{
- struct tsec_private *priv = (struct tsec_private *)dev->priv;
- struct tsec __iomem *regs = priv->regs;
-
- clrbits_be32(&regs->dmactrl, DMACTRL_GRS | DMACTRL_GTS);
- setbits_be32(&regs->dmactrl, DMACTRL_GRS | DMACTRL_GTS);
-
- while ((in_be32(&regs->ievent) & (IEVENT_GRSC | IEVENT_GTSC))
- != (IEVENT_GRSC | IEVENT_GTSC))
- ;
-
- clrbits_be32(&regs->maccfg1, MACCFG1_TX_EN | MACCFG1_RX_EN);
-
- /* Shut down the PHY, as needed */
- phy_shutdown(priv->phydev);
-}
-
-/* Initializes data structures and registers for the controller,
- * and brings the interface up. Returns the link status, meaning
+/*
+ * Initializes data structures and registers for the controller,
+ * and brings the interface up. Returns the link status, meaning
* that it returns success if the link is up, failure otherwise.
- * This allows u-boot to find the first active controller.
+ * This allows U-Boot to find the first active controller.
*/
+#ifndef CONFIG_DM_ETH
static int tsec_init(struct eth_device *dev, bd_t * bd)
+#else
+static int tsec_init(struct udevice *dev)
+#endif
{
struct tsec_private *priv = (struct tsec_private *)dev->priv;
+#ifdef CONFIG_DM_ETH
+ struct eth_pdata *pdata = dev_get_platdata(dev);
+#endif
struct tsec __iomem *regs = priv->regs;
u32 tempval;
int ret;
@@ -489,17 +554,27 @@ static int tsec_init(struct eth_device *dev, bd_t * bd)
/* Init ECNTRL */
out_be32(&regs->ecntrl, ECNTRL_INIT_SETTINGS);
- /* Copy the station address into the address registers.
+ /*
+ * Copy the station address into the address registers.
* For a station address of 0x12345678ABCD in transmission
* order (BE), MACnADDR1 is set to 0xCDAB7856 and
* MACnADDR2 is set to 0x34120000.
*/
+#ifndef CONFIG_DM_ETH
tempval = (dev->enetaddr[5] << 24) | (dev->enetaddr[4] << 16) |
(dev->enetaddr[3] << 8) | dev->enetaddr[2];
+#else
+ tempval = (pdata->enetaddr[5] << 24) | (pdata->enetaddr[4] << 16) |
+ (pdata->enetaddr[3] << 8) | pdata->enetaddr[2];
+#endif
out_be32(&regs->macstnaddr1, tempval);
+#ifndef CONFIG_DM_ETH
tempval = (dev->enetaddr[1] << 24) | (dev->enetaddr[0] << 16);
+#else
+ tempval = (pdata->enetaddr[1] << 24) | (pdata->enetaddr[0] << 16);
+#endif
out_be32(&regs->macstnaddr2, tempval);
@@ -507,7 +582,7 @@ static int tsec_init(struct eth_device *dev, bd_t * bd)
init_registers(regs);
/* Ready the device for tx/rx */
- startup_tsec(dev);
+ startup_tsec(priv);
/* Start up the PHY */
ret = phy_startup(priv->phydev);
@@ -551,8 +626,8 @@ static phy_interface_t tsec_get_interface(struct tsec_private *priv)
* be set by the platform code.
*/
if ((interface == PHY_INTERFACE_MODE_RGMII_ID) ||
- (interface == PHY_INTERFACE_MODE_RGMII_TXID) ||
- (interface == PHY_INTERFACE_MODE_RGMII_RXID))
+ (interface == PHY_INTERFACE_MODE_RGMII_TXID) ||
+ (interface == PHY_INTERFACE_MODE_RGMII_RXID))
return interface;
return PHY_INTERFACE_MODE_RGMII;
@@ -565,14 +640,13 @@ static phy_interface_t tsec_get_interface(struct tsec_private *priv)
return PHY_INTERFACE_MODE_MII;
}
-
-/* Discover which PHY is attached to the device, and configure it
+/*
+ * Discover which PHY is attached to the device, and configure it
* properly. If the PHY is not recognized, then return 0
* (failure). Otherwise, return 1
*/
-static int init_phy(struct eth_device *dev)
+static int init_phy(struct tsec_private *priv)
{
- struct tsec_private *priv = (struct tsec_private *)dev->priv;
struct phy_device *phydev;
struct tsec __iomem *regs = priv->regs;
u32 supported = (SUPPORTED_10baseT_Half |
@@ -584,14 +658,15 @@ static int init_phy(struct eth_device *dev)
supported |= SUPPORTED_1000baseT_Full;
/* Assign a Physical address to the TBI */
- out_be32(&regs->tbipa, CONFIG_SYS_TBIPA_VALUE);
+ out_be32(&regs->tbipa, priv->tbiaddr);
priv->interface = tsec_get_interface(priv);
if (priv->interface == PHY_INTERFACE_MODE_SGMII)
tsec_configure_serdes(priv);
- phydev = phy_connect(priv->bus, priv->phyaddr, dev, priv->interface);
+ phydev = phy_connect(priv->bus, priv->phyaddr, priv->dev,
+ priv->interface);
if (!phydev)
return 0;
@@ -605,7 +680,9 @@ static int init_phy(struct eth_device *dev)
return 1;
}
-/* Initialize device structure. Returns success if PHY
+#ifndef CONFIG_DM_ETH
+/*
+ * Initialize device structure. Returns success if PHY
* initialization succeeded (i.e. if it recognizes the PHY)
*/
static int tsec_initialize(bd_t *bis, struct tsec_info_struct *tsec_info)
@@ -630,11 +707,13 @@ static int tsec_initialize(bd_t *bis, struct tsec_info_struct *tsec_info)
priv->phyregs_sgmii = tsec_info->miiregs_sgmii;
priv->phyaddr = tsec_info->phyaddr;
+ priv->tbiaddr = CONFIG_SYS_TBIPA_VALUE;
priv->flags = tsec_info->flags;
strcpy(dev->name, tsec_info->devname);
priv->interface = tsec_info->interface;
priv->bus = miiphy_get_dev_by_name(tsec_info->mii_devname);
+ priv->dev = dev;
dev->iobase = 0;
dev->priv = priv;
dev->init = tsec_init;
@@ -645,7 +724,7 @@ static int tsec_initialize(bd_t *bis, struct tsec_info_struct *tsec_info)
dev->mcast = tsec_mcast_addr;
#endif
- /* Tell u-boot to get the addr from the env */
+ /* Tell U-Boot to get the addr from the env */
for (i = 0; i < 6; i++)
dev->enetaddr[i] = 0;
@@ -657,7 +736,7 @@ static int tsec_initialize(bd_t *bis, struct tsec_info_struct *tsec_info)
clrbits_be32(&priv->regs->maccfg1, MACCFG1_SOFT_RESET);
/* Try to initialize PHY here, and return */
- return init_phy(dev);
+ return init_phy(priv);
}
/*
@@ -690,3 +769,118 @@ int tsec_standard_init(bd_t *bis)
return tsec_eth_init(bis, tsec_info, ARRAY_SIZE(tsec_info));
}
+#else /* CONFIG_DM_ETH */
+int tsec_probe(struct udevice *dev)
+{
+ struct tsec_private *priv = dev_get_priv(dev);
+ struct eth_pdata *pdata = dev_get_platdata(dev);
+ struct fsl_pq_mdio_info mdio_info;
+ int offset = 0;
+ int reg;
+ const char *phy_mode;
+ int ret;
+
+ pdata->iobase = (phys_addr_t)dev_get_addr(dev);
+ priv->regs = (struct tsec *)pdata->iobase;
+
+ offset = fdtdec_lookup_phandle(gd->fdt_blob, dev->of_offset,
+ "phy-handle");
+ if (offset > 0) {
+ reg = fdtdec_get_int(gd->fdt_blob, offset, "reg", 0);
+ priv->phyaddr = reg;
+ } else {
+ debug("phy-handle does not exist under tsec %s\n", dev->name);
+ return -ENOENT;
+ }
+
+ offset = fdt_parent_offset(gd->fdt_blob, offset);
+ if (offset > 0) {
+ reg = fdtdec_get_int(gd->fdt_blob, offset, "reg", 0);
+ priv->phyregs_sgmii = (struct tsec_mii_mng *)(reg + 0x520);
+ } else {
+ debug("No parent node for PHY?\n");
+ return -ENOENT;
+ }
+
+ offset = fdtdec_lookup_phandle(gd->fdt_blob, dev->of_offset,
+ "tbi-handle");
+ if (offset > 0) {
+ reg = fdtdec_get_int(gd->fdt_blob, offset, "reg",
+ CONFIG_SYS_TBIPA_VALUE);
+ priv->tbiaddr = reg;
+ } else {
+ priv->tbiaddr = CONFIG_SYS_TBIPA_VALUE;
+ }
+
+ phy_mode = fdt_getprop(gd->fdt_blob, dev->of_offset,
+ "phy-connection-type", NULL);
+ if (phy_mode)
+ pdata->phy_interface = phy_get_interface_by_name(phy_mode);
+ if (pdata->phy_interface == -1) {
+ debug("Invalid PHY interface '%s'\n", phy_mode);
+ return -EINVAL;
+ }
+ priv->interface = pdata->phy_interface;
+
+ /* Initialize flags */
+ priv->flags = TSEC_GIGABIT;
+ if (priv->interface == PHY_INTERFACE_MODE_SGMII)
+ priv->flags |= TSEC_SGMII;
+
+ mdio_info.regs = priv->phyregs_sgmii;
+ mdio_info.name = (char *)dev->name;
+ ret = fsl_pq_mdio_init(NULL, &mdio_info);
+ if (ret)
+ return ret;
+
+ /* Reset the MAC */
+ setbits_be32(&priv->regs->maccfg1, MACCFG1_SOFT_RESET);
+ udelay(2); /* Soft Reset must be asserted for 3 TX clocks */
+ clrbits_be32(&priv->regs->maccfg1, MACCFG1_SOFT_RESET);
+
+ priv->dev = dev;
+ priv->bus = miiphy_get_dev_by_name(dev->name);
+
+ /* Try to initialize PHY here, and return */
+ return !init_phy(priv);
+}
+
+int tsec_remove(struct udevice *dev)
+{
+ struct tsec_private *priv = dev->priv;
+
+ free(priv->phydev);
+ mdio_unregister(priv->bus);
+ mdio_free(priv->bus);
+
+ return 0;
+}
+
+static const struct eth_ops tsec_ops = {
+ .start = tsec_init,
+ .send = tsec_send,
+ .recv = tsec_recv,
+ .free_pkt = tsec_free_pkt,
+ .stop = tsec_halt,
+#ifdef CONFIG_MCAST_TFTP
+ .mcast = tsec_mcast_addr,
+#endif
+};
+
+static const struct udevice_id tsec_ids[] = {
+ { .compatible = "fsl,tsec" },
+ { }
+};
+
+U_BOOT_DRIVER(eth_tsec) = {
+ .name = "tsec",
+ .id = UCLASS_ETH,
+ .of_match = tsec_ids,
+ .probe = tsec_probe,
+ .remove = tsec_remove,
+ .ops = &tsec_ops,
+ .priv_auto_alloc_size = sizeof(struct tsec_private),
+ .platdata_auto_alloc_size = sizeof(struct eth_pdata),
+ .flags = DM_FLAG_ALLOC_PRIV_DMA,
+};
+#endif /* CONFIG_DM_ETH */
diff --git a/drivers/net/vsc9953.c b/drivers/net/vsc9953.c
index 7595db1acbd..44afe140515 100644
--- a/drivers/net/vsc9953.c
+++ b/drivers/net/vsc9953.c
@@ -469,6 +469,47 @@ static void vsc9953_vlan_ingr_fltr_learn_drop(int enable)
clrbits_le32(&l2ana_reg->ana.adv_learn, VSC9953_VLAN_CHK);
}
+enum aggr_code_mode {
+ AGGR_CODE_RAND = 0,
+ AGGR_CODE_ALL, /* S/D MAC, IPv4 S/D IP, IPv6 Flow Label, S/D PORT */
+};
+
+/* Set aggregation code generation mode */
+static int vsc9953_aggr_code_set(enum aggr_code_mode ac)
+{
+ int rc;
+ struct vsc9953_analyzer *l2ana_reg;
+
+ l2ana_reg = (struct vsc9953_analyzer *)(VSC9953_OFFSET +
+ VSC9953_ANA_OFFSET);
+
+ switch (ac) {
+ case AGGR_CODE_RAND:
+ clrsetbits_le32(&l2ana_reg->common.aggr_cfg,
+ VSC9953_AC_DMAC_ENA | VSC9953_AC_SMAC_ENA |
+ VSC9953_AC_IP6_LBL_ENA |
+ VSC9953_AC_IP6_TCPUDP_ENA |
+ VSC9953_AC_IP4_SIPDIP_ENA |
+ VSC9953_AC_IP4_TCPUDP_ENA, VSC9953_AC_RND_ENA);
+ rc = 0;
+ break;
+ case AGGR_CODE_ALL:
+ clrsetbits_le32(&l2ana_reg->common.aggr_cfg, VSC9953_AC_RND_ENA,
+ VSC9953_AC_DMAC_ENA | VSC9953_AC_SMAC_ENA |
+ VSC9953_AC_IP6_LBL_ENA |
+ VSC9953_AC_IP6_TCPUDP_ENA |
+ VSC9953_AC_IP4_SIPDIP_ENA |
+ VSC9953_AC_IP4_TCPUDP_ENA);
+ rc = 0;
+ break;
+ default:
+ /* unknown mode for aggregation code */
+ rc = -EINVAL;
+ }
+
+ return rc;
+}
+
/* Egress untag modes of a VSC9953 port */
enum egress_untag_mode {
EGRESS_UNTAG_ALL = 0,
@@ -593,6 +634,25 @@ static void vsc9953_port_all_vlan_egress_untagged_set(
vsc9953_port_vlan_egr_untag_set(i, mode);
}
+static int vsc9953_autoage_time_set(int age_period)
+{
+ u32 autoage;
+ struct vsc9953_analyzer *l2ana_reg;
+
+ l2ana_reg = (struct vsc9953_analyzer *)(VSC9953_OFFSET +
+ VSC9953_ANA_OFFSET);
+
+ if (age_period < 0 || age_period > VSC9953_AUTOAGE_PERIOD_MASK)
+ return -EINVAL;
+
+ autoage = bitfield_replace_by_mask(in_le32(&l2ana_reg->ana.auto_age),
+ VSC9953_AUTOAGE_PERIOD_MASK,
+ age_period);
+ out_le32(&l2ana_reg->ana.auto_age, autoage);
+
+ return 0;
+}
+
#ifdef CONFIG_CMD_ETHSW
/* Enable/disable status of a VSC9953 port */
@@ -1474,6 +1534,224 @@ static int vsc9953_port_ingress_filtering_get(int port_no)
return !!(val & (1 << port_no));
}
+/* Get the aggregation group of a port */
+static int vsc9953_port_aggr_grp_get(int port_no, int *aggr_grp)
+{
+ u32 val;
+ struct vsc9953_analyzer *l2ana_reg;
+
+ if (!VSC9953_PORT_CHECK(port_no))
+ return -EINVAL;
+
+ l2ana_reg = (struct vsc9953_analyzer *)(VSC9953_OFFSET +
+ VSC9953_ANA_OFFSET);
+
+ val = in_le32(&l2ana_reg->port[port_no].port_cfg);
+ *aggr_grp = bitfield_extract_by_mask(val,
+ VSC9953_PORT_CFG_PORTID_MASK);
+
+ return 0;
+}
+
+static void vsc9953_aggr_grp_members_get(int aggr_grp,
+ u8 aggr_membr[VSC9953_MAX_PORTS])
+{
+ int port_no;
+ int aggr_membr_grp;
+
+ for (port_no = 0; port_no < VSC9953_MAX_PORTS; port_no++) {
+ aggr_membr[port_no] = 0;
+
+ if (vsc9953_port_aggr_grp_get(port_no, &aggr_membr_grp))
+ continue;
+
+ if (aggr_grp == aggr_membr_grp)
+ aggr_membr[port_no] = 1;
+ }
+}
+
+static void vsc9953_update_dest_members_masks(int port_no, u32 membr_bitfld_old,
+ u32 membr_bitfld_new)
+{
+ int i;
+ u32 pgid;
+ struct vsc9953_analyzer *l2ana_reg;
+
+ l2ana_reg = (struct vsc9953_analyzer *)(VSC9953_OFFSET +
+ VSC9953_ANA_OFFSET);
+
+ /*
+ * NOTE: Only the unicast destination masks are updated, since
+ * we do not support for now Layer-2 multicast entries
+ */
+ for (i = 0; i < VSC9953_MAX_PORTS; i++) {
+ if (i == port_no) {
+ clrsetbits_le32(&l2ana_reg->port_id_tbl.port_grp_id[i],
+ VSC9953_PGID_PORT_MASK,
+ membr_bitfld_new);
+ continue;
+ }
+
+ pgid = in_le32(&l2ana_reg->port_id_tbl.port_grp_id[i]);
+ if ((u32)(1 << i) & membr_bitfld_old & VSC9953_PGID_PORT_MASK)
+ pgid &= ~((u32)(1 << port_no));
+ if ((u32)(1 << i) & membr_bitfld_new & VSC9953_PGID_PORT_MASK)
+ pgid |= ((u32)(1 << port_no));
+
+ out_le32(&l2ana_reg->port_id_tbl.port_grp_id[i], pgid);
+ }
+}
+
+static void vsc9953_update_source_members_masks(int port_no,
+ u32 membr_bitfld_old,
+ u32 membr_bitfld_new)
+{
+ int i;
+ int index;
+ u32 pgid;
+ struct vsc9953_analyzer *l2ana_reg;
+
+ l2ana_reg = (struct vsc9953_analyzer *)(VSC9953_OFFSET +
+ VSC9953_ANA_OFFSET);
+
+ for (i = 0; i < VSC9953_MAX_PORTS + 1; i++) {
+ index = PGID_SRC_START + i;
+ pgid = in_le32(&l2ana_reg->port_id_tbl.port_grp_id[index]);
+ if (i == port_no) {
+ pgid = (pgid | VSC9953_PGID_PORT_MASK) &
+ ~membr_bitfld_new;
+ out_le32(&l2ana_reg->port_id_tbl.port_grp_id[index],
+ pgid);
+ continue;
+ }
+
+ if ((u32)(1 << i) & membr_bitfld_old & VSC9953_PGID_PORT_MASK)
+ pgid |= (u32)(1 << port_no);
+
+ if ((u32)(1 << i) & membr_bitfld_new & VSC9953_PGID_PORT_MASK)
+ pgid &= ~(u32)(1 << port_no);
+ out_le32(&l2ana_reg->port_id_tbl.port_grp_id[index], pgid);
+ }
+}
+
+static u32 vsc9953_aggr_mask_get_next(u32 aggr_mask, u32 member_bitfield)
+{
+ if (!member_bitfield)
+ return 0;
+
+ if (!(aggr_mask & VSC9953_PGID_PORT_MASK))
+ aggr_mask = 1;
+ else
+ aggr_mask <<= 1;
+
+ while (!(aggr_mask & member_bitfield)) {
+ aggr_mask <<= 1;
+ if (!(aggr_mask & VSC9953_PGID_PORT_MASK))
+ aggr_mask = 1;
+ }
+
+ return aggr_mask;
+}
+
+static void vsc9953_update_aggr_members_masks(int port_no, u32 membr_bitfld_old,
+ u32 membr_bitfld_new)
+{
+ int i;
+ u32 pgid;
+ u32 aggr_mask_old = 0;
+ u32 aggr_mask_new = 0;
+ struct vsc9953_analyzer *l2ana_reg;
+
+ l2ana_reg = (struct vsc9953_analyzer *)(VSC9953_OFFSET +
+ VSC9953_ANA_OFFSET);
+
+ /* Update all the PGID aggregation masks */
+ for (i = PGID_AGGR_START; i < PGID_SRC_START; i++) {
+ pgid = in_le32(&l2ana_reg->port_id_tbl.port_grp_id[i]);
+
+ aggr_mask_old = vsc9953_aggr_mask_get_next(aggr_mask_old,
+ membr_bitfld_old);
+ pgid = (pgid & ~membr_bitfld_old) | aggr_mask_old;
+
+ aggr_mask_new = vsc9953_aggr_mask_get_next(aggr_mask_new,
+ membr_bitfld_new);
+ pgid = (pgid & ~membr_bitfld_new) | aggr_mask_new;
+
+ out_le32(&l2ana_reg->port_id_tbl.port_grp_id[i], pgid);
+ }
+}
+
+static u32 vsc9953_aggr_membr_bitfield_get(u8 member[VSC9953_MAX_PORTS])
+{
+ int i;
+ u32 member_bitfield = 0;
+
+ for (i = 0; i < VSC9953_MAX_PORTS; i++) {
+ if (member[i])
+ member_bitfield |= 1 << i;
+ }
+ member_bitfield &= VSC9953_PGID_PORT_MASK;
+
+ return member_bitfield;
+}
+
+static void vsc9953_update_members_masks(int port_no,
+ u8 member_old[VSC9953_MAX_PORTS],
+ u8 member_new[VSC9953_MAX_PORTS])
+{
+ u32 membr_bitfld_old = vsc9953_aggr_membr_bitfield_get(member_old);
+ u32 membr_bitfld_new = vsc9953_aggr_membr_bitfield_get(member_new);
+
+ vsc9953_update_dest_members_masks(port_no, membr_bitfld_old,
+ membr_bitfld_new);
+ vsc9953_update_source_members_masks(port_no, membr_bitfld_old,
+ membr_bitfld_new);
+ vsc9953_update_aggr_members_masks(port_no, membr_bitfld_old,
+ membr_bitfld_new);
+}
+
+/* Set the aggregation group of a port */
+static int vsc9953_port_aggr_grp_set(int port_no, int aggr_grp)
+{
+ u8 aggr_membr_old[VSC9953_MAX_PORTS];
+ u8 aggr_membr_new[VSC9953_MAX_PORTS];
+ int rc;
+ int aggr_grp_old;
+ u32 val;
+ struct vsc9953_analyzer *l2ana_reg;
+
+ if (!VSC9953_PORT_CHECK(port_no) || !VSC9953_PORT_CHECK(aggr_grp))
+ return -EINVAL;
+
+ l2ana_reg = (struct vsc9953_analyzer *)(VSC9953_OFFSET +
+ VSC9953_ANA_OFFSET);
+
+ rc = vsc9953_port_aggr_grp_get(port_no, &aggr_grp_old);
+ if (rc)
+ return rc;
+
+ /* get all the members of the old aggregation group */
+ vsc9953_aggr_grp_members_get(aggr_grp_old, aggr_membr_old);
+
+ /* get all the members of the same aggregation group */
+ vsc9953_aggr_grp_members_get(aggr_grp, aggr_membr_new);
+
+ /* add current port as member to the new aggregation group */
+ aggr_membr_old[port_no] = 0;
+ aggr_membr_new[port_no] = 1;
+
+ /* update masks */
+ vsc9953_update_members_masks(port_no, aggr_membr_old, aggr_membr_new);
+
+ /* Change logical port number */
+ val = in_le32(&l2ana_reg->port[port_no].port_cfg);
+ val = bitfield_replace_by_mask(val,
+ VSC9953_PORT_CFG_PORTID_MASK, aggr_grp);
+ out_le32(&l2ana_reg->port[port_no].port_cfg, val);
+
+ return 0;
+}
+
static int vsc9953_port_status_key_func(struct ethsw_command_def *parsed_cmd)
{
int i;
@@ -2064,6 +2342,72 @@ static int vsc9953_ingr_fltr_set_key_func(struct ethsw_command_def *parsed_cmd)
return CMD_RET_SUCCESS;
}
+static int vsc9953_port_aggr_show_key_func(struct ethsw_command_def *parsed_cmd)
+{
+ int i;
+ int aggr_grp;
+
+ if (parsed_cmd->port != ETHSW_CMD_PORT_ALL) {
+ if (!VSC9953_PORT_CHECK(parsed_cmd->port)) {
+ printf("Invalid port number: %d\n", parsed_cmd->port);
+ return CMD_RET_FAILURE;
+ }
+
+ if (vsc9953_port_aggr_grp_get(parsed_cmd->port, &aggr_grp))
+ return CMD_RET_FAILURE;
+ printf("%7s %10s\n", "Port", "Aggr grp");
+ printf("%7d %10d\n", parsed_cmd->port, aggr_grp);
+ } else {
+ printf("%7s %10s\n", "Port", "Aggr grp");
+ for (i = 0; i < VSC9953_MAX_PORTS; i++) {
+ if (vsc9953_port_aggr_grp_get(i, &aggr_grp))
+ continue;
+ printf("%7d %10d\n", i, aggr_grp);
+ }
+ }
+
+ return CMD_RET_SUCCESS;
+}
+
+static int vsc9953_port_aggr_set_key_func(struct ethsw_command_def *parsed_cmd)
+{
+ int i;
+
+ /* Aggregation group number should be set in parsed_cmd->aggr_grp */
+ if (parsed_cmd->aggr_grp == ETHSW_CMD_AGGR_GRP_NONE) {
+ printf("Please set an aggregation group value\n");
+ return CMD_RET_FAILURE;
+ }
+
+ if (!VSC9953_PORT_CHECK(parsed_cmd->aggr_grp)) {
+ printf("Invalid aggregation group number: %d\n",
+ parsed_cmd->aggr_grp);
+ return CMD_RET_FAILURE;
+ }
+
+ if (parsed_cmd->port != ETHSW_CMD_PORT_ALL) {
+ if (!VSC9953_PORT_CHECK(parsed_cmd->port)) {
+ printf("Invalid port number: %d\n", parsed_cmd->port);
+ return CMD_RET_FAILURE;
+ }
+ if (vsc9953_port_aggr_grp_set(parsed_cmd->port,
+ parsed_cmd->aggr_grp)) {
+ printf("Port %d: failed to set aggr group %d\n",
+ parsed_cmd->port, parsed_cmd->aggr_grp);
+ }
+ } else {
+ for (i = 0; i < VSC9953_MAX_PORTS; i++) {
+ if (vsc9953_port_aggr_grp_set(i,
+ parsed_cmd->aggr_grp)) {
+ printf("Port %d: failed to set aggr group %d\n",
+ i, parsed_cmd->aggr_grp);
+ }
+ }
+ }
+
+ return CMD_RET_SUCCESS;
+}
+
static struct ethsw_command_func vsc9953_cmd_func = {
.ethsw_name = "L2 Switch VSC9953",
.port_enable = &vsc9953_port_status_key_func,
@@ -2088,7 +2432,9 @@ static struct ethsw_command_func vsc9953_cmd_func = {
.vlan_learn_show = &vsc9953_vlan_learn_show_key_func,
.vlan_learn_set = &vsc9953_vlan_learn_set_key_func,
.port_ingr_filt_show = &vsc9953_ingr_fltr_show_key_func,
- .port_ingr_filt_set = &vsc9953_ingr_fltr_set_key_func
+ .port_ingr_filt_set = &vsc9953_ingr_fltr_set_key_func,
+ .port_aggr_show = &vsc9953_port_aggr_show_key_func,
+ .port_aggr_set = &vsc9953_port_aggr_set_key_func,
};
#endif /* CONFIG_CMD_ETHSW */
@@ -2107,6 +2453,10 @@ void vsc9953_default_configuration(void)
{
int i;
+ if (vsc9953_autoage_time_set(VSC9953_DEFAULT_AGE_TIME))
+ debug("VSC9953: failed to set AGE time to %d\n",
+ VSC9953_DEFAULT_AGE_TIME);
+
for (i = 0; i < VSC9953_MAX_VLAN; i++)
vsc9953_vlan_table_membership_all_set(i, 0);
vsc9953_port_all_vlan_aware_set(1);
@@ -2115,6 +2465,8 @@ void vsc9953_default_configuration(void)
vsc9953_vlan_table_membership_all_set(1, 1);
vsc9953_vlan_ingr_fltr_learn_drop(1);
vsc9953_port_all_vlan_egress_untagged_set(EGRESS_UNTAG_PVID_AND_ZERO);
+ if (vsc9953_aggr_code_set(AGGR_CODE_ALL))
+ debug("VSC9953: failed to set default aggregation code mode\n");
}
void vsc9953_init(bd_t *bis)
diff --git a/drivers/net/xilinx_axi_emac.c b/drivers/net/xilinx_axi_emac.c
index df053feee8c..81274ee13bc 100644
--- a/drivers/net/xilinx_axi_emac.c
+++ b/drivers/net/xilinx_axi_emac.c
@@ -8,15 +8,14 @@
#include <config.h>
#include <common.h>
+#include <dm.h>
#include <net.h>
#include <malloc.h>
#include <asm/io.h>
#include <phy.h>
#include <miiphy.h>
-#if !defined(CONFIG_PHYLIB)
-# error AXI_ETHERNET requires PHYLIB
-#endif
+DECLARE_GLOBAL_DATA_PTR;
/* Link setup */
#define XAE_EMMC_LINKSPEED_MASK 0xC0000000 /* Link speed */
@@ -86,7 +85,8 @@ struct axidma_priv {
struct axidma_reg *dmatx;
struct axidma_reg *dmarx;
int phyaddr;
-
+ struct axi_regs *iobase;
+ phy_interface_t interface;
struct phy_device *phydev;
struct mii_dev *bus;
};
@@ -147,9 +147,8 @@ struct axi_regs {
*/
#define PHY_DETECT_MASK 0x1808
-static inline int mdio_wait(struct eth_device *dev)
+static inline int mdio_wait(struct axi_regs *regs)
{
- struct axi_regs *regs = (struct axi_regs *)dev->iobase;
u32 timeout = 200;
/* Wait till MDIO interface is ready to accept a new transaction. */
@@ -165,13 +164,13 @@ static inline int mdio_wait(struct eth_device *dev)
return 0;
}
-static u32 phyread(struct eth_device *dev, u32 phyaddress, u32 registernum,
- u16 *val)
+static u32 phyread(struct axidma_priv *priv, u32 phyaddress, u32 registernum,
+ u16 *val)
{
- struct axi_regs *regs = (struct axi_regs *)dev->iobase;
+ struct axi_regs *regs = priv->iobase;
u32 mdioctrlreg = 0;
- if (mdio_wait(dev))
+ if (mdio_wait(regs))
return 1;
mdioctrlreg = ((phyaddress << XAE_MDIO_MCR_PHYAD_SHIFT) &
@@ -183,7 +182,7 @@ static u32 phyread(struct eth_device *dev, u32 phyaddress, u32 registernum,
out_be32(&regs->mdio_mcr, mdioctrlreg);
- if (mdio_wait(dev))
+ if (mdio_wait(regs))
return 1;
/* Read data */
@@ -191,13 +190,13 @@ static u32 phyread(struct eth_device *dev, u32 phyaddress, u32 registernum,
return 0;
}
-static u32 phywrite(struct eth_device *dev, u32 phyaddress, u32 registernum,
- u32 data)
+static u32 phywrite(struct axidma_priv *priv, u32 phyaddress, u32 registernum,
+ u32 data)
{
- struct axi_regs *regs = (struct axi_regs *)dev->iobase;
+ struct axi_regs *regs = priv->iobase;
u32 mdioctrlreg = 0;
- if (mdio_wait(dev))
+ if (mdio_wait(regs))
return 1;
mdioctrlreg = ((phyaddress << XAE_MDIO_MCR_PHYAD_SHIFT) &
@@ -212,19 +211,18 @@ static u32 phywrite(struct eth_device *dev, u32 phyaddress, u32 registernum,
out_be32(&regs->mdio_mcr, mdioctrlreg);
- if (mdio_wait(dev))
+ if (mdio_wait(regs))
return 1;
return 0;
}
-/* Setting axi emac and phy to proper setting */
-static int setup_phy(struct eth_device *dev)
+static int axiemac_phy_init(struct udevice *dev)
{
u16 phyreg;
- u32 i, speed, emmc_reg, ret;
- struct axidma_priv *priv = dev->priv;
- struct axi_regs *regs = (struct axi_regs *)dev->iobase;
+ u32 i, ret;
+ struct axidma_priv *priv = dev_get_priv(dev);
+ struct axi_regs *regs = priv->iobase;
struct phy_device *phydev;
u32 supported = SUPPORTED_10baseT_Half |
@@ -234,16 +232,19 @@ static int setup_phy(struct eth_device *dev)
SUPPORTED_1000baseT_Half |
SUPPORTED_1000baseT_Full;
+ /* Set default MDIO divisor */
+ out_be32(&regs->mdio_mc, XAE_MDIO_DIV_DFT | XAE_MDIO_MC_MDIOEN_MASK);
+
if (priv->phyaddr == -1) {
/* Detect the PHY address */
for (i = 31; i >= 0; i--) {
- ret = phyread(dev, i, PHY_DETECT_REG, &phyreg);
+ ret = phyread(priv, i, PHY_DETECT_REG, &phyreg);
if (!ret && (phyreg != 0xFFFF) &&
((phyreg & PHY_DETECT_MASK) == PHY_DETECT_MASK)) {
/* Found a valid PHY address */
priv->phyaddr = i;
debug("axiemac: Found valid phy address, %x\n",
- phyreg);
+ i);
break;
}
}
@@ -256,6 +257,18 @@ static int setup_phy(struct eth_device *dev)
phydev->advertising = phydev->supported;
priv->phydev = phydev;
phy_config(phydev);
+
+ return 0;
+}
+
+/* Setting axi emac and phy to proper setting */
+static int setup_phy(struct udevice *dev)
+{
+ u32 speed, emmc_reg;
+ struct axidma_priv *priv = dev_get_priv(dev);
+ struct axi_regs *regs = priv->iobase;
+ struct phy_device *phydev = priv->phydev;
+
if (phy_startup(phydev)) {
printf("axiemac: could not initialize PHY %s\n",
phydev->dev->name);
@@ -299,9 +312,9 @@ static int setup_phy(struct eth_device *dev)
}
/* STOP DMA transfers */
-static void axiemac_halt(struct eth_device *dev)
+static void axiemac_stop(struct udevice *dev)
{
- struct axidma_priv *priv = dev->priv;
+ struct axidma_priv *priv = dev_get_priv(dev);
u32 temp;
/* Stop the hardware */
@@ -316,9 +329,9 @@ static void axiemac_halt(struct eth_device *dev)
debug("axiemac: Halted\n");
}
-static int axi_ethernet_init(struct eth_device *dev)
+static int axi_ethernet_init(struct axidma_priv *priv)
{
- struct axi_regs *regs = (struct axi_regs *)dev->iobase;
+ struct axi_regs *regs = priv->iobase;
u32 timeout = 200;
/*
@@ -359,25 +372,26 @@ static int axi_ethernet_init(struct eth_device *dev)
return 0;
}
-static int axiemac_setup_mac(struct eth_device *dev)
+static int axiemac_write_hwaddr(struct udevice *dev)
{
- struct axi_regs *regs = (struct axi_regs *)dev->iobase;
+ struct eth_pdata *pdata = dev_get_platdata(dev);
+ struct axidma_priv *priv = dev_get_priv(dev);
+ struct axi_regs *regs = priv->iobase;
/* Set the MAC address */
- int val = ((dev->enetaddr[3] << 24) | (dev->enetaddr[2] << 16) |
- (dev->enetaddr[1] << 8) | (dev->enetaddr[0]));
+ int val = ((pdata->enetaddr[3] << 24) | (pdata->enetaddr[2] << 16) |
+ (pdata->enetaddr[1] << 8) | (pdata->enetaddr[0]));
out_be32(&regs->uaw0, val);
- val = (dev->enetaddr[5] << 8) | dev->enetaddr[4] ;
+ val = (pdata->enetaddr[5] << 8) | pdata->enetaddr[4];
val |= in_be32(&regs->uaw1) & ~XAE_UAW1_UNICASTADDR_MASK;
out_be32(&regs->uaw1, val);
return 0;
}
/* Reset DMA engine */
-static void axi_dma_init(struct eth_device *dev)
+static void axi_dma_init(struct axidma_priv *priv)
{
- struct axidma_priv *priv = dev->priv;
u32 timeout = 500;
/* Reset the engine so the hardware starts from a known state */
@@ -388,9 +402,9 @@ static void axi_dma_init(struct eth_device *dev)
while (timeout--) {
/* Check transmit/receive channel */
/* Reset is done when the reset bit is low */
- if (!(in_be32(&priv->dmatx->control) |
+ if (!((in_be32(&priv->dmatx->control) |
in_be32(&priv->dmarx->control))
- & XAXIDMA_CR_RESET_MASK) {
+ & XAXIDMA_CR_RESET_MASK)) {
break;
}
}
@@ -398,10 +412,10 @@ static void axi_dma_init(struct eth_device *dev)
printf("%s: Timeout\n", __func__);
}
-static int axiemac_init(struct eth_device *dev, bd_t * bis)
+static int axiemac_start(struct udevice *dev)
{
- struct axidma_priv *priv = dev->priv;
- struct axi_regs *regs = (struct axi_regs *)dev->iobase;
+ struct axidma_priv *priv = dev_get_priv(dev);
+ struct axi_regs *regs = priv->iobase;
u32 temp;
debug("axiemac: Init started\n");
@@ -411,10 +425,10 @@ static int axiemac_init(struct eth_device *dev, bd_t * bis)
* reset, and since AXIDMA reset line is connected to AxiEthernet, this
* would ensure a reset of AxiEthernet.
*/
- axi_dma_init(dev);
+ axi_dma_init(priv);
/* Initialize AxiEthernet hardware. */
- if (axi_ethernet_init(dev))
+ if (axi_ethernet_init(priv))
return -1;
/* Disable all RX interrupts before RxBD space setup */
@@ -452,7 +466,7 @@ static int axiemac_init(struct eth_device *dev, bd_t * bis)
/* PHY setup */
if (!setup_phy(dev)) {
- axiemac_halt(dev);
+ axiemac_stop(dev);
return -1;
}
@@ -460,9 +474,9 @@ static int axiemac_init(struct eth_device *dev, bd_t * bis)
return 0;
}
-static int axiemac_send(struct eth_device *dev, void *ptr, int len)
+static int axiemac_send(struct udevice *dev, void *ptr, int len)
{
- struct axidma_priv *priv = dev->priv;
+ struct axidma_priv *priv = dev_get_priv(dev);
u32 timeout;
if (len > PKTSIZE_ALIGN)
@@ -498,8 +512,8 @@ static int axiemac_send(struct eth_device *dev, void *ptr, int len)
/* Wait for transmission to complete */
debug("axiemac: Waiting for tx to be done\n");
timeout = 200;
- while (timeout && (!in_be32(&priv->dmatx->status) &
- (XAXIDMA_IRQ_DELAY_MASK | XAXIDMA_IRQ_IOC_MASK))) {
+ while (timeout && (!(in_be32(&priv->dmatx->status) &
+ (XAXIDMA_IRQ_DELAY_MASK | XAXIDMA_IRQ_IOC_MASK)))) {
timeout--;
udelay(1);
}
@@ -512,10 +526,9 @@ static int axiemac_send(struct eth_device *dev, void *ptr, int len)
return 0;
}
-static int isrxready(struct eth_device *dev)
+static int isrxready(struct axidma_priv *priv)
{
u32 status;
- struct axidma_priv *priv = dev->priv;
/* Read pending interrupts */
status = in_be32(&priv->dmarx->status);
@@ -533,15 +546,15 @@ static int isrxready(struct eth_device *dev)
return 0;
}
-static int axiemac_recv(struct eth_device *dev)
+static int axiemac_recv(struct udevice *dev, int flags, uchar **packetp)
{
u32 length;
- struct axidma_priv *priv = dev->priv;
+ struct axidma_priv *priv = dev_get_priv(dev);
u32 temp;
/* Wait for an incoming packet */
- if (!isrxready(dev))
- return 0;
+ if (!isrxready(priv))
+ return -1;
debug("axiemac: RX data ready\n");
@@ -554,9 +567,14 @@ static int axiemac_recv(struct eth_device *dev)
#ifdef DEBUG
print_buffer(&rxframe, &rxframe[0], 1, length, 16);
#endif
- /* Pass the received frame up for processing */
- if (length)
- net_process_received_packet(rxframe, length);
+
+ *packetp = rxframe;
+ return length;
+}
+
+static int axiemac_free_pkt(struct udevice *dev, uchar *packet, int length)
+{
+ struct axidma_priv *priv = dev_get_priv(dev);
#ifdef DEBUG
/* It is useful to clear buffer to be sure that it is consistent */
@@ -581,76 +599,128 @@ static int axiemac_recv(struct eth_device *dev)
debug("axiemac: RX completed, framelength = %d\n", length);
- return length;
+ return 0;
}
-static int axiemac_miiphy_read(const char *devname, uchar addr,
- uchar reg, ushort *val)
+static int axiemac_miiphy_read(struct mii_dev *bus, int addr,
+ int devad, int reg)
{
- struct eth_device *dev = eth_get_dev();
- u32 ret;
+ int ret;
+ u16 value;
- ret = phyread(dev, addr, reg, val);
- debug("axiemac: Read MII 0x%x, 0x%x, 0x%x\n", addr, reg, *val);
- return ret;
+ ret = phyread(bus->priv, addr, reg, &value);
+ debug("axiemac: Read MII 0x%x, 0x%x, 0x%x, %d\n", addr, reg,
+ value, ret);
+ return value;
}
-static int axiemac_miiphy_write(const char *devname, uchar addr,
- uchar reg, ushort val)
+static int axiemac_miiphy_write(struct mii_dev *bus, int addr, int devad,
+ int reg, u16 value)
{
- struct eth_device *dev = eth_get_dev();
-
- debug("axiemac: Write MII 0x%x, 0x%x, 0x%x\n", addr, reg, val);
- return phywrite(dev, addr, reg, val);
+ debug("axiemac: Write MII 0x%x, 0x%x, 0x%x\n", addr, reg, value);
+ return phywrite(bus->priv, addr, reg, value);
}
-static int axiemac_bus_reset(struct mii_dev *bus)
+static int axi_emac_probe(struct udevice *dev)
{
- debug("axiemac: Bus reset\n");
+ struct axidma_priv *priv = dev_get_priv(dev);
+ int ret;
+
+ priv->bus = mdio_alloc();
+ priv->bus->read = axiemac_miiphy_read;
+ priv->bus->write = axiemac_miiphy_write;
+ priv->bus->priv = priv;
+ strcpy(priv->bus->name, "axi_emac");
+
+ ret = mdio_register(priv->bus);
+ if (ret)
+ return ret;
+
+ axiemac_phy_init(dev);
+
return 0;
}
-int xilinx_axiemac_initialize(bd_t *bis, unsigned long base_addr,
- unsigned long dma_addr)
+static int axi_emac_remove(struct udevice *dev)
{
- struct eth_device *dev;
- struct axidma_priv *priv;
+ struct axidma_priv *priv = dev_get_priv(dev);
- dev = calloc(1, sizeof(struct eth_device));
- if (dev == NULL)
- return -1;
+ free(priv->phydev);
+ mdio_unregister(priv->bus);
+ mdio_free(priv->bus);
- dev->priv = calloc(1, sizeof(struct axidma_priv));
- if (dev->priv == NULL) {
- free(dev);
- return -1;
- }
- priv = dev->priv;
+ return 0;
+}
- sprintf(dev->name, "aximac.%lx", base_addr);
+static const struct eth_ops axi_emac_ops = {
+ .start = axiemac_start,
+ .send = axiemac_send,
+ .recv = axiemac_recv,
+ .free_pkt = axiemac_free_pkt,
+ .stop = axiemac_stop,
+ .write_hwaddr = axiemac_write_hwaddr,
+};
- dev->iobase = base_addr;
- priv->dmatx = (struct axidma_reg *)dma_addr;
+static int axi_emac_ofdata_to_platdata(struct udevice *dev)
+{
+ struct eth_pdata *pdata = dev_get_platdata(dev);
+ struct axidma_priv *priv = dev_get_priv(dev);
+ int offset = 0;
+ const char *phy_mode;
+
+ pdata->iobase = (phys_addr_t)dev_get_addr(dev);
+ priv->iobase = (struct axi_regs *)pdata->iobase;
+
+ offset = fdtdec_lookup_phandle(gd->fdt_blob, dev->of_offset,
+ "axistream-connected");
+ if (offset <= 0) {
+ printf("%s: axistream is not found\n", __func__);
+ return -EINVAL;
+ }
+ priv->dmatx = (struct axidma_reg *)fdtdec_get_int(gd->fdt_blob,
+ offset, "reg", 0);
+ if (!priv->dmatx) {
+ printf("%s: axi_dma register space not found\n", __func__);
+ return -EINVAL;
+ }
/* RX channel offset is 0x30 */
- priv->dmarx = (struct axidma_reg *)(dma_addr + 0x30);
- dev->init = axiemac_init;
- dev->halt = axiemac_halt;
- dev->send = axiemac_send;
- dev->recv = axiemac_recv;
- dev->write_hwaddr = axiemac_setup_mac;
-
-#ifdef CONFIG_PHY_ADDR
- priv->phyaddr = CONFIG_PHY_ADDR;
-#else
+ priv->dmarx = (struct axidma_reg *)((u32)priv->dmatx + 0x30);
+
priv->phyaddr = -1;
-#endif
- eth_register(dev);
+ offset = fdtdec_lookup_phandle(gd->fdt_blob, dev->of_offset,
+ "phy-handle");
+ if (offset > 0)
+ priv->phyaddr = fdtdec_get_int(gd->fdt_blob, offset, "reg", -1);
+
+ phy_mode = fdt_getprop(gd->fdt_blob, dev->of_offset, "phy-mode", NULL);
+ if (phy_mode)
+ pdata->phy_interface = phy_get_interface_by_name(phy_mode);
+ if (pdata->phy_interface == -1) {
+ debug("%s: Invalid PHY interface '%s'\n", __func__, phy_mode);
+ return -EINVAL;
+ }
+ priv->interface = pdata->phy_interface;
+
+ printf("AXI EMAC: %lx, phyaddr %d, interface %s\n", (ulong)priv->iobase,
+ priv->phyaddr, phy_string_for_interface(priv->interface));
-#if defined(CONFIG_MII) || defined(CONFIG_CMD_MII) || defined(CONFIG_PHYLIB)
- miiphy_register(dev->name, axiemac_miiphy_read, axiemac_miiphy_write);
- priv->bus = miiphy_get_dev_by_name(dev->name);
- priv->bus->reset = axiemac_bus_reset;
-#endif
- return 1;
+ return 0;
}
+
+static const struct udevice_id axi_emac_ids[] = {
+ { .compatible = "xlnx,axi-ethernet-1.00.a" },
+ { }
+};
+
+U_BOOT_DRIVER(axi_emac) = {
+ .name = "axi_emac",
+ .id = UCLASS_ETH,
+ .of_match = axi_emac_ids,
+ .ofdata_to_platdata = axi_emac_ofdata_to_platdata,
+ .probe = axi_emac_probe,
+ .remove = axi_emac_remove,
+ .ops = &axi_emac_ops,
+ .priv_auto_alloc_size = sizeof(struct axidma_priv),
+ .platdata_auto_alloc_size = sizeof(struct eth_pdata),
+};
diff --git a/drivers/net/xilinx_emaclite.c b/drivers/net/xilinx_emaclite.c
index 564205df83d..5862bf0a7e2 100644
--- a/drivers/net/xilinx_emaclite.c
+++ b/drivers/net/xilinx_emaclite.c
@@ -10,27 +10,25 @@
#include <common.h>
#include <net.h>
#include <config.h>
+#include <dm.h>
+#include <console.h>
#include <malloc.h>
#include <asm/io.h>
+#include <phy.h>
+#include <miiphy.h>
#include <fdtdec.h>
+#include <asm-generic/errno.h>
+#include <linux/kernel.h>
-#undef DEBUG
+DECLARE_GLOBAL_DATA_PTR;
#define ENET_ADDR_LENGTH 6
-
-/* EmacLite constants */
-#define XEL_BUFFER_OFFSET 0x0800 /* Next buffer's offset */
-#define XEL_TPLR_OFFSET 0x07F4 /* Tx packet length */
-#define XEL_TSR_OFFSET 0x07FC /* Tx status */
-#define XEL_RSR_OFFSET 0x17FC /* Rx status */
-#define XEL_RXBUFF_OFFSET 0x1000 /* Receive Buffer */
+#define ETH_FCS_LEN 4 /* Octets in the FCS */
/* Xmit complete */
#define XEL_TSR_XMIT_BUSY_MASK 0x00000001UL
/* Xmit interrupt enable bit */
#define XEL_TSR_XMIT_IE_MASK 0x00000008UL
-/* Buffer is active, SW bit only */
-#define XEL_TSR_XMIT_ACTIVE_MASK 0x80000000UL
/* Program the MAC address */
#define XEL_TSR_PROGRAM_MASK 0x00000002UL
/* define for programming the MAC address into the EMAC Lite */
@@ -46,14 +44,56 @@
/* Recv interrupt enable bit */
#define XEL_RSR_RECV_IE_MASK 0x00000008UL
+/* MDIO Address Register Bit Masks */
+#define XEL_MDIOADDR_REGADR_MASK 0x0000001F /* Register Address */
+#define XEL_MDIOADDR_PHYADR_MASK 0x000003E0 /* PHY Address */
+#define XEL_MDIOADDR_PHYADR_SHIFT 5
+#define XEL_MDIOADDR_OP_MASK 0x00000400 /* RD/WR Operation */
+
+/* MDIO Write Data Register Bit Masks */
+#define XEL_MDIOWR_WRDATA_MASK 0x0000FFFF /* Data to be Written */
+
+/* MDIO Read Data Register Bit Masks */
+#define XEL_MDIORD_RDDATA_MASK 0x0000FFFF /* Data to be Read */
+
+/* MDIO Control Register Bit Masks */
+#define XEL_MDIOCTRL_MDIOSTS_MASK 0x00000001 /* MDIO Status Mask */
+#define XEL_MDIOCTRL_MDIOEN_MASK 0x00000008 /* MDIO Enable */
+
+struct emaclite_regs {
+ u32 tx_ping; /* 0x0 - TX Ping buffer */
+ u32 reserved1[504];
+ u32 mdioaddr; /* 0x7e4 - MDIO Address Register */
+ u32 mdiowr; /* 0x7e8 - MDIO Write Data Register */
+ u32 mdiord;/* 0x7ec - MDIO Read Data Register */
+ u32 mdioctrl; /* 0x7f0 - MDIO Control Register */
+ u32 tx_ping_tplr; /* 0x7f4 - Tx packet length */
+ u32 global_interrupt; /* 0x7f8 - Global interrupt enable */
+ u32 tx_ping_tsr; /* 0x7fc - Tx status */
+ u32 tx_pong; /* 0x800 - TX Pong buffer */
+ u32 reserved2[508];
+ u32 tx_pong_tplr; /* 0xff4 - Tx packet length */
+ u32 reserved3; /* 0xff8 */
+ u32 tx_pong_tsr; /* 0xffc - Tx status */
+ u32 rx_ping; /* 0x1000 - Receive Buffer */
+ u32 reserved4[510];
+ u32 rx_ping_rsr; /* 0x17fc - Rx status */
+ u32 rx_pong; /* 0x1800 - Receive Buffer */
+ u32 reserved5[510];
+ u32 rx_pong_rsr; /* 0x1ffc - Rx status */
+};
+
struct xemaclite {
- u32 nexttxbuffertouse; /* Next TX buffer to write to */
- u32 nextrxbuffertouse; /* Next RX buffer to read from */
+ bool use_rx_pong_buffer_next; /* Next RX buffer to read from */
u32 txpp; /* TX ping pong buffer */
u32 rxpp; /* RX ping pong buffer */
+ int phyaddr;
+ struct emaclite_regs *regs;
+ struct phy_device *phydev;
+ struct mii_dev *bus;
};
-static u32 etherrxbuff[PKTSIZE_ALIGN/4]; /* Receive buffer */
+static uchar etherrxbuff[PKTSIZE_ALIGN]; /* Receive buffer */
static void xemaclite_alignedread(u32 *srcptr, void *destptr, u32 bytecount)
{
@@ -81,7 +121,7 @@ static void xemaclite_alignedread(u32 *srcptr, void *destptr, u32 bytecount)
*to8ptr++ = *from8ptr++;
}
-static void xemaclite_alignedwrite(void *srcptr, u32 destptr, u32 bytecount)
+static void xemaclite_alignedwrite(void *srcptr, u32 *destptr, u32 bytecount)
{
u32 i;
u32 alignbuffer;
@@ -107,42 +147,206 @@ static void xemaclite_alignedwrite(void *srcptr, u32 destptr, u32 bytecount)
*to32ptr++ = alignbuffer;
}
-static void emaclite_halt(struct eth_device *dev)
+static int wait_for_bit(const char *func, u32 *reg, const u32 mask,
+ bool set, unsigned int timeout)
+{
+ u32 val;
+ unsigned long start = get_timer(0);
+
+ while (1) {
+ val = readl(reg);
+
+ if (!set)
+ val = ~val;
+
+ if ((val & mask) == mask)
+ return 0;
+
+ if (get_timer(start) > timeout)
+ break;
+
+ if (ctrlc()) {
+ puts("Abort\n");
+ return -EINTR;
+ }
+
+ udelay(1);
+ }
+
+ debug("%s: Timeout (reg=%p mask=%08x wait_set=%i)\n",
+ func, reg, mask, set);
+
+ return -ETIMEDOUT;
+}
+
+static int mdio_wait(struct emaclite_regs *regs)
{
- debug("eth_halt\n");
+ return wait_for_bit(__func__, &regs->mdioctrl,
+ XEL_MDIOCTRL_MDIOSTS_MASK, false, 2000);
}
-static int emaclite_init(struct eth_device *dev, bd_t *bis)
+static u32 phyread(struct xemaclite *emaclite, u32 phyaddress, u32 registernum,
+ u16 *data)
{
- struct xemaclite *emaclite = dev->priv;
+ struct emaclite_regs *regs = emaclite->regs;
+
+ if (mdio_wait(regs))
+ return 1;
+
+ u32 ctrl_reg = in_be32(&regs->mdioctrl);
+ out_be32(&regs->mdioaddr, XEL_MDIOADDR_OP_MASK |
+ ((phyaddress << XEL_MDIOADDR_PHYADR_SHIFT) | registernum));
+ out_be32(&regs->mdioctrl, ctrl_reg | XEL_MDIOCTRL_MDIOSTS_MASK);
+
+ if (mdio_wait(regs))
+ return 1;
+
+ /* Read data */
+ *data = in_be32(&regs->mdiord);
+ return 0;
+}
+
+static u32 phywrite(struct xemaclite *emaclite, u32 phyaddress, u32 registernum,
+ u16 data)
+{
+ struct emaclite_regs *regs = emaclite->regs;
+
+ if (mdio_wait(regs))
+ return 1;
+
+ /*
+ * Write the PHY address, register number and clear the OP bit in the
+ * MDIO Address register and then write the value into the MDIO Write
+ * Data register. Finally, set the Status bit in the MDIO Control
+ * register to start a MDIO write transaction.
+ */
+ u32 ctrl_reg = in_be32(&regs->mdioctrl);
+ out_be32(&regs->mdioaddr, ~XEL_MDIOADDR_OP_MASK &
+ ((phyaddress << XEL_MDIOADDR_PHYADR_SHIFT) | registernum));
+ out_be32(&regs->mdiowr, data);
+ out_be32(&regs->mdioctrl, ctrl_reg | XEL_MDIOCTRL_MDIOSTS_MASK);
+
+ if (mdio_wait(regs))
+ return 1;
+
+ return 0;
+}
+
+static void emaclite_stop(struct udevice *dev)
+{
+ debug("eth_stop\n");
+}
+
+/* Use MII register 1 (MII status register) to detect PHY */
+#define PHY_DETECT_REG 1
+
+/* Mask used to verify certain PHY features (or register contents)
+ * in the register above:
+ * 0x1000: 10Mbps full duplex support
+ * 0x0800: 10Mbps half duplex support
+ * 0x0008: Auto-negotiation support
+ */
+#define PHY_DETECT_MASK 0x1808
+
+static int setup_phy(struct udevice *dev)
+{
+ int i;
+ u16 phyreg;
+ struct xemaclite *emaclite = dev_get_priv(dev);
+ struct phy_device *phydev;
+
+ u32 supported = SUPPORTED_10baseT_Half |
+ SUPPORTED_10baseT_Full |
+ SUPPORTED_100baseT_Half |
+ SUPPORTED_100baseT_Full;
+
+ if (emaclite->phyaddr != -1) {
+ phyread(emaclite, emaclite->phyaddr, PHY_DETECT_REG, &phyreg);
+ if ((phyreg != 0xFFFF) &&
+ ((phyreg & PHY_DETECT_MASK) == PHY_DETECT_MASK)) {
+ /* Found a valid PHY address */
+ debug("Default phy address %d is valid\n",
+ emaclite->phyaddr);
+ } else {
+ debug("PHY address is not setup correctly %d\n",
+ emaclite->phyaddr);
+ emaclite->phyaddr = -1;
+ }
+ }
+
+ if (emaclite->phyaddr == -1) {
+ /* detect the PHY address */
+ for (i = 31; i >= 0; i--) {
+ phyread(emaclite, i, PHY_DETECT_REG, &phyreg);
+ if ((phyreg != 0xFFFF) &&
+ ((phyreg & PHY_DETECT_MASK) == PHY_DETECT_MASK)) {
+ /* Found a valid PHY address */
+ emaclite->phyaddr = i;
+ debug("emaclite: Found valid phy address, %d\n",
+ i);
+ break;
+ }
+ }
+ }
+
+ /* interface - look at tsec */
+ phydev = phy_connect(emaclite->bus, emaclite->phyaddr, dev,
+ PHY_INTERFACE_MODE_MII);
+ /*
+ * Phy can support 1000baseT but device NOT that's why phydev->supported
+ * must be setup for 1000baseT. phydev->advertising setups what speeds
+ * will be used for autonegotiation where 1000baseT must be disabled.
+ */
+ phydev->supported = supported | SUPPORTED_1000baseT_Half |
+ SUPPORTED_1000baseT_Full;
+ phydev->advertising = supported;
+ emaclite->phydev = phydev;
+ phy_config(phydev);
+ phy_startup(phydev);
+
+ if (!phydev->link) {
+ printf("%s: No link.\n", phydev->dev->name);
+ return 0;
+ }
+
+ /* Do not setup anything */
+ return 1;
+}
+
+static int emaclite_start(struct udevice *dev)
+{
+ struct xemaclite *emaclite = dev_get_priv(dev);
+ struct eth_pdata *pdata = dev_get_platdata(dev);
+ struct emaclite_regs *regs = emaclite->regs;
+
debug("EmacLite Initialization Started\n");
/*
* TX - TX_PING & TX_PONG initialization
*/
/* Restart PING TX */
- out_be32 (dev->iobase + XEL_TSR_OFFSET, 0);
+ out_be32(&regs->tx_ping_tsr, 0);
/* Copy MAC address */
- xemaclite_alignedwrite(dev->enetaddr, dev->iobase, ENET_ADDR_LENGTH);
+ xemaclite_alignedwrite(pdata->enetaddr, &regs->tx_ping,
+ ENET_ADDR_LENGTH);
/* Set the length */
- out_be32 (dev->iobase + XEL_TPLR_OFFSET, ENET_ADDR_LENGTH);
+ out_be32(&regs->tx_ping_tplr, ENET_ADDR_LENGTH);
/* Update the MAC address in the EMAC Lite */
- out_be32 (dev->iobase + XEL_TSR_OFFSET, XEL_TSR_PROG_MAC_ADDR);
+ out_be32(&regs->tx_ping_tsr, XEL_TSR_PROG_MAC_ADDR);
/* Wait for EMAC Lite to finish with the MAC address update */
- while ((in_be32 (dev->iobase + XEL_TSR_OFFSET) &
+ while ((in_be32 (&regs->tx_ping_tsr) &
XEL_TSR_PROG_MAC_ADDR) != 0)
;
if (emaclite->txpp) {
/* The same operation with PONG TX */
- out_be32 (dev->iobase + XEL_TSR_OFFSET + XEL_BUFFER_OFFSET, 0);
- xemaclite_alignedwrite(dev->enetaddr, dev->iobase +
- XEL_BUFFER_OFFSET, ENET_ADDR_LENGTH);
- out_be32 (dev->iobase + XEL_TPLR_OFFSET, ENET_ADDR_LENGTH);
- out_be32 (dev->iobase + XEL_TSR_OFFSET + XEL_BUFFER_OFFSET,
- XEL_TSR_PROG_MAC_ADDR);
- while ((in_be32 (dev->iobase + XEL_TSR_OFFSET +
- XEL_BUFFER_OFFSET) & XEL_TSR_PROG_MAC_ADDR) != 0)
+ out_be32(&regs->tx_pong_tsr, 0);
+ xemaclite_alignedwrite(pdata->enetaddr, &regs->tx_pong,
+ ENET_ADDR_LENGTH);
+ out_be32(&regs->tx_pong_tplr, ENET_ADDR_LENGTH);
+ out_be32(&regs->tx_pong_tsr, XEL_TSR_PROG_MAC_ADDR);
+ while ((in_be32(&regs->tx_pong_tsr) &
+ XEL_TSR_PROG_MAC_ADDR) != 0)
;
}
@@ -150,52 +354,48 @@ static int emaclite_init(struct eth_device *dev, bd_t *bis)
* RX - RX_PING & RX_PONG initialization
*/
/* Write out the value to flush the RX buffer */
- out_be32 (dev->iobase + XEL_RSR_OFFSET, XEL_RSR_RECV_IE_MASK);
+ out_be32(&regs->rx_ping_rsr, XEL_RSR_RECV_IE_MASK);
if (emaclite->rxpp)
- out_be32 (dev->iobase + XEL_RSR_OFFSET + XEL_BUFFER_OFFSET,
- XEL_RSR_RECV_IE_MASK);
+ out_be32(&regs->rx_pong_rsr, XEL_RSR_RECV_IE_MASK);
+
+ out_be32(&regs->mdioctrl, XEL_MDIOCTRL_MDIOEN_MASK);
+ if (in_be32(&regs->mdioctrl) & XEL_MDIOCTRL_MDIOEN_MASK)
+ if (!setup_phy(dev))
+ return -1;
debug("EmacLite Initialization complete\n");
return 0;
}
-static int xemaclite_txbufferavailable(struct eth_device *dev)
+static int xemaclite_txbufferavailable(struct xemaclite *emaclite)
{
- u32 reg;
- u32 txpingbusy;
- u32 txpongbusy;
- struct xemaclite *emaclite = dev->priv;
+ u32 tmp;
+ struct emaclite_regs *regs = emaclite->regs;
/*
* Read the other buffer register
* and determine if the other buffer is available
*/
- reg = in_be32 (dev->iobase +
- emaclite->nexttxbuffertouse + 0);
- txpingbusy = ((reg & XEL_TSR_XMIT_BUSY_MASK) ==
- XEL_TSR_XMIT_BUSY_MASK);
-
- reg = in_be32 (dev->iobase +
- (emaclite->nexttxbuffertouse ^ XEL_TSR_OFFSET) + 0);
- txpongbusy = ((reg & XEL_TSR_XMIT_BUSY_MASK) ==
- XEL_TSR_XMIT_BUSY_MASK);
+ tmp = ~in_be32(&regs->tx_ping_tsr);
+ if (emaclite->txpp)
+ tmp |= ~in_be32(&regs->tx_pong_tsr);
- return !(txpingbusy && txpongbusy);
+ return !(tmp & XEL_TSR_XMIT_BUSY_MASK);
}
-static int emaclite_send(struct eth_device *dev, void *ptr, int len)
+static int emaclite_send(struct udevice *dev, void *ptr, int len)
{
u32 reg;
- u32 baseaddress;
- struct xemaclite *emaclite = dev->priv;
+ struct xemaclite *emaclite = dev_get_priv(dev);
+ struct emaclite_regs *regs = emaclite->regs;
u32 maxtry = 1000;
if (len > PKTSIZE)
len = PKTSIZE;
- while (!xemaclite_txbufferavailable(dev) && maxtry) {
+ while (xemaclite_txbufferavailable(emaclite) && maxtry) {
udelay(10);
maxtry--;
}
@@ -203,58 +403,40 @@ static int emaclite_send(struct eth_device *dev, void *ptr, int len)
if (!maxtry) {
printf("Error: Timeout waiting for ethernet TX buffer\n");
/* Restart PING TX */
- out_be32 (dev->iobase + XEL_TSR_OFFSET, 0);
+ out_be32(&regs->tx_ping_tsr, 0);
if (emaclite->txpp) {
- out_be32 (dev->iobase + XEL_TSR_OFFSET +
- XEL_BUFFER_OFFSET, 0);
+ out_be32(&regs->tx_pong_tsr, 0);
}
return -1;
}
- /* Determine the expected TX buffer address */
- baseaddress = (dev->iobase + emaclite->nexttxbuffertouse);
-
/* Determine if the expected buffer address is empty */
- reg = in_be32 (baseaddress + XEL_TSR_OFFSET);
- if (((reg & XEL_TSR_XMIT_BUSY_MASK) == 0)
- && ((in_be32 ((baseaddress) + XEL_TSR_OFFSET)
- & XEL_TSR_XMIT_ACTIVE_MASK) == 0)) {
-
- if (emaclite->txpp)
- emaclite->nexttxbuffertouse ^= XEL_BUFFER_OFFSET;
-
- debug("Send packet from 0x%x\n", baseaddress);
+ reg = in_be32(&regs->tx_ping_tsr);
+ if ((reg & XEL_TSR_XMIT_BUSY_MASK) == 0) {
+ debug("Send packet from tx_ping buffer\n");
/* Write the frame to the buffer */
- xemaclite_alignedwrite(ptr, baseaddress, len);
- out_be32 (baseaddress + XEL_TPLR_OFFSET,(len &
- (XEL_TPLR_LENGTH_MASK_HI | XEL_TPLR_LENGTH_MASK_LO)));
- reg = in_be32 (baseaddress + XEL_TSR_OFFSET);
+ xemaclite_alignedwrite(ptr, &regs->tx_ping, len);
+ out_be32(&regs->tx_ping_tplr, len &
+ (XEL_TPLR_LENGTH_MASK_HI | XEL_TPLR_LENGTH_MASK_LO));
+ reg = in_be32(&regs->tx_ping_tsr);
reg |= XEL_TSR_XMIT_BUSY_MASK;
- if ((reg & XEL_TSR_XMIT_IE_MASK) != 0)
- reg |= XEL_TSR_XMIT_ACTIVE_MASK;
- out_be32 (baseaddress + XEL_TSR_OFFSET, reg);
+ out_be32(&regs->tx_ping_tsr, reg);
return 0;
}
if (emaclite->txpp) {
- /* Switch to second buffer */
- baseaddress ^= XEL_BUFFER_OFFSET;
/* Determine if the expected buffer address is empty */
- reg = in_be32 (baseaddress + XEL_TSR_OFFSET);
- if (((reg & XEL_TSR_XMIT_BUSY_MASK) == 0)
- && ((in_be32 ((baseaddress) + XEL_TSR_OFFSET)
- & XEL_TSR_XMIT_ACTIVE_MASK) == 0)) {
- debug("Send packet from 0x%x\n", baseaddress);
+ reg = in_be32(&regs->tx_pong_tsr);
+ if ((reg & XEL_TSR_XMIT_BUSY_MASK) == 0) {
+ debug("Send packet from tx_pong buffer\n");
/* Write the frame to the buffer */
- xemaclite_alignedwrite(ptr, baseaddress, len);
- out_be32 (baseaddress + XEL_TPLR_OFFSET, (len &
- (XEL_TPLR_LENGTH_MASK_HI |
- XEL_TPLR_LENGTH_MASK_LO)));
- reg = in_be32 (baseaddress + XEL_TSR_OFFSET);
+ xemaclite_alignedwrite(ptr, &regs->tx_pong, len);
+ out_be32(&regs->tx_pong_tplr, len &
+ (XEL_TPLR_LENGTH_MASK_HI |
+ XEL_TPLR_LENGTH_MASK_LO));
+ reg = in_be32(&regs->tx_pong_tsr);
reg |= XEL_TSR_XMIT_BUSY_MASK;
- if ((reg & XEL_TSR_XMIT_IE_MASK) != 0)
- reg |= XEL_TSR_XMIT_ACTIVE_MASK;
- out_be32 (baseaddress + XEL_TSR_OFFSET, reg);
+ out_be32(&regs->tx_pong_tsr, reg);
return 0;
}
}
@@ -263,130 +445,188 @@ static int emaclite_send(struct eth_device *dev, void *ptr, int len)
return -1;
}
-static int emaclite_recv(struct eth_device *dev)
+static int emaclite_recv(struct udevice *dev, int flags, uchar **packetp)
{
- u32 length;
- u32 reg;
- u32 baseaddress;
+ u32 length, first_read, reg, attempt = 0;
+ void *addr, *ack;
struct xemaclite *emaclite = dev->priv;
+ struct emaclite_regs *regs = emaclite->regs;
+ struct ethernet_hdr *eth;
+ struct ip_udp_hdr *ip;
+
+try_again:
+ if (!emaclite->use_rx_pong_buffer_next) {
+ reg = in_be32(&regs->rx_ping_rsr);
+ debug("Testing data at rx_ping\n");
+ if ((reg & XEL_RSR_RECV_DONE_MASK) == XEL_RSR_RECV_DONE_MASK) {
+ debug("Data found in rx_ping buffer\n");
+ addr = &regs->rx_ping;
+ ack = &regs->rx_ping_rsr;
+ } else {
+ debug("Data not found in rx_ping buffer\n");
+ /* Pong buffer is not available - return immediately */
+ if (!emaclite->rxpp)
+ return -1;
- baseaddress = dev->iobase + emaclite->nextrxbuffertouse;
- reg = in_be32 (baseaddress + XEL_RSR_OFFSET);
- debug("Testing data at address 0x%x\n", baseaddress);
- if ((reg & XEL_RSR_RECV_DONE_MASK) == XEL_RSR_RECV_DONE_MASK) {
- if (emaclite->rxpp)
- emaclite->nextrxbuffertouse ^= XEL_BUFFER_OFFSET;
+ /* Try pong buffer if this is first attempt */
+ if (attempt++)
+ return -1;
+ emaclite->use_rx_pong_buffer_next =
+ !emaclite->use_rx_pong_buffer_next;
+ goto try_again;
+ }
} else {
-
- if (!emaclite->rxpp) {
- debug("No data was available - address 0x%x\n",
- baseaddress);
- return 0;
+ reg = in_be32(&regs->rx_pong_rsr);
+ debug("Testing data at rx_pong\n");
+ if ((reg & XEL_RSR_RECV_DONE_MASK) == XEL_RSR_RECV_DONE_MASK) {
+ debug("Data found in rx_pong buffer\n");
+ addr = &regs->rx_pong;
+ ack = &regs->rx_pong_rsr;
} else {
- baseaddress ^= XEL_BUFFER_OFFSET;
- reg = in_be32 (baseaddress + XEL_RSR_OFFSET);
- if ((reg & XEL_RSR_RECV_DONE_MASK) !=
- XEL_RSR_RECV_DONE_MASK) {
- debug("No data was available - address 0x%x\n",
- baseaddress);
- return 0;
- }
+ debug("Data not found in rx_pong buffer\n");
+ /* Try ping buffer if this is first attempt */
+ if (attempt++)
+ return -1;
+ emaclite->use_rx_pong_buffer_next =
+ !emaclite->use_rx_pong_buffer_next;
+ goto try_again;
}
}
- /* Get the length of the frame that arrived */
- switch(((ntohl(in_be32 (baseaddress + XEL_RXBUFF_OFFSET + 0xC))) &
- 0xFFFF0000 ) >> 16) {
- case 0x806:
- length = 42 + 20; /* FIXME size of ARP */
- debug("ARP Packet\n");
- break;
- case 0x800:
- length = 14 + 14 +
- (((ntohl(in_be32 (baseaddress + XEL_RXBUFF_OFFSET +
- 0x10))) & 0xFFFF0000) >> 16);
- /* FIXME size of IP packet */
- debug ("IP Packet\n");
- break;
- default:
- debug("Other Packet\n");
- length = PKTSIZE;
- break;
+
+ /* Read all bytes for ARP packet with 32bit alignment - 48bytes */
+ first_read = ALIGN(ETHER_HDR_SIZE + ARP_HDR_SIZE + ETH_FCS_LEN, 4);
+ xemaclite_alignedread(addr, etherrxbuff, first_read);
+
+ /* Detect real packet size */
+ eth = (struct ethernet_hdr *)etherrxbuff;
+ switch (ntohs(eth->et_protlen)) {
+ case PROT_ARP:
+ length = first_read;
+ debug("ARP Packet %x\n", length);
+ break;
+ case PROT_IP:
+ ip = (struct ip_udp_hdr *)(etherrxbuff + ETHER_HDR_SIZE);
+ length = ntohs(ip->ip_len);
+ length += ETHER_HDR_SIZE + ETH_FCS_LEN;
+ debug("IP Packet %x\n", length);
+ break;
+ default:
+ debug("Other Packet\n");
+ length = PKTSIZE;
+ break;
}
- xemaclite_alignedread((u32 *) (baseaddress + XEL_RXBUFF_OFFSET),
- etherrxbuff, length);
+ /* Read the rest of the packet which is longer then first read */
+ if (length != first_read)
+ xemaclite_alignedread(addr + first_read,
+ etherrxbuff + first_read,
+ length - first_read);
/* Acknowledge the frame */
- reg = in_be32 (baseaddress + XEL_RSR_OFFSET);
+ reg = in_be32(ack);
reg &= ~XEL_RSR_RECV_DONE_MASK;
- out_be32 (baseaddress + XEL_RSR_OFFSET, reg);
+ out_be32(ack, reg);
- debug("Packet receive from 0x%x, length %dB\n", baseaddress, length);
- net_process_received_packet((uchar *)etherrxbuff, length);
+ debug("Packet receive from 0x%p, length %dB\n", addr, length);
+ *packetp = etherrxbuff;
return length;
-
}
-int xilinx_emaclite_initialize(bd_t *bis, unsigned long base_addr,
- int txpp, int rxpp)
+static int emaclite_miiphy_read(struct mii_dev *bus, int addr,
+ int devad, int reg)
{
- struct eth_device *dev;
- struct xemaclite *emaclite;
+ u32 ret;
+ u16 val = 0;
- dev = calloc(1, sizeof(*dev));
- if (dev == NULL)
- return -1;
+ ret = phyread(bus->priv, addr, reg, &val);
+ debug("emaclite: Read MII 0x%x, 0x%x, 0x%x, %d\n", addr, reg, val, ret);
+ return val;
+}
- emaclite = calloc(1, sizeof(struct xemaclite));
- if (emaclite == NULL) {
- free(dev);
- return -1;
- }
+static int emaclite_miiphy_write(struct mii_dev *bus, int addr, int devad,
+ int reg, u16 value)
+{
+ debug("emaclite: Write MII 0x%x, 0x%x, 0x%x\n", addr, reg, value);
+ return phywrite(bus->priv, addr, reg, value);
+}
+
+static int emaclite_probe(struct udevice *dev)
+{
+ struct xemaclite *emaclite = dev_get_priv(dev);
+ int ret;
- dev->priv = emaclite;
+ emaclite->bus = mdio_alloc();
+ emaclite->bus->read = emaclite_miiphy_read;
+ emaclite->bus->write = emaclite_miiphy_write;
+ emaclite->bus->priv = emaclite;
+ strcpy(emaclite->bus->name, "emaclite");
- emaclite->txpp = txpp;
- emaclite->rxpp = rxpp;
+ ret = mdio_register(emaclite->bus);
+ if (ret)
+ return ret;
- sprintf(dev->name, "Xelite.%lx", base_addr);
+ return 0;
+}
- dev->iobase = base_addr;
- dev->init = emaclite_init;
- dev->halt = emaclite_halt;
- dev->send = emaclite_send;
- dev->recv = emaclite_recv;
+static int emaclite_remove(struct udevice *dev)
+{
+ struct xemaclite *emaclite = dev_get_priv(dev);
- eth_register(dev);
+ free(emaclite->phydev);
+ mdio_unregister(emaclite->bus);
+ mdio_free(emaclite->bus);
- return 1;
+ return 0;
}
-#if CONFIG_IS_ENABLED(OF_CONTROL)
-int xilinx_emaclite_of_init(const void *blob)
+static const struct eth_ops emaclite_ops = {
+ .start = emaclite_start,
+ .send = emaclite_send,
+ .recv = emaclite_recv,
+ .stop = emaclite_stop,
+};
+
+static int emaclite_ofdata_to_platdata(struct udevice *dev)
{
+ struct eth_pdata *pdata = dev_get_platdata(dev);
+ struct xemaclite *emaclite = dev_get_priv(dev);
int offset = 0;
- u32 ret = 0;
- u32 reg;
- do {
- offset = fdt_node_offset_by_compatible(blob, offset,
- "xlnx,xps-ethernetlite-1.00.a");
- if (offset != -1) {
- reg = fdtdec_get_addr(blob, offset, "reg");
- if (reg != FDT_ADDR_T_NONE) {
- u32 rxpp = fdtdec_get_int(blob, offset,
- "xlnx,rx-ping-pong", 0);
- u32 txpp = fdtdec_get_int(blob, offset,
- "xlnx,tx-ping-pong", 0);
- ret |= xilinx_emaclite_initialize(NULL, reg,
- txpp, rxpp);
- } else {
- debug("EMACLITE: Can't get base address\n");
- return -1;
- }
- }
- } while (offset != -1);
+ pdata->iobase = (phys_addr_t)dev_get_addr(dev);
+ emaclite->regs = (struct emaclite_regs *)pdata->iobase;
+
+ emaclite->phyaddr = -1;
+
+ offset = fdtdec_lookup_phandle(gd->fdt_blob, dev->of_offset,
+ "phy-handle");
+ if (offset > 0)
+ emaclite->phyaddr = fdtdec_get_int(gd->fdt_blob, offset,
+ "reg", -1);
+
+ emaclite->txpp = fdtdec_get_int(gd->fdt_blob, dev->of_offset,
+ "xlnx,tx-ping-pong", 0);
+ emaclite->rxpp = fdtdec_get_int(gd->fdt_blob, dev->of_offset,
+ "xlnx,rx-ping-pong", 0);
- return ret;
+ printf("EMACLITE: %lx, phyaddr %d, %d/%d\n", (ulong)emaclite->regs,
+ emaclite->phyaddr, emaclite->txpp, emaclite->rxpp);
+
+ return 0;
}
-#endif
+
+static const struct udevice_id emaclite_ids[] = {
+ { .compatible = "xlnx,xps-ethernetlite-1.00.a" },
+ { }
+};
+
+U_BOOT_DRIVER(emaclite) = {
+ .name = "emaclite",
+ .id = UCLASS_ETH,
+ .of_match = emaclite_ids,
+ .ofdata_to_platdata = emaclite_ofdata_to_platdata,
+ .probe = emaclite_probe,
+ .remove = emaclite_remove,
+ .ops = &emaclite_ops,
+ .priv_auto_alloc_size = sizeof(struct xemaclite),
+ .platdata_auto_alloc_size = sizeof(struct eth_pdata),
+};
diff --git a/drivers/net/xilinx_ll_temac.c b/drivers/net/xilinx_ll_temac.c
index 7cc86571e49..ca09546ab59 100644
--- a/drivers/net/xilinx_ll_temac.c
+++ b/drivers/net/xilinx_ll_temac.c
@@ -303,7 +303,8 @@ int xilinx_ll_temac_initialize(bd_t *bis, struct ll_temac_info *devinf)
if (devinf->devname) {
strncpy(dev->name, devinf->devname, sizeof(dev->name));
} else {
- snprintf(dev->name, sizeof(dev->name), "lltemac.%lx", devinf->base_addr);
+ snprintf(dev->name, sizeof(dev->name), "ll_tem.%lx",
+ devinf->base_addr);
devinf->devname = dev->name;
}
diff --git a/drivers/net/zynq_gem.c b/drivers/net/zynq_gem.c
index 97e30f3be04..b3821c31a91 100644
--- a/drivers/net/zynq_gem.c
+++ b/drivers/net/zynq_gem.c
@@ -57,7 +57,11 @@ DECLARE_GLOBAL_DATA_PTR;
#define ZYNQ_GEM_NWCFG_SPEED1000 0x000000400 /* 1Gbps operation */
#define ZYNQ_GEM_NWCFG_FDEN 0x000000002 /* Full Duplex mode */
#define ZYNQ_GEM_NWCFG_FSREM 0x000020000 /* FCS removal */
+#ifdef CONFIG_ARM64
+#define ZYNQ_GEM_NWCFG_MDCCLKDIV 0x000100000 /* Div pclk by 64, max 160MHz */
+#else
#define ZYNQ_GEM_NWCFG_MDCCLKDIV 0x0000c0000 /* Div pclk by 48, max 120MHz */
+#endif
#ifdef CONFIG_ARM64
# define ZYNQ_GEM_DBUS_WIDTH (1 << 21) /* 64 bit bus */
diff --git a/drivers/pci/pci-uclass.c b/drivers/pci/pci-uclass.c
index 61292d72bda..d01bfc12e44 100644
--- a/drivers/pci/pci-uclass.c
+++ b/drivers/pci/pci-uclass.c
@@ -1241,3 +1241,18 @@ U_BOOT_DRIVER(pci_generic_drv) = {
.id = UCLASS_PCI_GENERIC,
.of_match = pci_generic_ids,
};
+
+void pci_init(void)
+{
+ struct udevice *bus;
+
+ /*
+ * Enumerate all known controller devices. Enumeration has the side-
+ * effect of probing them, so PCIe devices will be enumerated too.
+ */
+ for (uclass_first_device(UCLASS_PCI, &bus);
+ bus;
+ uclass_next_device(&bus)) {
+ ;
+ }
+}
diff --git a/drivers/pci/pci_tegra.c b/drivers/pci/pci_tegra.c
index 5a7fefed5e1..5dadf6fa62a 100644
--- a/drivers/pci/pci_tegra.c
+++ b/drivers/pci/pci_tegra.c
@@ -465,7 +465,11 @@ static int tegra_pcie_parse_dt(const void *fdt, int node, enum tegra_pci_id id,
return err;
}
- tegra_pcie_board_init();
+ err = tegra_pcie_board_init();
+ if (err < 0) {
+ error("tegra_pcie_board_init() failed: err=%d", err);
+ return err;
+ }
pcie->phy = tegra_xusb_phy_get(TEGRA_XUSB_PADCTL_PCIE);
if (pcie->phy) {
diff --git a/drivers/pinctrl/Kconfig b/drivers/pinctrl/Kconfig
index 57e6142c501..5dd2dddb44a 100644
--- a/drivers/pinctrl/Kconfig
+++ b/drivers/pinctrl/Kconfig
@@ -131,6 +131,16 @@ config PINCTRL_SANDBOX
actually does nothing but print debug messages when pinctrl
operations are invoked.
+config PIC32_PINCTRL
+ bool "Microchip PIC32 pin-control and pin-mux driver"
+ depends on DM && MACH_PIC32
+ default y
+ help
+ Supports individual pin selection and configuration for each remappable
+ peripheral available on Microchip PIC32 SoCs. This driver is controlled
+ by a device tree node which contains both GPIO defintion and pin control
+ functions.
+
endif
source "drivers/pinctrl/uniphier/Kconfig"
diff --git a/drivers/pinctrl/Makefile b/drivers/pinctrl/Makefile
index 70d25dc9813..b4f46500ebb 100644
--- a/drivers/pinctrl/Makefile
+++ b/drivers/pinctrl/Makefile
@@ -9,3 +9,4 @@ obj-$(CONFIG_ARCH_ROCKCHIP) += rockchip/
obj-$(CONFIG_PINCTRL_SANDBOX) += pinctrl-sandbox.o
obj-$(CONFIG_ARCH_UNIPHIER) += uniphier/
+obj-$(CONFIG_PIC32_PINCTRL) += pinctrl_pic32.o
diff --git a/drivers/pinctrl/pinctrl_pic32.c b/drivers/pinctrl/pinctrl_pic32.c
new file mode 100644
index 00000000000..5cf97ecec86
--- /dev/null
+++ b/drivers/pinctrl/pinctrl_pic32.c
@@ -0,0 +1,363 @@
+/*
+ * Pinctrl driver for Microchip PIC32 SoCs
+ * Copyright (c) 2015 Microchip Technology Inc.
+ * Written by Purna Chandra Mandal <purna.mandal@microchip.com>
+ *
+ * SPDX-License-Identifier: GPL-2.0+
+ */
+#include <common.h>
+#include <dm.h>
+#include <errno.h>
+#include <asm/io.h>
+#include <dm/pinctrl.h>
+#include <dm/root.h>
+#include <mach/pic32.h>
+
+DECLARE_GLOBAL_DATA_PTR;
+
+/* PIC32 has 10 peripheral ports with 16 pins each.
+ * Ports are marked PORTA-PORTK or PORT0-PORT9.
+ */
+enum {
+ PIC32_PORT_A = 0,
+ PIC32_PORT_B = 1,
+ PIC32_PORT_C = 2,
+ PIC32_PORT_D = 3,
+ PIC32_PORT_E = 4,
+ PIC32_PORT_F = 5,
+ PIC32_PORT_G = 6,
+ PIC32_PORT_H = 7,
+ PIC32_PORT_J = 8, /* no PORT_I */
+ PIC32_PORT_K = 9,
+ PIC32_PINS_PER_PORT = 16,
+};
+
+#define PIN_CONFIG_PIC32_DIGITAL (PIN_CONFIG_END + 1)
+#define PIN_CONFIG_PIC32_ANALOG (PIN_CONFIG_END + 2)
+
+/* pin configuration descriptor */
+struct pic32_pin_config {
+ u16 port; /* port number */
+ u16 pin; /* pin number in the port */
+ u32 config; /* one of PIN_CONFIG_* */
+};
+#define PIN_CONFIG(_prt, _pin, _cfg) \
+ {.port = (_prt), .pin = (_pin), .config = (_cfg), }
+
+/* In PIC32 muxing is performed at pin-level through two
+ * different set of registers - one set for input functions,
+ * and other for output functions.
+ * Pin configuration is handled through port register.
+ */
+/* Port control registers */
+struct pic32_reg_port {
+ struct pic32_reg_atomic ansel;
+ struct pic32_reg_atomic tris;
+ struct pic32_reg_atomic port;
+ struct pic32_reg_atomic lat;
+ struct pic32_reg_atomic odc;
+ struct pic32_reg_atomic cnpu;
+ struct pic32_reg_atomic cnpd;
+ struct pic32_reg_atomic cncon;
+ struct pic32_reg_atomic unused[8];
+};
+
+/* Input function mux registers */
+struct pic32_reg_in_mux {
+ u32 unused0;
+ u32 int1[4];
+ u32 unused1;
+ u32 t2ck[8];
+ u32 ic1[9];
+ u32 unused2;
+ u32 ocfar;
+ u32 unused3;
+ u32 u1rx;
+ u32 u1cts;
+ u32 u2rx;
+ u32 u2cts;
+ u32 u3rx;
+ u32 u3cts;
+ u32 u4rx;
+ u32 u4cts;
+ u32 u5rx;
+ u32 u5cts;
+ u32 u6rx;
+ u32 u6cts;
+ u32 unused4;
+ u32 sdi1;
+ u32 ss1;
+ u32 unused5;
+ u32 sdi2;
+ u32 ss2;
+ u32 unused6;
+ u32 sdi3;
+ u32 ss3;
+ u32 unused7;
+ u32 sdi4;
+ u32 ss4;
+ u32 unused8;
+ u32 sdi5;
+ u32 ss5;
+ u32 unused9;
+ u32 sdi6;
+ u32 ss6;
+ u32 c1rx;
+ u32 c2rx;
+ u32 refclki1;
+ u32 refclki2;
+ u32 refclki3;
+ u32 refclki4;
+};
+
+/* output mux register offset */
+#define PPS_OUT(__port, __pin) \
+ (((__port) * PIC32_PINS_PER_PORT + (__pin)) << 2)
+
+
+struct pic32_pinctrl_priv {
+ struct pic32_reg_in_mux *mux_in; /* mux input function */
+ struct pic32_reg_port *pinconf; /* pin configuration*/
+ void __iomem *mux_out; /* mux output function */
+};
+
+enum {
+ PERIPH_ID_UART1,
+ PERIPH_ID_UART2,
+ PERIPH_ID_ETH,
+ PERIPH_ID_USB,
+ PERIPH_ID_SDHCI,
+ PERIPH_ID_I2C1,
+ PERIPH_ID_I2C2,
+ PERIPH_ID_SPI1,
+ PERIPH_ID_SPI2,
+ PERIPH_ID_SQI,
+};
+
+static int pic32_pinconfig_one(struct pic32_pinctrl_priv *priv,
+ u32 port_nr, u32 pin, u32 param)
+{
+ struct pic32_reg_port *port;
+
+ port = &priv->pinconf[port_nr];
+ switch (param) {
+ case PIN_CONFIG_PIC32_DIGITAL:
+ writel(BIT(pin), &port->ansel.clr);
+ break;
+ case PIN_CONFIG_PIC32_ANALOG:
+ writel(BIT(pin), &port->ansel.set);
+ break;
+ case PIN_CONFIG_INPUT_ENABLE:
+ writel(BIT(pin), &port->tris.set);
+ break;
+ case PIN_CONFIG_OUTPUT:
+ writel(BIT(pin), &port->tris.clr);
+ break;
+ case PIN_CONFIG_BIAS_PULL_UP:
+ writel(BIT(pin), &port->cnpu.set);
+ break;
+ case PIN_CONFIG_BIAS_PULL_DOWN:
+ writel(BIT(pin), &port->cnpd.set);
+ break;
+ case PIN_CONFIG_DRIVE_OPEN_DRAIN:
+ writel(BIT(pin), &port->odc.set);
+ break;
+ default:
+ break;
+ }
+
+ return 0;
+}
+
+static int pic32_pinconfig_set(struct pic32_pinctrl_priv *priv,
+ const struct pic32_pin_config *list, int count)
+{
+ int i;
+
+ for (i = 0 ; i < count; i++)
+ pic32_pinconfig_one(priv, list[i].port,
+ list[i].pin, list[i].config);
+
+ return 0;
+}
+
+static void pic32_eth_pin_config(struct udevice *dev)
+{
+ struct pic32_pinctrl_priv *priv = dev_get_priv(dev);
+ const struct pic32_pin_config configs[] = {
+ /* EMDC - D11 */
+ PIN_CONFIG(PIC32_PORT_D, 11, PIN_CONFIG_PIC32_DIGITAL),
+ PIN_CONFIG(PIC32_PORT_D, 11, PIN_CONFIG_OUTPUT),
+ /* ETXEN */
+ PIN_CONFIG(PIC32_PORT_D, 6, PIN_CONFIG_PIC32_DIGITAL),
+ PIN_CONFIG(PIC32_PORT_D, 6, PIN_CONFIG_OUTPUT),
+ /* ECRSDV */
+ PIN_CONFIG(PIC32_PORT_H, 13, PIN_CONFIG_PIC32_DIGITAL),
+ PIN_CONFIG(PIC32_PORT_H, 13, PIN_CONFIG_INPUT_ENABLE),
+ /* ERXD0 */
+ PIN_CONFIG(PIC32_PORT_H, 8, PIN_CONFIG_PIC32_DIGITAL),
+ PIN_CONFIG(PIC32_PORT_H, 8, PIN_CONFIG_INPUT_ENABLE),
+ PIN_CONFIG(PIC32_PORT_H, 8, PIN_CONFIG_BIAS_PULL_DOWN),
+ /* ERXD1 */
+ PIN_CONFIG(PIC32_PORT_H, 5, PIN_CONFIG_PIC32_DIGITAL),
+ PIN_CONFIG(PIC32_PORT_H, 5, PIN_CONFIG_INPUT_ENABLE),
+ PIN_CONFIG(PIC32_PORT_H, 5, PIN_CONFIG_BIAS_PULL_DOWN),
+ /* EREFCLK */
+ PIN_CONFIG(PIC32_PORT_J, 11, PIN_CONFIG_PIC32_DIGITAL),
+ PIN_CONFIG(PIC32_PORT_J, 11, PIN_CONFIG_INPUT_ENABLE),
+ /* ETXD1 */
+ PIN_CONFIG(PIC32_PORT_J, 9, PIN_CONFIG_PIC32_DIGITAL),
+ PIN_CONFIG(PIC32_PORT_J, 9, PIN_CONFIG_OUTPUT),
+ /* ETXD0 */
+ PIN_CONFIG(PIC32_PORT_J, 8, PIN_CONFIG_PIC32_DIGITAL),
+ PIN_CONFIG(PIC32_PORT_J, 8, PIN_CONFIG_OUTPUT),
+ /* EMDIO */
+ PIN_CONFIG(PIC32_PORT_J, 1, PIN_CONFIG_PIC32_DIGITAL),
+ PIN_CONFIG(PIC32_PORT_J, 1, PIN_CONFIG_INPUT_ENABLE),
+ /* ERXERR */
+ PIN_CONFIG(PIC32_PORT_F, 3, PIN_CONFIG_PIC32_DIGITAL),
+ PIN_CONFIG(PIC32_PORT_F, 3, PIN_CONFIG_INPUT_ENABLE),
+ };
+
+ pic32_pinconfig_set(priv, configs, ARRAY_SIZE(configs));
+}
+
+static int pic32_pinctrl_request(struct udevice *dev, int func, int flags)
+{
+ struct pic32_pinctrl_priv *priv = dev_get_priv(dev);
+
+ switch (func) {
+ case PERIPH_ID_UART2:
+ /* PPS for U2 RX/TX */
+ writel(0x02, priv->mux_out + PPS_OUT(PIC32_PORT_G, 9));
+ writel(0x05, &priv->mux_in->u2rx); /* B0 */
+ /* set digital mode */
+ pic32_pinconfig_one(priv, PIC32_PORT_G, 9,
+ PIN_CONFIG_PIC32_DIGITAL);
+ pic32_pinconfig_one(priv, PIC32_PORT_B, 0,
+ PIN_CONFIG_PIC32_DIGITAL);
+ break;
+ case PERIPH_ID_ETH:
+ pic32_eth_pin_config(dev);
+ break;
+ default:
+ debug("%s: unknown-unhandled case\n", __func__);
+ break;
+ }
+
+ return 0;
+}
+
+static int pic32_pinctrl_get_periph_id(struct udevice *dev,
+ struct udevice *periph)
+{
+ int ret;
+ u32 cell[2];
+
+ ret = fdtdec_get_int_array(gd->fdt_blob, periph->of_offset,
+ "interrupts", cell, ARRAY_SIZE(cell));
+ if (ret < 0)
+ return -EINVAL;
+
+ /* interrupt number */
+ switch (cell[0]) {
+ case 112 ... 114:
+ return PERIPH_ID_UART1;
+ case 145 ... 147:
+ return PERIPH_ID_UART2;
+ case 109 ... 111:
+ return PERIPH_ID_SPI1;
+ case 142 ... 144:
+ return PERIPH_ID_SPI2;
+ case 115 ... 117:
+ return PERIPH_ID_I2C1;
+ case 148 ... 150:
+ return PERIPH_ID_I2C2;
+ case 132 ... 133:
+ return PERIPH_ID_USB;
+ case 169:
+ return PERIPH_ID_SQI;
+ case 191:
+ return PERIPH_ID_SDHCI;
+ case 153:
+ return PERIPH_ID_ETH;
+ default:
+ break;
+ }
+
+ return -ENOENT;
+}
+
+static int pic32_pinctrl_set_state_simple(struct udevice *dev,
+ struct udevice *periph)
+{
+ int func;
+
+ debug("%s: periph %s\n", __func__, periph->name);
+ func = pic32_pinctrl_get_periph_id(dev, periph);
+ if (func < 0)
+ return func;
+ return pic32_pinctrl_request(dev, func, 0);
+}
+
+static struct pinctrl_ops pic32_pinctrl_ops = {
+ .set_state_simple = pic32_pinctrl_set_state_simple,
+ .request = pic32_pinctrl_request,
+ .get_periph_id = pic32_pinctrl_get_periph_id,
+};
+
+static int pic32_pinctrl_probe(struct udevice *dev)
+{
+ struct pic32_pinctrl_priv *priv = dev_get_priv(dev);
+ struct fdt_resource res;
+ void *fdt = (void *)gd->fdt_blob;
+ int node = dev->of_offset;
+ int ret;
+
+ ret = fdt_get_named_resource(fdt, node, "reg", "reg-names",
+ "ppsin", &res);
+ if (ret < 0) {
+ printf("pinctrl: resource \"ppsin\" not found\n");
+ return ret;
+ }
+ priv->mux_in = ioremap(res.start, fdt_resource_size(&res));
+
+ ret = fdt_get_named_resource(fdt, node, "reg", "reg-names",
+ "ppsout", &res);
+ if (ret < 0) {
+ printf("pinctrl: resource \"ppsout\" not found\n");
+ return ret;
+ }
+ priv->mux_out = ioremap(res.start, fdt_resource_size(&res));
+
+ ret = fdt_get_named_resource(fdt, node, "reg", "reg-names",
+ "port", &res);
+ if (ret < 0) {
+ printf("pinctrl: resource \"port\" not found\n");
+ return ret;
+ }
+ priv->pinconf = ioremap(res.start, fdt_resource_size(&res));
+
+ return 0;
+}
+
+static int pic32_pinctrl_bind(struct udevice *dev)
+{
+ /* scan child GPIO banks */
+ return dm_scan_fdt_node(dev, gd->fdt_blob, dev->of_offset, false);
+}
+
+static const struct udevice_id pic32_pinctrl_ids[] = {
+ { .compatible = "microchip,pic32mzda-pinctrl" },
+ { }
+};
+
+U_BOOT_DRIVER(pinctrl_pic32) = {
+ .name = "pinctrl_pic32",
+ .id = UCLASS_PINCTRL,
+ .of_match = pic32_pinctrl_ids,
+ .ops = &pic32_pinctrl_ops,
+ .probe = pic32_pinctrl_probe,
+ .bind = pic32_pinctrl_bind,
+ .priv_auto_alloc_size = sizeof(struct pic32_pinctrl_priv),
+};
diff --git a/drivers/serial/Kconfig b/drivers/serial/Kconfig
index 83068cfd50f..fac317610e2 100644
--- a/drivers/serial/Kconfig
+++ b/drivers/serial/Kconfig
@@ -112,6 +112,13 @@ config DEBUG_UART_S5P
will need to provide parameters to make this work. The driver will
be available until the real driver-model serial is running.
+config DEBUG_UART_UARTLITE
+ bool "Xilinx Uartlite"
+ help
+ Select this to enable a debug UART using the serial_uartlite driver.
+ You will need to provide parameters to make this work. The driver will
+ be available until the real driver-model serial is running.
+
config DEBUG_UART_ZYNQ
bool "Xilinx Zynq"
help
@@ -143,6 +150,14 @@ config DEBUG_UART_PL011
work. The driver will be available until the real driver model
serial is running.
+config DEBUG_UART_PIC32
+ bool "Microchip PIC32"
+ depends on PIC32_SERIAL
+ help
+ Select this to enable a debug UART using the serial_pic32 driver. You
+ will need to provide parameters to make this work. The driver will
+ be available until the real driver model serial is running.
+
endchoice
config DEBUG_UART_BASE
@@ -234,6 +249,13 @@ config FSL_LPUART
Select this to enable a Low Power UART for Freescale VF610 and
QorIQ Layerscape devices.
+config PIC32_SERIAL
+ bool "Support for Microchip PIC32 on-chip UART"
+ depends on DM_SERIAL && MACH_PIC32
+ default y
+ help
+ Support for the UART found on Microchip PIC32 SoC's.
+
config SYS_NS16550
bool "NS16550 UART or compatible"
help
@@ -271,4 +293,11 @@ config UNIPHIER_SERIAL
If you have a UniPhier based board and want to use the on-chip
serial ports, say Y to this option. If unsure, say N.
+config XILINX_UARTLITE
+ bool "Xilinx Uarlite support"
+ depends on DM_SERIAL && (MICROBLAZE || ARCH_ZYNQ || ARCH_ZYNQMP || 4xx)
+ help
+ If you have a Xilinx based board and want to use the uartlite
+ serial ports, say Y to this option. If unsure, say N.
+
endmenu
diff --git a/drivers/serial/Makefile b/drivers/serial/Makefile
index dd871478ea9..57cd38bf6e4 100644
--- a/drivers/serial/Makefile
+++ b/drivers/serial/Makefile
@@ -41,6 +41,7 @@ obj-$(CONFIG_MXS_AUART) += mxs_auart.o
obj-$(CONFIG_ARC_SERIAL) += serial_arc.o
obj-$(CONFIG_UNIPHIER_SERIAL) += serial_uniphier.o
obj-$(CONFIG_STM32_SERIAL) += serial_stm32.o
+obj-$(CONFIG_PIC32_SERIAL) += serial_pic32.o
ifndef CONFIG_SPL_BUILD
obj-$(CONFIG_USB_TTY) += usbtty.o
diff --git a/drivers/serial/serial_pic32.c b/drivers/serial/serial_pic32.c
new file mode 100644
index 00000000000..af9fbbf6554
--- /dev/null
+++ b/drivers/serial/serial_pic32.c
@@ -0,0 +1,198 @@
+/*
+ * (c) 2015 Paul Thacker <paul.thacker@microchip.com>
+ *
+ * SPDX-License-Identifier: GPL-2.0+
+ *
+ */
+#include <common.h>
+#include <clk.h>
+#include <dm.h>
+#include <serial.h>
+#include <wait_bit.h>
+#include <mach/pic32.h>
+#include <dt-bindings/clock/microchip,clock.h>
+
+DECLARE_GLOBAL_DATA_PTR;
+
+/* UART Control Registers */
+#define U_MOD 0x00
+#define U_MODCLR (U_MOD + _CLR_OFFSET)
+#define U_MODSET (U_MOD + _SET_OFFSET)
+#define U_STA 0x10
+#define U_STACLR (U_STA + _CLR_OFFSET)
+#define U_STASET (U_STA + _SET_OFFSET)
+#define U_TXR 0x20
+#define U_RXR 0x30
+#define U_BRG 0x40
+
+/* U_MOD bits */
+#define UART_ENABLE BIT(15)
+
+/* U_STA bits */
+#define UART_RX_ENABLE BIT(12)
+#define UART_TX_BRK BIT(11)
+#define UART_TX_ENABLE BIT(10)
+#define UART_TX_FULL BIT(9)
+#define UART_TX_EMPTY BIT(8)
+#define UART_RX_OVER BIT(1)
+#define UART_RX_DATA_AVAIL BIT(0)
+
+struct pic32_uart_priv {
+ void __iomem *base;
+ ulong uartclk;
+};
+
+/*
+ * Initialize the serial port with the given baudrate.
+ * The settings are always 8 data bits, no parity, 1 stop bit, no start bits.
+ */
+static int pic32_serial_init(void __iomem *base, ulong clk, u32 baudrate)
+{
+ u32 div = DIV_ROUND_CLOSEST(clk, baudrate * 16);
+
+ /* wait for TX FIFO to empty */
+ wait_for_bit(__func__, base + U_STA, UART_TX_EMPTY,
+ true, CONFIG_SYS_HZ, false);
+
+ /* send break */
+ writel(UART_TX_BRK, base + U_STASET);
+
+ /* disable and clear mode */
+ writel(0, base + U_MOD);
+ writel(0, base + U_STA);
+
+ /* set baud rate generator */
+ writel(div - 1, base + U_BRG);
+
+ /* enable the UART for TX and RX */
+ writel(UART_TX_ENABLE | UART_RX_ENABLE, base + U_STASET);
+
+ /* enable the UART */
+ writel(UART_ENABLE, base + U_MODSET);
+ return 0;
+}
+
+/* Check whether any char pending in RX fifo */
+static int pic32_uart_pending_input(void __iomem *base)
+{
+ /* check if rx buffer overrun error has occurred */
+ if (readl(base + U_STA) & UART_RX_OVER) {
+ readl(base + U_RXR);
+
+ /* clear overrun error to keep receiving */
+ writel(UART_RX_OVER, base + U_STACLR);
+ }
+
+ /* In PIC32 there is no way to know number of outstanding
+ * chars in rx-fifo. Only it can be known whether there is any.
+ */
+ return readl(base + U_STA) & UART_RX_DATA_AVAIL;
+}
+
+static int pic32_uart_pending(struct udevice *dev, bool input)
+{
+ struct pic32_uart_priv *priv = dev_get_priv(dev);
+
+ if (input)
+ return pic32_uart_pending_input(priv->base);
+
+ return !(readl(priv->base + U_STA) & UART_TX_EMPTY);
+}
+
+static int pic32_uart_setbrg(struct udevice *dev, int baudrate)
+{
+ struct pic32_uart_priv *priv = dev_get_priv(dev);
+
+ return pic32_serial_init(priv->base, priv->uartclk, baudrate);
+}
+
+static int pic32_uart_putc(struct udevice *dev, const char ch)
+{
+ struct pic32_uart_priv *priv = dev_get_priv(dev);
+
+ /* Check if Tx FIFO is full */
+ if (readl(priv->base + U_STA) & UART_TX_FULL)
+ return -EAGAIN;
+
+ /* pump the char to tx buffer */
+ writel(ch, priv->base + U_TXR);
+
+ return 0;
+}
+
+static int pic32_uart_getc(struct udevice *dev)
+{
+ struct pic32_uart_priv *priv = dev_get_priv(dev);
+
+ /* return error if RX fifo is empty */
+ if (!pic32_uart_pending_input(priv->base))
+ return -EAGAIN;
+
+ /* read the character from rx buffer */
+ return readl(priv->base + U_RXR) & 0xff;
+}
+
+static int pic32_uart_probe(struct udevice *dev)
+{
+ struct pic32_uart_priv *priv = dev_get_priv(dev);
+ struct udevice *clkdev;
+ fdt_addr_t addr;
+ fdt_size_t size;
+ int ret;
+
+ /* get address */
+ addr = fdtdec_get_addr_size(gd->fdt_blob, dev->of_offset, "reg", &size);
+ if (addr == FDT_ADDR_T_NONE)
+ return -EINVAL;
+
+ priv->base = ioremap(addr, size);
+
+ /* get clock rate */
+ ret = clk_get_by_index(dev, 0, &clkdev);
+ if (ret < 0)
+ return ret;
+ priv->uartclk = clk_get_periph_rate(clkdev, ret);
+
+ /* initialize serial */
+ return pic32_serial_init(priv->base, priv->uartclk, CONFIG_BAUDRATE);
+}
+
+static const struct dm_serial_ops pic32_uart_ops = {
+ .putc = pic32_uart_putc,
+ .pending = pic32_uart_pending,
+ .getc = pic32_uart_getc,
+ .setbrg = pic32_uart_setbrg,
+};
+
+static const struct udevice_id pic32_uart_ids[] = {
+ { .compatible = "microchip,pic32mzda-uart" },
+ {}
+};
+
+U_BOOT_DRIVER(pic32_serial) = {
+ .name = "pic32-uart",
+ .id = UCLASS_SERIAL,
+ .of_match = pic32_uart_ids,
+ .probe = pic32_uart_probe,
+ .ops = &pic32_uart_ops,
+ .flags = DM_FLAG_PRE_RELOC,
+ .priv_auto_alloc_size = sizeof(struct pic32_uart_priv),
+};
+
+#ifdef CONFIG_DEBUG_UART_PIC32
+#include <debug_uart.h>
+
+static inline void _debug_uart_init(void)
+{
+ void __iomem *base = (void __iomem *)CONFIG_DEBUG_UART_BASE;
+
+ pic32_serial_init(base, CONFIG_DEBUG_UART_CLOCK, CONFIG_BAUDRATE);
+}
+
+static inline void _debug_uart_putc(int ch)
+{
+ writel(ch, CONFIG_DEBUG_UART_BASE + U_TXR);
+}
+
+DEBUG_UART_FUNCS
+#endif
diff --git a/drivers/serial/serial_xuartlite.c b/drivers/serial/serial_xuartlite.c
index 988438e7547..a2e93039257 100644
--- a/drivers/serial/serial_xuartlite.c
+++ b/drivers/serial/serial_xuartlite.c
@@ -1,5 +1,5 @@
/*
- * (C) Copyright 2008-2011 Michal Simek <monstr@monstr.eu>
+ * (C) Copyright 2008 - 2015 Michal Simek <monstr@monstr.eu>
* Clean driver and add xilinx constant from header file
*
* (C) Copyright 2004 Atmark Techno, Inc.
@@ -10,13 +10,17 @@
#include <config.h>
#include <common.h>
+#include <dm.h>
#include <asm/io.h>
#include <linux/compiler.h>
#include <serial.h>
-#define SR_TX_FIFO_FULL 0x08 /* transmit FIFO full */
-#define SR_RX_FIFO_VALID_DATA 0x01 /* data in receive FIFO */
-#define SR_RX_FIFO_FULL 0x02 /* receive FIFO full */
+DECLARE_GLOBAL_DATA_PTR;
+
+#define SR_TX_FIFO_FULL BIT(3) /* transmit FIFO full */
+#define SR_TX_FIFO_EMPTY BIT(2) /* transmit FIFO empty */
+#define SR_RX_FIFO_VALID_DATA BIT(0) /* data in receive FIFO */
+#define SR_RX_FIFO_FULL BIT(1) /* receive FIFO full */
#define ULITE_CONTROL_RST_TX 0x01
#define ULITE_CONTROL_RST_RX 0x02
@@ -28,135 +32,111 @@ struct uartlite {
unsigned int control;
};
-static struct uartlite *userial_ports[4] = {
-#ifdef XILINX_UARTLITE_BASEADDR
- [0] = (struct uartlite *)XILINX_UARTLITE_BASEADDR,
-#endif
-#ifdef XILINX_UARTLITE_BASEADDR1
- [1] = (struct uartlite *)XILINX_UARTLITE_BASEADDR1,
-#endif
-#ifdef XILINX_UARTLITE_BASEADDR2
- [2] = (struct uartlite *)XILINX_UARTLITE_BASEADDR2,
-#endif
-#ifdef XILINX_UARTLITE_BASEADDR3
- [3] = (struct uartlite *)XILINX_UARTLITE_BASEADDR3
-#endif
+struct uartlite_platdata {
+ struct uartlite *regs;
};
-static void uartlite_serial_putc(const char c, const int port)
+static int uartlite_serial_putc(struct udevice *dev, const char ch)
{
- struct uartlite *regs = userial_ports[port];
+ struct uartlite_platdata *plat = dev_get_platdata(dev);
+ struct uartlite *regs = plat->regs;
- if (c == '\n')
- uartlite_serial_putc('\r', port);
+ if (in_be32(&regs->status) & SR_TX_FIFO_FULL)
+ return -EAGAIN;
- while (in_be32(&regs->status) & SR_TX_FIFO_FULL)
- ;
- out_be32(&regs->tx_fifo, c & 0xff);
-}
+ out_be32(&regs->tx_fifo, ch & 0xff);
-static void uartlite_serial_puts(const char *s, const int port)
-{
- while (*s)
- uartlite_serial_putc(*s++, port);
+ return 0;
}
-static int uartlite_serial_getc(const int port)
+static int uartlite_serial_getc(struct udevice *dev)
{
- struct uartlite *regs = userial_ports[port];
+ struct uartlite_platdata *plat = dev_get_platdata(dev);
+ struct uartlite *regs = plat->regs;
+
+ if (!(in_be32(&regs->status) & SR_RX_FIFO_VALID_DATA))
+ return -EAGAIN;
- while (!(in_be32(&regs->status) & SR_RX_FIFO_VALID_DATA))
- ;
return in_be32(&regs->rx_fifo) & 0xff;
}
-static int uartlite_serial_tstc(const int port)
+static int uartlite_serial_pending(struct udevice *dev, bool input)
{
- struct uartlite *regs = userial_ports[port];
+ struct uartlite_platdata *plat = dev_get_platdata(dev);
+ struct uartlite *regs = plat->regs;
+
+ if (input)
+ return in_be32(&regs->status) & SR_RX_FIFO_VALID_DATA;
- return in_be32(&regs->status) & SR_RX_FIFO_VALID_DATA;
+ return !(in_be32(&regs->status) & SR_TX_FIFO_EMPTY);
}
-static int uartlite_serial_init(const int port)
+static int uartlite_serial_probe(struct udevice *dev)
{
- struct uartlite *regs = userial_ports[port];
+ struct uartlite_platdata *plat = dev_get_platdata(dev);
+ struct uartlite *regs = plat->regs;
- if (regs) {
- out_be32(&regs->control, 0);
- out_be32(&regs->control,
- ULITE_CONTROL_RST_RX | ULITE_CONTROL_RST_TX);
- in_be32(&regs->control);
- return 0;
- }
+ out_be32(&regs->control, 0);
+ out_be32(&regs->control, ULITE_CONTROL_RST_RX | ULITE_CONTROL_RST_TX);
+ in_be32(&regs->control);
- return -1;
+ return 0;
}
-/* Multi serial device functions */
-#define DECLARE_ESERIAL_FUNCTIONS(port) \
- static int userial##port##_init(void) \
- { return uartlite_serial_init(port); } \
- static void userial##port##_setbrg(void) {} \
- static int userial##port##_getc(void) \
- { return uartlite_serial_getc(port); } \
- static int userial##port##_tstc(void) \
- { return uartlite_serial_tstc(port); } \
- static void userial##port##_putc(const char c) \
- { uartlite_serial_putc(c, port); } \
- static void userial##port##_puts(const char *s) \
- { uartlite_serial_puts(s, port); }
-
-/* Serial device descriptor */
-#define INIT_ESERIAL_STRUCTURE(port, __name) { \
- .name = __name, \
- .start = userial##port##_init, \
- .stop = NULL, \
- .setbrg = userial##port##_setbrg, \
- .getc = userial##port##_getc, \
- .tstc = userial##port##_tstc, \
- .putc = userial##port##_putc, \
- .puts = userial##port##_puts, \
+static int uartlite_serial_ofdata_to_platdata(struct udevice *dev)
+{
+ struct uartlite_platdata *plat = dev_get_platdata(dev);
+
+ plat->regs = (struct uartlite *)dev_get_addr(dev);
+
+ return 0;
}
-DECLARE_ESERIAL_FUNCTIONS(0);
-struct serial_device uartlite_serial0_device =
- INIT_ESERIAL_STRUCTURE(0, "ttyUL0");
-DECLARE_ESERIAL_FUNCTIONS(1);
-struct serial_device uartlite_serial1_device =
- INIT_ESERIAL_STRUCTURE(1, "ttyUL1");
-DECLARE_ESERIAL_FUNCTIONS(2);
-struct serial_device uartlite_serial2_device =
- INIT_ESERIAL_STRUCTURE(2, "ttyUL2");
-DECLARE_ESERIAL_FUNCTIONS(3);
-struct serial_device uartlite_serial3_device =
- INIT_ESERIAL_STRUCTURE(3, "ttyUL3");
-
-__weak struct serial_device *default_serial_console(void)
+static const struct dm_serial_ops uartlite_serial_ops = {
+ .putc = uartlite_serial_putc,
+ .pending = uartlite_serial_pending,
+ .getc = uartlite_serial_getc,
+};
+
+static const struct udevice_id uartlite_serial_ids[] = {
+ { .compatible = "xlnx,opb-uartlite-1.00.b", },
+ { .compatible = "xlnx,xps-uartlite-1.00.a" },
+ { }
+};
+
+U_BOOT_DRIVER(serial_uartlite) = {
+ .name = "serial_uartlite",
+ .id = UCLASS_SERIAL,
+ .of_match = uartlite_serial_ids,
+ .ofdata_to_platdata = uartlite_serial_ofdata_to_platdata,
+ .platdata_auto_alloc_size = sizeof(struct uartlite_platdata),
+ .probe = uartlite_serial_probe,
+ .ops = &uartlite_serial_ops,
+ .flags = DM_FLAG_PRE_RELOC,
+};
+
+#ifdef CONFIG_DEBUG_UART_UARTLITE
+
+#include <debug_uart.h>
+
+static inline void _debug_uart_init(void)
{
- if (userial_ports[0])
- return &uartlite_serial0_device;
- if (userial_ports[1])
- return &uartlite_serial1_device;
- if (userial_ports[2])
- return &uartlite_serial2_device;
- if (userial_ports[3])
- return &uartlite_serial3_device;
-
- return NULL;
+ struct uartlite *regs = (struct uartlite *)CONFIG_DEBUG_UART_BASE;
+
+ out_be32(&regs->control, 0);
+ out_be32(&regs->control, ULITE_CONTROL_RST_RX | ULITE_CONTROL_RST_TX);
+ in_be32(&regs->control);
}
-void uartlite_serial_initialize(void)
+static inline void _debug_uart_putc(int ch)
{
-#ifdef XILINX_UARTLITE_BASEADDR
- serial_register(&uartlite_serial0_device);
-#endif /* XILINX_UARTLITE_BASEADDR */
-#ifdef XILINX_UARTLITE_BASEADDR1
- serial_register(&uartlite_serial1_device);
-#endif /* XILINX_UARTLITE_BASEADDR1 */
-#ifdef XILINX_UARTLITE_BASEADDR2
- serial_register(&uartlite_serial2_device);
-#endif /* XILINX_UARTLITE_BASEADDR2 */
-#ifdef XILINX_UARTLITE_BASEADDR3
- serial_register(&uartlite_serial3_device);
-#endif /* XILINX_UARTLITE_BASEADDR3 */
+ struct uartlite *regs = (struct uartlite *)CONFIG_DEBUG_UART_BASE;
+
+ while (in_be32(&regs->status) & SR_TX_FIFO_FULL)
+ ;
+
+ out_be32(&regs->tx_fifo, ch & 0xff);
}
+
+DEBUG_UART_FUNCS
+#endif
diff --git a/drivers/serial/serial_zynq.c b/drivers/serial/serial_zynq.c
index 3430482f8d8..e79d997cbab 100644
--- a/drivers/serial/serial_zynq.c
+++ b/drivers/serial/serial_zynq.c
@@ -156,13 +156,8 @@ static int zynq_serial_pending(struct udevice *dev, bool input)
static int zynq_serial_ofdata_to_platdata(struct udevice *dev)
{
struct zynq_uart_priv *priv = dev_get_priv(dev);
- fdt_addr_t addr;
- addr = fdtdec_get_addr(gd->fdt_blob, dev->of_offset, "reg");
- if (addr == FDT_ADDR_T_NONE)
- return -EINVAL;
-
- priv->regs = (struct uart_zynq *)addr;
+ priv->regs = (struct uart_zynq *)dev_get_addr(dev);
return 0;
}
@@ -177,6 +172,7 @@ static const struct dm_serial_ops zynq_serial_ops = {
static const struct udevice_id zynq_serial_ids[] = {
{ .compatible = "xlnx,xuartps" },
{ .compatible = "cdns,uart-r1p8" },
+ { .compatible = "cdns,uart-r1p12" },
{ }
};
diff --git a/drivers/spi/fsl_qspi.c b/drivers/spi/fsl_qspi.c
index 542b6cfe355..cb8d929d074 100644
--- a/drivers/spi/fsl_qspi.c
+++ b/drivers/spi/fsl_qspi.c
@@ -477,8 +477,8 @@ static void qspi_op_rdbank(struct fsl_qspi_priv *priv, u8 *rxbuf, u32 len)
static void qspi_op_rdid(struct fsl_qspi_priv *priv, u32 *rxbuf, u32 len)
{
struct fsl_qspi_regs *regs = priv->regs;
- u32 mcr_reg, rbsr_reg, data;
- int i, size;
+ u32 mcr_reg, rbsr_reg, data, size;
+ int i;
mcr_reg = qspi_read32(priv->flags, &regs->mcr);
qspi_write32(priv->flags, &regs->mcr,
@@ -494,15 +494,15 @@ static void qspi_op_rdid(struct fsl_qspi_priv *priv, u32 *rxbuf, u32 len)
;
i = 0;
- size = len;
- while ((RX_BUFFER_SIZE >= size) && (size > 0)) {
+ while ((RX_BUFFER_SIZE >= len) && (len > 0)) {
rbsr_reg = qspi_read32(priv->flags, &regs->rbsr);
if (rbsr_reg & QSPI_RBSR_RDBFL_MASK) {
data = qspi_read32(priv->flags, &regs->rbdr[i]);
data = qspi_endian_xchg(data);
- memcpy(rxbuf, &data, 4);
+ size = (len < 4) ? len : 4;
+ memcpy(rxbuf, &data, size);
+ len -= size;
rxbuf++;
- size -= 4;
i++;
}
}
@@ -639,7 +639,7 @@ static void qspi_op_write(struct fsl_qspi_priv *priv, u8 *txbuf, u32 len)
qspi_write32(priv->flags, &regs->mcr, mcr_reg);
}
-static void qspi_op_rdsr(struct fsl_qspi_priv *priv, u32 *rxbuf)
+static void qspi_op_rdsr(struct fsl_qspi_priv *priv, void *rxbuf, u32 len)
{
struct fsl_qspi_regs *regs = priv->regs;
u32 mcr_reg, reg, data;
@@ -662,7 +662,7 @@ static void qspi_op_rdsr(struct fsl_qspi_priv *priv, u32 *rxbuf)
if (reg & QSPI_RBSR_RDBFL_MASK) {
data = qspi_read32(priv->flags, &regs->rbdr[0]);
data = qspi_endian_xchg(data);
- memcpy(rxbuf, &data, 4);
+ memcpy(rxbuf, &data, len);
qspi_write32(priv->flags, &regs->mcr,
qspi_read32(priv->flags, &regs->mcr) |
QSPI_MCR_CLR_RXF_MASK);
@@ -751,7 +751,7 @@ int qspi_xfer(struct fsl_qspi_priv *priv, unsigned int bitlen,
} else if (priv->cur_seqid == QSPI_CMD_RDID)
qspi_op_rdid(priv, din, bytes);
else if (priv->cur_seqid == QSPI_CMD_RDSR)
- qspi_op_rdsr(priv, din);
+ qspi_op_rdsr(priv, din, bytes);
#ifdef CONFIG_SPI_FLASH_BAR
else if ((priv->cur_seqid == QSPI_CMD_BRRD) ||
(priv->cur_seqid == QSPI_CMD_RDEAR)) {
@@ -936,7 +936,7 @@ static int fsl_qspi_probe(struct udevice *bus)
dm_spi_bus->max_hz = plat->speed_hz;
- priv->regs = (struct fsl_qspi_regs *)plat->reg_base;
+ priv->regs = (struct fsl_qspi_regs *)(uintptr_t)plat->reg_base;
priv->flags = plat->flags;
priv->speed_hz = plat->speed_hz;
diff --git a/drivers/tpm/Kconfig b/drivers/tpm/Kconfig
index 31b35f75c96..9a7b7f535fb 100644
--- a/drivers/tpm/Kconfig
+++ b/drivers/tpm/Kconfig
@@ -50,7 +50,7 @@ config TPM_TIS_LPC
bool "Enable support for Infineon SLB9635/45 TPMs on LPC"
depends on TPM && X86
help
- This driver supports Infineon TPM devices connected on the I2C bus.
+ This driver supports Infineon TPM devices connected on the LPC bus.
The usual tpm operations and the 'tpm' command can be used to talk
to the device using the standard TPM Interface Specification (TIS)
protocol
@@ -64,4 +64,22 @@ config TPM_AUTH_SESSIONS
TPM_LoadKey2 and TPM_GetPubKey are provided. Both features are
available using the 'tpm' command, too.
+config TPM_ST33ZP24_I2C
+ bool "STMicroelectronics ST33ZP24 I2C TPM"
+ depends on TPM && DM_I2C
+ ---help---
+ This driver supports STMicroelectronics TPM devices connected on the I2C bus.
+ The usual tpm operations and the 'tpm' command can be used to talk
+ to the device using the standard TPM Interface Specification (TIS)
+ protocol
+
+config TPM_ST33ZP24_SPI
+ bool "STMicroelectronics ST33ZP24 SPI TPM"
+ depends on TPM && DM_SPI
+ ---help---
+ This driver supports STMicroelectronics TPM devices connected on the SPI bus.
+ The usual tpm operations and the 'tpm' command can be used to talk
+ to the device using the standard TPM Interface Specification (TIS)
+ protocol
+
endmenu
diff --git a/drivers/tpm/Makefile b/drivers/tpm/Makefile
index 1d49e952ae1..c42a93f267c 100644
--- a/drivers/tpm/Makefile
+++ b/drivers/tpm/Makefile
@@ -9,3 +9,5 @@ obj-$(CONFIG_TPM_ATMEL_TWI) += tpm_atmel_twi.o
obj-$(CONFIG_TPM_TIS_INFINEON) += tpm_tis_infineon.o
obj-$(CONFIG_TPM_TIS_LPC) += tpm_tis_lpc.o
obj-$(CONFIG_TPM_TIS_SANDBOX) += tpm_tis_sandbox.o
+obj-$(CONFIG_TPM_ST33ZP24_I2C) += tpm_tis_st33zp24_i2c.o
+obj-$(CONFIG_TPM_ST33ZP24_SPI) += tpm_tis_st33zp24_spi.o
diff --git a/drivers/tpm/tpm_tis_infineon.h b/drivers/tpm/tpm_tis.h
index 3b510d101e7..25b152b3213 100644
--- a/drivers/tpm/tpm_tis_infineon.h
+++ b/drivers/tpm/tpm_tis.h
@@ -37,18 +37,12 @@ enum tpm_timeout {
#define TPM_RSP_SIZE_BYTE 2
#define TPM_RSP_RC_BYTE 6
-enum i2c_chip_type {
- SLB9635,
- SLB9645,
- UNKNOWN,
-};
-
struct tpm_chip {
int is_open;
int locality;
u32 vend_dev;
unsigned long timeout_a, timeout_b, timeout_c, timeout_d; /* msec */
- enum i2c_chip_type chip_type;
+ ulong chip_type;
};
struct tpm_input_header {
@@ -134,13 +128,4 @@ enum tis_status {
TPM_STS_DATA_EXPECT = 0x08,
};
-/* expected value for DIDVID register */
-#define TPM_TIS_I2C_DID_VID_9635 0x000b15d1L
-#define TPM_TIS_I2C_DID_VID_9645 0x001a15d1L
-
-#define TPM_ACCESS(l) (0x0000 | ((l) << 4))
-#define TPM_STS(l) (0x0001 | ((l) << 4))
-#define TPM_DATA_FIFO(l) (0x0005 | ((l) << 4))
-#define TPM_DID_VID(l) (0x0006 | ((l) << 4))
-
#endif
diff --git a/drivers/tpm/tpm_tis_infineon.c b/drivers/tpm/tpm_tis_infineon.c
index f57c32837be..a4b67416762 100644
--- a/drivers/tpm/tpm_tis_infineon.c
+++ b/drivers/tpm/tpm_tis_infineon.c
@@ -30,17 +30,32 @@
#include <linux/types.h>
#include <linux/unaligned/be_byteshift.h>
-#include "tpm_tis_infineon.h"
+#include "tpm_tis.h"
#include "tpm_internal.h"
DECLARE_GLOBAL_DATA_PTR;
+enum i2c_chip_type {
+ SLB9635,
+ SLB9645,
+ UNKNOWN,
+};
+
+/* expected value for DIDVID register */
+#define TPM_TIS_I2C_DID_VID_9635 0x000b15d1L
+#define TPM_TIS_I2C_DID_VID_9645 0x001a15d1L
+
static const char * const chip_name[] = {
[SLB9635] = "slb9635tt",
[SLB9645] = "slb9645tt",
[UNKNOWN] = "unknown/fallback to slb9635",
};
+#define TPM_ACCESS(l) (0x0000 | ((l) << 4))
+#define TPM_STS(l) (0x0001 | ((l) << 4))
+#define TPM_DATA_FIFO(l) (0x0005 | ((l) << 4))
+#define TPM_DID_VID(l) (0x0006 | ((l) << 4))
+
/*
* tpm_tis_i2c_read() - read from TPM register
* @addr: register address to read from
diff --git a/drivers/tpm/tpm_tis_st33zp24_i2c.c b/drivers/tpm/tpm_tis_st33zp24_i2c.c
new file mode 100644
index 00000000000..9e4829fea2f
--- /dev/null
+++ b/drivers/tpm/tpm_tis_st33zp24_i2c.c
@@ -0,0 +1,543 @@
+/*
+ * STMicroelectronics TPM ST33ZP24 I2C UBOOT driver
+ *
+ * Copyright (C) 2016 STMicroelectronics
+ *
+ * Description: Device driver for ST33ZP24 I2C TPM TCG.
+ *
+ * This device driver implements the TPM interface as defined in
+ * the TCG TPM Interface Spec version 1.21, revision 1.0 and the
+ * STMicroelectronics Protocol Stack Specification version 1.2.0.
+ *
+ * SPDX-License-Identifier: GPL-2.0+
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <fdtdec.h>
+#include <i2c.h>
+#include <tpm.h>
+#include <errno.h>
+#include <linux/types.h>
+#include <asm/unaligned.h>
+
+#include "tpm_tis.h"
+#include "tpm_internal.h"
+
+#define TPM_ACCESS 0x0
+#define TPM_STS 0x18
+#define TPM_DATA_FIFO 0x24
+
+#define LOCALITY0 0
+
+#define TPM_DUMMY_BYTE 0xAA
+#define TPM_ST33ZP24_I2C_SLAVE_ADDR 0x13
+
+#define TPM_WRITE_DIRECTION 0x80
+
+/*
+ * st33zp24_i2c_write8_reg
+ * Send byte to the TIS register according to the ST33ZP24 I2C protocol.
+ * @param: tpm_register, the tpm tis register where the data should be written
+ * @param: tpm_data, the tpm_data to write inside the tpm_register
+ * @param: tpm_size, The length of the data
+ * @return: Number of byte written successfully else an error code.
+ */
+static int st33zp24_i2c_write8_reg(struct udevice *dev, u8 tpm_register,
+ const u8 *tpm_data, size_t tpm_size)
+{
+ struct tpm_chip_priv *chip_priv = dev_get_uclass_priv(dev);
+
+ chip_priv->buf[0] = tpm_register;
+ memcpy(chip_priv->buf + 1, tpm_data, tpm_size);
+
+ return dm_i2c_write(dev, 0, chip_priv->buf, tpm_size + 1);
+}
+
+/*
+* st33zp24_i2c_read8_reg
+* Recv byte from the TIS register according to the ST33ZP24 I2C protocol.
+* @param: tpm_register, the tpm tis register where the data should be read
+* @param: tpm_data, the TPM response
+* @param: tpm_size, tpm TPM response size to read.
+* @return: Number of byte read successfully else an error code.
+*/
+static int st33zp24_i2c_read8_reg(struct udevice *dev, u8 tpm_register,
+ u8 *tpm_data, size_t tpm_size)
+{
+ int status;
+ u8 data;
+
+ data = TPM_DUMMY_BYTE;
+ status = st33zp24_i2c_write8_reg(dev, tpm_register, &data, 1);
+ if (status < 0)
+ return status;
+
+ return dm_i2c_read(dev, 0, tpm_data, tpm_size);
+}
+
+/*
+ * st33zp24_i2c_write
+ * Send byte to the TIS register according to the ST33ZP24 I2C protocol.
+ * @param: phy_id, the phy description
+ * @param: tpm_register, the tpm tis register where the data should be written
+ * @param: tpm_data, the tpm_data to write inside the tpm_register
+ * @param: tpm_size, the length of the data
+ * @return: number of byte written successfully: should be one if success.
+ */
+static int st33zp24_i2c_write(struct udevice *dev, u8 tpm_register,
+ const u8 *tpm_data, size_t tpm_size)
+{
+ return st33zp24_i2c_write8_reg(dev, tpm_register | TPM_WRITE_DIRECTION,
+ tpm_data, tpm_size);
+}
+
+/*
+ * st33zp24_i2c_read
+ * Recv byte from the TIS register according to the ST33ZP24 I2C protocol.
+ * @param: phy_id, the phy description
+ * @param: tpm_register, the tpm tis register where the data should be read
+ * @param: tpm_data, the TPM response
+ * @param: tpm_size, tpm TPM response size to read.
+ * @return: number of byte read successfully: should be one if success.
+ */
+static int st33zp24_i2c_read(struct udevice *dev, u8 tpm_register,
+ u8 *tpm_data, size_t tpm_size)
+{
+ return st33zp24_i2c_read8_reg(dev, tpm_register, tpm_data, tpm_size);
+}
+
+/*
+ * st33zp24_i2c_release_locality release the active locality
+ * @param: chip, the tpm chip description.
+ */
+static void st33zp24_i2c_release_locality(struct udevice *dev)
+{
+ u8 data = TPM_ACCESS_ACTIVE_LOCALITY;
+
+ st33zp24_i2c_write(dev, TPM_ACCESS, &data, 1);
+}
+
+/*
+ * st33zp24_i2c_check_locality if the locality is active
+ * @param: chip, the tpm chip description
+ * @return: the active locality or -EACCES.
+ */
+static int st33zp24_i2c_check_locality(struct udevice *dev)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+ u8 data;
+ u8 status;
+
+ status = st33zp24_i2c_read(dev, TPM_ACCESS, &data, 1);
+ if (!status && (data &
+ (TPM_ACCESS_ACTIVE_LOCALITY | TPM_ACCESS_VALID)) ==
+ (TPM_ACCESS_ACTIVE_LOCALITY | TPM_ACCESS_VALID))
+ return chip->locality;
+
+ return -EACCES;
+}
+
+/*
+ * st33zp24_i2c_request_locality request the TPM locality
+ * @param: chip, the chip description
+ * @return: the active locality or negative value.
+ */
+static int st33zp24_i2c_request_locality(struct udevice *dev)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+ unsigned long start, stop;
+ long ret;
+ u8 data;
+
+ if (st33zp24_i2c_check_locality(dev) == chip->locality)
+ return chip->locality;
+
+ data = TPM_ACCESS_REQUEST_USE;
+ ret = st33zp24_i2c_write(dev, TPM_ACCESS, &data, 1);
+ if (ret < 0)
+ return ret;
+
+ /* wait for locality activated */
+ start = get_timer(0);
+ stop = chip->timeout_a;
+ do {
+ if (st33zp24_i2c_check_locality(dev) >= 0)
+ return chip->locality;
+ udelay(TPM_TIMEOUT_MS * 1000);
+ } while (get_timer(start) < stop);
+
+ return -EACCES;
+}
+
+/*
+ * st33zp24_i2c_status return the TPM_STS register
+ * @param: chip, the tpm chip description
+ * @return: the TPM_STS register value.
+ */
+static u8 st33zp24_i2c_status(struct udevice *dev)
+{
+ u8 data;
+
+ st33zp24_i2c_read(dev, TPM_STS, &data, 1);
+
+ return data;
+}
+
+/*
+ * st33zp24_i2c_get_burstcount return the burstcount address 0x19 0x1A
+ * @param: chip, the chip description
+ * return: the burstcount or -TPM_DRIVER_ERR in case of error.
+ */
+static int st33zp24_i2c_get_burstcount(struct udevice *dev)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+ unsigned long start, stop;
+ int burstcnt, status;
+ u8 tpm_reg, temp;
+
+ /* wait for burstcount */
+ start = get_timer(0);
+ stop = chip->timeout_d;
+ do {
+ tpm_reg = TPM_STS + 1;
+ status = st33zp24_i2c_read(dev, tpm_reg, &temp, 1);
+ if (status < 0)
+ return -EBUSY;
+
+ tpm_reg = TPM_STS + 2;
+ burstcnt = temp;
+ status = st33zp24_i2c_read(dev, tpm_reg, &temp, 1);
+ if (status < 0)
+ return -EBUSY;
+
+ burstcnt |= temp << 8;
+ if (burstcnt)
+ return burstcnt;
+ udelay(TIS_SHORT_TIMEOUT_MS * 1000);
+ } while (get_timer(start) < stop);
+
+ return -EBUSY;
+}
+
+/*
+ * st33zp24_i2c_cancel, cancel the current command execution or
+ * set STS to COMMAND READY.
+ * @param: chip, tpm_chip description.
+ */
+static void st33zp24_i2c_cancel(struct udevice *dev)
+{
+ u8 data;
+
+ data = TPM_STS_COMMAND_READY;
+ st33zp24_i2c_write(dev, TPM_STS, &data, 1);
+}
+
+/*
+ * st33zp24_i2c_wait_for_stat wait for a TPM_STS value
+ * @param: chip, the tpm chip description
+ * @param: mask, the value mask to wait
+ * @param: timeout, the timeout
+ * @param: status,
+ * @return: the tpm status, 0 if success, -ETIME if timeout is reached.
+ */
+static int st33zp24_i2c_wait_for_stat(struct udevice *dev, u8 mask,
+ unsigned long timeout, int *status)
+{
+ unsigned long start, stop;
+
+ /* Check current status */
+ *status = st33zp24_i2c_status(dev);
+ if ((*status & mask) == mask)
+ return 0;
+
+ start = get_timer(0);
+ stop = timeout;
+ do {
+ udelay(TPM_TIMEOUT_MS * 1000);
+ *status = st33zp24_i2c_status(dev);
+ if ((*status & mask) == mask)
+ return 0;
+ } while (get_timer(start) < stop);
+
+ return -ETIME;
+}
+
+/*
+ * st33zp24_i2c_recv_data receive data
+ * @param: chip, the tpm chip description
+ * @param: buf, the buffer where the data are received
+ * @param: count, the number of data to receive
+ * @return: the number of bytes read from TPM FIFO.
+ */
+static int st33zp24_i2c_recv_data(struct udevice *dev, u8 *buf, size_t count)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+ int size = 0, burstcnt, len, ret, status;
+
+ while (size < count &&
+ st33zp24_i2c_wait_for_stat(dev, TPM_STS_DATA_AVAIL | TPM_STS_VALID,
+ chip->timeout_c, &status) == 0) {
+ burstcnt = st33zp24_i2c_get_burstcount(dev);
+ if (burstcnt < 0)
+ return burstcnt;
+ len = min_t(int, burstcnt, count - size);
+ ret = st33zp24_i2c_read(dev, TPM_DATA_FIFO, buf + size, len);
+ if (ret < 0)
+ return ret;
+
+ size += len;
+ }
+
+ return size;
+}
+
+/*
+ * st33zp24_i2c_recv received TPM response through TPM phy.
+ * @param: chip, tpm_chip description.
+ * @param: buf, the buffer to store data.
+ * @param: count, the number of bytes that can received (sizeof buf).
+ * @return: Returns zero in case of success else -EIO.
+ */
+static int st33zp24_i2c_recv(struct udevice *dev, u8 *buf, size_t count)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+ int size, expected;
+
+ if (!chip)
+ return -ENODEV;
+
+ if (count < TPM_HEADER_SIZE) {
+ size = -EIO;
+ goto out;
+ }
+
+ size = st33zp24_i2c_recv_data(dev, buf, TPM_HEADER_SIZE);
+ if (size < TPM_HEADER_SIZE) {
+ debug("TPM error, unable to read header\n");
+ goto out;
+ }
+
+ expected = get_unaligned_be32(buf + 2);
+ if (expected > count) {
+ size = -EIO;
+ goto out;
+ }
+
+ size += st33zp24_i2c_recv_data(dev, &buf[TPM_HEADER_SIZE],
+ expected - TPM_HEADER_SIZE);
+ if (size < expected) {
+ debug("TPM error, unable to read remaining bytes of result\n");
+ size = -EIO;
+ goto out;
+ }
+
+out:
+ st33zp24_i2c_cancel(dev);
+ st33zp24_i2c_release_locality(dev);
+
+ return size;
+}
+
+/*
+ * st33zp24_i2c_send send TPM commands through TPM phy.
+ * @param: chip, tpm_chip description.
+ * @param: buf, the buffer to send.
+ * @param: len, the number of bytes to send.
+ * @return: Returns zero in case of success else the negative error code.
+ */
+static int st33zp24_i2c_send(struct udevice *dev, const u8 *buf, size_t len)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+ u32 i, size;
+ int burstcnt, ret, status;
+ u8 data, tpm_stat;
+
+ if (!chip)
+ return -ENODEV;
+ if (len < TPM_HEADER_SIZE)
+ return -EIO;
+
+ ret = st33zp24_i2c_request_locality(dev);
+ if (ret < 0)
+ return ret;
+
+ tpm_stat = st33zp24_i2c_status(dev);
+ if ((tpm_stat & TPM_STS_COMMAND_READY) == 0) {
+ st33zp24_i2c_cancel(dev);
+ if (st33zp24_i2c_wait_for_stat(dev, TPM_STS_COMMAND_READY,
+ chip->timeout_b, &status) < 0) {
+ ret = -ETIME;
+ goto out_err;
+ }
+ }
+
+ for (i = 0; i < len - 1;) {
+ burstcnt = st33zp24_i2c_get_burstcount(dev);
+ if (burstcnt < 0)
+ return burstcnt;
+
+ size = min_t(int, len - i - 1, burstcnt);
+ ret = st33zp24_i2c_write(dev, TPM_DATA_FIFO, buf + i, size);
+ if (ret < 0)
+ goto out_err;
+
+ i += size;
+ }
+
+ tpm_stat = st33zp24_i2c_status(dev);
+ if ((tpm_stat & TPM_STS_DATA_EXPECT) == 0) {
+ ret = -EIO;
+ goto out_err;
+ }
+
+ ret = st33zp24_i2c_write(dev, TPM_DATA_FIFO, buf + len - 1, 1);
+ if (ret < 0)
+ goto out_err;
+
+ tpm_stat = st33zp24_i2c_status(dev);
+ if ((tpm_stat & TPM_STS_DATA_EXPECT) != 0) {
+ ret = -EIO;
+ goto out_err;
+ }
+
+ data = TPM_STS_GO;
+ ret = st33zp24_i2c_write(dev, TPM_STS, &data, 1);
+ if (ret < 0)
+ goto out_err;
+
+ return len;
+
+out_err:
+ st33zp24_i2c_cancel(dev);
+ st33zp24_i2c_release_locality(dev);
+
+ return ret;
+}
+
+static int st33zp24_i2c_cleanup(struct udevice *dev)
+{
+ st33zp24_i2c_cancel(dev);
+ /*
+ * The TPM needs some time to clean up here,
+ * so we sleep rather than keeping the bus busy
+ */
+ mdelay(2);
+ st33zp24_i2c_release_locality(dev);
+
+ return 0;
+}
+
+static int st33zp24_i2c_init(struct udevice *dev)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+
+ chip->is_open = 1;
+
+ /* Default timeouts - these could move to the device tree */
+ chip->timeout_a = TIS_SHORT_TIMEOUT_MS;
+ chip->timeout_b = TIS_LONG_TIMEOUT_MS;
+ chip->timeout_c = TIS_SHORT_TIMEOUT_MS;
+ chip->timeout_d = TIS_SHORT_TIMEOUT_MS;
+
+ chip->locality = LOCALITY0;
+
+ /*
+ * A timeout query to TPM can be placed here.
+ * Standard timeout values are used so far
+ */
+
+ return 0;
+}
+
+static int st33zp24_i2c_open(struct udevice *dev)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+ int rc;
+
+ debug("%s: start\n", __func__);
+ if (chip->is_open)
+ return -EBUSY;
+
+ rc = st33zp24_i2c_init(dev);
+ if (rc < 0)
+ chip->is_open = 0;
+
+ return rc;
+}
+
+static int st33zp24_i2c_close(struct udevice *dev)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+
+ if (chip->is_open) {
+ st33zp24_i2c_release_locality(dev);
+ chip->is_open = 0;
+ chip->vend_dev = 0;
+ }
+
+ return 0;
+}
+
+static int st33zp24_i2c_get_desc(struct udevice *dev, char *buf, int size)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+
+ if (size < 50)
+ return -ENOSPC;
+
+ return snprintf(buf, size, "1.2 TPM (%s, chip type %s device-id 0x%x)",
+ chip->is_open ? "open" : "closed",
+ dev->name,
+ chip->vend_dev >> 16);
+}
+
+static const struct tpm_ops st33zp24_i2c_tpm_ops = {
+ .open = st33zp24_i2c_open,
+ .close = st33zp24_i2c_close,
+ .recv = st33zp24_i2c_recv,
+ .send = st33zp24_i2c_send,
+ .cleanup = st33zp24_i2c_cleanup,
+ .get_desc = st33zp24_i2c_get_desc,
+};
+
+static int st33zp24_i2c_probe(struct udevice *dev)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+
+ /* Default timeouts */
+ chip->timeout_a = TIS_SHORT_TIMEOUT_MS;
+ chip->timeout_b = TIS_LONG_TIMEOUT_MS;
+ chip->timeout_c = TIS_SHORT_TIMEOUT_MS;
+ chip->timeout_d = TIS_SHORT_TIMEOUT_MS;
+
+ chip->locality = LOCALITY0;
+
+ i2c_set_chip_offset_len(dev, 0);
+
+ debug("ST33ZP24 I2C TPM from STMicroelectronics found\n");
+
+ return 0;
+}
+
+static int st33zp24_i2c_remove(struct udevice *dev)
+{
+ st33zp24_i2c_release_locality(dev);
+
+ return 0;
+}
+
+static const struct udevice_id st33zp24_i2c_ids[] = {
+ { .compatible = "st,st33zp24-i2c" },
+ { }
+};
+
+U_BOOT_DRIVER(st33zp24_i2c) = {
+ .name = "st33zp24-i2c",
+ .id = UCLASS_TPM,
+ .of_match = of_match_ptr(st33zp24_i2c_ids),
+ .probe = st33zp24_i2c_probe,
+ .remove = st33zp24_i2c_remove,
+ .ops = &st33zp24_i2c_tpm_ops,
+ .priv_auto_alloc_size = sizeof(struct tpm_chip),
+};
diff --git a/drivers/tpm/tpm_tis_st33zp24_spi.c b/drivers/tpm/tpm_tis_st33zp24_spi.c
new file mode 100644
index 00000000000..417bbf1c690
--- /dev/null
+++ b/drivers/tpm/tpm_tis_st33zp24_spi.c
@@ -0,0 +1,672 @@
+/*
+ * STMicroelectronics TPM ST33ZP24 SPI UBOOT driver
+ *
+ * Copyright (C) 2016 STMicroelectronics
+ *
+ * Description: Device driver for ST33ZP24 SPI TPM TCG.
+ *
+ * This device driver implements the TPM interface as defined in
+ * the TCG TPM Interface Spec version 1.21, revision 1.0 and the
+ * STMicroelectronics Protocol Stack Specification version 1.2.0.
+ *
+ * SPDX-License-Identifier: GPL-2.0+
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <fdtdec.h>
+#include <spi.h>
+#include <tpm.h>
+#include <errno.h>
+#include <linux/types.h>
+#include <asm/unaligned.h>
+#include <linux/compat.h>
+
+#include "tpm_tis.h"
+#include "tpm_internal.h"
+
+#define TPM_ACCESS 0x0
+#define TPM_STS 0x18
+#define TPM_DATA_FIFO 0x24
+
+#define LOCALITY0 0
+
+#define TPM_DATA_FIFO 0x24
+#define TPM_INTF_CAPABILITY 0x14
+
+#define TPM_DUMMY_BYTE 0x00
+#define TPM_WRITE_DIRECTION 0x80
+
+#define MAX_SPI_LATENCY 15
+#define LOCALITY0 0
+
+#define ST33ZP24_OK 0x5A
+#define ST33ZP24_UNDEFINED_ERR 0x80
+#define ST33ZP24_BADLOCALITY 0x81
+#define ST33ZP24_TISREGISTER_UKNOWN 0x82
+#define ST33ZP24_LOCALITY_NOT_ACTIVATED 0x83
+#define ST33ZP24_HASH_END_BEFORE_HASH_START 0x84
+#define ST33ZP24_BAD_COMMAND_ORDER 0x85
+#define ST33ZP24_INCORECT_RECEIVED_LENGTH 0x86
+#define ST33ZP24_TPM_FIFO_OVERFLOW 0x89
+#define ST33ZP24_UNEXPECTED_READ_FIFO 0x8A
+#define ST33ZP24_UNEXPECTED_WRITE_FIFO 0x8B
+#define ST33ZP24_CMDRDY_SET_WHEN_PROCESSING_HASH_END 0x90
+#define ST33ZP24_DUMMY_BYTES 0x00
+
+/*
+ * TPM command can be up to 2048 byte, A TPM response can be up to
+ * 1024 byte.
+ * Between command and response, there are latency byte (up to 15
+ * usually on st33zp24 2 are enough).
+ *
+ * Overall when sending a command and expecting an answer we need if
+ * worst case:
+ * 2048 (for the TPM command) + 1024 (for the TPM answer). We need
+ * some latency byte before the answer is available (max 15).
+ * We have 2048 + 1024 + 15.
+ */
+#define ST33ZP24_SPI_BUFFER_SIZE (TPM_BUFSIZE + (TPM_BUFSIZE / 2) +\
+ MAX_SPI_LATENCY)
+
+struct st33zp24_spi_phy {
+ int latency;
+
+ u8 tx_buf[ST33ZP24_SPI_BUFFER_SIZE];
+ u8 rx_buf[ST33ZP24_SPI_BUFFER_SIZE];
+};
+
+static int st33zp24_spi_status_to_errno(u8 code)
+{
+ switch (code) {
+ case ST33ZP24_OK:
+ return 0;
+ case ST33ZP24_UNDEFINED_ERR:
+ case ST33ZP24_BADLOCALITY:
+ case ST33ZP24_TISREGISTER_UKNOWN:
+ case ST33ZP24_LOCALITY_NOT_ACTIVATED:
+ case ST33ZP24_HASH_END_BEFORE_HASH_START:
+ case ST33ZP24_BAD_COMMAND_ORDER:
+ case ST33ZP24_UNEXPECTED_READ_FIFO:
+ case ST33ZP24_UNEXPECTED_WRITE_FIFO:
+ case ST33ZP24_CMDRDY_SET_WHEN_PROCESSING_HASH_END:
+ return -EPROTO;
+ case ST33ZP24_INCORECT_RECEIVED_LENGTH:
+ case ST33ZP24_TPM_FIFO_OVERFLOW:
+ return -EMSGSIZE;
+ case ST33ZP24_DUMMY_BYTES:
+ return -ENOSYS;
+ }
+ return code;
+}
+
+/*
+ * st33zp24_spi_send
+ * Send byte to TPM register according to the ST33ZP24 SPI protocol.
+ * @param: tpm, the chip description
+ * @param: tpm_register, the tpm tis register where the data should be written
+ * @param: tpm_data, the tpm_data to write inside the tpm_register
+ * @param: tpm_size, The length of the data
+ * @return: should be zero if success else a negative error code.
+ */
+static int st33zp24_spi_write(struct udevice *dev, u8 tpm_register,
+ const u8 *tpm_data, size_t tpm_size)
+{
+ int total_length = 0, ret;
+ struct spi_slave *slave = dev_get_parent_priv(dev);
+ struct st33zp24_spi_phy *phy = dev_get_platdata(dev);
+
+ u8 *tx_buf = (u8 *)phy->tx_buf;
+ u8 *rx_buf = phy->rx_buf;
+
+ tx_buf[total_length++] = TPM_WRITE_DIRECTION | LOCALITY0;
+ tx_buf[total_length++] = tpm_register;
+
+ if (tpm_size > 0 && tpm_register == TPM_DATA_FIFO) {
+ tx_buf[total_length++] = tpm_size >> 8;
+ tx_buf[total_length++] = tpm_size;
+ }
+ memcpy(tx_buf + total_length, tpm_data, tpm_size);
+ total_length += tpm_size;
+
+ memset(tx_buf + total_length, TPM_DUMMY_BYTE, phy->latency);
+
+ total_length += phy->latency;
+
+ ret = spi_claim_bus(slave);
+ if (ret < 0)
+ return ret;
+
+ ret = spi_xfer(slave, total_length * 8, tx_buf, rx_buf,
+ SPI_XFER_BEGIN | SPI_XFER_END);
+ if (ret < 0)
+ return ret;
+
+ spi_release_bus(slave);
+
+ if (ret == 0)
+ ret = rx_buf[total_length - 1];
+
+ return st33zp24_spi_status_to_errno(ret);
+}
+
+/*
+ * spi_st33zp24_spi_read8_reg
+ * Recv byte from the TIS register according to the ST33ZP24 SPI protocol.
+ * @param: tpm, the chip description
+ * @param: tpm_loc, the locality to read register from
+ * @param: tpm_register, the tpm tis register where the data should be read
+ * @param: tpm_data, the TPM response
+ * @param: tpm_size, tpm TPM response size to read.
+ * @return: should be zero if success else a negative error code.
+ */
+static u8 st33zp24_spi_read8_reg(struct udevice *dev, u8 tpm_register,
+ u8 *tpm_data, size_t tpm_size)
+{
+ int total_length = 0, ret;
+ struct spi_slave *slave = dev_get_parent_priv(dev);
+ struct st33zp24_spi_phy *phy = dev_get_platdata(dev);
+
+ u8 *tx_buf = (u8 *)phy->tx_buf;
+ u8 *rx_buf = phy->rx_buf;
+
+ /* Pre-Header */
+ tx_buf[total_length++] = LOCALITY0;
+ tx_buf[total_length++] = tpm_register;
+
+ memset(&tx_buf[total_length], TPM_DUMMY_BYTE,
+ phy->latency + tpm_size);
+ total_length += phy->latency + tpm_size;
+
+ ret = spi_claim_bus(slave);
+ if (ret < 0)
+ return 0;
+
+ ret = spi_xfer(slave, total_length * 8, tx_buf, rx_buf,
+ SPI_XFER_BEGIN | SPI_XFER_END);
+ if (ret < 0)
+ return 0;
+
+ spi_release_bus(slave);
+
+ if (tpm_size > 0 && ret == 0) {
+ ret = rx_buf[total_length - tpm_size - 1];
+ memcpy(tpm_data, rx_buf + total_length - tpm_size, tpm_size);
+ }
+ return ret;
+}
+
+/*
+ * st33zp24_spi_recv
+ * Recv byte from the TIS register according to the ST33ZP24 SPI protocol.
+ * @param: phy_id, the phy description
+ * @param: tpm_register, the tpm tis register where the data should be read
+ * @param: tpm_data, the TPM response
+ * @param: tpm_size, tpm TPM response size to read.
+ * @return: number of byte read successfully: should be one if success.
+ */
+static int st33zp24_spi_read(struct udevice *dev, u8 tpm_register,
+ u8 *tpm_data, size_t tpm_size)
+{
+ int ret;
+
+ ret = st33zp24_spi_read8_reg(dev, tpm_register, tpm_data, tpm_size);
+ if (!st33zp24_spi_status_to_errno(ret))
+ return tpm_size;
+
+ return ret;
+}
+
+static int st33zp24_spi_evaluate_latency(struct udevice *dev)
+{
+ int latency = 1, status = 0;
+ u8 data = 0;
+ struct st33zp24_spi_phy *phy = dev_get_platdata(dev);
+
+ while (!status && latency < MAX_SPI_LATENCY) {
+ phy->latency = latency;
+ status = st33zp24_spi_read8_reg(dev, TPM_INTF_CAPABILITY,
+ &data, 1);
+ latency++;
+ }
+ if (status < 0)
+ return status;
+ if (latency == MAX_SPI_LATENCY)
+ return -ENODEV;
+
+ return latency - 1;
+}
+
+/*
+ * st33zp24_spi_release_locality release the active locality
+ * @param: chip, the tpm chip description.
+ */
+static void st33zp24_spi_release_locality(struct udevice *dev)
+{
+ u8 data = TPM_ACCESS_ACTIVE_LOCALITY;
+
+ st33zp24_spi_write(dev, TPM_ACCESS, &data, 1);
+}
+
+/*
+ * st33zp24_spi_check_locality if the locality is active
+ * @param: chip, the tpm chip description
+ * @return: the active locality or -EACCES.
+ */
+static int st33zp24_spi_check_locality(struct udevice *dev)
+{
+ u8 data;
+ u8 status;
+ struct tpm_chip *chip = dev_get_priv(dev);
+
+ status = st33zp24_spi_read(dev, TPM_ACCESS, &data, 1);
+ if (status && (data &
+ (TPM_ACCESS_ACTIVE_LOCALITY | TPM_ACCESS_VALID)) ==
+ (TPM_ACCESS_ACTIVE_LOCALITY | TPM_ACCESS_VALID))
+ return chip->locality;
+
+ return -EACCES;
+}
+
+/*
+ * st33zp24_spi_request_locality request the TPM locality
+ * @param: chip, the chip description
+ * @return: the active locality or negative value.
+ */
+static int st33zp24_spi_request_locality(struct udevice *dev)
+{
+ unsigned long start, stop;
+ long ret;
+ u8 data;
+ struct tpm_chip *chip = dev_get_priv(dev);
+
+ if (st33zp24_spi_check_locality(dev) == chip->locality)
+ return chip->locality;
+
+ data = TPM_ACCESS_REQUEST_USE;
+ ret = st33zp24_spi_write(dev, TPM_ACCESS, &data, 1);
+ if (ret < 0)
+ return ret;
+
+ /* wait for locality activated */
+ start = get_timer(0);
+ stop = chip->timeout_a;
+ do {
+ if (st33zp24_spi_check_locality(dev) >= 0)
+ return chip->locality;
+ udelay(TPM_TIMEOUT_MS * 1000);
+ } while (get_timer(start) < stop);
+
+ return -EACCES;
+}
+
+/*
+ * st33zp24_spi_status return the TPM_STS register
+ * @param: chip, the tpm chip description
+ * @return: the TPM_STS register value.
+ */
+static u8 st33zp24_spi_status(struct udevice *dev)
+{
+ u8 data;
+
+ st33zp24_spi_read(dev, TPM_STS, &data, 1);
+ return data;
+}
+
+/*
+ * st33zp24_spi_get_burstcount return the burstcount address 0x19 0x1A
+ * @param: chip, the chip description
+ * return: the burstcount or -TPM_DRIVER_ERR in case of error.
+ */
+static int st33zp24_spi_get_burstcount(struct udevice *dev)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+ unsigned long start, stop;
+ int burstcnt, status;
+ u8 tpm_reg, temp;
+
+ /* wait for burstcount */
+ start = get_timer(0);
+ stop = chip->timeout_d;
+ do {
+ tpm_reg = TPM_STS + 1;
+ status = st33zp24_spi_read(dev, tpm_reg, &temp, 1);
+ if (status < 0)
+ return -EBUSY;
+
+ tpm_reg = TPM_STS + 2;
+ burstcnt = temp;
+ status = st33zp24_spi_read(dev, tpm_reg, &temp, 1);
+ if (status < 0)
+ return -EBUSY;
+
+ burstcnt |= temp << 8;
+ if (burstcnt)
+ return burstcnt;
+ udelay(TIS_SHORT_TIMEOUT_MS * 1000);
+ } while (get_timer(start) < stop);
+
+ return -EBUSY;
+}
+
+/*
+ * st33zp24_spi_cancel, cancel the current command execution or
+ * set STS to COMMAND READY.
+ * @param: chip, tpm_chip description.
+ */
+static void st33zp24_spi_cancel(struct udevice *dev)
+{
+ u8 data;
+
+ data = TPM_STS_COMMAND_READY;
+ st33zp24_spi_write(dev, TPM_STS, &data, 1);
+}
+
+/*
+ * st33zp24_spi_wait_for_stat wait for a TPM_STS value
+ * @param: chip, the tpm chip description
+ * @param: mask, the value mask to wait
+ * @param: timeout, the timeout
+ * @param: status,
+ * @return: the tpm status, 0 if success, -ETIME if timeout is reached.
+ */
+static int st33zp24_spi_wait_for_stat(struct udevice *dev, u8 mask,
+ unsigned long timeout, int *status)
+{
+ unsigned long start, stop;
+
+ /* Check current status */
+ *status = st33zp24_spi_status(dev);
+ if ((*status & mask) == mask)
+ return 0;
+
+ start = get_timer(0);
+ stop = timeout;
+ do {
+ udelay(TPM_TIMEOUT_MS * 1000);
+ *status = st33zp24_spi_status(dev);
+ if ((*status & mask) == mask)
+ return 0;
+ } while (get_timer(start) < stop);
+
+ return -ETIME;
+}
+
+/*
+ * st33zp24_spi_recv_data receive data
+ * @param: chip, the tpm chip description
+ * @param: buf, the buffer where the data are received
+ * @param: count, the number of data to receive
+ * @return: the number of bytes read from TPM FIFO.
+ */
+static int st33zp24_spi_recv_data(struct udevice *dev, u8 *buf, size_t count)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+ int size = 0, burstcnt, len, ret, status;
+
+ while (size < count &&
+ st33zp24_spi_wait_for_stat(dev, TPM_STS_DATA_AVAIL | TPM_STS_VALID,
+ chip->timeout_c, &status) == 0) {
+ burstcnt = st33zp24_spi_get_burstcount(dev);
+ if (burstcnt < 0)
+ return burstcnt;
+ len = min_t(int, burstcnt, count - size);
+ ret = st33zp24_spi_read(dev, TPM_DATA_FIFO, buf + size, len);
+ if (ret < 0)
+ return ret;
+
+ size += len;
+ }
+ return size;
+}
+
+/*
+ * st33zp24_spi_recv received TPM response through TPM phy.
+ * @param: chip, tpm_chip description.
+ * @param: buf, the buffer to store data.
+ * @param: count, the number of bytes that can received (sizeof buf).
+ * @return: Returns zero in case of success else -EIO.
+ */
+static int st33zp24_spi_recv(struct udevice *dev, u8 *buf, size_t count)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+ int size, expected;
+
+ if (!chip)
+ return -ENODEV;
+
+ if (count < TPM_HEADER_SIZE) {
+ size = -EIO;
+ goto out;
+ }
+
+ size = st33zp24_spi_recv_data(dev, buf, TPM_HEADER_SIZE);
+ if (size < TPM_HEADER_SIZE) {
+ debug("TPM error, unable to read header\n");
+ goto out;
+ }
+
+ expected = get_unaligned_be32(buf + 2);
+ if (expected > count) {
+ size = -EIO;
+ goto out;
+ }
+
+ size += st33zp24_spi_recv_data(dev, &buf[TPM_HEADER_SIZE],
+ expected - TPM_HEADER_SIZE);
+ if (size < expected) {
+ debug("TPM error, unable to read remaining bytes of result\n");
+ size = -EIO;
+ goto out;
+ }
+
+out:
+ st33zp24_spi_cancel(dev);
+ st33zp24_spi_release_locality(dev);
+
+ return size;
+}
+
+/*
+ * st33zp24_spi_send send TPM commands through TPM phy.
+ * @param: chip, tpm_chip description.
+ * @param: buf, the buffer to send.
+ * @param: len, the number of bytes to send.
+ * @return: Returns zero in case of success else the negative error code.
+ */
+static int st33zp24_spi_send(struct udevice *dev, const u8 *buf, size_t len)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+ u32 i, size;
+ int burstcnt, ret, status;
+ u8 data, tpm_stat;
+
+ if (!chip)
+ return -ENODEV;
+ if (len < TPM_HEADER_SIZE)
+ return -EIO;
+
+ ret = st33zp24_spi_request_locality(dev);
+ if (ret < 0)
+ return ret;
+
+ tpm_stat = st33zp24_spi_status(dev);
+ if ((tpm_stat & TPM_STS_COMMAND_READY) == 0) {
+ st33zp24_spi_cancel(dev);
+ if (st33zp24_spi_wait_for_stat(dev, TPM_STS_COMMAND_READY,
+ chip->timeout_b, &status) < 0) {
+ ret = -ETIME;
+ goto out_err;
+ }
+ }
+
+ for (i = 0; i < len - 1;) {
+ burstcnt = st33zp24_spi_get_burstcount(dev);
+ if (burstcnt < 0)
+ return burstcnt;
+
+ size = min_t(int, len - i - 1, burstcnt);
+ ret = st33zp24_spi_write(dev, TPM_DATA_FIFO, buf + i, size);
+ if (ret < 0)
+ goto out_err;
+
+ i += size;
+ }
+
+ tpm_stat = st33zp24_spi_status(dev);
+ if ((tpm_stat & TPM_STS_DATA_EXPECT) == 0) {
+ ret = -EIO;
+ goto out_err;
+ }
+
+ ret = st33zp24_spi_write(dev, TPM_DATA_FIFO, buf + len - 1, 1);
+ if (ret < 0)
+ goto out_err;
+
+ tpm_stat = st33zp24_spi_status(dev);
+ if ((tpm_stat & TPM_STS_DATA_EXPECT) != 0) {
+ ret = -EIO;
+ goto out_err;
+ }
+
+ data = TPM_STS_GO;
+ ret = st33zp24_spi_write(dev, TPM_STS, &data, 1);
+ if (ret < 0)
+ goto out_err;
+
+ return len;
+
+out_err:
+ st33zp24_spi_cancel(dev);
+ st33zp24_spi_release_locality(dev);
+
+ return ret;
+}
+
+static int st33zp24_spi_cleanup(struct udevice *dev)
+{
+ st33zp24_spi_cancel(dev);
+ /*
+ * The TPM needs some time to clean up here,
+ * so we sleep rather than keeping the bus busy
+ */
+ mdelay(2);
+ st33zp24_spi_release_locality(dev);
+
+ return 0;
+}
+
+static int st33zp24_spi_init(struct udevice *dev)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+ struct st33zp24_spi_phy *phy = dev_get_platdata(dev);
+
+ chip->is_open = 1;
+
+ /* Default timeouts - these could move to the device tree */
+ chip->timeout_a = TIS_SHORT_TIMEOUT_MS;
+ chip->timeout_b = TIS_LONG_TIMEOUT_MS;
+ chip->timeout_c = TIS_SHORT_TIMEOUT_MS;
+ chip->timeout_d = TIS_SHORT_TIMEOUT_MS;
+
+ chip->locality = LOCALITY0;
+
+ phy->latency = st33zp24_spi_evaluate_latency(dev);
+ if (phy->latency <= 0)
+ return -ENODEV;
+
+ /*
+ * A timeout query to TPM can be placed here.
+ * Standard timeout values are used so far
+ */
+
+ return 0;
+}
+
+static int st33zp24_spi_open(struct udevice *dev)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+ int rc;
+
+ debug("%s: start\n", __func__);
+ if (chip->is_open)
+ return -EBUSY;
+
+ rc = st33zp24_spi_init(dev);
+ if (rc < 0)
+ chip->is_open = 0;
+
+ return rc;
+}
+
+static int st33zp24_spi_close(struct udevice *dev)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+
+ if (chip->is_open) {
+ st33zp24_spi_release_locality(dev);
+ chip->is_open = 0;
+ chip->vend_dev = 0;
+ }
+
+ return 0;
+}
+
+static int st33zp24_spi_get_desc(struct udevice *dev, char *buf, int size)
+{
+ struct tpm_chip *chip = dev_get_priv(dev);
+
+ if (size < 50)
+ return -ENOSPC;
+
+ return snprintf(buf, size, "1.2 TPM (%s, chip type %s device-id 0x%x)",
+ chip->is_open ? "open" : "closed",
+ dev->name,
+ chip->vend_dev >> 16);
+}
+
+const struct tpm_ops st33zp24_spi_tpm_ops = {
+ .open = st33zp24_spi_open,
+ .close = st33zp24_spi_close,
+ .recv = st33zp24_spi_recv,
+ .send = st33zp24_spi_send,
+ .cleanup = st33zp24_spi_cleanup,
+ .get_desc = st33zp24_spi_get_desc,
+};
+
+static int st33zp24_spi_probe(struct udevice *dev)
+{
+ struct tpm_chip_priv *uc_priv = dev_get_uclass_priv(dev);
+
+ uc_priv->duration_ms[TPM_SHORT] = TIS_SHORT_TIMEOUT_MS;
+ uc_priv->duration_ms[TPM_MEDIUM] = TIS_LONG_TIMEOUT_MS;
+ uc_priv->duration_ms[TPM_LONG] = TIS_LONG_TIMEOUT_MS;
+ uc_priv->retry_time_ms = TPM_TIMEOUT_MS;
+
+ debug("ST33ZP24 SPI TPM from STMicroelectronics found\n");
+
+ return 0;
+}
+
+static int st33zp24_spi_remove(struct udevice *dev)
+{
+ st33zp24_spi_release_locality(dev);
+
+ return 0;
+}
+
+static const struct udevice_id st33zp24_spi_ids[] = {
+ { .compatible = "st,st33zp24-spi" },
+ { }
+};
+
+U_BOOT_DRIVER(st33zp24_spi_spi) = {
+ .name = "st33zp24-spi",
+ .id = UCLASS_TPM,
+ .of_match = of_match_ptr(st33zp24_spi_ids),
+ .probe = st33zp24_spi_probe,
+ .remove = st33zp24_spi_remove,
+ .ops = &st33zp24_spi_tpm_ops,
+ .priv_auto_alloc_size = sizeof(struct tpm_chip),
+ .platdata_auto_alloc_size = sizeof(struct st33zp24_spi_phy),
+};
diff --git a/drivers/video/Kconfig b/drivers/video/Kconfig
index f54631cc172..fbc5d7cfe7e 100644
--- a/drivers/video/Kconfig
+++ b/drivers/video/Kconfig
@@ -44,7 +44,17 @@ config VIDEO_BPP32
this option, such displays will not be supported and console output
will be empty.
-config VIDEO_ROTATION
+config CONSOLE_NORMAL
+ bool "Support a simple text console"
+ depends on DM_VIDEO
+ default y if DM_VIDEO
+ help
+ Support drawing text on the frame buffer console so that it can be
+ used as a console. Rotation is not supported by this driver (see
+ CONFIG_CONSOLE_ROTATION for that). A built-in 8x16 font is used
+ for the display.
+
+config CONSOLE_ROTATION
bool "Support rotated displays"
depends on DM_VIDEO
help
@@ -57,6 +67,30 @@ config VIDEO_ROTATION
struct video_priv: 0=unrotated, 1=90 degrees clockwise, 2=180
degrees, 3=270 degrees.
+config CONSOLE_TRUETYPE
+ bool "Support a console that uses TrueType fonts"
+ depends on DM_VIDEO
+ help
+ TrueTrype fonts can provide outline-drawing capability rather than
+ needing to provide a bitmap for each font and size that is needed.
+ With this option you can adjust the text size and use a variety of
+ fonts. Note that this is noticeably slower than with normal console.
+
+config CONSOLE_TRUETYPE_SIZE
+ int "TrueType font size"
+ depends on CONSOLE_TRUETYPE
+ default 18
+ help
+ This sets the font size for the console. The size is measured in
+ pixels and is the nominal height of a character. Note that fonts
+ are commonly measured in 'points', being 1/72 inch (about 3.52mm).
+ However that measurement depends on the size of your display and
+ there is no standard display density. At present there is not a
+ method to select the display's physical size, which would allow
+ U-Boot to calculate the correct font size.
+
+source "drivers/video/fonts/Kconfig"
+
config VIDEO_VESA
bool "Enable VESA video driver support"
default n
diff --git a/drivers/video/Makefile b/drivers/video/Makefile
index be908f6ed8f..c55e6eda3b9 100644
--- a/drivers/video/Makefile
+++ b/drivers/video/Makefile
@@ -9,12 +9,14 @@ ifdef CONFIG_DM
obj-$(CONFIG_DISPLAY) += display-uclass.o
obj-$(CONFIG_DM_VIDEO) += backlight-uclass.o
obj-$(CONFIG_DM_VIDEO) += panel-uclass.o simple_panel.o
-obj-$(CONFIG_DM_VIDEO) += video-uclass.o vidconsole-uclass.o console_normal.o
+obj-$(CONFIG_DM_VIDEO) += video-uclass.o vidconsole-uclass.o
obj-$(CONFIG_DM_VIDEO) += video_bmp.o
ifdef CONFIG_DM_VIDEO
obj-$(CONFIG_DM_PWM) += pwm_backlight.o
endif
-obj-$(CONFIG_VIDEO_ROTATION) += console_rotate.o
+obj-$(CONFIG_CONSOLE_NORMAL) += console_normal.o
+obj-$(CONFIG_CONSOLE_ROTATION) += console_rotate.o
+obj-$(CONFIG_CONSOLE_TRUETYPE) += console_truetype.o fonts/
endif
obj-$(CONFIG_ATI_RADEON_FB) += ati_radeon_fb.o videomodes.o
diff --git a/drivers/video/console_normal.c b/drivers/video/console_normal.c
index d1031c8ed17..89a55dd11df 100644
--- a/drivers/video/console_normal.c
+++ b/drivers/video/console_normal.c
@@ -71,13 +71,18 @@ static int console_normal_move_rows(struct udevice *dev, uint rowdst,
return 0;
}
-static int console_normal_putc_xy(struct udevice *dev, uint x, uint y, char ch)
+static int console_normal_putc_xy(struct udevice *dev, uint x_frac, uint y,
+ char ch)
{
+ struct vidconsole_priv *vc_priv = dev_get_uclass_priv(dev);
struct udevice *vid = dev->parent;
struct video_priv *vid_priv = dev_get_uclass_priv(vid);
int i, row;
void *line = vid_priv->fb + y * vid_priv->line_length +
- x * VNBYTES(vid_priv->bpix);
+ VID_TO_PIXEL(x_frac) * VNBYTES(vid_priv->bpix);
+
+ if (x_frac + VID_TO_POS(vc_priv->x_charsize) > vc_priv->xsize_frac)
+ return -EAGAIN;
for (row = 0; row < VIDEO_FONT_HEIGHT; row++) {
uchar bits = video_fontdata[ch * VIDEO_FONT_HEIGHT + row];
@@ -125,6 +130,20 @@ static int console_normal_putc_xy(struct udevice *dev, uint x, uint y, char ch)
line += vid_priv->line_length;
}
+ return VID_TO_POS(VIDEO_FONT_WIDTH);
+}
+
+static int console_normal_probe(struct udevice *dev)
+{
+ struct vidconsole_priv *vc_priv = dev_get_uclass_priv(dev);
+ struct udevice *vid_dev = dev->parent;
+ struct video_priv *vid_priv = dev_get_uclass_priv(vid_dev);
+
+ vc_priv->x_charsize = VIDEO_FONT_WIDTH;
+ vc_priv->y_charsize = VIDEO_FONT_HEIGHT;
+ vc_priv->cols = vid_priv->xsize / VIDEO_FONT_WIDTH;
+ vc_priv->rows = vid_priv->ysize / VIDEO_FONT_HEIGHT;
+
return 0;
}
@@ -138,4 +157,5 @@ U_BOOT_DRIVER(vidconsole_normal) = {
.name = "vidconsole0",
.id = UCLASS_VIDEO_CONSOLE,
.ops = &console_normal_ops,
+ .probe = console_normal_probe,
};
diff --git a/drivers/video/console_rotate.c b/drivers/video/console_rotate.c
index ebb31d8cd0d..227141d6876 100644
--- a/drivers/video/console_rotate.c
+++ b/drivers/video/console_rotate.c
@@ -82,17 +82,22 @@ static int console_move_rows_1(struct udevice *dev, uint rowdst, uint rowsrc,
return 0;
}
-static int console_putc_xy_1(struct udevice *dev, uint x, uint y, char ch)
+static int console_putc_xy_1(struct udevice *dev, uint x_frac, uint y, char ch)
{
+ struct vidconsole_priv *vc_priv = dev_get_uclass_priv(dev);
struct udevice *vid = dev->parent;
struct video_priv *vid_priv = dev_get_uclass_priv(vid);
int pbytes = VNBYTES(vid_priv->bpix);
int i, col;
int mask = 0x80;
- void *line = vid_priv->fb + (x + 1) * vid_priv->line_length -
- (y + 1) * pbytes;
+ void *line;
uchar *pfont = video_fontdata + ch * VIDEO_FONT_HEIGHT;
+ line = vid_priv->fb + (VID_TO_PIXEL(x_frac) + 1) *
+ vid_priv->line_length - (y + 1) * pbytes;
+ if (x_frac + VID_TO_POS(vc_priv->x_charsize) > vc_priv->xsize_frac)
+ return -EAGAIN;
+
for (col = 0; col < VIDEO_FONT_HEIGHT; col++) {
switch (vid_priv->bpix) {
#ifdef CONFIG_VIDEO_BPP8
@@ -135,7 +140,7 @@ static int console_putc_xy_1(struct udevice *dev, uint x, uint y, char ch)
mask >>= 1;
}
- return 0;
+ return VID_TO_POS(VIDEO_FONT_WIDTH);
}
@@ -201,17 +206,21 @@ static int console_move_rows_2(struct udevice *dev, uint rowdst, uint rowsrc,
return 0;
}
-static int console_putc_xy_2(struct udevice *dev, uint x, uint y, char ch)
+static int console_putc_xy_2(struct udevice *dev, uint x_frac, uint y, char ch)
{
+ struct vidconsole_priv *vc_priv = dev_get_uclass_priv(dev);
struct udevice *vid = dev->parent;
struct video_priv *vid_priv = dev_get_uclass_priv(vid);
int i, row;
void *line;
+ if (x_frac + VID_TO_POS(vc_priv->x_charsize) > vc_priv->xsize_frac)
+ return -EAGAIN;
+
line = vid_priv->fb + (vid_priv->ysize - y - 1) *
- vid_priv->line_length +
- (vid_priv->xsize - x - VIDEO_FONT_WIDTH - 1) *
- VNBYTES(vid_priv->bpix);
+ vid_priv->line_length +
+ (vid_priv->xsize - VID_TO_PIXEL(x_frac) -
+ VIDEO_FONT_WIDTH - 1) * VNBYTES(vid_priv->bpix);
for (row = 0; row < VIDEO_FONT_HEIGHT; row++) {
uchar bits = video_fontdata[ch * VIDEO_FONT_HEIGHT + row];
@@ -259,7 +268,7 @@ static int console_putc_xy_2(struct udevice *dev, uint x, uint y, char ch)
line -= vid_priv->line_length;
}
- return 0;
+ return VID_TO_POS(VIDEO_FONT_WIDTH);
}
static int console_set_row_3(struct udevice *dev, uint row, int clr)
@@ -329,17 +338,22 @@ static int console_move_rows_3(struct udevice *dev, uint rowdst, uint rowsrc,
return 0;
}
-static int console_putc_xy_3(struct udevice *dev, uint x, uint y, char ch)
+static int console_putc_xy_3(struct udevice *dev, uint x_frac, uint y, char ch)
{
+ struct vidconsole_priv *vc_priv = dev_get_uclass_priv(dev);
struct udevice *vid = dev->parent;
struct video_priv *vid_priv = dev_get_uclass_priv(vid);
int pbytes = VNBYTES(vid_priv->bpix);
int i, col;
int mask = 0x80;
- void *line = vid_priv->fb + (vid_priv->ysize - x - 1) *
+ void *line = vid_priv->fb +
+ (vid_priv->ysize - VID_TO_PIXEL(x_frac) - 1) *
vid_priv->line_length + y * pbytes;
uchar *pfont = video_fontdata + ch * VIDEO_FONT_HEIGHT;
+ if (x_frac + VID_TO_POS(vc_priv->x_charsize) > vc_priv->xsize_frac)
+ return -EAGAIN;
+
for (col = 0; col < VIDEO_FONT_HEIGHT; col++) {
switch (vid_priv->bpix) {
#ifdef CONFIG_VIDEO_BPP8
@@ -382,17 +396,35 @@ static int console_putc_xy_3(struct udevice *dev, uint x, uint y, char ch)
mask >>= 1;
}
- return 0;
+ return VID_TO_POS(VIDEO_FONT_WIDTH);
}
+static int console_probe_2(struct udevice *dev)
+{
+ struct vidconsole_priv *vc_priv = dev_get_uclass_priv(dev);
+ struct udevice *vid_dev = dev->parent;
+ struct video_priv *vid_priv = dev_get_uclass_priv(vid_dev);
+
+ vc_priv->x_charsize = VIDEO_FONT_WIDTH;
+ vc_priv->y_charsize = VIDEO_FONT_HEIGHT;
+ vc_priv->cols = vid_priv->xsize / VIDEO_FONT_WIDTH;
+ vc_priv->rows = vid_priv->ysize / VIDEO_FONT_HEIGHT;
+
+ return 0;
+}
+
static int console_probe_1_3(struct udevice *dev)
{
- struct vidconsole_priv *priv = dev_get_uclass_priv(dev);
- struct video_priv *vid_priv = dev_get_uclass_priv(dev->parent);
+ struct vidconsole_priv *vc_priv = dev_get_uclass_priv(dev);
+ struct udevice *vid_dev = dev->parent;
+ struct video_priv *vid_priv = dev_get_uclass_priv(vid_dev);
- priv->cols = vid_priv->ysize / VIDEO_FONT_WIDTH;
- priv->rows = vid_priv->xsize / VIDEO_FONT_HEIGHT;
+ vc_priv->x_charsize = VIDEO_FONT_WIDTH;
+ vc_priv->y_charsize = VIDEO_FONT_HEIGHT;
+ vc_priv->cols = vid_priv->ysize / VIDEO_FONT_WIDTH;
+ vc_priv->rows = vid_priv->xsize / VIDEO_FONT_HEIGHT;
+ vc_priv->xsize_frac = VID_TO_POS(vid_priv->ysize);
return 0;
}
@@ -426,6 +458,7 @@ U_BOOT_DRIVER(vidconsole_2) = {
.name = "vidconsole2",
.id = UCLASS_VIDEO_CONSOLE,
.ops = &console_ops_2,
+ .probe = console_probe_2,
};
U_BOOT_DRIVER(vidconsole_3) = {
diff --git a/drivers/video/console_truetype.c b/drivers/video/console_truetype.c
new file mode 100644
index 00000000000..c249f047f5b
--- /dev/null
+++ b/drivers/video/console_truetype.c
@@ -0,0 +1,550 @@
+/*
+ * Copyright (c) 2016 Google, Inc
+ *
+ * SPDX-License-Identifier: GPL-2.0+
+ */
+
+#include <common.h>
+#include <dm.h>
+#include <video.h>
+#include <video_console.h>
+
+/* Functions needed by stb_truetype.h */
+static int tt_floor(double val)
+{
+ if (val < 0)
+ return (int)(val - 0.999);
+
+ return (int)val;
+}
+
+static int tt_ceil(double val)
+{
+ if (val < 0)
+ return (int)val;
+
+ return (int)(val + 0.999);
+}
+
+static double frac(double val)
+{
+ return val - tt_floor(val);
+}
+
+static double tt_fabs(double x)
+{
+ return x < 0 ? -x : x;
+}
+
+ /*
+ * Simple square root algorithm. This is from:
+ * http://stackoverflow.com/questions/1623375/writing-your-own-square-root-function
+ * Written by Chihung Yu
+ * Creative Commons license
+ * http://creativecommons.org/licenses/by-sa/3.0/legalcode
+ * It has been modified to compile correctly, and for U-Boot style.
+ */
+static double tt_sqrt(double value)
+{
+ double lo = 1.0;
+ double hi = value;
+
+ while (hi - lo > 0.00001) {
+ double mid = lo + (hi - lo) / 2;
+
+ if (mid * mid - value > 0.00001)
+ hi = mid;
+ else
+ lo = mid;
+ }
+
+ return lo;
+}
+
+#define STBTT_ifloor tt_floor
+#define STBTT_iceil tt_ceil
+#define STBTT_fabs tt_fabs
+#define STBTT_sqrt tt_sqrt
+#define STBTT_malloc(size, u) ((void)(u), malloc(size))
+#define STBTT_free(size, u) ((void)(u), free(size))
+#define STBTT_assert(x)
+#define STBTT_strlen(x) strlen(x)
+#define STBTT_memcpy memcpy
+#define STBTT_memset memset
+
+#define STB_TRUETYPE_IMPLEMENTATION
+#include "stb_truetype.h"
+
+/**
+ * struct pos_info - Records a cursor position
+ *
+ * @xpos_frac: Fractional X position in pixels (multiplied by VID_FRAC_DIV)
+ * @ypos: Y position (pixels from the top)
+ */
+struct pos_info {
+ int xpos_frac;
+ int ypos;
+};
+
+/*
+ * Allow one for each character on the command line plus one for each newline.
+ * This is just an estimate, but it should not be exceeded.
+ */
+#define POS_HISTORY_SIZE (CONFIG_SYS_CBSIZE * 11 / 10)
+
+/**
+ * struct console_tt_priv - Private data for this driver
+ *
+ * @font_size: Vertical font size in pixels
+ * @font_data: Pointer to TrueType font file contents
+ * @font: TrueType font information for the current font
+ * @pos: List of cursor positions for each character written. This is
+ * used to handle backspace. We clear the frame buffer between
+ * the last position and the current position, thus erasing the
+ * last character. We record enough characters to go back to the
+ * start of the current command line.
+ * @pos_ptr: Current position in the position history
+ * @baseline: Pixel offset of the font's baseline from the cursor position.
+ * This is the 'ascent' of the font, scaled to pixel coordinates.
+ * It measures the distance from the baseline to the top of the
+ * font.
+ * @scale: Scale of the font. This is calculated from the pixel height
+ * of the font. It is used by the STB library to generate images
+ * of the correct size.
+ */
+struct console_tt_priv {
+ int font_size;
+ u8 *font_data;
+ stbtt_fontinfo font;
+ struct pos_info pos[POS_HISTORY_SIZE];
+ int pos_ptr;
+ int baseline;
+ double scale;
+};
+
+static int console_truetype_set_row(struct udevice *dev, uint row, int clr)
+{
+ struct video_priv *vid_priv = dev_get_uclass_priv(dev->parent);
+ struct console_tt_priv *priv = dev_get_priv(dev);
+ void *line;
+ int pixels = priv->font_size * vid_priv->line_length;
+ int i;
+
+ line = vid_priv->fb + row * priv->font_size * vid_priv->line_length;
+ switch (vid_priv->bpix) {
+#ifdef CONFIG_VIDEO_BPP8
+ case VIDEO_BPP8: {
+ uint8_t *dst = line;
+
+ for (i = 0; i < pixels; i++)
+ *dst++ = clr;
+ break;
+ }
+#endif
+#ifdef CONFIG_VIDEO_BPP16
+ case VIDEO_BPP16: {
+ uint16_t *dst = line;
+
+ for (i = 0; i < pixels; i++)
+ *dst++ = clr;
+ break;
+ }
+#endif
+#ifdef CONFIG_VIDEO_BPP32
+ case VIDEO_BPP32: {
+ uint32_t *dst = line;
+
+ for (i = 0; i < pixels; i++)
+ *dst++ = clr;
+ break;
+ }
+#endif
+ default:
+ return -ENOSYS;
+ }
+
+ return 0;
+}
+
+static int console_truetype_move_rows(struct udevice *dev, uint rowdst,
+ uint rowsrc, uint count)
+{
+ struct video_priv *vid_priv = dev_get_uclass_priv(dev->parent);
+ struct console_tt_priv *priv = dev_get_priv(dev);
+ void *dst;
+ void *src;
+ int i, diff;
+
+ dst = vid_priv->fb + rowdst * priv->font_size * vid_priv->line_length;
+ src = vid_priv->fb + rowsrc * priv->font_size * vid_priv->line_length;
+ memmove(dst, src, priv->font_size * vid_priv->line_length * count);
+
+ /* Scroll up our position history */
+ diff = (rowsrc - rowdst) * priv->font_size;
+ for (i = 0; i < priv->pos_ptr; i++)
+ priv->pos[i].ypos -= diff;
+
+ return 0;
+}
+
+static int console_truetype_putc_xy(struct udevice *dev, uint x, uint y,
+ char ch)
+{
+ struct vidconsole_priv *vc_priv = dev_get_uclass_priv(dev);
+ struct udevice *vid = dev->parent;
+ struct video_priv *vid_priv = dev_get_uclass_priv(vid);
+ struct console_tt_priv *priv = dev_get_priv(dev);
+ stbtt_fontinfo *font = &priv->font;
+ int width, height, xoff, yoff;
+ double xpos, x_shift;
+ int lsb;
+ int width_frac, linenum;
+ struct pos_info *pos;
+ u8 *bits, *data;
+ int advance;
+ void *line;
+ int row;
+
+ /* First get some basic metrics about this character */
+ stbtt_GetCodepointHMetrics(font, ch, &advance, &lsb);
+
+ /*
+ * First out our current X position in fractional pixels. If we wrote
+ * a character previously, using kerning to fine-tune the position of
+ * this character */
+ xpos = frac(VID_TO_PIXEL((double)x));
+ if (vc_priv->last_ch) {
+ xpos += priv->scale * stbtt_GetCodepointKernAdvance(font,
+ vc_priv->last_ch, ch);
+ }
+
+ /*
+ * Figure out where the cursor will move to after this character, and
+ * abort if we are out of space on this line. Also calculate the
+ * effective width of this character, which will be our return value:
+ * it dictates how much the cursor will move forward on the line.
+ */
+ x_shift = xpos - (double)tt_floor(xpos);
+ xpos += advance * priv->scale;
+ width_frac = (int)VID_TO_POS(xpos);
+ if (x + width_frac >= vc_priv->xsize_frac)
+ return -EAGAIN;
+
+ /* Write the current cursor position into history */
+ if (priv->pos_ptr < POS_HISTORY_SIZE) {
+ pos = &priv->pos[priv->pos_ptr];
+ pos->xpos_frac = vc_priv->xcur_frac;
+ pos->ypos = vc_priv->ycur;
+ priv->pos_ptr++;
+ }
+
+ /*
+ * Figure out how much past the start of a pixel we are, and pass this
+ * information into the render, which will return a 8-bit-per-pixel
+ * image of the character. For empty characters, like ' ', data will
+ * return NULL;
+ */
+ data = stbtt_GetCodepointBitmapSubpixel(font, priv->scale, priv->scale,
+ x_shift, 0, ch, &width, &height,
+ &xoff, &yoff);
+ if (!data)
+ return width_frac;
+
+ /* Figure out where to write the character in the frame buffer */
+ bits = data;
+ line = vid_priv->fb + y * vid_priv->line_length +
+ VID_TO_PIXEL(x) * VNBYTES(vid_priv->bpix);
+ linenum = priv->baseline + yoff;
+ if (linenum > 0)
+ line += linenum * vid_priv->line_length;
+
+ /*
+ * Write a row at a time, converting the 8bpp image into the colour
+ * depth of the display. We only expect white-on-black or the reverse
+ * so the code only handles this simple case.
+ */
+ for (row = 0; row < height; row++) {
+ switch (vid_priv->bpix) {
+#ifdef CONFIG_VIDEO_BPP16
+ case VIDEO_BPP16: {
+ uint16_t *dst = (uint16_t *)line + xoff;
+ int i;
+
+ for (i = 0; i < width; i++) {
+ int val = *bits;
+ int out;
+
+ if (vid_priv->colour_bg)
+ val = 255 - val;
+ out = val >> 3 |
+ (val >> 2) << 5 |
+ (val >> 3) << 11;
+ if (vid_priv->colour_fg)
+ *dst++ |= out;
+ else
+ *dst++ &= out;
+ bits++;
+ }
+ break;
+ }
+#endif
+ default:
+ return -ENOSYS;
+ }
+
+ line += vid_priv->line_length;
+ }
+ free(data);
+
+ return width_frac;
+}
+
+/**
+ * console_truetype_erase() - Erase a character
+ *
+ * This is used for backspace. We erase a square of the display within the
+ * given bounds.
+ *
+ * @dev: Device to update
+ * @xstart: X start position in pixels from the left
+ * @ystart: Y start position in pixels from the top
+ * @xend: X end position in pixels from the left
+ * @yend: Y end position in pixels from the top
+ * @clr: Value to write
+ * @return 0 if OK, -ENOSYS if the display depth is not supported
+ */
+static int console_truetype_erase(struct udevice *dev, int xstart, int ystart,
+ int xend, int yend, int clr)
+{
+ struct video_priv *vid_priv = dev_get_uclass_priv(dev->parent);
+ void *line;
+ int pixels = xend - xstart;
+ int row, i;
+
+ line = vid_priv->fb + ystart * vid_priv->line_length;
+ line += xstart * VNBYTES(vid_priv->bpix);
+ for (row = ystart; row < yend; row++) {
+ switch (vid_priv->bpix) {
+#ifdef CONFIG_VIDEO_BPP8
+ case VIDEO_BPP8: {
+ uint8_t *dst = line;
+
+ for (i = 0; i < pixels; i++)
+ *dst++ = clr;
+ break;
+ }
+#endif
+#ifdef CONFIG_VIDEO_BPP16
+ case VIDEO_BPP16: {
+ uint16_t *dst = line;
+
+ for (i = 0; i < pixels; i++)
+ *dst++ = clr;
+ break;
+ }
+#endif
+#ifdef CONFIG_VIDEO_BPP32
+ case VIDEO_BPP32: {
+ uint32_t *dst = line;
+
+ for (i = 0; i < pixels; i++)
+ *dst++ = clr;
+ break;
+ }
+#endif
+ default:
+ return -ENOSYS;
+ }
+ line += vid_priv->line_length;
+ }
+
+ return 0;
+}
+
+/**
+ * console_truetype_backspace() - Handle a backspace operation
+ *
+ * This clears the previous character so that the console looks as if it had
+ * not been entered.
+ *
+ * @dev: Device to update
+ * @return 0 if OK, -ENOSYS if not supported
+ */
+static int console_truetype_backspace(struct udevice *dev)
+{
+ struct vidconsole_priv *vc_priv = dev_get_uclass_priv(dev);
+ struct console_tt_priv *priv = dev_get_priv(dev);
+ struct udevice *vid_dev = dev->parent;
+ struct video_priv *vid_priv = dev_get_uclass_priv(vid_dev);
+ struct pos_info *pos;
+ int xend;
+
+ /*
+ * This indicates a very strange error higher in the stack. The caller
+ * has sent out n character and n + 1 backspaces.
+ */
+ if (!priv->pos_ptr)
+ return -ENOSYS;
+
+ /* Pop the last cursor position off the stack */
+ pos = &priv->pos[--priv->pos_ptr];
+
+ /*
+ * Figure out the end position for clearing. Normlly it is the current
+ * cursor position, but if we are clearing a character on the previous
+ * line, we clear from the end of the line.
+ */
+ if (pos->ypos == vc_priv->ycur)
+ xend = VID_TO_PIXEL(vc_priv->xcur_frac);
+ else
+ xend = vid_priv->xsize;
+
+ console_truetype_erase(dev, VID_TO_PIXEL(pos->xpos_frac), pos->ypos,
+ xend, pos->ypos + vc_priv->y_charsize,
+ vid_priv->colour_bg);
+
+ /* Move the cursor back to where it was when we pushed this record */
+ vc_priv->xcur_frac = pos->xpos_frac;
+ vc_priv->ycur = pos->ypos;
+
+ return 0;
+}
+
+static int console_truetype_entry_start(struct udevice *dev)
+{
+ struct console_tt_priv *priv = dev_get_priv(dev);
+
+ /* A new input line has start, so clear our history */
+ priv->pos_ptr = 0;
+
+ return 0;
+}
+
+/*
+ * Provides a list of fonts which can be obtained at run-time in U-Boot. These
+ * are compiled in by the Makefile.
+ *
+ * At present there is no mechanism to select a particular font - the first
+ * one found is the one that is used. But the build system and the code here
+ * supports multiple fonts, which may be useful for certain firmware screens.
+ */
+struct font_info {
+ char *name;
+ u8 *begin;
+ u8 *end;
+};
+
+#define FONT_DECL(_name) \
+ extern u8 __ttf_ ## _name ## _begin[]; \
+ extern u8 __ttf_ ## _name ## _end[];
+
+#define FONT_ENTRY(_name) { \
+ .name = #_name, \
+ .begin = __ttf_ ## _name ## _begin, \
+ .end = __ttf_ ## _name ## _end, \
+ }
+
+FONT_DECL(nimbus_sans_l_regular);
+FONT_DECL(ankacoder_c75_r);
+FONT_DECL(rufscript010);
+FONT_DECL(cantoraone_regular);
+
+static struct font_info font_table[] = {
+#ifdef CONFIG_CONSOLE_TRUETYPE_NIMBUS
+ FONT_ENTRY(nimbus_sans_l_regular),
+#endif
+#ifdef CONFIG_CONSOLE_TRUETYPE_ANKACODER
+ FONT_ENTRY(ankacoder_c75_r),
+#endif
+#ifdef CONFIG_CONSOLE_TRUETYPE_RUFSCRIPT
+ FONT_ENTRY(rufscript010),
+#endif
+#ifdef CONFIG_CONSOLE_TRUETYPE_CANTORAONE
+ FONT_ENTRY(cantoraone_regular),
+#endif
+ {} /* sentinel */
+};
+
+#define FONT_BEGIN(name) __ttf_ ## name ## _begin
+#define FONT_END(name) __ttf_ ## name ## _end
+#define FONT_IS_VALID(name) (abs(FONT_END(name) - FONT_BEGIN) > 4)
+
+/**
+ * console_truetype_find_font() - Find a suitable font
+ *
+ * This searched for the first available font.
+ *
+ * @return pointer to the font, or NULL if none is found
+ */
+static u8 *console_truetype_find_font(void)
+{
+ struct font_info *tab;
+
+ for (tab = font_table; tab->begin; tab++) {
+ if (abs(tab->begin - tab->end) > 4) {
+ debug("%s: Font '%s', at %p, size %lx\n", __func__,
+ tab->name, tab->begin,
+ (ulong)(tab->end - tab->begin));
+ return tab->begin;
+ }
+ }
+
+ return NULL;
+}
+
+static int console_truetype_probe(struct udevice *dev)
+{
+ struct vidconsole_priv *vc_priv = dev_get_uclass_priv(dev);
+ struct console_tt_priv *priv = dev_get_priv(dev);
+ struct udevice *vid_dev = dev->parent;
+ struct video_priv *vid_priv = dev_get_uclass_priv(vid_dev);
+ stbtt_fontinfo *font = &priv->font;
+ int ascent;
+
+ debug("%s: start\n", __func__);
+ if (vid_priv->font_size)
+ priv->font_size = vid_priv->font_size;
+ else
+ priv->font_size = CONFIG_CONSOLE_TRUETYPE_SIZE;
+ priv->font_data = console_truetype_find_font();
+ if (!priv->font_data) {
+ debug("%s: Could not find any fonts\n", __func__);
+ return -EBFONT;
+ }
+
+ vc_priv->x_charsize = priv->font_size;
+ vc_priv->y_charsize = priv->font_size;
+ vc_priv->xstart_frac = VID_TO_POS(2);
+ vc_priv->cols = vid_priv->xsize / priv->font_size;
+ vc_priv->rows = vid_priv->ysize / priv->font_size;
+ vc_priv->tab_width_frac = VID_TO_POS(priv->font_size) * 8 / 2;
+
+ if (!stbtt_InitFont(font, priv->font_data, 0)) {
+ debug("%s: Font init failed\n", __func__);
+ return -EPERM;
+ }
+
+ /* Pre-calculate some things we will need regularly */
+ priv->scale = stbtt_ScaleForPixelHeight(font, priv->font_size);
+ stbtt_GetFontVMetrics(font, &ascent, 0, 0);
+ priv->baseline = (int)(ascent * priv->scale);
+ debug("%s: ready\n", __func__);
+
+ return 0;
+}
+
+struct vidconsole_ops console_truetype_ops = {
+ .putc_xy = console_truetype_putc_xy,
+ .move_rows = console_truetype_move_rows,
+ .set_row = console_truetype_set_row,
+ .backspace = console_truetype_backspace,
+ .entry_start = console_truetype_entry_start,
+};
+
+U_BOOT_DRIVER(vidconsole_truetype) = {
+ .name = "vidconsole_tt",
+ .id = UCLASS_VIDEO_CONSOLE,
+ .ops = &console_truetype_ops,
+ .probe = console_truetype_probe,
+ .priv_auto_alloc_size = sizeof(struct console_tt_priv),
+};
diff --git a/drivers/video/fonts/Kconfig b/drivers/video/fonts/Kconfig
new file mode 100644
index 00000000000..3f1398db50c
--- /dev/null
+++ b/drivers/video/fonts/Kconfig
@@ -0,0 +1,51 @@
+#
+# Video fonts
+#
+
+menu "TrueType Fonts"
+
+config CONSOLE_TRUETYPE_NIMBUS
+ bool "Nimbus Sans Regular"
+ depends on CONSOLE_TRUETYPE
+ help
+ Nimbus Sans L is a version of Nimbus Sans using Adobe font sources.
+ It was designed in 1987. A subset of Nimbus Sans L were released
+ under the GPL. Although the characters are not exactly the same,
+ Nimbus Sans L has metrics almost identical to Helvetica and Arial.
+ (From Wikipedia, the free encyclopedia)
+ From: https://fontlibrary.org/en/font/nimbus-sans-l
+ License: GNU GPL v3
+ http://www.gnu.org/copyleft/gpl.html
+
+config CONSOLE_TRUETYPE_ANKACODER
+ bool "Anka Coder Narrow"
+ depends on CONSOLE_TRUETYPE
+ help
+ The Anka/Coder family is a monospaced, courier-width font for source
+ code and terminals, in two styles and weights. Anka/Coder Narrow was
+ developed for printing source code.
+ https://code.google.com/p/anka-coder-fonts/
+ From: https://fontlibrary.org/en/font/anka-coder-narrow
+ License: SIL Open Font Licence
+ http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL
+
+config CONSOLE_TRUETYPE_RUFSCRIPT
+ bool "Ruf Script"
+ depends on CONSOLE_TRUETYPE
+ help
+ A laid-back handwritten font.
+ Font: https://fontlibrary.org/en/font/rufscript
+ License: GPL with font exception
+ http://www.gnu.org/copyleft/gpl.html
+
+config CONSOLE_TRUETYPE_CANTORAONE
+ bool "Cantoraone"
+ depends on CONSOLE_TRUETYPE
+ help
+ Cantora is a friendly semi formal, semi condensed, semi sans-serif
+ with a hint of handwriting. Perfect for headlines.
+ From https://fontlibrary.org/en/font/cantora
+ License: SIL Open Font Licence
+ http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL
+
+endmenu
diff --git a/drivers/video/fonts/Makefile b/drivers/video/fonts/Makefile
new file mode 100644
index 00000000000..46137f4f7e5
--- /dev/null
+++ b/drivers/video/fonts/Makefile
@@ -0,0 +1,11 @@
+#
+# (C) Copyright 2000-2007
+# Wolfgang Denk, DENX Software Engineering, wd@denx.de.
+#
+# SPDX-License-Identifier: GPL-2.0+
+#
+
+obj-$(CONFIG_CONSOLE_TRUETYPE_NIMBUS) += nimbus_sans_l_regular.o
+obj-$(CONFIG_CONSOLE_TRUETYPE_ANKACODER) += ankacoder_c75_r.o
+obj-$(CONFIG_CONSOLE_TRUETYPE_RUFSCRIPT) += rufscript010.o
+obj-$(CONFIG_CONSOLE_TRUETYPE_CANTORAONE) += cantoraone_regular.o
diff --git a/drivers/video/fonts/ankacoder_c75_r.ttf b/drivers/video/fonts/ankacoder_c75_r.ttf
new file mode 100644
index 00000000000..3b73dcf00e7
--- /dev/null
+++ b/drivers/video/fonts/ankacoder_c75_r.ttf
Binary files differ
diff --git a/drivers/video/fonts/cantoraone_regular.ttf b/drivers/video/fonts/cantoraone_regular.ttf
new file mode 100644
index 00000000000..57446a27a03
--- /dev/null
+++ b/drivers/video/fonts/cantoraone_regular.ttf
Binary files differ
diff --git a/drivers/video/fonts/nimbus_sans_l_regular.ttf b/drivers/video/fonts/nimbus_sans_l_regular.ttf
new file mode 100644
index 00000000000..3bd694d8ee5
--- /dev/null
+++ b/drivers/video/fonts/nimbus_sans_l_regular.ttf
Binary files differ
diff --git a/drivers/video/fonts/rufscript010.ttf b/drivers/video/fonts/rufscript010.ttf
new file mode 100644
index 00000000000..887a4496f3c
--- /dev/null
+++ b/drivers/video/fonts/rufscript010.ttf
Binary files differ
diff --git a/drivers/video/sandbox_sdl.c b/drivers/video/sandbox_sdl.c
index 21448a14115..dc5a220d512 100644
--- a/drivers/video/sandbox_sdl.c
+++ b/drivers/video/sandbox_sdl.c
@@ -35,6 +35,8 @@ static int sandbox_sdl_probe(struct udevice *dev)
uc_priv->ysize = plat->yres;
uc_priv->bpix = plat->bpix;
uc_priv->rot = plat->rot;
+ uc_priv->vidconsole_drv_name = plat->vidconsole_drv_name;
+ uc_priv->font_size = plat->font_size;
return 0;
}
diff --git a/drivers/video/stb_truetype.h b/drivers/video/stb_truetype.h
new file mode 100644
index 00000000000..91d8e6f905c
--- /dev/null
+++ b/drivers/video/stb_truetype.h
@@ -0,0 +1,3240 @@
+// stb_truetype.h - v1.08 - public domain
+// authored from 2009-2015 by Sean Barrett / RAD Game Tools
+//
+// This library processes TrueType files:
+// parse files
+// extract glyph metrics
+// extract glyph shapes
+// render glyphs to one-channel bitmaps with antialiasing (box filter)
+//
+// Todo:
+// non-MS cmaps
+// crashproof on bad data
+// hinting? (no longer patented)
+// cleartype-style AA?
+// optimize: use simple memory allocator for intermediates
+// optimize: build edge-list directly from curves
+// optimize: rasterize directly from curves?
+//
+// ADDITIONAL CONTRIBUTORS
+//
+// Mikko Mononen: compound shape support, more cmap formats
+// Tor Andersson: kerning, subpixel rendering
+//
+// Bug/warning reports/fixes:
+// "Zer" on mollyrocket (with fix)
+// Cass Everitt
+// stoiko (Haemimont Games)
+// Brian Hook
+// Walter van Niftrik
+// David Gow
+// David Given
+// Ivan-Assen Ivanov
+// Anthony Pesch
+// Johan Duparc
+// Hou Qiming
+// Fabian "ryg" Giesen
+// Martins Mozeiko
+// Cap Petschulat
+// Omar Cornut
+// github:aloucks
+// Peter LaValle
+// Sergey Popov
+// Giumo X. Clanjor
+// Higor Euripedes
+//
+// Misc other:
+// Ryan Gordon
+//
+// VERSION HISTORY
+//
+// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
+// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
+// variant PackFontRanges to pack and render in separate phases;
+// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
+// fixed an assert() bug in the new rasterizer
+// replace assert() with STBTT_assert() in new rasterizer
+// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine)
+// also more precise AA rasterizer, except if shapes overlap
+// remove need for STBTT_sort
+// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC
+// 1.04 (2015-04-15) typo in example
+// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes
+//
+// Full history can be found at the end of this file.
+//
+// LICENSE
+//
+// This software is in the public domain. Where that dedication is not
+// recognized, you are granted a perpetual, irrevocable license to copy,
+// distribute, and modify this file as you see fit.
+//
+// USAGE
+//
+// Include this file in whatever places neeed to refer to it. In ONE C/C++
+// file, write:
+// #define STB_TRUETYPE_IMPLEMENTATION
+// before the #include of this file. This expands out the actual
+// implementation into that C/C++ file.
+//
+// To make the implementation private to the file that generates the implementation,
+// #define STBTT_STATIC
+//
+// Simple 3D API (don't ship this, but it's fine for tools and quick start)
+// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture
+// stbtt_GetBakedQuad() -- compute quad to draw for a given char
+//
+// Improved 3D API (more shippable):
+// #include "stb_rect_pack.h" -- optional, but you really want it
+// stbtt_PackBegin()
+// stbtt_PackSetOversample() -- for improved quality on small fonts
+// stbtt_PackFontRanges() -- pack and renders
+// stbtt_PackEnd()
+// stbtt_GetPackedQuad()
+//
+// "Load" a font file from a memory buffer (you have to keep the buffer loaded)
+// stbtt_InitFont()
+// stbtt_GetFontOffsetForIndex() -- use for TTC font collections
+//
+// Render a unicode codepoint to a bitmap
+// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap
+// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide
+// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be
+//
+// Character advance/positioning
+// stbtt_GetCodepointHMetrics()
+// stbtt_GetFontVMetrics()
+// stbtt_GetCodepointKernAdvance()
+//
+// Starting with version 1.06, the rasterizer was replaced with a new,
+// faster and generally-more-precise rasterizer. The new rasterizer more
+// accurately measures pixel coverage for anti-aliasing, except in the case
+// where multiple shapes overlap, in which case it overestimates the AA pixel
+// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If
+// this turns out to be a problem, you can re-enable the old rasterizer with
+// #define STBTT_RASTERIZER_VERSION 1
+// which will incur about a 15% speed hit.
+//
+// ADDITIONAL DOCUMENTATION
+//
+// Immediately after this block comment are a series of sample programs.
+//
+// After the sample programs is the "header file" section. This section
+// includes documentation for each API function.
+//
+// Some important concepts to understand to use this library:
+//
+// Codepoint
+// Characters are defined by unicode codepoints, e.g. 65 is
+// uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is
+// the hiragana for "ma".
+//
+// Glyph
+// A visual character shape (every codepoint is rendered as
+// some glyph)
+//
+// Glyph index
+// A font-specific integer ID representing a glyph
+//
+// Baseline
+// Glyph shapes are defined relative to a baseline, which is the
+// bottom of uppercase characters. Characters extend both above
+// and below the baseline.
+//
+// Current Point
+// As you draw text to the screen, you keep track of a "current point"
+// which is the origin of each character. The current point's vertical
+// position is the baseline. Even "baked fonts" use this model.
+//
+// Vertical Font Metrics
+// The vertical qualities of the font, used to vertically position
+// and space the characters. See docs for stbtt_GetFontVMetrics.
+//
+// Font Size in Pixels or Points
+// The preferred interface for specifying font sizes in stb_truetype
+// is to specify how tall the font's vertical extent should be in pixels.
+// If that sounds good enough, skip the next paragraph.
+//
+// Most font APIs instead use "points", which are a common typographic
+// measurement for describing font size, defined as 72 points per inch.
+// stb_truetype provides a point API for compatibility. However, true
+// "per inch" conventions don't make much sense on computer displays
+// since they different monitors have different number of pixels per
+// inch. For example, Windows traditionally uses a convention that
+// there are 96 pixels per inch, thus making 'inch' measurements have
+// nothing to do with inches, and thus effectively defining a point to
+// be 1.333 pixels. Additionally, the TrueType font data provides
+// an explicit scale factor to scale a given font's glyphs to points,
+// but the author has observed that this scale factor is often wrong
+// for non-commercial fonts, thus making fonts scaled in points
+// according to the TrueType spec incoherently sized in practice.
+//
+// ADVANCED USAGE
+//
+// Quality:
+//
+// - Use the functions with Subpixel at the end to allow your characters
+// to have subpixel positioning. Since the font is anti-aliased, not
+// hinted, this is very import for quality. (This is not possible with
+// baked fonts.)
+//
+// - Kerning is now supported, and if you're supporting subpixel rendering
+// then kerning is worth using to give your text a polished look.
+//
+// Performance:
+//
+// - Convert Unicode codepoints to glyph indexes and operate on the glyphs;
+// if you don't do this, stb_truetype is forced to do the conversion on
+// every call.
+//
+// - There are a lot of memory allocations. We should modify it to take
+// a temp buffer and allocate from the temp buffer (without freeing),
+// should help performance a lot.
+//
+// NOTES
+//
+// The system uses the raw data found in the .ttf file without changing it
+// and without building auxiliary data structures. This is a bit inefficient
+// on little-endian systems (the data is big-endian), but assuming you're
+// caching the bitmaps or glyph shapes this shouldn't be a big deal.
+//
+// It appears to be very hard to programmatically determine what font a
+// given file is in a general way. I provide an API for this, but I don't
+// recommend it.
+//
+//
+// SOURCE STATISTICS (based on v0.6c, 2050 LOC)
+//
+// Documentation & header file 520 LOC \___ 660 LOC documentation
+// Sample code 140 LOC /
+// Truetype parsing 620 LOC ---- 620 LOC TrueType
+// Software rasterization 240 LOC \ .
+// Curve tesselation 120 LOC \__ 550 LOC Bitmap creation
+// Bitmap management 100 LOC /
+// Baked bitmap interface 70 LOC /
+// Font name matching & access 150 LOC ---- 150
+// C runtime library abstraction 60 LOC ---- 60
+//
+//
+// PERFORMANCE MEASUREMENTS FOR 1.06:
+//
+// 32-bit 64-bit
+// Previous release: 8.83 s 7.68 s
+// Pool allocations: 7.72 s 6.34 s
+// Inline sort : 6.54 s 5.65 s
+// New rasterizer : 5.63 s 5.00 s
+
+//////////////////////////////////////////////////////////////////////////////
+//////////////////////////////////////////////////////////////////////////////
+////
+//// SAMPLE PROGRAMS
+////
+//
+// Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless
+//
+#if 0
+#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
+#include "stb_truetype.h"
+
+unsigned char ttf_buffer[1<<20];
+unsigned char temp_bitmap[512*512];
+
+stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
+GLuint ftex;
+
+void my_stbtt_initfont(void)
+{
+ fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
+ stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!
+ // can free ttf_buffer at this point
+ glGenTextures(1, &ftex);
+ glBindTexture(GL_TEXTURE_2D, ftex);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);
+ // can free temp_bitmap at this point
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+}
+
+void my_stbtt_print(float x, float y, char *text)
+{
+ // assume orthographic projection with units = screen pixels, origin at top left
+ glEnable(GL_TEXTURE_2D);
+ glBindTexture(GL_TEXTURE_2D, ftex);
+ glBegin(GL_QUADS);
+ while (*text) {
+ if (*text >= 32 && *text < 128) {
+ stbtt_aligned_quad q;
+ stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9
+ glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0);
+ glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0);
+ glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1);
+ glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1);
+ }
+ ++text;
+ }
+ glEnd();
+}
+#endif
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+//
+// Complete program (this compiles): get a single bitmap, print as ASCII art
+//
+#if 0
+#include <stdio.h>
+#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
+#include "stb_truetype.h"
+
+char ttf_buffer[1<<25];
+
+int main(int argc, char **argv)
+{
+ stbtt_fontinfo font;
+ unsigned char *bitmap;
+ int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);
+
+ fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));
+
+ stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));
+ bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);
+
+ for (j=0; j < h; ++j) {
+ for (i=0; i < w; ++i)
+ putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);
+ putchar('\n');
+ }
+ return 0;
+}
+#endif
+//
+// Output:
+//
+// .ii.
+// @@@@@@.
+// V@Mio@@o
+// :i. V@V
+// :oM@@M
+// :@@@MM@M
+// @@o o@M
+// :@@. M@M
+// @@@o@@@@
+// :M@@V:@@.
+//
+//////////////////////////////////////////////////////////////////////////////
+//
+// Complete program: print "Hello World!" banner, with bugs
+//
+#if 0
+char buffer[24<<20];
+unsigned char screen[20][79];
+
+int main(int arg, char **argv)
+{
+ stbtt_fontinfo font;
+ int i,j,ascent,baseline,ch=0;
+ float scale, xpos=2; // leave a little padding in case the character extends left
+ char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness
+
+ fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
+ stbtt_InitFont(&font, buffer, 0);
+
+ scale = stbtt_ScaleForPixelHeight(&font, 15);
+ stbtt_GetFontVMetrics(&font, &ascent,0,0);
+ baseline = (int) (ascent*scale);
+
+ while (text[ch]) {
+ int advance,lsb,x0,y0,x1,y1;
+ float x_shift = xpos - (float) floor(xpos);
+ stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);
+ stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
+ stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);
+ // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
+ // because this API is really for baking character bitmaps into textures. if you want to render
+ // a sequence of characters, you really need to render each bitmap to a temp buffer, then
+ // "alpha blend" that into the working buffer
+ xpos += (advance * scale);
+ if (text[ch+1])
+ xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);
+ ++ch;
+ }
+
+ for (j=0; j < 20; ++j) {
+ for (i=0; i < 78; ++i)
+ putchar(" .:ioVM@"[screen[j][i]>>5]);
+ putchar('\n');
+ }
+
+ return 0;
+}
+#endif
+
+
+//////////////////////////////////////////////////////////////////////////////
+//////////////////////////////////////////////////////////////////////////////
+////
+//// INTEGRATION WITH YOUR CODEBASE
+////
+//// The following sections allow you to supply alternate definitions
+//// of C library functions used by stb_truetype.
+
+#ifdef STB_TRUETYPE_IMPLEMENTATION
+ // #define your own (u)stbtt_int8/16/32 before including to override this
+ #ifndef stbtt_uint8
+ typedef unsigned char stbtt_uint8;
+ typedef signed char stbtt_int8;
+ typedef unsigned short stbtt_uint16;
+ typedef signed short stbtt_int16;
+ typedef unsigned int stbtt_uint32;
+ typedef signed int stbtt_int32;
+ #endif
+
+ typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];
+ typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];
+
+ // #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h
+ #ifndef STBTT_ifloor
+ #include <math.h>
+ #define STBTT_ifloor(x) ((int) floor(x))
+ #define STBTT_iceil(x) ((int) ceil(x))
+ #endif
+
+ #ifndef STBTT_sqrt
+ #include <math.h>
+ #define STBTT_sqrt(x) sqrt(x)
+ #endif
+
+ #ifndef STBTT_fabs
+ #include <math.h>
+ #define STBTT_fabs(x) fabs(x)
+ #endif
+
+ // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
+ #ifndef STBTT_malloc
+ #include <stdlib.h>
+ #define STBTT_malloc(x,u) ((void)(u),malloc(x))
+ #define STBTT_free(x,u) ((void)(u),free(x))
+ #endif
+
+ #ifndef STBTT_assert
+ #include <assert.h>
+ #define STBTT_assert(x) assert(x)
+ #endif
+
+ #ifndef STBTT_strlen
+ #include <string.h>
+ #define STBTT_strlen(x) strlen(x)
+ #endif
+
+ #ifndef STBTT_memcpy
+ #include <memory.h>
+ #define STBTT_memcpy memcpy
+ #define STBTT_memset memset
+ #endif
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+////
+//// INTERFACE
+////
+////
+
+#ifndef __STB_INCLUDE_STB_TRUETYPE_H__
+#define __STB_INCLUDE_STB_TRUETYPE_H__
+
+#ifdef STBTT_STATIC
+#define STBTT_DEF static
+#else
+#define STBTT_DEF extern
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// TEXTURE BAKING API
+//
+// If you use this API, you only have to call two functions ever.
+//
+
+typedef struct
+{
+ unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
+ float xoff,yoff,xadvance;
+} stbtt_bakedchar;
+
+STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)
+ float pixel_height, // height of font in pixels
+ unsigned char *pixels, int pw, int ph, // bitmap to be filled in
+ int first_char, int num_chars, // characters to bake
+ stbtt_bakedchar *chardata); // you allocate this, it's num_chars long
+// if return is positive, the first unused row of the bitmap
+// if return is negative, returns the negative of the number of characters that fit
+// if return is 0, no characters fit and no rows were used
+// This uses a very crappy packing.
+
+typedef struct
+{
+ float x0,y0,s0,t0; // top-left
+ float x1,y1,s1,t1; // bottom-right
+} stbtt_aligned_quad;
+
+STBTT_DEF void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, // same data as above
+ int char_index, // character to display
+ float *xpos, float *ypos, // pointers to current position in screen pixel space
+ stbtt_aligned_quad *q, // output: quad to draw
+ int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier
+// Call GetBakedQuad with char_index = 'character - first_char', and it
+// creates the quad you need to draw and advances the current position.
+//
+// The coordinate system used assumes y increases downwards.
+//
+// Characters will extend both above and below the current position;
+// see discussion of "BASELINE" above.
+//
+// It's inefficient; you might want to c&p it and optimize it.
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// NEW TEXTURE BAKING API
+//
+// This provides options for packing multiple fonts into one atlas, not
+// perfectly but better than nothing.
+
+typedef struct
+{
+ unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap
+ float xoff,yoff,xadvance;
+ float xoff2,yoff2;
+} stbtt_packedchar;
+
+typedef struct stbtt_pack_context stbtt_pack_context;
+typedef struct stbtt_fontinfo stbtt_fontinfo;
+#ifndef STB_RECT_PACK_VERSION
+typedef struct stbrp_rect stbrp_rect;
+#endif
+
+STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context);
+// Initializes a packing context stored in the passed-in stbtt_pack_context.
+// Future calls using this context will pack characters into the bitmap passed
+// in here: a 1-channel bitmap that is weight x height. stride_in_bytes is
+// the distance from one row to the next (or 0 to mean they are packed tightly
+// together). "padding" is the amount of padding to leave between each
+// character (normally you want '1' for bitmaps you'll use as textures with
+// bilinear filtering).
+//
+// Returns 0 on failure, 1 on success.
+
+STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc);
+// Cleans up the packing context and frees all memory.
+
+#define STBTT_POINT_SIZE(x) (-(x))
+
+STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, float font_size,
+ int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range);
+// Creates character bitmaps from the font_index'th font found in fontdata (use
+// font_index=0 if you don't know what that is). It creates num_chars_in_range
+// bitmaps for characters with unicode values starting at first_unicode_char_in_range
+// and increasing. Data for how to render them is stored in chardata_for_range;
+// pass these to stbtt_GetPackedQuad to get back renderable quads.
+//
+// font_size is the full height of the character from ascender to descender,
+// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed
+// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE()
+// and pass that result as 'font_size':
+// ..., 20 , ... // font max minus min y is 20 pixels tall
+// ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall
+
+typedef struct
+{
+ float font_size;
+ int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint
+ int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints
+ int num_chars;
+ stbtt_packedchar *chardata_for_range; // output
+ unsigned char h_oversample, v_oversample; // don't set these, they're used internally
+} stbtt_pack_range;
+
+STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges);
+// Creates character bitmaps from multiple ranges of characters stored in
+// ranges. This will usually create a better-packed bitmap than multiple
+// calls to stbtt_PackFontRange. Note that you can call this multiple
+// times within a single PackBegin/PackEnd.
+
+STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample);
+// Oversampling a font increases the quality by allowing higher-quality subpixel
+// positioning, and is especially valuable at smaller text sizes.
+//
+// This function sets the amount of oversampling for all following calls to
+// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given
+// pack context. The default (no oversampling) is achieved by h_oversample=1
+// and v_oversample=1. The total number of pixels required is
+// h_oversample*v_oversample larger than the default; for example, 2x2
+// oversampling requires 4x the storage of 1x1. For best results, render
+// oversampled textures with bilinear filtering. Look at the readme in
+// stb/tests/oversample for information about oversampled fonts
+//
+// To use with PackFontRangesGather etc., you must set it before calls
+// call to PackFontRangesGatherRects.
+
+STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, // same data as above
+ int char_index, // character to display
+ float *xpos, float *ypos, // pointers to current position in screen pixel space
+ stbtt_aligned_quad *q, // output: quad to draw
+ int align_to_integer);
+
+STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
+STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects);
+STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
+// Calling these functions in sequence is roughly equivalent to calling
+// stbtt_PackFontRanges(). If you more control over the packing of multiple
+// fonts, or if you want to pack custom data into a font texture, take a look
+// at the source to of stbtt_PackFontRanges() and create a custom version
+// using these functions, e.g. call GatherRects multiple times,
+// building up a single array of rects, then call PackRects once,
+// then call RenderIntoRects repeatedly. This may result in a
+// better packing than calling PackFontRanges multiple times
+// (or it may not).
+
+// this is an opaque structure that you shouldn't mess with which holds
+// all the context needed from PackBegin to PackEnd.
+struct stbtt_pack_context {
+ void *user_allocator_context;
+ void *pack_info;
+ int width;
+ int height;
+ int stride_in_bytes;
+ int padding;
+ unsigned int h_oversample, v_oversample;
+ unsigned char *pixels;
+ void *nodes;
+};
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// FONT LOADING
+//
+//
+
+STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);
+// Each .ttf/.ttc file may have more than one font. Each font has a sequential
+// index number starting from 0. Call this function to get the font offset for
+// a given index; it returns -1 if the index is out of range. A regular .ttf
+// file will only define one font and it always be at offset 0, so it will
+// return '0' for index 0, and -1 for all other indices. You can just skip
+// this step if you know it's that kind of font.
+
+
+// The following structure is defined publically so you can declare one on
+// the stack or as a global or etc, but you should treat it as opaque.
+typedef struct stbtt_fontinfo
+{
+ void * userdata;
+ unsigned char * data; // pointer to .ttf file
+ int fontstart; // offset of start of font
+
+ int numGlyphs; // number of glyphs, needed for range checking
+
+ int loca,head,glyf,hhea,hmtx,kern; // table locations as offset from start of .ttf
+ int index_map; // a cmap mapping for our chosen character encoding
+ int indexToLocFormat; // format needed to map from glyph index to glyph
+} stbtt_fontinfo;
+
+STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);
+// Given an offset into the file that defines a font, this function builds
+// the necessary cached info for the rest of the system. You must allocate
+// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't
+// need to do anything special to free it, because the contents are pure
+// value data with no additional data structures. Returns 0 on failure.
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CHARACTER TO GLYPH-INDEX CONVERSIOn
+
+STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);
+// If you're going to perform multiple operations on the same character
+// and you want a speed-up, call this function with the character you're
+// going to process, then use glyph-based functions instead of the
+// codepoint-based functions.
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CHARACTER PROPERTIES
+//
+
+STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);
+// computes a scale factor to produce a font whose "height" is 'pixels' tall.
+// Height is measured as the distance from the highest ascender to the lowest
+// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics
+// and computing:
+// scale = pixels / (ascent - descent)
+// so if you prefer to measure height by the ascent only, use a similar calculation.
+
+STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels);
+// computes a scale factor to produce a font whose EM size is mapped to
+// 'pixels' tall. This is probably what traditional APIs compute, but
+// I'm not positive.
+
+STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);
+// ascent is the coordinate above the baseline the font extends; descent
+// is the coordinate below the baseline the font extends (i.e. it is typically negative)
+// lineGap is the spacing between one row's descent and the next row's ascent...
+// so you should advance the vertical position by "*ascent - *descent + *lineGap"
+// these are expressed in unscaled coordinates, so you must multiply by
+// the scale factor for a given size
+
+STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);
+// the bounding box around all possible characters
+
+STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);
+// leftSideBearing is the offset from the current horizontal position to the left edge of the character
+// advanceWidth is the offset from the current horizontal position to the next horizontal position
+// these are expressed in unscaled coordinates
+
+STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);
+// an additional amount to add to the 'advance' value between ch1 and ch2
+
+STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);
+// Gets the bounding box of the visible part of the glyph, in unscaled coordinates
+
+STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);
+STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);
+STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);
+// as above, but takes one or more glyph indices for greater efficiency
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// GLYPH SHAPES (you probably don't need these, but they have to go before
+// the bitmaps for C declaration-order reasons)
+//
+
+#ifndef STBTT_vmove // you can predefine these to use different values (but why?)
+ enum {
+ STBTT_vmove=1,
+ STBTT_vline,
+ STBTT_vcurve
+ };
+#endif
+
+#ifndef stbtt_vertex // you can predefine this to use different values
+ // (we share this with other code at RAD)
+ #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file
+ typedef struct
+ {
+ stbtt_vertex_type x,y,cx,cy;
+ unsigned char type,padding;
+ } stbtt_vertex;
+#endif
+
+STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);
+// returns non-zero if nothing is drawn for this glyph
+
+STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);
+STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);
+// returns # of vertices and fills *vertices with the pointer to them
+// these are expressed in "unscaled" coordinates
+//
+// The shape is a series of countours. Each one starts with
+// a STBTT_moveto, then consists of a series of mixed
+// STBTT_lineto and STBTT_curveto segments. A lineto
+// draws a line from previous endpoint to its x,y; a curveto
+// draws a quadratic bezier from previous endpoint to
+// its x,y, using cx,cy as the bezier control point.
+
+STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);
+// frees the data allocated above
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// BITMAP RENDERING
+//
+
+STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);
+// frees the bitmap allocated below
+
+STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff);
+// allocates a large-enough single-channel 8bpp bitmap and renders the
+// specified character/glyph at the specified scale into it, with
+// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).
+// *width & *height are filled out with the width & height of the bitmap,
+// which is stored left-to-right, top-to-bottom.
+//
+// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap
+
+STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff);
+// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel
+// shift for the character
+
+STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint);
+// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap
+// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap
+// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the
+// width and height and positioning info for it first.
+
+STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint);
+// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel
+// shift for the character
+
+STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
+// get the bbox of the bitmap centered around the glyph origin; so the
+// bitmap width is ix1-ix0, height is iy1-iy0, and location to place
+// the bitmap top left is (leftSideBearing*scale,iy0).
+// (Note that the bitmap uses y-increases-down, but the shape uses
+// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)
+
+STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);
+// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel
+// shift for the character
+
+// the following functions are equivalent to the above functions, but operate
+// on glyph indices instead of Unicode codepoints (for efficiency)
+STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff);
+STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff);
+STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph);
+STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph);
+STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);
+STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);
+
+
+// @TODO: don't expose this structure
+typedef struct
+{
+ int w,h,stride;
+ unsigned char *pixels;
+} stbtt__bitmap;
+
+// rasterize a shape with quadratic beziers into a bitmap
+STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into
+ float flatness_in_pixels, // allowable error of curve in pixels
+ stbtt_vertex *vertices, // array of vertices defining shape
+ int num_verts, // number of vertices in above array
+ float scale_x, float scale_y, // scale applied to input vertices
+ float shift_x, float shift_y, // translation applied to input vertices
+ int x_off, int y_off, // another translation applied to input
+ int invert, // if non-zero, vertically flip shape
+ void *userdata); // context for to STBTT_MALLOC
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// Finding the right font...
+//
+// You should really just solve this offline, keep your own tables
+// of what font is what, and don't try to get it out of the .ttf file.
+// That's because getting it out of the .ttf file is really hard, because
+// the names in the file can appear in many possible encodings, in many
+// possible languages, and e.g. if you need a case-insensitive comparison,
+// the details of that depend on the encoding & language in a complex way
+// (actually underspecified in truetype, but also gigantic).
+//
+// But you can use the provided functions in two possible ways:
+// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on
+// unicode-encoded names to try to find the font you want;
+// you can run this before calling stbtt_InitFont()
+//
+// stbtt_GetFontNameString() lets you get any of the various strings
+// from the file yourself and do your own comparisons on them.
+// You have to have called stbtt_InitFont() first.
+
+
+STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);
+// returns the offset (not index) of the font that matches, or -1 if none
+// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".
+// if you use any other flag, use a font name like "Arial"; this checks
+// the 'macStyle' header field; i don't know if fonts set this consistently
+#define STBTT_MACSTYLE_DONTCARE 0
+#define STBTT_MACSTYLE_BOLD 1
+#define STBTT_MACSTYLE_ITALIC 2
+#define STBTT_MACSTYLE_UNDERSCORE 4
+#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0
+
+STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);
+// returns 1/0 whether the first string interpreted as utf8 is identical to
+// the second string interpreted as big-endian utf16... useful for strings from next func
+
+STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);
+// returns the string (which may be big-endian double byte, e.g. for unicode)
+// and puts the length in bytes in *length.
+//
+// some of the values for the IDs are below; for more see the truetype spec:
+// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html
+// http://www.microsoft.com/typography/otspec/name.htm
+
+enum { // platformID
+ STBTT_PLATFORM_ID_UNICODE =0,
+ STBTT_PLATFORM_ID_MAC =1,
+ STBTT_PLATFORM_ID_ISO =2,
+ STBTT_PLATFORM_ID_MICROSOFT =3
+};
+
+enum { // encodingID for STBTT_PLATFORM_ID_UNICODE
+ STBTT_UNICODE_EID_UNICODE_1_0 =0,
+ STBTT_UNICODE_EID_UNICODE_1_1 =1,
+ STBTT_UNICODE_EID_ISO_10646 =2,
+ STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,
+ STBTT_UNICODE_EID_UNICODE_2_0_FULL=4
+};
+
+enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT
+ STBTT_MS_EID_SYMBOL =0,
+ STBTT_MS_EID_UNICODE_BMP =1,
+ STBTT_MS_EID_SHIFTJIS =2,
+ STBTT_MS_EID_UNICODE_FULL =10
+};
+
+enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes
+ STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4,
+ STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5,
+ STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6,
+ STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7
+};
+
+enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...
+ // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs
+ STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410,
+ STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411,
+ STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412,
+ STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419,
+ STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409,
+ STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D
+};
+
+enum { // languageID for STBTT_PLATFORM_ID_MAC
+ STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11,
+ STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23,
+ STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32,
+ STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 ,
+ STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 ,
+ STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,
+ STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // __STB_INCLUDE_STB_TRUETYPE_H__
+
+///////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////
+////
+//// IMPLEMENTATION
+////
+////
+
+#ifdef STB_TRUETYPE_IMPLEMENTATION
+
+#ifndef STBTT_MAX_OVERSAMPLE
+#define STBTT_MAX_OVERSAMPLE 8
+#endif
+
+#if STBTT_MAX_OVERSAMPLE > 255
+#error "STBTT_MAX_OVERSAMPLE cannot be > 255"
+#endif
+
+typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1];
+
+#ifndef STBTT_RASTERIZER_VERSION
+#define STBTT_RASTERIZER_VERSION 2
+#endif
+
+//////////////////////////////////////////////////////////////////////////
+//
+// accessors to parse data from file
+//
+
+// on platforms that don't allow misaligned reads, if we want to allow
+// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE
+
+#define ttBYTE(p) (* (stbtt_uint8 *) (p))
+#define ttCHAR(p) (* (stbtt_int8 *) (p))
+#define ttFixed(p) ttLONG(p)
+
+#if defined(STB_TRUETYPE_BIGENDIAN) && !defined(ALLOW_UNALIGNED_TRUETYPE)
+
+ #define ttUSHORT(p) (* (stbtt_uint16 *) (p))
+ #define ttSHORT(p) (* (stbtt_int16 *) (p))
+ #define ttULONG(p) (* (stbtt_uint32 *) (p))
+ #define ttLONG(p) (* (stbtt_int32 *) (p))
+
+#else
+
+ static stbtt_uint16 ttUSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; }
+ static stbtt_int16 ttSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; }
+ static stbtt_uint32 ttULONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
+ static stbtt_int32 ttLONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }
+
+#endif
+
+#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))
+#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3])
+
+static int stbtt__isfont(const stbtt_uint8 *font)
+{
+ // check the version number
+ if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1
+ if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this!
+ if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF
+ if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0
+ return 0;
+}
+
+// @OPTIMIZE: binary search
+static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag)
+{
+ stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);
+ stbtt_uint32 tabledir = fontstart + 12;
+ stbtt_int32 i;
+ for (i=0; i < num_tables; ++i) {
+ stbtt_uint32 loc = tabledir + 16*i;
+ if (stbtt_tag(data+loc+0, tag))
+ return ttULONG(data+loc+8);
+ }
+ return 0;
+}
+
+STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *font_collection, int index)
+{
+ // if it's just a font, there's only one valid index
+ if (stbtt__isfont(font_collection))
+ return index == 0 ? 0 : -1;
+
+ // check if it's a TTC
+ if (stbtt_tag(font_collection, "ttcf")) {
+ // version 1?
+ if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {
+ stbtt_int32 n = ttLONG(font_collection+8);
+ if (index >= n)
+ return -1;
+ return ttULONG(font_collection+12+index*4);
+ }
+ }
+ return -1;
+}
+
+STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data2, int fontstart)
+{
+ stbtt_uint8 *data = (stbtt_uint8 *) data2;
+ stbtt_uint32 cmap, t;
+ stbtt_int32 i,numTables;
+
+ info->data = data;
+ info->fontstart = fontstart;
+
+ cmap = stbtt__find_table(data, fontstart, "cmap"); // required
+ info->loca = stbtt__find_table(data, fontstart, "loca"); // required
+ info->head = stbtt__find_table(data, fontstart, "head"); // required
+ info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required
+ info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required
+ info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required
+ info->kern = stbtt__find_table(data, fontstart, "kern"); // not required
+ if (!cmap || !info->loca || !info->head || !info->glyf || !info->hhea || !info->hmtx)
+ return 0;
+
+ t = stbtt__find_table(data, fontstart, "maxp");
+ if (t)
+ info->numGlyphs = ttUSHORT(data+t+4);
+ else
+ info->numGlyphs = 0xffff;
+
+ // find a cmap encoding table we understand *now* to avoid searching
+ // later. (todo: could make this installable)
+ // the same regardless of glyph.
+ numTables = ttUSHORT(data + cmap + 2);
+ info->index_map = 0;
+ for (i=0; i < numTables; ++i) {
+ stbtt_uint32 encoding_record = cmap + 4 + 8 * i;
+ // find an encoding we understand:
+ switch(ttUSHORT(data+encoding_record)) {
+ case STBTT_PLATFORM_ID_MICROSOFT:
+ switch (ttUSHORT(data+encoding_record+2)) {
+ case STBTT_MS_EID_UNICODE_BMP:
+ case STBTT_MS_EID_UNICODE_FULL:
+ // MS/Unicode
+ info->index_map = cmap + ttULONG(data+encoding_record+4);
+ break;
+ }
+ break;
+ case STBTT_PLATFORM_ID_UNICODE:
+ // Mac/iOS has these
+ // all the encodingIDs are unicode, so we don't bother to check it
+ info->index_map = cmap + ttULONG(data+encoding_record+4);
+ break;
+ }
+ }
+ if (info->index_map == 0)
+ return 0;
+
+ info->indexToLocFormat = ttUSHORT(data+info->head + 50);
+ return 1;
+}
+
+STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)
+{
+ stbtt_uint8 *data = info->data;
+ stbtt_uint32 index_map = info->index_map;
+
+ stbtt_uint16 format = ttUSHORT(data + index_map + 0);
+ if (format == 0) { // apple byte encoding
+ stbtt_int32 bytes = ttUSHORT(data + index_map + 2);
+ if (unicode_codepoint < bytes-6)
+ return ttBYTE(data + index_map + 6 + unicode_codepoint);
+ return 0;
+ } else if (format == 6) {
+ stbtt_uint32 first = ttUSHORT(data + index_map + 6);
+ stbtt_uint32 count = ttUSHORT(data + index_map + 8);
+ if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)
+ return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);
+ return 0;
+ } else if (format == 2) {
+ STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean
+ return 0;
+ } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges
+ stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;
+ stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;
+ stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);
+ stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;
+
+ // do a binary search of the segments
+ stbtt_uint32 endCount = index_map + 14;
+ stbtt_uint32 search = endCount;
+
+ if (unicode_codepoint > 0xffff)
+ return 0;
+
+ // they lie from endCount .. endCount + segCount
+ // but searchRange is the nearest power of two, so...
+ if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))
+ search += rangeShift*2;
+
+ // now decrement to bias correctly to find smallest
+ search -= 2;
+ while (entrySelector) {
+ stbtt_uint16 end;
+ searchRange >>= 1;
+ end = ttUSHORT(data + search + searchRange*2);
+ if (unicode_codepoint > end)
+ search += searchRange*2;
+ --entrySelector;
+ }
+ search += 2;
+
+ {
+ stbtt_uint16 offset, start;
+ stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1);
+
+ STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item));
+ start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);
+ if (unicode_codepoint < start)
+ return 0;
+
+ offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);
+ if (offset == 0)
+ return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item));
+
+ return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);
+ }
+ } else if (format == 12 || format == 13) {
+ stbtt_uint32 ngroups = ttULONG(data+index_map+12);
+ stbtt_int32 low,high;
+ low = 0; high = (stbtt_int32)ngroups;
+ // Binary search the right group.
+ while (low < high) {
+ stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high
+ stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);
+ stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);
+ if ((stbtt_uint32) unicode_codepoint < start_char)
+ high = mid;
+ else if ((stbtt_uint32) unicode_codepoint > end_char)
+ low = mid+1;
+ else {
+ stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);
+ if (format == 12)
+ return start_glyph + unicode_codepoint-start_char;
+ else // format == 13
+ return start_glyph;
+ }
+ }
+ return 0; // not found
+ }
+ // @TODO
+ STBTT_assert(0);
+ return 0;
+}
+
+STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)
+{
+ return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);
+}
+
+static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)
+{
+ v->type = type;
+ v->x = (stbtt_int16) x;
+ v->y = (stbtt_int16) y;
+ v->cx = (stbtt_int16) cx;
+ v->cy = (stbtt_int16) cy;
+}
+
+static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)
+{
+ int g1,g2;
+
+ if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range
+ if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format
+
+ if (info->indexToLocFormat == 0) {
+ g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;
+ g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;
+ } else {
+ g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);
+ g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);
+ }
+
+ return g1==g2 ? -1 : g1; // if length is 0, return -1
+}
+
+STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)
+{
+ int g = stbtt__GetGlyfOffset(info, glyph_index);
+ if (g < 0) return 0;
+
+ if (x0) *x0 = ttSHORT(info->data + g + 2);
+ if (y0) *y0 = ttSHORT(info->data + g + 4);
+ if (x1) *x1 = ttSHORT(info->data + g + 6);
+ if (y1) *y1 = ttSHORT(info->data + g + 8);
+ return 1;
+}
+
+STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)
+{
+ return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);
+}
+
+STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)
+{
+ stbtt_int16 numberOfContours;
+ int g = stbtt__GetGlyfOffset(info, glyph_index);
+ if (g < 0) return 1;
+ numberOfContours = ttSHORT(info->data + g);
+ return numberOfContours == 0;
+}
+
+static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off,
+ stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)
+{
+ if (start_off) {
+ if (was_off)
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy);
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy);
+ } else {
+ if (was_off)
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);
+ else
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);
+ }
+ return num_vertices;
+}
+
+STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)
+{
+ stbtt_int16 numberOfContours;
+ stbtt_uint8 *endPtsOfContours;
+ stbtt_uint8 *data = info->data;
+ stbtt_vertex *vertices=0;
+ int num_vertices=0;
+ int g = stbtt__GetGlyfOffset(info, glyph_index);
+
+ *pvertices = NULL;
+
+ if (g < 0) return 0;
+
+ numberOfContours = ttSHORT(data + g);
+
+ if (numberOfContours > 0) {
+ stbtt_uint8 flags=0,flagcount;
+ stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0;
+ stbtt_int32 x,y,cx,cy,sx,sy, scx,scy;
+ stbtt_uint8 *points;
+ endPtsOfContours = (data + g + 10);
+ ins = ttUSHORT(data + g + 10 + numberOfContours * 2);
+ points = data + g + 10 + numberOfContours * 2 + 2 + ins;
+
+ n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);
+
+ m = n + 2*numberOfContours; // a loose bound on how many vertices we might need
+ vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);
+ if (vertices == 0)
+ return 0;
+
+ next_move = 0;
+ flagcount=0;
+
+ // in first pass, we load uninterpreted data into the allocated array
+ // above, shifted to the end of the array so we won't overwrite it when
+ // we create our final data starting from the front
+
+ off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated
+
+ // first load flags
+
+ for (i=0; i < n; ++i) {
+ if (flagcount == 0) {
+ flags = *points++;
+ if (flags & 8)
+ flagcount = *points++;
+ } else
+ --flagcount;
+ vertices[off+i].type = flags;
+ }
+
+ // now load x coordinates
+ x=0;
+ for (i=0; i < n; ++i) {
+ flags = vertices[off+i].type;
+ if (flags & 2) {
+ stbtt_int16 dx = *points++;
+ x += (flags & 16) ? dx : -dx; // ???
+ } else {
+ if (!(flags & 16)) {
+ x = x + (stbtt_int16) (points[0]*256 + points[1]);
+ points += 2;
+ }
+ }
+ vertices[off+i].x = (stbtt_int16) x;
+ }
+
+ // now load y coordinates
+ y=0;
+ for (i=0; i < n; ++i) {
+ flags = vertices[off+i].type;
+ if (flags & 4) {
+ stbtt_int16 dy = *points++;
+ y += (flags & 32) ? dy : -dy; // ???
+ } else {
+ if (!(flags & 32)) {
+ y = y + (stbtt_int16) (points[0]*256 + points[1]);
+ points += 2;
+ }
+ }
+ vertices[off+i].y = (stbtt_int16) y;
+ }
+
+ // now convert them to our format
+ num_vertices=0;
+ sx = sy = cx = cy = scx = scy = 0;
+ for (i=0; i < n; ++i) {
+ flags = vertices[off+i].type;
+ x = (stbtt_int16) vertices[off+i].x;
+ y = (stbtt_int16) vertices[off+i].y;
+
+ if (next_move == i) {
+ if (i != 0)
+ num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
+
+ // now start the new one
+ start_off = !(flags & 1);
+ if (start_off) {
+ // if we start off with an off-curve point, then when we need to find a point on the curve
+ // where we can start, and we need to save some state for when we wraparound.
+ scx = x;
+ scy = y;
+ if (!(vertices[off+i+1].type & 1)) {
+ // next point is also a curve point, so interpolate an on-point curve
+ sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1;
+ sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1;
+ } else {
+ // otherwise just use the next point as our start point
+ sx = (stbtt_int32) vertices[off+i+1].x;
+ sy = (stbtt_int32) vertices[off+i+1].y;
+ ++i; // we're using point i+1 as the starting point, so skip it
+ }
+ } else {
+ sx = x;
+ sy = y;
+ }
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0);
+ was_off = 0;
+ next_move = 1 + ttUSHORT(endPtsOfContours+j*2);
+ ++j;
+ } else {
+ if (!(flags & 1)) { // if it's a curve
+ if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);
+ cx = x;
+ cy = y;
+ was_off = 1;
+ } else {
+ if (was_off)
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);
+ else
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);
+ was_off = 0;
+ }
+ }
+ }
+ num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);
+ } else if (numberOfContours == -1) {
+ // Compound shapes.
+ int more = 1;
+ stbtt_uint8 *comp = data + g + 10;
+ num_vertices = 0;
+ vertices = 0;
+ while (more) {
+ stbtt_uint16 flags, gidx;
+ int comp_num_verts = 0, i;
+ stbtt_vertex *comp_verts = 0, *tmp = 0;
+ float mtx[6] = {1,0,0,1,0,0}, m, n;
+
+ flags = ttSHORT(comp); comp+=2;
+ gidx = ttSHORT(comp); comp+=2;
+
+ if (flags & 2) { // XY values
+ if (flags & 1) { // shorts
+ mtx[4] = ttSHORT(comp); comp+=2;
+ mtx[5] = ttSHORT(comp); comp+=2;
+ } else {
+ mtx[4] = ttCHAR(comp); comp+=1;
+ mtx[5] = ttCHAR(comp); comp+=1;
+ }
+ }
+ else {
+ // @TODO handle matching point
+ STBTT_assert(0);
+ }
+ if (flags & (1<<3)) { // WE_HAVE_A_SCALE
+ mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
+ mtx[1] = mtx[2] = 0;
+ } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE
+ mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
+ mtx[1] = mtx[2] = 0;
+ mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
+ } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO
+ mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;
+ mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;
+ mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;
+ mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;
+ }
+
+ // Find transformation scales.
+ m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);
+ n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);
+
+ // Get indexed glyph.
+ comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);
+ if (comp_num_verts > 0) {
+ // Transform vertices.
+ for (i = 0; i < comp_num_verts; ++i) {
+ stbtt_vertex* v = &comp_verts[i];
+ stbtt_vertex_type x,y;
+ x=v->x; y=v->y;
+ v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
+ v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
+ x=v->cx; y=v->cy;
+ v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));
+ v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));
+ }
+ // Append vertices.
+ tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);
+ if (!tmp) {
+ if (vertices) STBTT_free(vertices, info->userdata);
+ if (comp_verts) STBTT_free(comp_verts, info->userdata);
+ return 0;
+ }
+ if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex));
+ STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));
+ if (vertices) STBTT_free(vertices, info->userdata);
+ vertices = tmp;
+ STBTT_free(comp_verts, info->userdata);
+ num_vertices += comp_num_verts;
+ }
+ // More components ?
+ more = flags & (1<<5);
+ }
+ } else if (numberOfContours < 0) {
+ // @TODO other compound variations?
+ STBTT_assert(0);
+ } else {
+ // numberOfCounters == 0, do nothing
+ }
+
+ *pvertices = vertices;
+ return num_vertices;
+}
+
+STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)
+{
+ stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);
+ if (glyph_index < numOfLongHorMetrics) {
+ if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index);
+ if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2);
+ } else {
+ if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1));
+ if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics));
+ }
+}
+
+STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)
+{
+ stbtt_uint8 *data = info->data + info->kern;
+ stbtt_uint32 needle, straw;
+ int l, r, m;
+
+ // we only look at the first table. it must be 'horizontal' and format 0.
+ if (!info->kern)
+ return 0;
+ if (ttUSHORT(data+2) < 1) // number of tables, need at least 1
+ return 0;
+ if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format
+ return 0;
+
+ l = 0;
+ r = ttUSHORT(data+10) - 1;
+ needle = glyph1 << 16 | glyph2;
+ while (l <= r) {
+ m = (l + r) >> 1;
+ straw = ttULONG(data+18+(m*6)); // note: unaligned read
+ if (needle < straw)
+ r = m - 1;
+ else if (needle > straw)
+ l = m + 1;
+ else
+ return ttSHORT(data+22+(m*6));
+ }
+ return 0;
+}
+
+STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)
+{
+ if (!info->kern) // if no kerning table, don't waste time looking up both codepoint->glyphs
+ return 0;
+ return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2));
+}
+
+STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)
+{
+ stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);
+}
+
+STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap)
+{
+ if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4);
+ if (descent) *descent = ttSHORT(info->data+info->hhea + 6);
+ if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);
+}
+
+STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1)
+{
+ *x0 = ttSHORT(info->data + info->head + 36);
+ *y0 = ttSHORT(info->data + info->head + 38);
+ *x1 = ttSHORT(info->data + info->head + 40);
+ *y1 = ttSHORT(info->data + info->head + 42);
+}
+
+STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height)
+{
+ int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);
+ return (float) height / fheight;
+}
+
+STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels)
+{
+ int unitsPerEm = ttUSHORT(info->data + info->head + 18);
+ return pixels / unitsPerEm;
+}
+
+STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)
+{
+ STBTT_free(v, info->userdata);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// antialiasing software rasterizer
+//
+
+STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1)
+{
+ int x0,y0,x1,y1;
+ if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) {
+ // e.g. space character
+ if (ix0) *ix0 = 0;
+ if (iy0) *iy0 = 0;
+ if (ix1) *ix1 = 0;
+ if (iy1) *iy1 = 0;
+ } else {
+ // move to integral bboxes (treating pixels as little squares, what pixels get touched)?
+ if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x);
+ if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y);
+ if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x);
+ if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y);
+ }
+}
+
+STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
+{
+ stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1);
+}
+
+STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1)
+{
+ stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1);
+}
+
+STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)
+{
+ stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// Rasterizer
+
+typedef struct stbtt__hheap_chunk
+{
+ struct stbtt__hheap_chunk *next;
+} stbtt__hheap_chunk;
+
+typedef struct stbtt__hheap
+{
+ struct stbtt__hheap_chunk *head;
+ void *first_free;
+ int num_remaining_in_head_chunk;
+} stbtt__hheap;
+
+static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata)
+{
+ if (hh->first_free) {
+ void *p = hh->first_free;
+ hh->first_free = * (void **) p;
+ return p;
+ } else {
+ if (hh->num_remaining_in_head_chunk == 0) {
+ int count = (size < 32 ? 2000 : size < 128 ? 800 : 100);
+ stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata);
+ if (c == NULL)
+ return NULL;
+ c->next = hh->head;
+ hh->head = c;
+ hh->num_remaining_in_head_chunk = count;
+ }
+ --hh->num_remaining_in_head_chunk;
+ return (char *) (hh->head) + size * hh->num_remaining_in_head_chunk;
+ }
+}
+
+static void stbtt__hheap_free(stbtt__hheap *hh, void *p)
+{
+ *(void **) p = hh->first_free;
+ hh->first_free = p;
+}
+
+static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata)
+{
+ stbtt__hheap_chunk *c = hh->head;
+ while (c) {
+ stbtt__hheap_chunk *n = c->next;
+ STBTT_free(c, userdata);
+ c = n;
+ }
+}
+
+typedef struct stbtt__edge {
+ float x0,y0, x1,y1;
+ int invert;
+} stbtt__edge;
+
+
+typedef struct stbtt__active_edge
+{
+ struct stbtt__active_edge *next;
+ #if STBTT_RASTERIZER_VERSION==1
+ int x,dx;
+ float ey;
+ int direction;
+ #elif STBTT_RASTERIZER_VERSION==2
+ float fx,fdx,fdy;
+ float direction;
+ float sy;
+ float ey;
+ #else
+ #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
+ #endif
+} stbtt__active_edge;
+
+#if STBTT_RASTERIZER_VERSION == 1
+#define STBTT_FIXSHIFT 10
+#define STBTT_FIX (1 << STBTT_FIXSHIFT)
+#define STBTT_FIXMASK (STBTT_FIX-1)
+
+static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)
+{
+ stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);
+ float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
+ if (!z) return z;
+
+ // round dx down to avoid overshooting
+ if (dxdy < 0)
+ z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy);
+ else
+ z->dx = STBTT_ifloor(STBTT_FIX * dxdy);
+
+ z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount
+ z->x -= off_x * STBTT_FIX;
+
+ z->ey = e->y1;
+ z->next = 0;
+ z->direction = e->invert ? 1 : -1;
+ return z;
+}
+#elif STBTT_RASTERIZER_VERSION == 2
+static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)
+{
+ stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);
+ float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);
+ //STBTT_assert(e->y0 <= start_point);
+ if (!z) return z;
+ z->fdx = dxdy;
+ z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f;
+ z->fx = e->x0 + dxdy * (start_point - e->y0);
+ z->fx -= off_x;
+ z->direction = e->invert ? 1.0f : -1.0f;
+ z->sy = e->y0;
+ z->ey = e->y1;
+ z->next = 0;
+ return z;
+}
+#else
+#error "Unrecognized value of STBTT_RASTERIZER_VERSION"
+#endif
+
+#if STBTT_RASTERIZER_VERSION == 1
+// note: this routine clips fills that extend off the edges... ideally this
+// wouldn't happen, but it could happen if the truetype glyph bounding boxes
+// are wrong, or if the user supplies a too-small bitmap
+static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight)
+{
+ // non-zero winding fill
+ int x0=0, w=0;
+
+ while (e) {
+ if (w == 0) {
+ // if we're currently at zero, we need to record the edge start point
+ x0 = e->x; w += e->direction;
+ } else {
+ int x1 = e->x; w += e->direction;
+ // if we went to zero, we need to draw
+ if (w == 0) {
+ int i = x0 >> STBTT_FIXSHIFT;
+ int j = x1 >> STBTT_FIXSHIFT;
+
+ if (i < len && j >= 0) {
+ if (i == j) {
+ // x0,x1 are the same pixel, so compute combined coverage
+ scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT);
+ } else {
+ if (i >= 0) // add antialiasing for x0
+ scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT);
+ else
+ i = -1; // clip
+
+ if (j < len) // add antialiasing for x1
+ scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT);
+ else
+ j = len; // clip
+
+ for (++i; i < j; ++i) // fill pixels between x0 and x1
+ scanline[i] = scanline[i] + (stbtt_uint8) max_weight;
+ }
+ }
+ }
+ }
+
+ e = e->next;
+ }
+}
+
+static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
+{
+ stbtt__hheap hh = { 0, 0, 0 };
+ stbtt__active_edge *active = NULL;
+ int y,j=0;
+ int max_weight = (255 / vsubsample); // weight per vertical scanline
+ int s; // vertical subsample index
+ unsigned char scanline_data[512], *scanline;
+
+ if (result->w > 512)
+ scanline = (unsigned char *) STBTT_malloc(result->w, userdata);
+ else
+ scanline = scanline_data;
+
+ y = off_y * vsubsample;
+ e[n].y0 = (off_y + result->h) * (float) vsubsample + 1;
+
+ while (j < result->h) {
+ STBTT_memset(scanline, 0, result->w);
+ for (s=0; s < vsubsample; ++s) {
+ // find center of pixel for this scanline
+ float scan_y = y + 0.5f;
+ stbtt__active_edge **step = &active;
+
+ // update all active edges;
+ // remove all active edges that terminate before the center of this scanline
+ while (*step) {
+ stbtt__active_edge * z = *step;
+ if (z->ey <= scan_y) {
+ *step = z->next; // delete from list
+ STBTT_assert(z->direction);
+ z->direction = 0;
+ stbtt__hheap_free(&hh, z);
+ } else {
+ z->x += z->dx; // advance to position for current scanline
+ step = &((*step)->next); // advance through list
+ }
+ }
+
+ // resort the list if needed
+ for(;;) {
+ int changed=0;
+ step = &active;
+ while (*step && (*step)->next) {
+ if ((*step)->x > (*step)->next->x) {
+ stbtt__active_edge *t = *step;
+ stbtt__active_edge *q = t->next;
+
+ t->next = q->next;
+ q->next = t;
+ *step = q;
+ changed = 1;
+ }
+ step = &(*step)->next;
+ }
+ if (!changed) break;
+ }
+
+ // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline
+ while (e->y0 <= scan_y) {
+ if (e->y1 > scan_y) {
+ stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata);
+ // find insertion point
+ if (active == NULL)
+ active = z;
+ else if (z->x < active->x) {
+ // insert at front
+ z->next = active;
+ active = z;
+ } else {
+ // find thing to insert AFTER
+ stbtt__active_edge *p = active;
+ while (p->next && p->next->x < z->x)
+ p = p->next;
+ // at this point, p->next->x is NOT < z->x
+ z->next = p->next;
+ p->next = z;
+ }
+ }
+ ++e;
+ }
+
+ // now process all active edges in XOR fashion
+ if (active)
+ stbtt__fill_active_edges(scanline, result->w, active, max_weight);
+
+ ++y;
+ }
+ STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);
+ ++j;
+ }
+
+ stbtt__hheap_cleanup(&hh, userdata);
+
+ if (scanline != scanline_data)
+ STBTT_free(scanline, userdata);
+}
+
+#elif STBTT_RASTERIZER_VERSION == 2
+
+// the edge passed in here does not cross the vertical line at x or the vertical line at x+1
+// (i.e. it has already been clipped to those)
+static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1)
+{
+ if (y0 == y1) return;
+ STBTT_assert(y0 < y1);
+ STBTT_assert(e->sy <= e->ey);
+ if (y0 > e->ey) return;
+ if (y1 < e->sy) return;
+ if (y0 < e->sy) {
+ x0 += (x1-x0) * (e->sy - y0) / (y1-y0);
+ y0 = e->sy;
+ }
+ if (y1 > e->ey) {
+ x1 += (x1-x0) * (e->ey - y1) / (y1-y0);
+ y1 = e->ey;
+ }
+
+ if (x0 == x)
+ STBTT_assert(x1 <= x+1);
+ else if (x0 == x+1)
+ STBTT_assert(x1 >= x);
+ else if (x0 <= x)
+ STBTT_assert(x1 <= x);
+ else if (x0 >= x+1)
+ STBTT_assert(x1 >= x+1);
+ else
+ STBTT_assert(x1 >= x && x1 <= x+1);
+
+ if (x0 <= x && x1 <= x)
+ scanline[x] += e->direction * (y1-y0);
+ else if (x0 >= x+1 && x1 >= x+1)
+ ;
+ else {
+ STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1);
+ scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position
+ }
+}
+
+static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top)
+{
+ float y_bottom = y_top+1;
+
+ while (e) {
+ // brute force every pixel
+
+ // compute intersection points with top & bottom
+ STBTT_assert(e->ey >= y_top);
+
+ if (e->fdx == 0) {
+ float x0 = e->fx;
+ if (x0 < len) {
+ if (x0 >= 0) {
+ stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom);
+ stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom);
+ } else {
+ stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom);
+ }
+ }
+ } else {
+ float x0 = e->fx;
+ float dx = e->fdx;
+ float xb = x0 + dx;
+ float x_top, x_bottom;
+ float sy0,sy1;
+ float dy = e->fdy;
+ STBTT_assert(e->sy <= y_bottom && e->ey >= y_top);
+
+ // compute endpoints of line segment clipped to this scanline (if the
+ // line segment starts on this scanline. x0 is the intersection of the
+ // line with y_top, but that may be off the line segment.
+ if (e->sy > y_top) {
+ x_top = x0 + dx * (e->sy - y_top);
+ sy0 = e->sy;
+ } else {
+ x_top = x0;
+ sy0 = y_top;
+ }
+ if (e->ey < y_bottom) {
+ x_bottom = x0 + dx * (e->ey - y_top);
+ sy1 = e->ey;
+ } else {
+ x_bottom = xb;
+ sy1 = y_bottom;
+ }
+
+ if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) {
+ // from here on, we don't have to range check x values
+
+ if ((int) x_top == (int) x_bottom) {
+ float height;
+ // simple case, only spans one pixel
+ int x = (int) x_top;
+ height = sy1 - sy0;
+ STBTT_assert(x >= 0 && x < len);
+ scanline[x] += e->direction * (1-((x_top - x) + (x_bottom-x))/2) * height;
+ scanline_fill[x] += e->direction * height; // everything right of this pixel is filled
+ } else {
+ int x,x1,x2;
+ float y_crossing, step, sign, area;
+ // covers 2+ pixels
+ if (x_top > x_bottom) {
+ // flip scanline vertically; signed area is the same
+ float t;
+ sy0 = y_bottom - (sy0 - y_top);
+ sy1 = y_bottom - (sy1 - y_top);
+ t = sy0, sy0 = sy1, sy1 = t;
+ t = x_bottom, x_bottom = x_top, x_top = t;
+ dx = -dx;
+ dy = -dy;
+ t = x0, x0 = xb, xb = t;
+ }
+
+ x1 = (int) x_top;
+ x2 = (int) x_bottom;
+ // compute intersection with y axis at x1+1
+ y_crossing = (x1+1 - x0) * dy + y_top;
+
+ sign = e->direction;
+ // area of the rectangle covered from y0..y_crossing
+ area = sign * (y_crossing-sy0);
+ // area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing)
+ scanline[x1] += area * (1-((x_top - x1)+(x1+1-x1))/2);
+
+ step = sign * dy;
+ for (x = x1+1; x < x2; ++x) {
+ scanline[x] += area + step/2;
+ area += step;
+ }
+ y_crossing += dy * (x2 - (x1+1));
+
+ STBTT_assert(fabs(area) <= 1.01f);
+
+ scanline[x2] += area + sign * (1-((x2-x2)+(x_bottom-x2))/2) * (sy1-y_crossing);
+
+ scanline_fill[x2] += sign * (sy1-sy0);
+ }
+ } else {
+ // if edge goes outside of box we're drawing, we require
+ // clipping logic. since this does not match the intended use
+ // of this library, we use a different, very slow brute
+ // force implementation
+ int x;
+ for (x=0; x < len; ++x) {
+ // cases:
+ //
+ // there can be up to two intersections with the pixel. any intersection
+ // with left or right edges can be handled by splitting into two (or three)
+ // regions. intersections with top & bottom do not necessitate case-wise logic.
+ //
+ // the old way of doing this found the intersections with the left & right edges,
+ // then used some simple logic to produce up to three segments in sorted order
+ // from top-to-bottom. however, this had a problem: if an x edge was epsilon
+ // across the x border, then the corresponding y position might not be distinct
+ // from the other y segment, and it might ignored as an empty segment. to avoid
+ // that, we need to explicitly produce segments based on x positions.
+
+ // rename variables to clear pairs
+ float y0 = y_top;
+ float x1 = (float) (x);
+ float x2 = (float) (x+1);
+ float x3 = xb;
+ float y3 = y_bottom;
+ float y1,y2;
+
+ // x = e->x + e->dx * (y-y_top)
+ // (y-y_top) = (x - e->x) / e->dx
+ // y = (x - e->x) / e->dx + y_top
+ y1 = (x - x0) / dx + y_top;
+ y2 = (x+1 - x0) / dx + y_top;
+
+ if (x0 < x1 && x3 > x2) { // three segments descending down-right
+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
+ stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2);
+ stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
+ } else if (x3 < x1 && x0 > x2) { // three segments descending down-left
+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
+ stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1);
+ stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
+ } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right
+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
+ stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
+ } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left
+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);
+ stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);
+ } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right
+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
+ stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
+ } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left
+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);
+ stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);
+ } else { // one segment
+ stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3);
+ }
+ }
+ }
+ }
+ e = e->next;
+ }
+}
+
+// directly AA rasterize edges w/o supersampling
+static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)
+{
+ stbtt__hheap hh = { 0, 0, 0 };
+ stbtt__active_edge *active = NULL;
+ int y,j=0, i;
+ float scanline_data[129], *scanline, *scanline2;
+
+ if (result->w > 64)
+ scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata);
+ else
+ scanline = scanline_data;
+
+ scanline2 = scanline + result->w;
+
+ y = off_y;
+ e[n].y0 = (float) (off_y + result->h) + 1;
+
+ while (j < result->h) {
+ // find center of pixel for this scanline
+ float scan_y_top = y + 0.0f;
+ float scan_y_bottom = y + 1.0f;
+ stbtt__active_edge **step = &active;
+
+ STBTT_memset(scanline , 0, result->w*sizeof(scanline[0]));
+ STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0]));
+
+ // update all active edges;
+ // remove all active edges that terminate before the top of this scanline
+ while (*step) {
+ stbtt__active_edge * z = *step;
+ if (z->ey <= scan_y_top) {
+ *step = z->next; // delete from list
+ STBTT_assert(z->direction);
+ z->direction = 0;
+ stbtt__hheap_free(&hh, z);
+ } else {
+ step = &((*step)->next); // advance through list
+ }
+ }
+
+ // insert all edges that start before the bottom of this scanline
+ while (e->y0 <= scan_y_bottom) {
+ if (e->y0 != e->y1) {
+ stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata);
+ STBTT_assert(z->ey >= scan_y_top);
+ // insert at front
+ z->next = active;
+ active = z;
+ }
+ ++e;
+ }
+
+ // now process all active edges
+ if (active)
+ stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top);
+
+ {
+ float sum = 0;
+ for (i=0; i < result->w; ++i) {
+ float k;
+ int m;
+ sum += scanline2[i];
+ k = scanline[i] + sum;
+ k = (float) STBTT_fabs(k)*255 + 0.5f;
+ m = (int) k;
+ if (m > 255) m = 255;
+ result->pixels[j*result->stride + i] = (unsigned char) m;
+ }
+ }
+ // advance all the edges
+ step = &active;
+ while (*step) {
+ stbtt__active_edge *z = *step;
+ z->fx += z->fdx; // advance to position for current scanline
+ step = &((*step)->next); // advance through list
+ }
+
+ ++y;
+ ++j;
+ }
+
+ stbtt__hheap_cleanup(&hh, userdata);
+
+ if (scanline != scanline_data)
+ STBTT_free(scanline, userdata);
+}
+#else
+#error "Unrecognized value of STBTT_RASTERIZER_VERSION"
+#endif
+
+#define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0)
+
+static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n)
+{
+ int i,j;
+ for (i=1; i < n; ++i) {
+ stbtt__edge t = p[i], *a = &t;
+ j = i;
+ while (j > 0) {
+ stbtt__edge *b = &p[j-1];
+ int c = STBTT__COMPARE(a,b);
+ if (!c) break;
+ p[j] = p[j-1];
+ --j;
+ }
+ if (i != j)
+ p[j] = t;
+ }
+}
+
+static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n)
+{
+ /* threshhold for transitioning to insertion sort */
+ while (n > 12) {
+ stbtt__edge t;
+ int c01,c12,c,m,i,j;
+
+ /* compute median of three */
+ m = n >> 1;
+ c01 = STBTT__COMPARE(&p[0],&p[m]);
+ c12 = STBTT__COMPARE(&p[m],&p[n-1]);
+ /* if 0 >= mid >= end, or 0 < mid < end, then use mid */
+ if (c01 != c12) {
+ /* otherwise, we'll need to swap something else to middle */
+ int z;
+ c = STBTT__COMPARE(&p[0],&p[n-1]);
+ /* 0>mid && mid<n: 0>n => n; 0<n => 0 */
+ /* 0<mid && mid>n: 0>n => 0; 0<n => n */
+ z = (c == c12) ? 0 : n-1;
+ t = p[z];
+ p[z] = p[m];
+ p[m] = t;
+ }
+ /* now p[m] is the median-of-three */
+ /* swap it to the beginning so it won't move around */
+ t = p[0];
+ p[0] = p[m];
+ p[m] = t;
+
+ /* partition loop */
+ i=1;
+ j=n-1;
+ for(;;) {
+ /* handling of equality is crucial here */
+ /* for sentinels & efficiency with duplicates */
+ for (;;++i) {
+ if (!STBTT__COMPARE(&p[i], &p[0])) break;
+ }
+ for (;;--j) {
+ if (!STBTT__COMPARE(&p[0], &p[j])) break;
+ }
+ /* make sure we haven't crossed */
+ if (i >= j) break;
+ t = p[i];
+ p[i] = p[j];
+ p[j] = t;
+
+ ++i;
+ --j;
+ }
+ /* recurse on smaller side, iterate on larger */
+ if (j < (n-i)) {
+ stbtt__sort_edges_quicksort(p,j);
+ p = p+i;
+ n = n-i;
+ } else {
+ stbtt__sort_edges_quicksort(p+i, n-i);
+ n = j;
+ }
+ }
+}
+
+static void stbtt__sort_edges(stbtt__edge *p, int n)
+{
+ stbtt__sort_edges_quicksort(p, n);
+ stbtt__sort_edges_ins_sort(p, n);
+}
+
+typedef struct
+{
+ float x,y;
+} stbtt__point;
+
+static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata)
+{
+ float y_scale_inv = invert ? -scale_y : scale_y;
+ stbtt__edge *e;
+ int n,i,j,k,m;
+#if STBTT_RASTERIZER_VERSION == 1
+ int vsubsample = result->h < 8 ? 15 : 5;
+#elif STBTT_RASTERIZER_VERSION == 2
+ int vsubsample = 1;
+#else
+ #error "Unrecognized value of STBTT_RASTERIZER_VERSION"
+#endif
+ // vsubsample should divide 255 evenly; otherwise we won't reach full opacity
+
+ // now we have to blow out the windings into explicit edge lists
+ n = 0;
+ for (i=0; i < windings; ++i)
+ n += wcount[i];
+
+ e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel
+ if (e == 0) return;
+ n = 0;
+
+ m=0;
+ for (i=0; i < windings; ++i) {
+ stbtt__point *p = pts + m;
+ m += wcount[i];
+ j = wcount[i]-1;
+ for (k=0; k < wcount[i]; j=k++) {
+ int a=k,b=j;
+ // skip the edge if horizontal
+ if (p[j].y == p[k].y)
+ continue;
+ // add edge from j to k to the list
+ e[n].invert = 0;
+ if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) {
+ e[n].invert = 1;
+ a=j,b=k;
+ }
+ e[n].x0 = p[a].x * scale_x + shift_x;
+ e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample;
+ e[n].x1 = p[b].x * scale_x + shift_x;
+ e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample;
+ ++n;
+ }
+ }
+
+ // now sort the edges by their highest point (should snap to integer, and then by x)
+ //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);
+ stbtt__sort_edges(e, n);
+
+ // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule
+ stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);
+
+ STBTT_free(e, userdata);
+}
+
+static void stbtt__add_point(stbtt__point *points, int n, float x, float y)
+{
+ if (!points) return; // during first pass, it's unallocated
+ points[n].x = x;
+ points[n].y = y;
+}
+
+// tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching
+static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n)
+{
+ // midpoint
+ float mx = (x0 + 2*x1 + x2)/4;
+ float my = (y0 + 2*y1 + y2)/4;
+ // versus directly drawn line
+ float dx = (x0+x2)/2 - mx;
+ float dy = (y0+y2)/2 - my;
+ if (n > 16) // 65536 segments on one curve better be enough!
+ return 1;
+ if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA
+ stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1);
+ stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1);
+ } else {
+ stbtt__add_point(points, *num_points,x2,y2);
+ *num_points = *num_points+1;
+ }
+ return 1;
+}
+
+// returns number of contours
+static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)
+{
+ stbtt__point *points=0;
+ int num_points=0;
+
+ float objspace_flatness_squared = objspace_flatness * objspace_flatness;
+ int i,n=0,start=0, pass;
+
+ // count how many "moves" there are to get the contour count
+ for (i=0; i < num_verts; ++i)
+ if (vertices[i].type == STBTT_vmove)
+ ++n;
+
+ *num_contours = n;
+ if (n == 0) return 0;
+
+ *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata);
+
+ if (*contour_lengths == 0) {
+ *num_contours = 0;
+ return 0;
+ }
+
+ // make two passes through the points so we don't need to realloc
+ for (pass=0; pass < 2; ++pass) {
+ float x=0,y=0;
+ if (pass == 1) {
+ points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata);
+ if (points == NULL) goto error;
+ }
+ num_points = 0;
+ n= -1;
+ for (i=0; i < num_verts; ++i) {
+ switch (vertices[i].type) {
+ case STBTT_vmove:
+ // start the next contour
+ if (n >= 0)
+ (*contour_lengths)[n] = num_points - start;
+ ++n;
+ start = num_points;
+
+ x = vertices[i].x, y = vertices[i].y;
+ stbtt__add_point(points, num_points++, x,y);
+ break;
+ case STBTT_vline:
+ x = vertices[i].x, y = vertices[i].y;
+ stbtt__add_point(points, num_points++, x, y);
+ break;
+ case STBTT_vcurve:
+ stbtt__tesselate_curve(points, &num_points, x,y,
+ vertices[i].cx, vertices[i].cy,
+ vertices[i].x, vertices[i].y,
+ objspace_flatness_squared, 0);
+ x = vertices[i].x, y = vertices[i].y;
+ break;
+ }
+ }
+ (*contour_lengths)[n] = num_points - start;
+ }
+
+ return points;
+error:
+ STBTT_free(points, userdata);
+ STBTT_free(*contour_lengths, userdata);
+ *contour_lengths = 0;
+ *num_contours = 0;
+ return NULL;
+}
+
+STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata)
+{
+ float scale = scale_x > scale_y ? scale_y : scale_x;
+ int winding_count, *winding_lengths;
+ stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);
+ if (windings) {
+ stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);
+ STBTT_free(winding_lengths, userdata);
+ STBTT_free(windings, userdata);
+ }
+}
+
+STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)
+{
+ STBTT_free(bitmap, userdata);
+}
+
+STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff)
+{
+ int ix0,iy0,ix1,iy1;
+ stbtt__bitmap gbm;
+ stbtt_vertex *vertices;
+ int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
+
+ if (scale_x == 0) scale_x = scale_y;
+ if (scale_y == 0) {
+ if (scale_x == 0) return NULL;
+ scale_y = scale_x;
+ }
+
+ stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1);
+
+ // now we get the size
+ gbm.w = (ix1 - ix0);
+ gbm.h = (iy1 - iy0);
+ gbm.pixels = NULL; // in case we error
+
+ if (width ) *width = gbm.w;
+ if (height) *height = gbm.h;
+ if (xoff ) *xoff = ix0;
+ if (yoff ) *yoff = iy0;
+
+ if (gbm.w && gbm.h) {
+ gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata);
+ if (gbm.pixels) {
+ gbm.stride = gbm.w;
+
+ stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);
+ }
+ }
+ STBTT_free(vertices, info->userdata);
+ return gbm.pixels;
+}
+
+STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff)
+{
+ return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);
+}
+
+STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph)
+{
+ int ix0,iy0;
+ stbtt_vertex *vertices;
+ int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);
+ stbtt__bitmap gbm;
+
+ stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0);
+ gbm.pixels = output;
+ gbm.w = out_w;
+ gbm.h = out_h;
+ gbm.stride = out_stride;
+
+ if (gbm.w && gbm.h)
+ stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata);
+
+ STBTT_free(vertices, info->userdata);
+}
+
+STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph)
+{
+ stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph);
+}
+
+STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff)
+{
+ return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);
+}
+
+STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint)
+{
+ stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint));
+}
+
+STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff)
+{
+ return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff);
+}
+
+STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint)
+{
+ stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// bitmap baking
+//
+// This is SUPER-CRAPPY packing to keep source code small
+
+STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)
+ float pixel_height, // height of font in pixels
+ unsigned char *pixels, int pw, int ph, // bitmap to be filled in
+ int first_char, int num_chars, // characters to bake
+ stbtt_bakedchar *chardata)
+{
+ float scale;
+ int x,y,bottom_y, i;
+ stbtt_fontinfo f;
+ if (!stbtt_InitFont(&f, data, offset))
+ return -1;
+ STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
+ x=y=1;
+ bottom_y = 1;
+
+ scale = stbtt_ScaleForPixelHeight(&f, pixel_height);
+
+ for (i=0; i < num_chars; ++i) {
+ int advance, lsb, x0,y0,x1,y1,gw,gh;
+ int g = stbtt_FindGlyphIndex(&f, first_char + i);
+ stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);
+ stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1);
+ gw = x1-x0;
+ gh = y1-y0;
+ if (x + gw + 1 >= pw)
+ y = bottom_y, x = 1; // advance to next row
+ if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row
+ return -i;
+ STBTT_assert(x+gw < pw);
+ STBTT_assert(y+gh < ph);
+ stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g);
+ chardata[i].x0 = (stbtt_int16) x;
+ chardata[i].y0 = (stbtt_int16) y;
+ chardata[i].x1 = (stbtt_int16) (x + gw);
+ chardata[i].y1 = (stbtt_int16) (y + gh);
+ chardata[i].xadvance = scale * advance;
+ chardata[i].xoff = (float) x0;
+ chardata[i].yoff = (float) y0;
+ x = x + gw + 1;
+ if (y+gh+1 > bottom_y)
+ bottom_y = y+gh+1;
+ }
+ return bottom_y;
+}
+
+STBTT_DEF void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)
+{
+ float d3d_bias = opengl_fillrule ? 0 : -0.5f;
+ float ipw = 1.0f / pw, iph = 1.0f / ph;
+ stbtt_bakedchar *b = chardata + char_index;
+ int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f);
+ int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f);
+
+ q->x0 = round_x + d3d_bias;
+ q->y0 = round_y + d3d_bias;
+ q->x1 = round_x + b->x1 - b->x0 + d3d_bias;
+ q->y1 = round_y + b->y1 - b->y0 + d3d_bias;
+
+ q->s0 = b->x0 * ipw;
+ q->t0 = b->y0 * iph;
+ q->s1 = b->x1 * ipw;
+ q->t1 = b->y1 * iph;
+
+ *xpos += b->xadvance;
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// rectangle packing replacement routines if you don't have stb_rect_pack.h
+//
+
+#ifndef STB_RECT_PACK_VERSION
+#ifdef _MSC_VER
+#define STBTT__NOTUSED(v) (void)(v)
+#else
+#define STBTT__NOTUSED(v) (void)sizeof(v)
+#endif
+
+typedef int stbrp_coord;
+
+////////////////////////////////////////////////////////////////////////////////////
+// //
+// //
+// COMPILER WARNING ?!?!? //
+// //
+// //
+// if you get a compile warning due to these symbols being defined more than //
+// once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" //
+// //
+////////////////////////////////////////////////////////////////////////////////////
+
+typedef struct
+{
+ int width,height;
+ int x,y,bottom_y;
+} stbrp_context;
+
+typedef struct
+{
+ unsigned char x;
+} stbrp_node;
+
+struct stbrp_rect
+{
+ stbrp_coord x,y;
+ int id,w,h,was_packed;
+};
+
+static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes)
+{
+ con->width = pw;
+ con->height = ph;
+ con->x = 0;
+ con->y = 0;
+ con->bottom_y = 0;
+ STBTT__NOTUSED(nodes);
+ STBTT__NOTUSED(num_nodes);
+}
+
+static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects)
+{
+ int i;
+ for (i=0; i < num_rects; ++i) {
+ if (con->x + rects[i].w > con->width) {
+ con->x = 0;
+ con->y = con->bottom_y;
+ }
+ if (con->y + rects[i].h > con->height)
+ break;
+ rects[i].x = con->x;
+ rects[i].y = con->y;
+ rects[i].was_packed = 1;
+ con->x += rects[i].w;
+ if (con->y + rects[i].h > con->bottom_y)
+ con->bottom_y = con->y + rects[i].h;
+ }
+ for ( ; i < num_rects; ++i)
+ rects[i].was_packed = 0;
+}
+#endif
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// bitmap baking
+//
+// This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If
+// stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy.
+
+STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context)
+{
+ stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context);
+ int num_nodes = pw - padding;
+ stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context);
+
+ if (context == NULL || nodes == NULL) {
+ if (context != NULL) STBTT_free(context, alloc_context);
+ if (nodes != NULL) STBTT_free(nodes , alloc_context);
+ return 0;
+ }
+
+ spc->user_allocator_context = alloc_context;
+ spc->width = pw;
+ spc->height = ph;
+ spc->pixels = pixels;
+ spc->pack_info = context;
+ spc->nodes = nodes;
+ spc->padding = padding;
+ spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw;
+ spc->h_oversample = 1;
+ spc->v_oversample = 1;
+
+ stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes);
+
+ if (pixels)
+ STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels
+
+ return 1;
+}
+
+STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc)
+{
+ STBTT_free(spc->nodes , spc->user_allocator_context);
+ STBTT_free(spc->pack_info, spc->user_allocator_context);
+}
+
+STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample)
+{
+ STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE);
+ STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE);
+ if (h_oversample <= STBTT_MAX_OVERSAMPLE)
+ spc->h_oversample = h_oversample;
+ if (v_oversample <= STBTT_MAX_OVERSAMPLE)
+ spc->v_oversample = v_oversample;
+}
+
+#define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1)
+
+static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
+{
+ unsigned char buffer[STBTT_MAX_OVERSAMPLE];
+ int safe_w = w - kernel_width;
+ int j;
+ for (j=0; j < h; ++j) {
+ int i;
+ unsigned int total;
+ STBTT_memset(buffer, 0, kernel_width);
+
+ total = 0;
+
+ // make kernel_width a constant in common cases so compiler can optimize out the divide
+ switch (kernel_width) {
+ case 2:
+ for (i=0; i <= safe_w; ++i) {
+ total += pixels[i] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
+ pixels[i] = (unsigned char) (total / 2);
+ }
+ break;
+ case 3:
+ for (i=0; i <= safe_w; ++i) {
+ total += pixels[i] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
+ pixels[i] = (unsigned char) (total / 3);
+ }
+ break;
+ case 4:
+ for (i=0; i <= safe_w; ++i) {
+ total += pixels[i] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
+ pixels[i] = (unsigned char) (total / 4);
+ }
+ break;
+ case 5:
+ for (i=0; i <= safe_w; ++i) {
+ total += pixels[i] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
+ pixels[i] = (unsigned char) (total / 5);
+ }
+ break;
+ default:
+ for (i=0; i <= safe_w; ++i) {
+ total += pixels[i] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];
+ pixels[i] = (unsigned char) (total / kernel_width);
+ }
+ break;
+ }
+
+ for (; i < w; ++i) {
+ STBTT_assert(pixels[i] == 0);
+ total -= buffer[i & STBTT__OVER_MASK];
+ pixels[i] = (unsigned char) (total / kernel_width);
+ }
+
+ pixels += stride_in_bytes;
+ }
+}
+
+static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)
+{
+ unsigned char buffer[STBTT_MAX_OVERSAMPLE];
+ int safe_h = h - kernel_width;
+ int j;
+ for (j=0; j < w; ++j) {
+ int i;
+ unsigned int total;
+ STBTT_memset(buffer, 0, kernel_width);
+
+ total = 0;
+
+ // make kernel_width a constant in common cases so compiler can optimize out the divide
+ switch (kernel_width) {
+ case 2:
+ for (i=0; i <= safe_h; ++i) {
+ total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
+ pixels[i*stride_in_bytes] = (unsigned char) (total / 2);
+ }
+ break;
+ case 3:
+ for (i=0; i <= safe_h; ++i) {
+ total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
+ pixels[i*stride_in_bytes] = (unsigned char) (total / 3);
+ }
+ break;
+ case 4:
+ for (i=0; i <= safe_h; ++i) {
+ total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
+ pixels[i*stride_in_bytes] = (unsigned char) (total / 4);
+ }
+ break;
+ case 5:
+ for (i=0; i <= safe_h; ++i) {
+ total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
+ pixels[i*stride_in_bytes] = (unsigned char) (total / 5);
+ }
+ break;
+ default:
+ for (i=0; i <= safe_h; ++i) {
+ total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];
+ buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];
+ pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
+ }
+ break;
+ }
+
+ for (; i < h; ++i) {
+ STBTT_assert(pixels[i*stride_in_bytes] == 0);
+ total -= buffer[i & STBTT__OVER_MASK];
+ pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);
+ }
+
+ pixels += 1;
+ }
+}
+
+static float stbtt__oversample_shift(int oversample)
+{
+ if (!oversample)
+ return 0.0f;
+
+ // The prefilter is a box filter of width "oversample",
+ // which shifts phase by (oversample - 1)/2 pixels in
+ // oversampled space. We want to shift in the opposite
+ // direction to counter this.
+ return (float)-(oversample - 1) / (2.0f * (float)oversample);
+}
+
+// rects array must be big enough to accommodate all characters in the given ranges
+STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
+{
+ int i,j,k;
+
+ k=0;
+ for (i=0; i < num_ranges; ++i) {
+ float fh = ranges[i].font_size;
+ float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
+ ranges[i].h_oversample = (unsigned char) spc->h_oversample;
+ ranges[i].v_oversample = (unsigned char) spc->v_oversample;
+ for (j=0; j < ranges[i].num_chars; ++j) {
+ int x0,y0,x1,y1;
+ int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
+ int glyph = stbtt_FindGlyphIndex(info, codepoint);
+ stbtt_GetGlyphBitmapBoxSubpixel(info,glyph,
+ scale * spc->h_oversample,
+ scale * spc->v_oversample,
+ 0,0,
+ &x0,&y0,&x1,&y1);
+ rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1);
+ rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1);
+ ++k;
+ }
+ }
+
+ return k;
+}
+
+// rects array must be big enough to accommodate all characters in the given ranges
+STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)
+{
+ int i,j,k, return_value = 1;
+
+ // save current values
+ int old_h_over = spc->h_oversample;
+ int old_v_over = spc->v_oversample;
+
+ k = 0;
+ for (i=0; i < num_ranges; ++i) {
+ float fh = ranges[i].font_size;
+ float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);
+ float recip_h,recip_v,sub_x,sub_y;
+ spc->h_oversample = ranges[i].h_oversample;
+ spc->v_oversample = ranges[i].v_oversample;
+ recip_h = 1.0f / spc->h_oversample;
+ recip_v = 1.0f / spc->v_oversample;
+ sub_x = stbtt__oversample_shift(spc->h_oversample);
+ sub_y = stbtt__oversample_shift(spc->v_oversample);
+ for (j=0; j < ranges[i].num_chars; ++j) {
+ stbrp_rect *r = &rects[k];
+ if (r->was_packed) {
+ stbtt_packedchar *bc = &ranges[i].chardata_for_range[j];
+ int advance, lsb, x0,y0,x1,y1;
+ int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];
+ int glyph = stbtt_FindGlyphIndex(info, codepoint);
+ stbrp_coord pad = (stbrp_coord) spc->padding;
+
+ // pad on left and top
+ r->x += pad;
+ r->y += pad;
+ r->w -= pad;
+ r->h -= pad;
+ stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb);
+ stbtt_GetGlyphBitmapBox(info, glyph,
+ scale * spc->h_oversample,
+ scale * spc->v_oversample,
+ &x0,&y0,&x1,&y1);
+ stbtt_MakeGlyphBitmapSubpixel(info,
+ spc->pixels + r->x + r->y*spc->stride_in_bytes,
+ r->w - spc->h_oversample+1,
+ r->h - spc->v_oversample+1,
+ spc->stride_in_bytes,
+ scale * spc->h_oversample,
+ scale * spc->v_oversample,
+ 0,0,
+ glyph);
+
+ if (spc->h_oversample > 1)
+ stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
+ r->w, r->h, spc->stride_in_bytes,
+ spc->h_oversample);
+
+ if (spc->v_oversample > 1)
+ stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,
+ r->w, r->h, spc->stride_in_bytes,
+ spc->v_oversample);
+
+ bc->x0 = (stbtt_int16) r->x;
+ bc->y0 = (stbtt_int16) r->y;
+ bc->x1 = (stbtt_int16) (r->x + r->w);
+ bc->y1 = (stbtt_int16) (r->y + r->h);
+ bc->xadvance = scale * advance;
+ bc->xoff = (float) x0 * recip_h + sub_x;
+ bc->yoff = (float) y0 * recip_v + sub_y;
+ bc->xoff2 = (x0 + r->w) * recip_h + sub_x;
+ bc->yoff2 = (y0 + r->h) * recip_v + sub_y;
+ } else {
+ return_value = 0; // if any fail, report failure
+ }
+
+ ++k;
+ }
+ }
+
+ // restore original values
+ spc->h_oversample = old_h_over;
+ spc->v_oversample = old_v_over;
+
+ return return_value;
+}
+
+STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects)
+{
+ stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects);
+}
+
+STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges)
+{
+ stbtt_fontinfo info;
+ int i,j,n, return_value = 1;
+ //stbrp_context *context = (stbrp_context *) spc->pack_info;
+ stbrp_rect *rects;
+
+ // flag all characters as NOT packed
+ for (i=0; i < num_ranges; ++i)
+ for (j=0; j < ranges[i].num_chars; ++j)
+ ranges[i].chardata_for_range[j].x0 =
+ ranges[i].chardata_for_range[j].y0 =
+ ranges[i].chardata_for_range[j].x1 =
+ ranges[i].chardata_for_range[j].y1 = 0;
+
+ n = 0;
+ for (i=0; i < num_ranges; ++i)
+ n += ranges[i].num_chars;
+
+ rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context);
+ if (rects == NULL)
+ return 0;
+
+ stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index));
+
+ n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects);
+
+ stbtt_PackFontRangesPackRects(spc, rects, n);
+
+ return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects);
+
+ STBTT_free(rects, spc->user_allocator_context);
+ return return_value;
+}
+
+STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, float font_size,
+ int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range)
+{
+ stbtt_pack_range range;
+ range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range;
+ range.array_of_unicode_codepoints = NULL;
+ range.num_chars = num_chars_in_range;
+ range.chardata_for_range = chardata_for_range;
+ range.font_size = font_size;
+ return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1);
+}
+
+STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer)
+{
+ float ipw = 1.0f / pw, iph = 1.0f / ph;
+ stbtt_packedchar *b = chardata + char_index;
+
+ if (align_to_integer) {
+ float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f);
+ float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f);
+ q->x0 = x;
+ q->y0 = y;
+ q->x1 = x + b->xoff2 - b->xoff;
+ q->y1 = y + b->yoff2 - b->yoff;
+ } else {
+ q->x0 = *xpos + b->xoff;
+ q->y0 = *ypos + b->yoff;
+ q->x1 = *xpos + b->xoff2;
+ q->y1 = *ypos + b->yoff2;
+ }
+
+ q->s0 = b->x0 * ipw;
+ q->t0 = b->y0 * iph;
+ q->s1 = b->x1 * ipw;
+ q->t1 = b->y1 * iph;
+
+ *xpos += b->xadvance;
+}
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// font name matching -- recommended not to use this
+//
+
+// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string
+static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(const stbtt_uint8 *s1, stbtt_int32 len1, const stbtt_uint8 *s2, stbtt_int32 len2)
+{
+ stbtt_int32 i=0;
+
+ // convert utf16 to utf8 and compare the results while converting
+ while (len2) {
+ stbtt_uint16 ch = s2[0]*256 + s2[1];
+ if (ch < 0x80) {
+ if (i >= len1) return -1;
+ if (s1[i++] != ch) return -1;
+ } else if (ch < 0x800) {
+ if (i+1 >= len1) return -1;
+ if (s1[i++] != 0xc0 + (ch >> 6)) return -1;
+ if (s1[i++] != 0x80 + (ch & 0x3f)) return -1;
+ } else if (ch >= 0xd800 && ch < 0xdc00) {
+ stbtt_uint32 c;
+ stbtt_uint16 ch2 = s2[2]*256 + s2[3];
+ if (i+3 >= len1) return -1;
+ c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;
+ if (s1[i++] != 0xf0 + (c >> 18)) return -1;
+ if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;
+ if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1;
+ if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1;
+ s2 += 2; // plus another 2 below
+ len2 -= 2;
+ } else if (ch >= 0xdc00 && ch < 0xe000) {
+ return -1;
+ } else {
+ if (i+2 >= len1) return -1;
+ if (s1[i++] != 0xe0 + (ch >> 12)) return -1;
+ if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;
+ if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1;
+ }
+ s2 += 2;
+ len2 -= 2;
+ }
+ return i;
+}
+
+STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2)
+{
+ return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((const stbtt_uint8*) s1, len1, (const stbtt_uint8*) s2, len2);
+}
+
+// returns results in whatever encoding you request... but note that 2-byte encodings
+// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare
+STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID)
+{
+ stbtt_int32 i,count,stringOffset;
+ stbtt_uint8 *fc = font->data;
+ stbtt_uint32 offset = font->fontstart;
+ stbtt_uint32 nm = stbtt__find_table(fc, offset, "name");
+ if (!nm) return NULL;
+
+ count = ttUSHORT(fc+nm+2);
+ stringOffset = nm + ttUSHORT(fc+nm+4);
+ for (i=0; i < count; ++i) {
+ stbtt_uint32 loc = nm + 6 + 12 * i;
+ if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2)
+ && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) {
+ *length = ttUSHORT(fc+loc+8);
+ return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10));
+ }
+ }
+ return NULL;
+}
+
+static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)
+{
+ stbtt_int32 i;
+ stbtt_int32 count = ttUSHORT(fc+nm+2);
+ stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4);
+
+ for (i=0; i < count; ++i) {
+ stbtt_uint32 loc = nm + 6 + 12 * i;
+ stbtt_int32 id = ttUSHORT(fc+loc+6);
+ if (id == target_id) {
+ // find the encoding
+ stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4);
+
+ // is this a Unicode encoding?
+ if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {
+ stbtt_int32 slen = ttUSHORT(fc+loc+8);
+ stbtt_int32 off = ttUSHORT(fc+loc+10);
+
+ // check if there's a prefix match
+ stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen);
+ if (matchlen >= 0) {
+ // check for target_id+1 immediately following, with same encoding & language
+ if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) {
+ slen = ttUSHORT(fc+loc+12+8);
+ off = ttUSHORT(fc+loc+12+10);
+ if (slen == 0) {
+ if (matchlen == nlen)
+ return 1;
+ } else if (matchlen < nlen && name[matchlen] == ' ') {
+ ++matchlen;
+ if (stbtt_CompareUTF8toUTF16_bigendian((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen))
+ return 1;
+ }
+ } else {
+ // if nothing immediately following
+ if (matchlen == nlen)
+ return 1;
+ }
+ }
+ }
+
+ // @TODO handle other encodings
+ }
+ }
+ return 0;
+}
+
+static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags)
+{
+ stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name);
+ stbtt_uint32 nm,hd;
+ if (!stbtt__isfont(fc+offset)) return 0;
+
+ // check italics/bold/underline flags in macStyle...
+ if (flags) {
+ hd = stbtt__find_table(fc, offset, "head");
+ if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0;
+ }
+
+ nm = stbtt__find_table(fc, offset, "name");
+ if (!nm) return 0;
+
+ if (flags) {
+ // if we checked the macStyle flags, then just check the family and ignore the subfamily
+ if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1;
+ if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1;
+ if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
+ } else {
+ if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1;
+ if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1;
+ if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;
+ }
+
+ return 0;
+}
+
+STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *font_collection, const char *name_utf8, stbtt_int32 flags)
+{
+ stbtt_int32 i;
+ for (i=0;;++i) {
+ stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);
+ if (off < 0) return off;
+ if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags))
+ return off;
+ }
+}
+
+#endif // STB_TRUETYPE_IMPLEMENTATION
+
+
+// FULL VERSION HISTORY
+//
+// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges
+// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;
+// allow PackFontRanges to pack and render in separate phases;
+// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);
+// fixed an assert() bug in the new rasterizer
+// replace assert() with STBTT_assert() in new rasterizer
+// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine)
+// also more precise AA rasterizer, except if shapes overlap
+// remove need for STBTT_sort
+// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC
+// 1.04 (2015-04-15) typo in example
+// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes
+// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++
+// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match
+// non-oversampled; STBTT_POINT_SIZE for packed case only
+// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling
+// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg)
+// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID
+// 0.8b (2014-07-07) fix a warning
+// 0.8 (2014-05-25) fix a few more warnings
+// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back
+// 0.6c (2012-07-24) improve documentation
+// 0.6b (2012-07-20) fix a few more warnings
+// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,
+// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty
+// 0.5 (2011-12-09) bugfixes:
+// subpixel glyph renderer computed wrong bounding box
+// first vertex of shape can be off-curve (FreeSans)
+// 0.4b (2011-12-03) fixed an error in the font baking example
+// 0.4 (2011-12-01) kerning, subpixel rendering (tor)
+// bugfixes for:
+// codepoint-to-glyph conversion using table fmt=12
+// codepoint-to-glyph conversion using table fmt=4
+// stbtt_GetBakedQuad with non-square texture (Zer)
+// updated Hello World! sample to use kerning and subpixel
+// fixed some warnings
+// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM)
+// userdata, malloc-from-userdata, non-zero fill (stb)
+// 0.2 (2009-03-11) Fix unsigned/signed char warnings
+// 0.1 (2009-03-09) First public release
+//
diff --git a/drivers/video/vidconsole-uclass.c b/drivers/video/vidconsole-uclass.c
index 706a1894cce..f6326b6e072 100644
--- a/drivers/video/vidconsole-uclass.c
+++ b/drivers/video/vidconsole-uclass.c
@@ -47,19 +47,38 @@ int vidconsole_set_row(struct udevice *dev, uint row, int clr)
return ops->set_row(dev, row, clr);
}
+static int vidconsole_entry_start(struct udevice *dev)
+{
+ struct vidconsole_ops *ops = vidconsole_get_ops(dev);
+
+ if (!ops->entry_start)
+ return -ENOSYS;
+ return ops->entry_start(dev);
+}
+
/* Move backwards one space */
-static void vidconsole_back(struct udevice *dev)
+static int vidconsole_back(struct udevice *dev)
{
struct vidconsole_priv *priv = dev_get_uclass_priv(dev);
+ struct vidconsole_ops *ops = vidconsole_get_ops(dev);
+ int ret;
- if (--priv->curr_col < 0) {
- priv->curr_col = priv->cols - 1;
- if (--priv->curr_row < 0)
- priv->curr_row = 0;
+ if (ops->backspace) {
+ ret = ops->backspace(dev);
+ if (ret != -ENOSYS)
+ return ret;
}
- vidconsole_putc_xy(dev, priv->curr_col * VIDEO_FONT_WIDTH,
- priv->curr_row * VIDEO_FONT_HEIGHT, ' ');
+ priv->xcur_frac -= VID_TO_POS(priv->x_charsize);
+ if (priv->xcur_frac < priv->xstart_frac) {
+ priv->xcur_frac = (priv->cols - 1) *
+ VID_TO_POS(priv->x_charsize);
+ priv->ycur -= priv->y_charsize;
+ if (priv->ycur < 0)
+ priv->ycur = 0;
+ }
+
+ return 0;
}
/* Move to a newline, scrolling the display if necessary */
@@ -71,16 +90,19 @@ static void vidconsole_newline(struct udevice *dev)
const int rows = CONFIG_CONSOLE_SCROLL_LINES;
int i;
- priv->curr_col = 0;
+ priv->xcur_frac = priv->xstart_frac;
+ priv->ycur += priv->y_charsize;
/* Check if we need to scroll the terminal */
- if (++priv->curr_row >= priv->rows) {
+ if ((priv->ycur + priv->y_charsize) / priv->y_charsize > priv->rows) {
vidconsole_move_rows(dev, 0, rows, priv->rows - rows);
for (i = 0; i < rows; i++)
vidconsole_set_row(dev, priv->rows - i - 1,
vid_priv->colour_bg);
- priv->curr_row -= rows;
+ priv->ycur -= rows * priv->y_charsize;
}
+ priv->last_ch = 0;
+
video_sync(dev->parent);
}
@@ -90,21 +112,26 @@ int vidconsole_put_char(struct udevice *dev, char ch)
int ret;
switch (ch) {
+ case '\a':
+ /* beep */
+ break;
case '\r':
- priv->curr_col = 0;
+ priv->xcur_frac = priv->xstart_frac;
break;
case '\n':
vidconsole_newline(dev);
+ vidconsole_entry_start(dev);
break;
case '\t': /* Tab (8 chars alignment) */
- priv->curr_col += 8;
- priv->curr_col &= ~7;
+ priv->xcur_frac = ((priv->xcur_frac / priv->tab_width_frac)
+ + 1) * priv->tab_width_frac;
- if (priv->curr_col >= priv->cols)
+ if (priv->xcur_frac >= priv->xsize_frac)
vidconsole_newline(dev);
break;
case '\b':
vidconsole_back(dev);
+ priv->last_ch = 0;
break;
default:
/*
@@ -112,13 +139,17 @@ int vidconsole_put_char(struct udevice *dev, char ch)
* colour depth. Check this and return an error to help with
* diagnosis.
*/
- ret = vidconsole_putc_xy(dev,
- priv->curr_col * VIDEO_FONT_WIDTH,
- priv->curr_row * VIDEO_FONT_HEIGHT,
- ch);
- if (ret)
+ ret = vidconsole_putc_xy(dev, priv->xcur_frac, priv->ycur, ch);
+ if (ret == -EAGAIN) {
+ vidconsole_newline(dev);
+ ret = vidconsole_putc_xy(dev, priv->xcur_frac,
+ priv->ycur, ch);
+ }
+ if (ret < 0)
return ret;
- if (++priv->curr_col >= priv->cols)
+ priv->xcur_frac += ret;
+ priv->last_ch = ch;
+ if (priv->xcur_frac >= priv->xsize_frac)
vidconsole_newline(dev);
break;
}
@@ -148,8 +179,7 @@ static int vidconsole_pre_probe(struct udevice *dev)
struct udevice *vid = dev->parent;
struct video_priv *vid_priv = dev_get_uclass_priv(vid);
- priv->rows = vid_priv->ysize / VIDEO_FONT_HEIGHT;
- priv->cols = vid_priv->xsize / VIDEO_FONT_WIDTH;
+ priv->xsize_frac = VID_TO_POS(vid_priv->xsize);
return 0;
}
@@ -161,12 +191,16 @@ static int vidconsole_post_probe(struct udevice *dev)
struct stdio_dev *sdev = &priv->sdev;
int ret;
+ if (!priv->tab_width_frac)
+ priv->tab_width_frac = VID_TO_POS(priv->x_charsize) * 8;
+
if (dev->seq) {
snprintf(sdev->name, sizeof(sdev->name), "vidconsole%d",
dev->seq);
} else {
strcpy(sdev->name, "vidconsole");
}
+
sdev->flags = DEV_FLAGS_OUTPUT;
sdev->putc = vidconsole_putc;
sdev->puts = vidconsole_puts;
@@ -189,9 +223,11 @@ UCLASS_DRIVER(vidconsole) = {
void vidconsole_position_cursor(struct udevice *dev, unsigned col, unsigned row)
{
struct vidconsole_priv *priv = dev_get_uclass_priv(dev);
+ struct udevice *vid_dev = dev->parent;
+ struct video_priv *vid_priv = dev_get_uclass_priv(vid_dev);
- priv->curr_col = min_t(short, col, priv->cols - 1);
- priv->curr_row = min_t(short, row, priv->rows - 1);
+ priv->xcur_frac = VID_TO_POS(min_t(short, col, vid_priv->xsize - 1));
+ priv->ycur = min_t(short, row, vid_priv->ysize - 1);
}
static int do_video_setcursor(cmd_tbl_t *cmdtp, int flag, int argc,
diff --git a/drivers/video/video-uclass.c b/drivers/video/video-uclass.c
index 24d537e6c44..b6dd0f5a583 100644
--- a/drivers/video/video-uclass.c
+++ b/drivers/video/video-uclass.c
@@ -180,6 +180,7 @@ static int video_post_probe(struct udevice *dev)
struct video_uc_platdata *plat = dev_get_uclass_platdata(dev);
struct video_priv *priv = dev_get_uclass_priv(dev);
char name[30], drv[15], *str;
+ const char *drv_name = drv;
struct udevice *cons;
int ret;
@@ -197,20 +198,38 @@ static int video_post_probe(struct udevice *dev)
video_clear(dev);
/*
- * Create a text console devices. For now we always do this, although
+ * Create a text console device. For now we always do this, although
* it might be useful to support only bitmap drawing on the device
- * for boards that don't need to display text.
+ * for boards that don't need to display text. We create a TrueType
+ * console if enabled, a rotated console if the video driver requests
+ * it, otherwise a normal console.
+ *
+ * The console can be override by setting vidconsole_drv_name before
+ * probing this video driver, or in the probe() method.
+ *
+ * TrueType does not support rotation at present so fall back to the
+ * rotated console in that case.
*/
- snprintf(name, sizeof(name), "%s.vidconsole", dev->name);
+ if (!priv->rot && IS_ENABLED(CONFIG_CONSOLE_TRUETYPE)) {
+ snprintf(name, sizeof(name), "%s.vidconsole_tt", dev->name);
+ strcpy(drv, "vidconsole_tt");
+ } else {
+ snprintf(name, sizeof(name), "%s.vidconsole%d", dev->name,
+ priv->rot);
+ snprintf(drv, sizeof(drv), "vidconsole%d", priv->rot);
+ }
+
str = strdup(name);
if (!str)
return -ENOMEM;
- snprintf(drv, sizeof(drv), "vidconsole%d", priv->rot);
- ret = device_bind_driver(dev, drv, str, &cons);
+ if (priv->vidconsole_drv_name)
+ drv_name = priv->vidconsole_drv_name;
+ ret = device_bind_driver(dev, drv_name, str, &cons);
if (ret) {
debug("%s: Cannot bind console driver\n", __func__);
return ret;
}
+
ret = device_probe(cons);
if (ret) {
debug("%s: Cannot probe console driver\n", __func__);