All of lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH v3 0/6] Additional NPCM7xx features, devices and tests
@ 2020-10-23 21:06 Havard Skinnemoen via
  2020-10-23 21:06 ` [PATCH v3 1/6] tests/qtest: Make npcm7xx_timer-test conditional on CONFIG_NPCM7XX Havard Skinnemoen via
                   ` (6 more replies)
  0 siblings, 7 replies; 15+ messages in thread
From: Havard Skinnemoen via @ 2020-10-23 21:06 UTC (permalink / raw)
  To: peter.maydell
  Cc: qemu-arm, qemu-devel, Avi.Fishman, kfting, venture, wuhaotsh,
	thuth, Havard Skinnemoen

This is an update to the initial NPCM7xx patch series adding

  - Watchdog timer support. This makes the reboot command work.
  - Random Number Generator device.
  - USB Host Controllers.
  - GPIO Controllers.

The watchdog was implemented by my new teammate Hao Wu. Expect to see more
patches from him in the near future.

This series has also been pushed to the npcm7xx-5.2-update branch of my github
repository at

  https://github.com/hskinnemoen/qemu

Changes since v2:

  - Watchdog timer test now uses libqos/libqtest.h API consistently instead of
    a mix of that and libqtest-single.h.
  - Made all npcm7xx-related tests conditional on CONFIG_NPCM7XX. An extra
    patch was added for the previously submitted timer test.

Changes since v1:

  - Dropped the timer test since it's already applied (thanks Peter).
  - Watchdog reset signaling is now using GPIOs instead of a custom API
    (thanks Peter for suggesting, and Hao for implementing it).
  - Various comment updates for the timer.
  - VMState added to GPIO device.
  - Missing VMstate terminator added to RNG device.
  - Include order in RNG test fixed.

Again, thanks a lot for reviewing!

Havard

Hao Wu (1):
  hw/timer: Adding watchdog for NPCM7XX Timer.

Havard Skinnemoen (5):
  tests/qtest: Make npcm7xx_timer-test conditional on CONFIG_NPCM7XX
  Move npcm7xx_timer_reached_zero call out of npcm7xx_timer_pause
  hw/misc: Add npcm7xx random number generator
  hw/arm/npcm7xx: Add EHCI and OHCI controllers
  hw/gpio: Add GPIO model for Nuvoton NPCM7xx

 docs/system/arm/nuvoton.rst               |   6 +-
 hw/usb/hcd-ehci.h                         |   1 +
 include/hw/arm/npcm7xx.h                  |   8 +
 include/hw/gpio/npcm7xx_gpio.h            |  55 +++
 include/hw/misc/npcm7xx_clk.h             |   2 +
 include/hw/misc/npcm7xx_rng.h             |  34 ++
 include/hw/timer/npcm7xx_timer.h          |  48 ++-
 hw/arm/npcm7xx.c                          | 126 ++++++-
 hw/gpio/npcm7xx_gpio.c                    | 424 ++++++++++++++++++++++
 hw/misc/npcm7xx_clk.c                     |  28 ++
 hw/misc/npcm7xx_rng.c                     | 180 +++++++++
 hw/timer/npcm7xx_timer.c                  | 270 +++++++++++---
 hw/usb/hcd-ehci-sysbus.c                  |  19 +
 tests/qtest/npcm7xx_gpio-test.c           | 385 ++++++++++++++++++++
 tests/qtest/npcm7xx_rng-test.c            | 278 ++++++++++++++
 tests/qtest/npcm7xx_watchdog_timer-test.c | 320 ++++++++++++++++
 MAINTAINERS                               |   1 +
 hw/gpio/meson.build                       |   1 +
 hw/gpio/trace-events                      |   7 +
 hw/misc/meson.build                       |   1 +
 hw/misc/trace-events                      |   4 +
 tests/qtest/meson.build                   |   7 +-
 22 files changed, 2143 insertions(+), 62 deletions(-)
 create mode 100644 include/hw/gpio/npcm7xx_gpio.h
 create mode 100644 include/hw/misc/npcm7xx_rng.h
 create mode 100644 hw/gpio/npcm7xx_gpio.c
 create mode 100644 hw/misc/npcm7xx_rng.c
 create mode 100644 tests/qtest/npcm7xx_gpio-test.c
 create mode 100644 tests/qtest/npcm7xx_rng-test.c
 create mode 100644 tests/qtest/npcm7xx_watchdog_timer-test.c

-- 
2.29.0.rc1.297.gfa9743e501-goog



^ permalink raw reply	[flat|nested] 15+ messages in thread

* [PATCH v3 1/6] tests/qtest: Make npcm7xx_timer-test conditional on CONFIG_NPCM7XX
  2020-10-23 21:06 [PATCH v3 0/6] Additional NPCM7xx features, devices and tests Havard Skinnemoen via
@ 2020-10-23 21:06 ` Havard Skinnemoen via
  2020-10-24  5:26   ` Thomas Huth
  2020-10-23 21:06 ` [PATCH v3 2/6] Move npcm7xx_timer_reached_zero call out of npcm7xx_timer_pause Havard Skinnemoen via
                   ` (5 subsequent siblings)
  6 siblings, 1 reply; 15+ messages in thread
From: Havard Skinnemoen via @ 2020-10-23 21:06 UTC (permalink / raw)
  To: peter.maydell
  Cc: qemu-arm, qemu-devel, Avi.Fishman, kfting, venture, wuhaotsh,
	thuth, Havard Skinnemoen

This test won't work if qemu was compiled without CONFIG_NPCM7XX, as
pointed out by Thomas Huth on a different patch.

Signed-off-by: Havard Skinnemoen <hskinnemoen@google.com>
---
 tests/qtest/meson.build | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/tests/qtest/meson.build b/tests/qtest/meson.build
index 28d4068718..7e0ecaa2c5 100644
--- a/tests/qtest/meson.build
+++ b/tests/qtest/meson.build
@@ -133,12 +133,13 @@ qtests_sparc64 = \
   (config_all_devices.has_key('CONFIG_ISA_TESTDEV') ? ['endianness-test'] : []) +            \
   ['prom-env-test', 'boot-serial-test']
 
+qtests_npcm7xx = ['npcm7xx_timer-test']
 qtests_arm = \
   (config_all_devices.has_key('CONFIG_PFLASH_CFI02') ? ['pflash-cfi02-test'] : []) +         \
+  (config_all_devices.has_key('CONFIG_NPCM7XX') ? qtests_npcm7xx : []) + \
   ['arm-cpu-features',
    'microbit-test',
    'm25p80-test',
-   'npcm7xx_timer-test',
    'test-arm-mptimer',
    'boot-serial-test',
    'hexloader-test']
-- 
2.29.0.rc1.297.gfa9743e501-goog



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v3 2/6] Move npcm7xx_timer_reached_zero call out of npcm7xx_timer_pause
  2020-10-23 21:06 [PATCH v3 0/6] Additional NPCM7xx features, devices and tests Havard Skinnemoen via
  2020-10-23 21:06 ` [PATCH v3 1/6] tests/qtest: Make npcm7xx_timer-test conditional on CONFIG_NPCM7XX Havard Skinnemoen via
@ 2020-10-23 21:06 ` Havard Skinnemoen via
  2020-10-23 21:06 ` [PATCH v3 3/6] hw/timer: Adding watchdog for NPCM7XX Timer Havard Skinnemoen via
                   ` (4 subsequent siblings)
  6 siblings, 0 replies; 15+ messages in thread
From: Havard Skinnemoen via @ 2020-10-23 21:06 UTC (permalink / raw)
  To: peter.maydell
  Cc: qemu-arm, qemu-devel, Avi.Fishman, kfting, venture, wuhaotsh,
	thuth, Havard Skinnemoen, Philippe Mathieu-Daudé

This allows us to reuse npcm7xx_timer_pause for the watchdog timer.

Reviewed-by: Philippe Mathieu-Daudé <f4bug@amsat.org>
Signed-off-by: Havard Skinnemoen <hskinnemoen@google.com>
---
 hw/timer/npcm7xx_timer.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/hw/timer/npcm7xx_timer.c b/hw/timer/npcm7xx_timer.c
index 5703e43d40..2df9e3e496 100644
--- a/hw/timer/npcm7xx_timer.c
+++ b/hw/timer/npcm7xx_timer.c
@@ -157,9 +157,6 @@ static void npcm7xx_timer_pause(NPCM7xxTimer *t)
     timer_del(&t->qtimer);
     now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
     t->remaining_ns = t->expires_ns - now;
-    if (t->remaining_ns <= 0) {
-        npcm7xx_timer_reached_zero(t);
-    }
 }
 
 /*
@@ -239,6 +236,9 @@ static void npcm7xx_timer_write_tcsr(NPCM7xxTimer *t, uint32_t new_tcsr)
         } else {
             t->tcsr &= ~NPCM7XX_TCSR_CACT;
             npcm7xx_timer_pause(t);
+            if (t->remaining_ns <= 0) {
+                npcm7xx_timer_reached_zero(t);
+            }
         }
     }
 }
-- 
2.29.0.rc1.297.gfa9743e501-goog



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v3 3/6] hw/timer: Adding watchdog for NPCM7XX Timer.
  2020-10-23 21:06 [PATCH v3 0/6] Additional NPCM7xx features, devices and tests Havard Skinnemoen via
  2020-10-23 21:06 ` [PATCH v3 1/6] tests/qtest: Make npcm7xx_timer-test conditional on CONFIG_NPCM7XX Havard Skinnemoen via
  2020-10-23 21:06 ` [PATCH v3 2/6] Move npcm7xx_timer_reached_zero call out of npcm7xx_timer_pause Havard Skinnemoen via
@ 2020-10-23 21:06 ` Havard Skinnemoen via
  2020-10-23 21:06 ` [PATCH v3 4/6] hw/misc: Add npcm7xx random number generator Havard Skinnemoen via
                   ` (3 subsequent siblings)
  6 siblings, 0 replies; 15+ messages in thread
From: Havard Skinnemoen via @ 2020-10-23 21:06 UTC (permalink / raw)
  To: peter.maydell
  Cc: qemu-arm, qemu-devel, Avi.Fishman, kfting, venture, wuhaotsh,
	thuth, Havard Skinnemoen

From: Hao Wu <wuhaotsh@google.com>

The watchdog is part of NPCM7XX's timer module. Its behavior is
controlled by the WTCR register in the timer.

When enabled, the watchdog issues an interrupt signal after a pre-set
amount of cycles, and issues a reset signal shortly after that.

Reviewed-by: Tyrone Ting <kfting@nuvoton.com>
Signed-off-by: Hao Wu <wuhaotsh@google.com>
Signed-off-by: Havard Skinnemoen <hskinnemoen@google.com>
---
 include/hw/misc/npcm7xx_clk.h             |   2 +
 include/hw/timer/npcm7xx_timer.h          |  48 +++-
 hw/arm/npcm7xx.c                          |  12 +
 hw/misc/npcm7xx_clk.c                     |  28 ++
 hw/timer/npcm7xx_timer.c                  | 266 ++++++++++++++----
 tests/qtest/npcm7xx_watchdog_timer-test.c | 320 ++++++++++++++++++++++
 MAINTAINERS                               |   1 +
 tests/qtest/meson.build                   |   2 +-
 8 files changed, 625 insertions(+), 54 deletions(-)
 create mode 100644 tests/qtest/npcm7xx_watchdog_timer-test.c

diff --git a/include/hw/misc/npcm7xx_clk.h b/include/hw/misc/npcm7xx_clk.h
index cdcc9e8534..2338fbbdb5 100644
--- a/include/hw/misc/npcm7xx_clk.h
+++ b/include/hw/misc/npcm7xx_clk.h
@@ -31,6 +31,8 @@
  */
 #define NPCM7XX_CLK_NR_REGS             (0x70 / sizeof(uint32_t))
 
+#define NPCM7XX_WATCHDOG_RESET_GPIO_IN "npcm7xx-clk-watchdog-reset-gpio-in"
+
 typedef struct NPCM7xxCLKState {
     SysBusDevice parent;
 
diff --git a/include/hw/timer/npcm7xx_timer.h b/include/hw/timer/npcm7xx_timer.h
index 878a365a79..6993fd723a 100644
--- a/include/hw/timer/npcm7xx_timer.h
+++ b/include/hw/timer/npcm7xx_timer.h
@@ -29,14 +29,31 @@
  */
 #define NPCM7XX_TIMER_NR_REGS (0x54 / sizeof(uint32_t))
 
+/* The basic watchdog timer period is 2^14 clock cycles. */
+#define NPCM7XX_WATCHDOG_BASETIME_SHIFT 14
+
+#define NPCM7XX_WATCHDOG_RESET_GPIO_OUT "npcm7xx-clk-watchdog-reset-gpio-out"
+
 typedef struct NPCM7xxTimerCtrlState NPCM7xxTimerCtrlState;
 
 /**
- * struct NPCM7xxTimer - Individual timer state.
- * @irq: GIC interrupt line to fire on expiration (if enabled).
+ * struct NPCM7xxBaseTimer - Basic functionality that both regular timer and
+ * watchdog timer use.
  * @qtimer: QEMU timer that notifies us on expiration.
  * @expires_ns: Absolute virtual expiration time.
  * @remaining_ns: Remaining time until expiration if timer is paused.
+ */
+typedef struct NPCM7xxBaseTimer {
+    QEMUTimer   qtimer;
+    int64_t     expires_ns;
+    int64_t     remaining_ns;
+} NPCM7xxBaseTimer;
+
+/**
+ * struct NPCM7xxTimer - Individual timer state.
+ * @ctrl: The timer module that owns this timer.
+ * @irq: GIC interrupt line to fire on expiration (if enabled).
+ * @base_timer: The basic timer functionality for this timer.
  * @tcsr: The Timer Control and Status Register.
  * @ticr: The Timer Initial Count Register.
  */
@@ -44,21 +61,38 @@ typedef struct NPCM7xxTimer {
     NPCM7xxTimerCtrlState *ctrl;
 
     qemu_irq    irq;
-    QEMUTimer   qtimer;
-    int64_t     expires_ns;
-    int64_t     remaining_ns;
+    NPCM7xxBaseTimer base_timer;
 
     uint32_t    tcsr;
     uint32_t    ticr;
 } NPCM7xxTimer;
 
+/**
+ * struct NPCM7xxWatchdogTimer - The watchdog timer state.
+ * @ctrl: The timer module that owns this timer.
+ * @irq: GIC interrupt line to fire on expiration (if enabled).
+ * @reset_signal: The GPIO used to send a reset signal.
+ * @base_timer: The basic timer functionality for this timer.
+ * @wtcr: The Watchdog Timer Control Register.
+ */
+typedef struct NPCM7xxWatchdogTimer {
+    NPCM7xxTimerCtrlState *ctrl;
+
+    qemu_irq            irq;
+    qemu_irq            reset_signal;
+    NPCM7xxBaseTimer base_timer;
+
+    uint32_t            wtcr;
+} NPCM7xxWatchdogTimer;
+
 /**
  * struct NPCM7xxTimerCtrlState - Timer Module device state.
  * @parent: System bus device.
  * @iomem: Memory region through which registers are accessed.
+ * @index: The index of this timer module.
  * @tisr: The Timer Interrupt Status Register.
- * @wtcr: The Watchdog Timer Control Register.
  * @timer: The five individual timers managed by this module.
+ * @watchdog_timer: The watchdog timer managed by this module.
  */
 struct NPCM7xxTimerCtrlState {
     SysBusDevice parent;
@@ -66,9 +100,9 @@ struct NPCM7xxTimerCtrlState {
     MemoryRegion iomem;
 
     uint32_t    tisr;
-    uint32_t    wtcr;
 
     NPCM7xxTimer timer[NPCM7XX_TIMERS_PER_CTRL];
+    NPCM7xxWatchdogTimer watchdog_timer;
 };
 
 #define TYPE_NPCM7XX_TIMER "npcm7xx-timer"
diff --git a/hw/arm/npcm7xx.c b/hw/arm/npcm7xx.c
index 037f3a26f2..c341dcab8b 100644
--- a/hw/arm/npcm7xx.c
+++ b/hw/arm/npcm7xx.c
@@ -86,6 +86,9 @@ enum NPCM7xxInterrupt {
     NPCM7XX_TIMER12_IRQ,
     NPCM7XX_TIMER13_IRQ,
     NPCM7XX_TIMER14_IRQ,
+    NPCM7XX_WDG0_IRQ            = 47,   /* Timer Module 0 Watchdog */
+    NPCM7XX_WDG1_IRQ,                   /* Timer Module 1 Watchdog */
+    NPCM7XX_WDG2_IRQ,                   /* Timer Module 2 Watchdog */
 };
 
 /* Total number of GIC interrupts, including internal Cortex-A9 interrupts. */
@@ -353,6 +356,15 @@ static void npcm7xx_realize(DeviceState *dev, Error **errp)
             qemu_irq irq = npcm7xx_irq(s, first_irq + j);
             sysbus_connect_irq(sbd, j, irq);
         }
+
+        /* IRQ for watchdogs */
+        sysbus_connect_irq(sbd, NPCM7XX_TIMERS_PER_CTRL,
+                npcm7xx_irq(s, NPCM7XX_WDG0_IRQ + i));
+        /* GPIO that connects clk module with watchdog */
+        qdev_connect_gpio_out_named(DEVICE(&s->tim[i]),
+                NPCM7XX_WATCHDOG_RESET_GPIO_OUT, 0,
+                qdev_get_gpio_in_named(DEVICE(&s->clk),
+                        NPCM7XX_WATCHDOG_RESET_GPIO_IN, i));
     }
 
     /* UART0..3 (16550 compatible) */
diff --git a/hw/misc/npcm7xx_clk.c b/hw/misc/npcm7xx_clk.c
index 21ab4200d1..6732437fe2 100644
--- a/hw/misc/npcm7xx_clk.c
+++ b/hw/misc/npcm7xx_clk.c
@@ -17,6 +17,7 @@
 #include "qemu/osdep.h"
 
 #include "hw/misc/npcm7xx_clk.h"
+#include "hw/timer/npcm7xx_timer.h"
 #include "migration/vmstate.h"
 #include "qemu/error-report.h"
 #include "qemu/log.h"
@@ -24,6 +25,7 @@
 #include "qemu/timer.h"
 #include "qemu/units.h"
 #include "trace.h"
+#include "sysemu/watchdog.h"
 
 #define PLLCON_LOKI     BIT(31)
 #define PLLCON_LOKS     BIT(30)
@@ -87,6 +89,12 @@ static const uint32_t cold_reset_values[NPCM7XX_CLK_NR_REGS] = {
     [NPCM7XX_CLK_AHBCKFI]       = 0x000000c8,
 };
 
+/* Register Field Definitions */
+#define NPCM7XX_CLK_WDRCR_CA9C  BIT(0) /* Cortex A9 Cores */
+
+/* The number of watchdogs that can trigger a reset. */
+#define NPCM7XX_NR_WATCHDOGS    (3)
+
 static uint64_t npcm7xx_clk_read(void *opaque, hwaddr offset, unsigned size)
 {
     uint32_t reg = offset / sizeof(uint32_t);
@@ -187,6 +195,24 @@ static void npcm7xx_clk_write(void *opaque, hwaddr offset,
     s->regs[reg] = value;
 }
 
+/* Perform reset action triggered by a watchdog */
+static void npcm7xx_clk_perform_watchdog_reset(void *opaque, int n,
+        int level)
+{
+    NPCM7xxCLKState *clk = NPCM7XX_CLK(opaque);
+    uint32_t rcr;
+
+    g_assert(n >= 0 && n <= NPCM7XX_NR_WATCHDOGS);
+    rcr = clk->regs[NPCM7XX_CLK_WD0RCR + n];
+    if (rcr & NPCM7XX_CLK_WDRCR_CA9C) {
+        watchdog_perform_action();
+    } else {
+        qemu_log_mask(LOG_UNIMP,
+                "%s: only CPU reset is implemented. (requested 0x%" PRIx32")\n",
+                __func__, rcr);
+    }
+}
+
 static const struct MemoryRegionOps npcm7xx_clk_ops = {
     .read       = npcm7xx_clk_read,
     .write      = npcm7xx_clk_write,
@@ -226,6 +252,8 @@ static void npcm7xx_clk_init(Object *obj)
     memory_region_init_io(&s->iomem, obj, &npcm7xx_clk_ops, s,
                           TYPE_NPCM7XX_CLK, 4 * KiB);
     sysbus_init_mmio(&s->parent, &s->iomem);
+    qdev_init_gpio_in_named(DEVICE(s), npcm7xx_clk_perform_watchdog_reset,
+            NPCM7XX_WATCHDOG_RESET_GPIO_IN, NPCM7XX_NR_WATCHDOGS);
 }
 
 static const VMStateDescription vmstate_npcm7xx_clk = {
diff --git a/hw/timer/npcm7xx_timer.c b/hw/timer/npcm7xx_timer.c
index 2df9e3e496..d24445bd6e 100644
--- a/hw/timer/npcm7xx_timer.c
+++ b/hw/timer/npcm7xx_timer.c
@@ -17,6 +17,7 @@
 #include "qemu/osdep.h"
 
 #include "hw/irq.h"
+#include "hw/qdev-properties.h"
 #include "hw/misc/npcm7xx_clk.h"
 #include "hw/timer/npcm7xx_timer.h"
 #include "migration/vmstate.h"
@@ -60,6 +61,50 @@ enum NPCM7xxTimerRegisters {
 #define NPCM7XX_TCSR_PRESCALE_START     0
 #define NPCM7XX_TCSR_PRESCALE_LEN       8
 
+#define NPCM7XX_WTCR_WTCLK(rv)          extract32(rv, 10, 2)
+#define NPCM7XX_WTCR_FREEZE_EN          BIT(9)
+#define NPCM7XX_WTCR_WTE                BIT(7)
+#define NPCM7XX_WTCR_WTIE               BIT(6)
+#define NPCM7XX_WTCR_WTIS(rv)           extract32(rv, 4, 2)
+#define NPCM7XX_WTCR_WTIF               BIT(3)
+#define NPCM7XX_WTCR_WTRF               BIT(2)
+#define NPCM7XX_WTCR_WTRE               BIT(1)
+#define NPCM7XX_WTCR_WTR                BIT(0)
+
+/*
+ * The number of clock cycles between interrupt and reset in watchdog, used
+ * by the software to handle the interrupt before system is reset.
+ */
+#define NPCM7XX_WATCHDOG_INTERRUPT_TO_RESET_CYCLES 1024
+
+/* Start or resume the timer. */
+static void npcm7xx_timer_start(NPCM7xxBaseTimer *t)
+{
+    int64_t now;
+
+    now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
+    t->expires_ns = now + t->remaining_ns;
+    timer_mod(&t->qtimer, t->expires_ns);
+}
+
+/* Stop counting. Record the time remaining so we can continue later. */
+static void npcm7xx_timer_pause(NPCM7xxBaseTimer *t)
+{
+    int64_t now;
+
+    timer_del(&t->qtimer);
+    now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
+    t->remaining_ns = t->expires_ns - now;
+}
+
+/* Delete the timer and reset it to default state. */
+static void npcm7xx_timer_clear(NPCM7xxBaseTimer *t)
+{
+    timer_del(&t->qtimer);
+    t->expires_ns = 0;
+    t->remaining_ns = 0;
+}
+
 /*
  * Returns the index of timer in the tc->timer array. This can be used to
  * locate the registers that belong to this timer.
@@ -102,6 +147,52 @@ static uint32_t npcm7xx_timer_ns_to_count(NPCM7xxTimer *t, int64_t ns)
     return count;
 }
 
+static uint32_t npcm7xx_watchdog_timer_prescaler(const NPCM7xxWatchdogTimer *t)
+{
+    switch (NPCM7XX_WTCR_WTCLK(t->wtcr)) {
+    case 0:
+        return 1;
+    case 1:
+        return 256;
+    case 2:
+        return 2048;
+    case 3:
+        return 65536;
+    default:
+        g_assert_not_reached();
+    }
+}
+
+static void npcm7xx_watchdog_timer_reset_cycles(NPCM7xxWatchdogTimer *t,
+        int64_t cycles)
+{
+    uint32_t prescaler = npcm7xx_watchdog_timer_prescaler(t);
+    int64_t ns = (NANOSECONDS_PER_SECOND / NPCM7XX_TIMER_REF_HZ) * cycles;
+
+    /*
+     * The reset function always clears the current timer. The caller of the
+     * this needs to decide whether to start the watchdog timer based on
+     * specific flag in WTCR.
+     */
+    npcm7xx_timer_clear(&t->base_timer);
+
+    ns *= prescaler;
+    t->base_timer.remaining_ns = ns;
+}
+
+static void npcm7xx_watchdog_timer_reset(NPCM7xxWatchdogTimer *t)
+{
+    int64_t cycles = 1;
+    uint32_t s = NPCM7XX_WTCR_WTIS(t->wtcr);
+
+    g_assert(s <= 3);
+
+    cycles <<= NPCM7XX_WATCHDOG_BASETIME_SHIFT;
+    cycles <<= 2 * s;
+
+    npcm7xx_watchdog_timer_reset_cycles(t, cycles);
+}
+
 /*
  * Raise the interrupt line if there's a pending interrupt and interrupts are
  * enabled for this timer. If not, lower it.
@@ -116,16 +207,6 @@ static void npcm7xx_timer_check_interrupt(NPCM7xxTimer *t)
     trace_npcm7xx_timer_irq(DEVICE(tc)->canonical_path, index, pending);
 }
 
-/* Start or resume the timer. */
-static void npcm7xx_timer_start(NPCM7xxTimer *t)
-{
-    int64_t now;
-
-    now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
-    t->expires_ns = now + t->remaining_ns;
-    timer_mod(&t->qtimer, t->expires_ns);
-}
-
 /*
  * Called when the counter reaches zero. Sets the interrupt flag, and either
  * restarts or disables the timer.
@@ -138,9 +219,9 @@ static void npcm7xx_timer_reached_zero(NPCM7xxTimer *t)
     tc->tisr |= BIT(index);
 
     if (t->tcsr & NPCM7XX_TCSR_PERIODIC) {
-        t->remaining_ns = npcm7xx_timer_count_to_ns(t, t->ticr);
+        t->base_timer.remaining_ns = npcm7xx_timer_count_to_ns(t, t->ticr);
         if (t->tcsr & NPCM7XX_TCSR_CEN) {
-            npcm7xx_timer_start(t);
+            npcm7xx_timer_start(&t->base_timer);
         }
     } else {
         t->tcsr &= ~(NPCM7XX_TCSR_CEN | NPCM7XX_TCSR_CACT);
@@ -149,15 +230,6 @@ static void npcm7xx_timer_reached_zero(NPCM7xxTimer *t)
     npcm7xx_timer_check_interrupt(t);
 }
 
-/* Stop counting. Record the time remaining so we can continue later. */
-static void npcm7xx_timer_pause(NPCM7xxTimer *t)
-{
-    int64_t now;
-
-    timer_del(&t->qtimer);
-    now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
-    t->remaining_ns = t->expires_ns - now;
-}
 
 /*
  * Restart the timer from its initial value. If the timer was enabled and stays
@@ -167,10 +239,10 @@ static void npcm7xx_timer_pause(NPCM7xxTimer *t)
  */
 static void npcm7xx_timer_restart(NPCM7xxTimer *t, uint32_t old_tcsr)
 {
-    t->remaining_ns = npcm7xx_timer_count_to_ns(t, t->ticr);
+    t->base_timer.remaining_ns = npcm7xx_timer_count_to_ns(t, t->ticr);
 
     if (old_tcsr & t->tcsr & NPCM7XX_TCSR_CEN) {
-        npcm7xx_timer_start(t);
+        npcm7xx_timer_start(&t->base_timer);
     }
 }
 
@@ -181,10 +253,10 @@ static uint32_t npcm7xx_timer_read_tdr(NPCM7xxTimer *t)
     if (t->tcsr & NPCM7XX_TCSR_CEN) {
         int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
 
-        return npcm7xx_timer_ns_to_count(t, t->expires_ns - now);
+        return npcm7xx_timer_ns_to_count(t, t->base_timer.expires_ns - now);
     }
 
-    return npcm7xx_timer_ns_to_count(t, t->remaining_ns);
+    return npcm7xx_timer_ns_to_count(t, t->base_timer.remaining_ns);
 }
 
 static void npcm7xx_timer_write_tcsr(NPCM7xxTimer *t, uint32_t new_tcsr)
@@ -216,9 +288,9 @@ static void npcm7xx_timer_write_tcsr(NPCM7xxTimer *t, uint32_t new_tcsr)
 
     if (npcm7xx_tcsr_prescaler(old_tcsr) != npcm7xx_tcsr_prescaler(new_tcsr)) {
         /* Recalculate time remaining based on the current TDR value. */
-        t->remaining_ns = npcm7xx_timer_count_to_ns(t, tdr);
+        t->base_timer.remaining_ns = npcm7xx_timer_count_to_ns(t, tdr);
         if (old_tcsr & t->tcsr & NPCM7XX_TCSR_CEN) {
-            npcm7xx_timer_start(t);
+            npcm7xx_timer_start(&t->base_timer);
         }
     }
 
@@ -232,11 +304,11 @@ static void npcm7xx_timer_write_tcsr(NPCM7xxTimer *t, uint32_t new_tcsr)
     if ((old_tcsr ^ new_tcsr) & NPCM7XX_TCSR_CEN) {
         if (new_tcsr & NPCM7XX_TCSR_CEN) {
             t->tcsr |= NPCM7XX_TCSR_CACT;
-            npcm7xx_timer_start(t);
+            npcm7xx_timer_start(&t->base_timer);
         } else {
             t->tcsr &= ~NPCM7XX_TCSR_CACT;
-            npcm7xx_timer_pause(t);
-            if (t->remaining_ns <= 0) {
+            npcm7xx_timer_pause(&t->base_timer);
+            if (t->base_timer.remaining_ns <= 0) {
                 npcm7xx_timer_reached_zero(t);
             }
         }
@@ -259,9 +331,47 @@ static void npcm7xx_timer_write_tisr(NPCM7xxTimerCtrlState *s, uint32_t value)
         if (value & (1U << i)) {
             npcm7xx_timer_check_interrupt(&s->timer[i]);
         }
+
     }
 }
 
+static void npcm7xx_timer_write_wtcr(NPCM7xxWatchdogTimer *t, uint32_t new_wtcr)
+{
+    uint32_t old_wtcr = t->wtcr;
+
+    /*
+     * WTIF and WTRF are cleared by writing 1. Writing 0 makes these bits
+     * unchanged.
+     */
+    if (new_wtcr & NPCM7XX_WTCR_WTIF) {
+        new_wtcr &= ~NPCM7XX_WTCR_WTIF;
+    } else if (old_wtcr & NPCM7XX_WTCR_WTIF) {
+        new_wtcr |= NPCM7XX_WTCR_WTIF;
+    }
+    if (new_wtcr & NPCM7XX_WTCR_WTRF) {
+        new_wtcr &= ~NPCM7XX_WTCR_WTRF;
+    } else if (old_wtcr & NPCM7XX_WTCR_WTRF) {
+        new_wtcr |= NPCM7XX_WTCR_WTRF;
+    }
+
+    t->wtcr = new_wtcr;
+
+    if (new_wtcr & NPCM7XX_WTCR_WTR) {
+        t->wtcr &= ~NPCM7XX_WTCR_WTR;
+        npcm7xx_watchdog_timer_reset(t);
+        if (new_wtcr & NPCM7XX_WTCR_WTE) {
+            npcm7xx_timer_start(&t->base_timer);
+        }
+    } else if ((old_wtcr ^ new_wtcr) & NPCM7XX_WTCR_WTE) {
+        if (new_wtcr & NPCM7XX_WTCR_WTE) {
+            npcm7xx_timer_start(&t->base_timer);
+        } else {
+            npcm7xx_timer_pause(&t->base_timer);
+        }
+    }
+
+}
+
 static hwaddr npcm7xx_tcsr_index(hwaddr reg)
 {
     switch (reg) {
@@ -353,7 +463,7 @@ static uint64_t npcm7xx_timer_read(void *opaque, hwaddr offset, unsigned size)
         break;
 
     case NPCM7XX_TIMER_WTCR:
-        value = s->wtcr;
+        value = s->watchdog_timer.wtcr;
         break;
 
     default:
@@ -409,8 +519,7 @@ static void npcm7xx_timer_write(void *opaque, hwaddr offset,
         return;
 
     case NPCM7XX_TIMER_WTCR:
-        qemu_log_mask(LOG_UNIMP, "%s: WTCR write not implemented: 0x%08x\n",
-                      __func__, value);
+        npcm7xx_timer_write_wtcr(&s->watchdog_timer, value);
         return;
     }
 
@@ -448,15 +557,42 @@ static void npcm7xx_timer_enter_reset(Object *obj, ResetType type)
     for (i = 0; i < NPCM7XX_TIMERS_PER_CTRL; i++) {
         NPCM7xxTimer *t = &s->timer[i];
 
-        timer_del(&t->qtimer);
-        t->expires_ns = 0;
-        t->remaining_ns = 0;
+        npcm7xx_timer_clear(&t->base_timer);
         t->tcsr = 0x00000005;
         t->ticr = 0x00000000;
     }
 
     s->tisr = 0x00000000;
-    s->wtcr = 0x00000400;
+    /*
+     * Set WTCLK to 1(default) and reset all flags except WTRF.
+     * WTRF is not reset during a core domain reset.
+     */
+    s->watchdog_timer.wtcr = 0x00000400 | (s->watchdog_timer.wtcr &
+            NPCM7XX_WTCR_WTRF);
+}
+
+static void npcm7xx_watchdog_timer_expired(void *opaque)
+{
+    NPCM7xxWatchdogTimer *t = opaque;
+
+    if (t->wtcr & NPCM7XX_WTCR_WTE) {
+        if (t->wtcr & NPCM7XX_WTCR_WTIF) {
+            if (t->wtcr & NPCM7XX_WTCR_WTRE) {
+                t->wtcr |= NPCM7XX_WTCR_WTRF;
+                /* send reset signal to CLK module*/
+                qemu_irq_raise(t->reset_signal);
+            }
+        } else {
+            t->wtcr |= NPCM7XX_WTCR_WTIF;
+            if (t->wtcr & NPCM7XX_WTCR_WTIE) {
+                /* send interrupt */
+                qemu_irq_raise(t->irq);
+            }
+            npcm7xx_watchdog_timer_reset_cycles(t,
+                    NPCM7XX_WATCHDOG_INTERRUPT_TO_RESET_CYCLES);
+            npcm7xx_timer_start(&t->base_timer);
+        }
+    }
 }
 
 static void npcm7xx_timer_hold_reset(Object *obj)
@@ -467,6 +603,7 @@ static void npcm7xx_timer_hold_reset(Object *obj)
     for (i = 0; i < NPCM7XX_TIMERS_PER_CTRL; i++) {
         qemu_irq_lower(s->timer[i].irq);
     }
+    qemu_irq_lower(s->watchdog_timer.irq);
 }
 
 static void npcm7xx_timer_realize(DeviceState *dev, Error **errp)
@@ -474,43 +611,80 @@ static void npcm7xx_timer_realize(DeviceState *dev, Error **errp)
     NPCM7xxTimerCtrlState *s = NPCM7XX_TIMER(dev);
     SysBusDevice *sbd = &s->parent;
     int i;
+    NPCM7xxWatchdogTimer *w;
 
     for (i = 0; i < NPCM7XX_TIMERS_PER_CTRL; i++) {
         NPCM7xxTimer *t = &s->timer[i];
         t->ctrl = s;
-        timer_init_ns(&t->qtimer, QEMU_CLOCK_VIRTUAL, npcm7xx_timer_expired, t);
+        timer_init_ns(&t->base_timer.qtimer, QEMU_CLOCK_VIRTUAL,
+                npcm7xx_timer_expired, t);
         sysbus_init_irq(sbd, &t->irq);
     }
 
+    w = &s->watchdog_timer;
+    w->ctrl = s;
+    timer_init_ns(&w->base_timer.qtimer, QEMU_CLOCK_VIRTUAL,
+            npcm7xx_watchdog_timer_expired, w);
+    sysbus_init_irq(sbd, &w->irq);
+
     memory_region_init_io(&s->iomem, OBJECT(s), &npcm7xx_timer_ops, s,
                           TYPE_NPCM7XX_TIMER, 4 * KiB);
     sysbus_init_mmio(sbd, &s->iomem);
+    qdev_init_gpio_out_named(dev, &w->reset_signal,
+            NPCM7XX_WATCHDOG_RESET_GPIO_OUT, 1);
 }
 
-static const VMStateDescription vmstate_npcm7xx_timer = {
-    .name = "npcm7xx-timer",
+static const VMStateDescription vmstate_npcm7xx_base_timer = {
+    .name = "npcm7xx-base-timer",
     .version_id = 0,
     .minimum_version_id = 0,
     .fields = (VMStateField[]) {
-        VMSTATE_TIMER(qtimer, NPCM7xxTimer),
-        VMSTATE_INT64(expires_ns, NPCM7xxTimer),
-        VMSTATE_INT64(remaining_ns, NPCM7xxTimer),
+        VMSTATE_TIMER(qtimer, NPCM7xxBaseTimer),
+        VMSTATE_INT64(expires_ns, NPCM7xxBaseTimer),
+        VMSTATE_INT64(remaining_ns, NPCM7xxBaseTimer),
+        VMSTATE_END_OF_LIST(),
+    },
+};
+
+static const VMStateDescription vmstate_npcm7xx_timer = {
+    .name = "npcm7xx-timer",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField[]) {
+        VMSTATE_STRUCT(base_timer, NPCM7xxTimer,
+                             0, vmstate_npcm7xx_base_timer,
+                             NPCM7xxBaseTimer),
         VMSTATE_UINT32(tcsr, NPCM7xxTimer),
         VMSTATE_UINT32(ticr, NPCM7xxTimer),
         VMSTATE_END_OF_LIST(),
     },
 };
 
-static const VMStateDescription vmstate_npcm7xx_timer_ctrl = {
-    .name = "npcm7xx-timer-ctrl",
+static const VMStateDescription vmstate_npcm7xx_watchdog_timer = {
+    .name = "npcm7xx-watchdog-timer",
     .version_id = 0,
     .minimum_version_id = 0,
+    .fields = (VMStateField[]) {
+        VMSTATE_STRUCT(base_timer, NPCM7xxWatchdogTimer,
+                             0, vmstate_npcm7xx_base_timer,
+                             NPCM7xxBaseTimer),
+        VMSTATE_UINT32(wtcr, NPCM7xxWatchdogTimer),
+        VMSTATE_END_OF_LIST(),
+    },
+};
+
+static const VMStateDescription vmstate_npcm7xx_timer_ctrl = {
+    .name = "npcm7xx-timer-ctrl",
+    .version_id = 1,
+    .minimum_version_id = 1,
     .fields = (VMStateField[]) {
         VMSTATE_UINT32(tisr, NPCM7xxTimerCtrlState),
-        VMSTATE_UINT32(wtcr, NPCM7xxTimerCtrlState),
         VMSTATE_STRUCT_ARRAY(timer, NPCM7xxTimerCtrlState,
                              NPCM7XX_TIMERS_PER_CTRL, 0, vmstate_npcm7xx_timer,
                              NPCM7xxTimer),
+        VMSTATE_STRUCT(watchdog_timer, NPCM7xxTimerCtrlState,
+                             0, vmstate_npcm7xx_watchdog_timer,
+                             NPCM7xxWatchdogTimer),
         VMSTATE_END_OF_LIST(),
     },
 };
diff --git a/tests/qtest/npcm7xx_watchdog_timer-test.c b/tests/qtest/npcm7xx_watchdog_timer-test.c
new file mode 100644
index 0000000000..226a213527
--- /dev/null
+++ b/tests/qtest/npcm7xx_watchdog_timer-test.c
@@ -0,0 +1,320 @@
+/*
+ * QTests for Nuvoton NPCM7xx Timer Watchdog Modules.
+ *
+ * Copyright 2020 Google LLC
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
+ */
+
+#include "qemu/osdep.h"
+#include "qemu/timer.h"
+
+#include "libqos/libqtest.h"
+#include "qapi/qmp/qdict.h"
+
+#define WTCR_OFFSET     0x1c
+#define REF_HZ          (25000000)
+
+/* WTCR bit fields */
+#define WTCLK(rv)       ((rv) << 10)
+#define WTE             BIT(7)
+#define WTIE            BIT(6)
+#define WTIS(rv)        ((rv) << 4)
+#define WTIF            BIT(3)
+#define WTRF            BIT(2)
+#define WTRE            BIT(1)
+#define WTR             BIT(0)
+
+typedef struct Watchdog {
+    int irq;
+    uint64_t base_addr;
+} Watchdog;
+
+static const Watchdog watchdog_list[] = {
+    {
+        .irq        = 47,
+        .base_addr  = 0xf0008000
+    },
+    {
+        .irq        = 48,
+        .base_addr  = 0xf0009000
+    },
+    {
+        .irq        = 49,
+        .base_addr  = 0xf000a000
+    }
+};
+
+static int watchdog_index(const Watchdog *wd)
+{
+    ptrdiff_t diff = wd - watchdog_list;
+
+    g_assert(diff >= 0 && diff < ARRAY_SIZE(watchdog_list));
+
+    return diff;
+}
+
+static uint32_t watchdog_read_wtcr(QTestState *qts, const Watchdog *wd)
+{
+    return qtest_readl(qts, wd->base_addr + WTCR_OFFSET);
+}
+
+static void watchdog_write_wtcr(QTestState *qts, const Watchdog *wd,
+        uint32_t value)
+{
+    qtest_writel(qts, wd->base_addr + WTCR_OFFSET, value);
+}
+
+static uint32_t watchdog_prescaler(QTestState *qts, const Watchdog *wd)
+{
+    switch (extract32(watchdog_read_wtcr(qts, wd), 10, 2)) {
+    case 0:
+        return 1;
+    case 1:
+        return 256;
+    case 2:
+        return 2048;
+    case 3:
+        return 65536;
+    default:
+        g_assert_not_reached();
+    }
+}
+
+static QDict *get_watchdog_action(QTestState *qts)
+{
+    QDict *ev = qtest_qmp_eventwait_ref(qts, "WATCHDOG");
+    QDict *data;
+
+    data = qdict_get_qdict(ev, "data");
+    qobject_ref(data);
+    qobject_unref(ev);
+    return data;
+}
+
+#define RESET_CYCLES 1024
+static uint32_t watchdog_interrupt_cycles(QTestState *qts, const Watchdog *wd)
+{
+    uint32_t wtis = extract32(watchdog_read_wtcr(qts, wd), 4, 2);
+    return 1 << (14 + 2 * wtis);
+}
+
+static int64_t watchdog_calculate_steps(uint32_t count, uint32_t prescale)
+{
+    return (NANOSECONDS_PER_SECOND / REF_HZ) * count * prescale;
+}
+
+static int64_t watchdog_interrupt_steps(QTestState *qts, const Watchdog *wd)
+{
+    return watchdog_calculate_steps(watchdog_interrupt_cycles(qts, wd),
+            watchdog_prescaler(qts, wd));
+}
+
+/* Check wtcr can be reset to default value */
+static void test_init(gconstpointer watchdog)
+{
+    const Watchdog *wd = watchdog;
+    QTestState *qts = qtest_init("-machine quanta-gsj");
+
+    qtest_irq_intercept_in(qts, "/machine/soc/a9mpcore/gic");
+
+    watchdog_write_wtcr(qts, wd, WTCLK(1) | WTRF | WTIF | WTR);
+    g_assert_cmphex(watchdog_read_wtcr(qts, wd), ==, WTCLK(1));
+
+    qtest_quit(qts);
+}
+
+/* Check a watchdog can generate interrupt and reset actions */
+static void test_reset_action(gconstpointer watchdog)
+{
+    const Watchdog *wd = watchdog;
+    QTestState *qts = qtest_init("-machine quanta-gsj");
+    QDict *ad;
+
+    qtest_irq_intercept_in(qts, "/machine/soc/a9mpcore/gic");
+
+    watchdog_write_wtcr(qts, wd,
+            WTCLK(0) | WTE | WTRF | WTRE | WTIF | WTIE | WTR);
+    g_assert_cmphex(watchdog_read_wtcr(qts, wd), ==,
+            WTCLK(0) | WTE | WTRE | WTIE);
+
+    /* Check a watchdog can generate an interrupt */
+    qtest_clock_step(qts, watchdog_interrupt_steps(qts, wd));
+    g_assert_cmphex(watchdog_read_wtcr(qts, wd), ==,
+            WTCLK(0) | WTE | WTIF | WTIE | WTRE);
+    g_assert_true(qtest_get_irq(qts, wd->irq));
+
+    /* Check a watchdog can generate a reset signal */
+    qtest_clock_step(qts, watchdog_calculate_steps(RESET_CYCLES,
+                watchdog_prescaler(qts, wd)));
+    ad = get_watchdog_action(qts);
+    /* The signal is a reset signal */
+    g_assert_false(strcmp(qdict_get_str(ad, "action"), "reset"));
+    qobject_unref(ad);
+    qtest_qmp_eventwait(qts, "RESET");
+    /*
+     * Make sure WTCR is reset to default except for WTRF bit which shouldn't
+     * be reset.
+     */
+    g_assert_cmphex(watchdog_read_wtcr(qts, wd), ==, WTCLK(1) | WTRF);
+    qtest_quit(qts);
+}
+
+/* Check a watchdog works with all possible WTCLK prescalers and WTIS cycles */
+static void test_prescaler(gconstpointer watchdog)
+{
+    const Watchdog *wd = watchdog;
+
+    for (int wtclk = 0; wtclk < 4; ++wtclk) {
+        for (int wtis = 0; wtis < 4; ++wtis) {
+            QTestState *qts = qtest_init("-machine quanta-gsj");
+
+            qtest_irq_intercept_in(qts, "/machine/soc/a9mpcore/gic");
+            watchdog_write_wtcr(qts, wd,
+                    WTCLK(wtclk) | WTE | WTIF | WTIS(wtis) | WTIE | WTR);
+            /*
+             * The interrupt doesn't fire until watchdog_interrupt_steps()
+             * cycles passed
+             */
+            qtest_clock_step(qts, watchdog_interrupt_steps(qts, wd) - 1);
+            g_assert_false(watchdog_read_wtcr(qts, wd) & WTIF);
+            g_assert_false(qtest_get_irq(qts, wd->irq));
+            qtest_clock_step(qts, 1);
+            g_assert_true(watchdog_read_wtcr(qts, wd) & WTIF);
+            g_assert_true(qtest_get_irq(qts, wd->irq));
+
+            qtest_quit(qts);
+        }
+    }
+}
+
+/*
+ * Check a watchdog doesn't fire if corresponding flags (WTIE and WTRE) are not
+ * set.
+ */
+static void test_enabling_flags(gconstpointer watchdog)
+{
+    const Watchdog *wd = watchdog;
+    QTestState *qts;
+
+    /* Neither WTIE or WTRE is set, no interrupt or reset should happen */
+    qts = qtest_init("-machine quanta-gsj");
+    qtest_irq_intercept_in(qts, "/machine/soc/a9mpcore/gic");
+    watchdog_write_wtcr(qts, wd, WTCLK(0) | WTE | WTIF | WTRF | WTR);
+    qtest_clock_step(qts, watchdog_interrupt_steps(qts, wd));
+    g_assert_true(watchdog_read_wtcr(qts, wd) & WTIF);
+    g_assert_false(qtest_get_irq(qts, wd->irq));
+    qtest_clock_step(qts, watchdog_calculate_steps(RESET_CYCLES,
+                watchdog_prescaler(qts, wd)));
+    g_assert_true(watchdog_read_wtcr(qts, wd) & WTIF);
+    g_assert_false(watchdog_read_wtcr(qts, wd) & WTRF);
+    qtest_quit(qts);
+
+    /* Only WTIE is set, interrupt is triggered but reset should not happen */
+    qts = qtest_init("-machine quanta-gsj");
+    qtest_irq_intercept_in(qts, "/machine/soc/a9mpcore/gic");
+    watchdog_write_wtcr(qts, wd, WTCLK(0) | WTE | WTIF | WTIE | WTRF | WTR);
+    qtest_clock_step(qts, watchdog_interrupt_steps(qts, wd));
+    g_assert_true(watchdog_read_wtcr(qts, wd) & WTIF);
+    g_assert_true(qtest_get_irq(qts, wd->irq));
+    qtest_clock_step(qts, watchdog_calculate_steps(RESET_CYCLES,
+                watchdog_prescaler(qts, wd)));
+    g_assert_true(watchdog_read_wtcr(qts, wd) & WTIF);
+    g_assert_false(watchdog_read_wtcr(qts, wd) & WTRF);
+    qtest_quit(qts);
+
+    /* Only WTRE is set, interrupt is triggered but reset should not happen */
+    qts = qtest_init("-machine quanta-gsj");
+    qtest_irq_intercept_in(qts, "/machine/soc/a9mpcore/gic");
+    watchdog_write_wtcr(qts, wd, WTCLK(0) | WTE | WTIF | WTRE | WTRF | WTR);
+    qtest_clock_step(qts, watchdog_interrupt_steps(qts, wd));
+    g_assert_true(watchdog_read_wtcr(qts, wd) & WTIF);
+    g_assert_false(qtest_get_irq(qts, wd->irq));
+    qtest_clock_step(qts, watchdog_calculate_steps(RESET_CYCLES,
+                watchdog_prescaler(qts, wd)));
+    g_assert_false(strcmp(qdict_get_str(get_watchdog_action(qts), "action"),
+                "reset"));
+    qtest_qmp_eventwait(qts, "RESET");
+    qtest_quit(qts);
+
+    /*
+     * The case when both flags are set is already tested in
+     * test_reset_action().
+     */
+}
+
+/* Check a watchdog can pause and resume by setting WTE bits */
+static void test_pause(gconstpointer watchdog)
+{
+    const Watchdog *wd = watchdog;
+    QTestState *qts;
+    int64_t remaining_steps, steps;
+
+    qts = qtest_init("-machine quanta-gsj");
+    qtest_irq_intercept_in(qts, "/machine/soc/a9mpcore/gic");
+    watchdog_write_wtcr(qts, wd, WTCLK(0) | WTE | WTIF | WTIE | WTRF | WTR);
+    remaining_steps = watchdog_interrupt_steps(qts, wd);
+    g_assert_cmphex(watchdog_read_wtcr(qts, wd), ==, WTCLK(0) | WTE | WTIE);
+
+    /* Run for half of the execution period. */
+    steps = remaining_steps / 2;
+    remaining_steps -= steps;
+    qtest_clock_step(qts, steps);
+
+    /* Pause the watchdog */
+    watchdog_write_wtcr(qts, wd, WTCLK(0) | WTIE);
+    g_assert_cmphex(watchdog_read_wtcr(qts, wd), ==, WTCLK(0) | WTIE);
+
+    /* Run for a long period of time, the watchdog shouldn't fire */
+    qtest_clock_step(qts, steps << 4);
+    g_assert_cmphex(watchdog_read_wtcr(qts, wd), ==, WTCLK(0) | WTIE);
+    g_assert_false(qtest_get_irq(qts, wd->irq));
+
+    /* Resume the watchdog */
+    watchdog_write_wtcr(qts, wd, WTCLK(0) | WTE | WTIE);
+    g_assert_cmphex(watchdog_read_wtcr(qts, wd), ==, WTCLK(0) | WTE | WTIE);
+
+    /* Run for the reset of the execution period, the watchdog should fire */
+    qtest_clock_step(qts, remaining_steps);
+    g_assert_cmphex(watchdog_read_wtcr(qts, wd), ==,
+            WTCLK(0) | WTE | WTIF | WTIE);
+    g_assert_true(qtest_get_irq(qts, wd->irq));
+
+    qtest_quit(qts);
+}
+
+static void watchdog_add_test(const char *name, const Watchdog* wd,
+        GTestDataFunc fn)
+{
+    g_autofree char *full_name = g_strdup_printf(
+            "npcm7xx_watchdog_timer[%d]/%s", watchdog_index(wd), name);
+    qtest_add_data_func(full_name, wd, fn);
+}
+#define add_test(name, td) watchdog_add_test(#name, td, test_##name)
+
+int main(int argc, char **argv)
+{
+    g_test_init(&argc, &argv, NULL);
+    g_test_set_nonfatal_assertions();
+
+    for (int i = 0; i < ARRAY_SIZE(watchdog_list); ++i) {
+        const Watchdog *wd = &watchdog_list[i];
+
+        add_test(init, wd);
+        add_test(reset_action, wd);
+        add_test(prescaler, wd);
+        add_test(enabling_flags, wd);
+        add_test(pause, wd);
+    }
+
+    return g_test_run();
+}
+
diff --git a/MAINTAINERS b/MAINTAINERS
index 6a197bd358..0fa74b9bf3 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -755,6 +755,7 @@ L: qemu-arm@nongnu.org
 S: Supported
 F: hw/*/npcm7xx*
 F: include/hw/*/npcm7xx*
+F: tests/qtest/npcm7xx*
 F: pc-bios/npcm7xx_bootrom.bin
 F: roms/vbootrom
 
diff --git a/tests/qtest/meson.build b/tests/qtest/meson.build
index 7e0ecaa2c5..b160c6f787 100644
--- a/tests/qtest/meson.build
+++ b/tests/qtest/meson.build
@@ -133,7 +133,7 @@ qtests_sparc64 = \
   (config_all_devices.has_key('CONFIG_ISA_TESTDEV') ? ['endianness-test'] : []) +            \
   ['prom-env-test', 'boot-serial-test']
 
-qtests_npcm7xx = ['npcm7xx_timer-test']
+qtests_npcm7xx = ['npcm7xx_timer-test', 'npcm7xx_watchdog_timer-test']
 qtests_arm = \
   (config_all_devices.has_key('CONFIG_PFLASH_CFI02') ? ['pflash-cfi02-test'] : []) +         \
   (config_all_devices.has_key('CONFIG_NPCM7XX') ? qtests_npcm7xx : []) + \
-- 
2.29.0.rc1.297.gfa9743e501-goog



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v3 4/6] hw/misc: Add npcm7xx random number generator
  2020-10-23 21:06 [PATCH v3 0/6] Additional NPCM7xx features, devices and tests Havard Skinnemoen via
                   ` (2 preceding siblings ...)
  2020-10-23 21:06 ` [PATCH v3 3/6] hw/timer: Adding watchdog for NPCM7XX Timer Havard Skinnemoen via
@ 2020-10-23 21:06 ` Havard Skinnemoen via
  2020-10-30 13:34   ` Peter Maydell
  2020-11-02 11:36   ` Peter Maydell
  2020-10-23 21:06 ` [PATCH v3 5/6] hw/arm/npcm7xx: Add EHCI and OHCI controllers Havard Skinnemoen via
                   ` (2 subsequent siblings)
  6 siblings, 2 replies; 15+ messages in thread
From: Havard Skinnemoen via @ 2020-10-23 21:06 UTC (permalink / raw)
  To: peter.maydell
  Cc: qemu-arm, qemu-devel, Avi.Fishman, kfting, venture, wuhaotsh,
	thuth, Havard Skinnemoen

The RNG module returns a byte of randomness when the Data Valid bit is
set.

This implementation ignores the prescaler setting, and loads a new value
into RNGD every time RNGCS is read while the RNG is enabled and random
data is available.

A qtest featuring some simple randomness tests is included.

Reviewed-by: Tyrone Ting <kfting@nuvoton.com>
Reviewed-by: Peter Maydell <peter.maydell@linaro.org>
Signed-off-by: Havard Skinnemoen <hskinnemoen@google.com>
---
 docs/system/arm/nuvoton.rst    |   2 +-
 include/hw/arm/npcm7xx.h       |   2 +
 include/hw/misc/npcm7xx_rng.h  |  34 ++++
 hw/arm/npcm7xx.c               |   7 +-
 hw/misc/npcm7xx_rng.c          | 180 +++++++++++++++++++++
 tests/qtest/npcm7xx_rng-test.c | 278 +++++++++++++++++++++++++++++++++
 hw/misc/meson.build            |   1 +
 hw/misc/trace-events           |   4 +
 tests/qtest/meson.build        |   5 +-
 9 files changed, 510 insertions(+), 3 deletions(-)
 create mode 100644 include/hw/misc/npcm7xx_rng.h
 create mode 100644 hw/misc/npcm7xx_rng.c
 create mode 100644 tests/qtest/npcm7xx_rng-test.c

diff --git a/docs/system/arm/nuvoton.rst b/docs/system/arm/nuvoton.rst
index e3e1a3a3a7..4342434df4 100644
--- a/docs/system/arm/nuvoton.rst
+++ b/docs/system/arm/nuvoton.rst
@@ -38,6 +38,7 @@ Supported devices
  * DDR4 memory controller (dummy interface indicating memory training is done)
  * OTP controllers (no protection features)
  * Flash Interface Unit (FIU; no protection features)
+ * Random Number Generator (RNG)
 
 Missing devices
 ---------------
@@ -59,7 +60,6 @@ Missing devices
  * Peripheral SPI controller (PSPI)
  * Analog to Digital Converter (ADC)
  * SD/MMC host
- * Random Number Generator (RNG)
  * PECI interface
  * Pulse Width Modulation (PWM)
  * Tachometer
diff --git a/include/hw/arm/npcm7xx.h b/include/hw/arm/npcm7xx.h
index 13106af215..761f9b987e 100644
--- a/include/hw/arm/npcm7xx.h
+++ b/include/hw/arm/npcm7xx.h
@@ -21,6 +21,7 @@
 #include "hw/mem/npcm7xx_mc.h"
 #include "hw/misc/npcm7xx_clk.h"
 #include "hw/misc/npcm7xx_gcr.h"
+#include "hw/misc/npcm7xx_rng.h"
 #include "hw/nvram/npcm7xx_otp.h"
 #include "hw/timer/npcm7xx_timer.h"
 #include "hw/ssi/npcm7xx_fiu.h"
@@ -75,6 +76,7 @@ typedef struct NPCM7xxState {
     NPCM7xxOTPState     key_storage;
     NPCM7xxOTPState     fuse_array;
     NPCM7xxMCState      mc;
+    NPCM7xxRNGState     rng;
     NPCM7xxFIUState     fiu[2];
 } NPCM7xxState;
 
diff --git a/include/hw/misc/npcm7xx_rng.h b/include/hw/misc/npcm7xx_rng.h
new file mode 100644
index 0000000000..5e85fd439d
--- /dev/null
+++ b/include/hw/misc/npcm7xx_rng.h
@@ -0,0 +1,34 @@
+/*
+ * Nuvoton NPCM7xx Random Number Generator.
+ *
+ * Copyright 2020 Google LLC
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
+ */
+#ifndef NPCM7XX_RNG_H
+#define NPCM7XX_RNG_H
+
+#include "hw/sysbus.h"
+
+typedef struct NPCM7xxRNGState {
+    SysBusDevice parent;
+
+    MemoryRegion iomem;
+
+    uint8_t rngcs;
+    uint8_t rngd;
+    uint8_t rngmode;
+} NPCM7xxRNGState;
+
+#define TYPE_NPCM7XX_RNG "npcm7xx-rng"
+#define NPCM7XX_RNG(obj) OBJECT_CHECK(NPCM7xxRNGState, (obj), TYPE_NPCM7XX_RNG)
+
+#endif /* NPCM7XX_RNG_H */
diff --git a/hw/arm/npcm7xx.c b/hw/arm/npcm7xx.c
index c341dcab8b..cb4db41c54 100644
--- a/hw/arm/npcm7xx.c
+++ b/hw/arm/npcm7xx.c
@@ -44,6 +44,7 @@
 #define NPCM7XX_GCR_BA          (0xf0800000)
 #define NPCM7XX_CLK_BA          (0xf0801000)
 #define NPCM7XX_MC_BA           (0xf0824000)
+#define NPCM7XX_RNG_BA          (0xf000b000)
 
 /* Internal AHB SRAM */
 #define NPCM7XX_RAM3_BA         (0xc0008000)
@@ -256,6 +257,7 @@ static void npcm7xx_init(Object *obj)
     object_initialize_child(obj, "otp2", &s->fuse_array,
                             TYPE_NPCM7XX_FUSE_ARRAY);
     object_initialize_child(obj, "mc", &s->mc, TYPE_NPCM7XX_MC);
+    object_initialize_child(obj, "rng", &s->rng, TYPE_NPCM7XX_RNG);
 
     for (i = 0; i < ARRAY_SIZE(s->tim); i++) {
         object_initialize_child(obj, "tim[*]", &s->tim[i], TYPE_NPCM7XX_TIMER);
@@ -374,6 +376,10 @@ static void npcm7xx_realize(DeviceState *dev, Error **errp)
                        serial_hd(i), DEVICE_LITTLE_ENDIAN);
     }
 
+    /* Random Number Generator. Cannot fail. */
+    sysbus_realize(SYS_BUS_DEVICE(&s->rng), &error_abort);
+    sysbus_mmio_map(SYS_BUS_DEVICE(&s->rng), 0, NPCM7XX_RNG_BA);
+
     /*
      * Flash Interface Unit (FIU). Can fail if incorrect number of chip selects
      * specified, but this is a programming error.
@@ -412,7 +418,6 @@ static void npcm7xx_realize(DeviceState *dev, Error **errp)
     create_unimplemented_device("npcm7xx.vdmx",         0xe0800000,   4 * KiB);
     create_unimplemented_device("npcm7xx.pcierc",       0xe1000000,  64 * KiB);
     create_unimplemented_device("npcm7xx.kcs",          0xf0007000,   4 * KiB);
-    create_unimplemented_device("npcm7xx.rng",          0xf000b000,   4 * KiB);
     create_unimplemented_device("npcm7xx.adc",          0xf000c000,   4 * KiB);
     create_unimplemented_device("npcm7xx.gfxi",         0xf000e000,   4 * KiB);
     create_unimplemented_device("npcm7xx.gpio[0]",      0xf0010000,   4 * KiB);
diff --git a/hw/misc/npcm7xx_rng.c b/hw/misc/npcm7xx_rng.c
new file mode 100644
index 0000000000..f650f3401f
--- /dev/null
+++ b/hw/misc/npcm7xx_rng.c
@@ -0,0 +1,180 @@
+/*
+ * Nuvoton NPCM7xx Random Number Generator.
+ *
+ * Copyright 2020 Google LLC
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
+ */
+
+#include "qemu/osdep.h"
+
+#include "hw/misc/npcm7xx_rng.h"
+#include "migration/vmstate.h"
+#include "qemu/bitops.h"
+#include "qemu/guest-random.h"
+#include "qemu/log.h"
+#include "qemu/module.h"
+#include "qemu/units.h"
+
+#include "trace.h"
+
+#define NPCM7XX_RNG_REGS_SIZE   (4 * KiB)
+
+#define NPCM7XX_RNGCS           (0x00)
+#define NPCM7XX_RNGCS_CLKP(rv)      extract32(rv, 2, 4)
+#define NPCM7XX_RNGCS_DVALID        BIT(1)
+#define NPCM7XX_RNGCS_RNGE          BIT(0)
+
+#define NPCM7XX_RNGD            (0x04)
+#define NPCM7XX_RNGMODE         (0x08)
+#define NPCM7XX_RNGMODE_NORMAL      (0x02)
+
+static bool npcm7xx_rng_is_enabled(NPCM7xxRNGState *s)
+{
+    return (s->rngcs & NPCM7XX_RNGCS_RNGE) &&
+        (s->rngmode == NPCM7XX_RNGMODE_NORMAL);
+}
+
+static uint64_t npcm7xx_rng_read(void *opaque, hwaddr offset, unsigned size)
+{
+    NPCM7xxRNGState *s = opaque;
+    uint64_t value = 0;
+
+    switch (offset) {
+    case NPCM7XX_RNGCS:
+        /*
+         * If the RNG is enabled, but we don't have any valid random data, try
+         * obtaining some and update the DVALID bit accordingly.
+         */
+        if (!npcm7xx_rng_is_enabled(s)) {
+            s->rngcs &= ~NPCM7XX_RNGCS_DVALID;
+        } else if (!(s->rngcs & NPCM7XX_RNGCS_DVALID)) {
+            uint8_t byte = 0;
+
+            if (qemu_guest_getrandom(&byte, sizeof(byte), NULL) == 0) {
+                s->rngd = byte;
+                s->rngcs |= NPCM7XX_RNGCS_DVALID;
+            }
+        }
+        value = s->rngcs;
+        break;
+    case NPCM7XX_RNGD:
+        if (npcm7xx_rng_is_enabled(s) && s->rngcs & NPCM7XX_RNGCS_DVALID) {
+            s->rngcs &= ~NPCM7XX_RNGCS_DVALID;
+            value = s->rngd;
+            s->rngd = 0;
+        }
+        break;
+    case NPCM7XX_RNGMODE:
+        value = s->rngmode;
+        break;
+
+    default:
+        qemu_log_mask(LOG_GUEST_ERROR,
+                      "%s: read from invalid offset 0x%" HWADDR_PRIx "\n",
+                      DEVICE(s)->canonical_path, offset);
+        break;
+    }
+
+    trace_npcm7xx_rng_read(offset, value, size);
+
+    return value;
+}
+
+static void npcm7xx_rng_write(void *opaque, hwaddr offset, uint64_t value,
+                              unsigned size)
+{
+    NPCM7xxRNGState *s = opaque;
+
+    trace_npcm7xx_rng_write(offset, value, size);
+
+    switch (offset) {
+    case NPCM7XX_RNGCS:
+        s->rngcs &= NPCM7XX_RNGCS_DVALID;
+        s->rngcs |= value & ~NPCM7XX_RNGCS_DVALID;
+        break;
+    case NPCM7XX_RNGD:
+        qemu_log_mask(LOG_GUEST_ERROR,
+                      "%s: write to read-only register @ 0x%" HWADDR_PRIx "\n",
+                      DEVICE(s)->canonical_path, offset);
+        break;
+    case NPCM7XX_RNGMODE:
+        s->rngmode = value;
+        break;
+    default:
+        qemu_log_mask(LOG_GUEST_ERROR,
+                      "%s: write to invalid offset 0x%" HWADDR_PRIx "\n",
+                      DEVICE(s)->canonical_path, offset);
+        break;
+    }
+}
+
+static const MemoryRegionOps npcm7xx_rng_ops = {
+    .read = npcm7xx_rng_read,
+    .write = npcm7xx_rng_write,
+    .endianness = DEVICE_LITTLE_ENDIAN,
+    .valid = {
+        .min_access_size = 1,
+        .max_access_size = 4,
+        .unaligned = false,
+    },
+};
+
+static void npcm7xx_rng_enter_reset(Object *obj, ResetType type)
+{
+    NPCM7xxRNGState *s = NPCM7XX_RNG(obj);
+
+    s->rngcs = 0;
+    s->rngd = 0;
+    s->rngmode = 0;
+}
+
+static void npcm7xx_rng_init(Object *obj)
+{
+    NPCM7xxRNGState *s = NPCM7XX_RNG(obj);
+
+    memory_region_init_io(&s->iomem, obj, &npcm7xx_rng_ops, s, "regs",
+                          NPCM7XX_RNG_REGS_SIZE);
+    sysbus_init_mmio(&s->parent, &s->iomem);
+}
+
+static const VMStateDescription vmstate_npcm7xx_rng = {
+    .name = "npcm7xx-rng",
+    .version_id = 0,
+    .minimum_version_id = 0,
+    .fields = (VMStateField[]) {
+        VMSTATE_UINT8(rngcs, NPCM7xxRNGState),
+        VMSTATE_UINT8(rngd, NPCM7xxRNGState),
+        VMSTATE_UINT8(rngmode, NPCM7xxRNGState),
+        VMSTATE_END_OF_LIST(),
+    },
+};
+
+static void npcm7xx_rng_class_init(ObjectClass *klass, void *data)
+{
+    ResettableClass *rc = RESETTABLE_CLASS(klass);
+    DeviceClass *dc = DEVICE_CLASS(klass);
+
+    dc->desc = "NPCM7xx Random Number Generator";
+    dc->vmsd = &vmstate_npcm7xx_rng;
+    rc->phases.enter = npcm7xx_rng_enter_reset;
+}
+
+static const TypeInfo npcm7xx_rng_types[] = {
+    {
+        .name = TYPE_NPCM7XX_RNG,
+        .parent = TYPE_SYS_BUS_DEVICE,
+        .instance_size = sizeof(NPCM7xxRNGState),
+        .class_init = npcm7xx_rng_class_init,
+        .instance_init = npcm7xx_rng_init,
+    },
+};
+DEFINE_TYPES(npcm7xx_rng_types);
diff --git a/tests/qtest/npcm7xx_rng-test.c b/tests/qtest/npcm7xx_rng-test.c
new file mode 100644
index 0000000000..da6e639bf6
--- /dev/null
+++ b/tests/qtest/npcm7xx_rng-test.c
@@ -0,0 +1,278 @@
+/*
+ * QTest testcase for the Nuvoton NPCM7xx Random Number Generator
+ *
+ * Copyright 2020 Google LLC
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
+ */
+
+#include "qemu/osdep.h"
+
+#include <math.h>
+
+#include "libqtest-single.h"
+#include "qemu/bitops.h"
+
+#define RNG_BASE_ADDR   0xf000b000
+
+/* Control and Status Register */
+#define RNGCS   0x00
+# define DVALID     BIT(1)  /* Data Valid */
+# define RNGE       BIT(0)  /* RNG Enable */
+/* Data Register */
+#define RNGD    0x04
+/* Mode Register */
+#define RNGMODE 0x08
+# define ROSEL_NORMAL   (2) /* RNG only works in this mode */
+
+/* Number of bits to collect for randomness tests. */
+#define TEST_INPUT_BITS  (128)
+
+static void rng_writeb(unsigned int offset, uint8_t value)
+{
+    writeb(RNG_BASE_ADDR + offset, value);
+}
+
+static uint8_t rng_readb(unsigned int offset)
+{
+    return readb(RNG_BASE_ADDR + offset);
+}
+
+/* Disable RNG and set normal ring oscillator mode. */
+static void rng_reset(void)
+{
+    rng_writeb(RNGCS, 0);
+    rng_writeb(RNGMODE, ROSEL_NORMAL);
+}
+
+/* Reset RNG and then enable it. */
+static void rng_reset_enable(void)
+{
+    rng_reset();
+    rng_writeb(RNGCS, RNGE);
+}
+
+/* Wait until Data Valid bit is set. */
+static bool rng_wait_ready(void)
+{
+    /* qemu_guest_getrandom may fail. Assume it won't fail 10 times in a row. */
+    int retries = 10;
+
+    while (retries-- > 0) {
+        if (rng_readb(RNGCS) & DVALID) {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+/*
+ * Perform a frequency (monobit) test, as defined by NIST SP 800-22, on the
+ * sequence in buf and return the P-value. This represents the probability of a
+ * truly random sequence having the same proportion of zeros and ones as the
+ * sequence in buf.
+ *
+ * An RNG which always returns 0x00 or 0xff, or has some bits stuck at 0 or 1,
+ * will fail this test. However, an RNG which always returns 0x55, 0xf0 or some
+ * other value with an equal number of zeroes and ones will pass.
+ */
+static double calc_monobit_p(const uint8_t *buf, unsigned int len)
+{
+    unsigned int i;
+    double s_obs;
+    int sn = 0;
+
+    for (i = 0; i < len; i++) {
+        /*
+         * Each 1 counts as 1, each 0 counts as -1.
+         * s = cp - (8 - cp) = 2 * cp - 8
+         */
+        sn += 2 * ctpop8(buf[i]) - 8;
+    }
+
+    s_obs = abs(sn) / sqrt(len * BITS_PER_BYTE);
+
+    return erfc(s_obs / sqrt(2));
+}
+
+/*
+ * Perform a runs test, as defined by NIST SP 800-22, and return the P-value.
+ * This represents the probability of a truly random sequence having the same
+ * number of runs (i.e. uninterrupted sequences of identical bits) as the
+ * sequence in buf.
+ */
+static double calc_runs_p(const unsigned long *buf, unsigned int nr_bits)
+{
+    unsigned int j;
+    unsigned int k;
+    int nr_ones = 0;
+    int vn_obs = 0;
+    double pi;
+
+    g_assert(nr_bits % BITS_PER_LONG == 0);
+
+    for (j = 0; j < nr_bits / BITS_PER_LONG; j++) {
+        nr_ones += __builtin_popcountl(buf[j]);
+    }
+    pi = (double)nr_ones / nr_bits;
+
+    for (k = 0; k < nr_bits - 1; k++) {
+        vn_obs += !(test_bit(k, buf) ^ test_bit(k + 1, buf));
+    }
+    vn_obs += 1;
+
+    return erfc(fabs(vn_obs - 2 * nr_bits * pi * (1.0 - pi))
+                / (2 * sqrt(2 * nr_bits) * pi * (1.0 - pi)));
+}
+
+/*
+ * Verifies that DVALID is clear, and RNGD reads zero, when RNGE is cleared,
+ * and DVALID eventually becomes set when RNGE is set.
+ */
+static void test_enable_disable(void)
+{
+    /* Disable: DVALID should not be set, and RNGD should read zero */
+    rng_reset();
+    g_assert_cmphex(rng_readb(RNGCS), ==, 0);
+    g_assert_cmphex(rng_readb(RNGD), ==, 0);
+
+    /* Enable: DVALID should be set, but we can't make assumptions about RNGD */
+    rng_writeb(RNGCS, RNGE);
+    g_assert_true(rng_wait_ready());
+    g_assert_cmphex(rng_readb(RNGCS), ==, DVALID | RNGE);
+
+    /* Disable: DVALID should not be set, and RNGD should read zero */
+    rng_writeb(RNGCS, 0);
+    g_assert_cmphex(rng_readb(RNGCS), ==, 0);
+    g_assert_cmphex(rng_readb(RNGD), ==, 0);
+}
+
+/*
+ * Verifies that the RNG only produces data when RNGMODE is set to 'normal'
+ * ring oscillator mode.
+ */
+static void test_rosel(void)
+{
+    rng_reset_enable();
+    g_assert_true(rng_wait_ready());
+    rng_writeb(RNGMODE, 0);
+    g_assert_false(rng_wait_ready());
+    rng_writeb(RNGMODE, ROSEL_NORMAL);
+    g_assert_true(rng_wait_ready());
+    rng_writeb(RNGMODE, 0);
+    g_assert_false(rng_wait_ready());
+}
+
+/*
+ * Verifies that a continuous sequence of bits collected after enabling the RNG
+ * satisfies a monobit test.
+ */
+static void test_continuous_monobit(void)
+{
+    uint8_t buf[TEST_INPUT_BITS / BITS_PER_BYTE];
+    unsigned int i;
+
+    rng_reset_enable();
+    for (i = 0; i < sizeof(buf); i++) {
+        g_assert_true(rng_wait_ready());
+        buf[i] = rng_readb(RNGD);
+    }
+
+    g_assert_cmpfloat(calc_monobit_p(buf, sizeof(buf)), >, 0.01);
+}
+
+/*
+ * Verifies that a continuous sequence of bits collected after enabling the RNG
+ * satisfies a runs test.
+ */
+static void test_continuous_runs(void)
+{
+    union {
+        unsigned long l[TEST_INPUT_BITS / BITS_PER_LONG];
+        uint8_t c[TEST_INPUT_BITS / BITS_PER_BYTE];
+    } buf;
+    unsigned int i;
+
+    rng_reset_enable();
+    for (i = 0; i < sizeof(buf); i++) {
+        g_assert_true(rng_wait_ready());
+        buf.c[i] = rng_readb(RNGD);
+    }
+
+    g_assert_cmpfloat(calc_runs_p(buf.l, sizeof(buf) * BITS_PER_BYTE), >, 0.01);
+}
+
+/*
+ * Verifies that the first data byte collected after enabling the RNG satisfies
+ * a monobit test.
+ */
+static void test_first_byte_monobit(void)
+{
+    /* Enable, collect one byte, disable. Repeat until we have 100 bits. */
+    uint8_t buf[TEST_INPUT_BITS / BITS_PER_BYTE];
+    unsigned int i;
+
+    rng_reset();
+    for (i = 0; i < sizeof(buf); i++) {
+        rng_writeb(RNGCS, RNGE);
+        g_assert_true(rng_wait_ready());
+        buf[i] = rng_readb(RNGD);
+        rng_writeb(RNGCS, 0);
+    }
+
+    g_assert_cmpfloat(calc_monobit_p(buf, sizeof(buf)), >, 0.01);
+}
+
+/*
+ * Verifies that the first data byte collected after enabling the RNG satisfies
+ * a runs test.
+ */
+static void test_first_byte_runs(void)
+{
+    /* Enable, collect one byte, disable. Repeat until we have 100 bits. */
+    union {
+        unsigned long l[TEST_INPUT_BITS / BITS_PER_LONG];
+        uint8_t c[TEST_INPUT_BITS / BITS_PER_BYTE];
+    } buf;
+    unsigned int i;
+
+    rng_reset();
+    for (i = 0; i < sizeof(buf); i++) {
+        rng_writeb(RNGCS, RNGE);
+        g_assert_true(rng_wait_ready());
+        buf.c[i] = rng_readb(RNGD);
+        rng_writeb(RNGCS, 0);
+    }
+
+    g_assert_cmpfloat(calc_runs_p(buf.l, sizeof(buf) * BITS_PER_BYTE), >, 0.01);
+}
+
+int main(int argc, char **argv)
+{
+    int ret;
+
+    g_test_init(&argc, &argv, NULL);
+    g_test_set_nonfatal_assertions();
+
+    qtest_add_func("npcm7xx_rng/enable_disable", test_enable_disable);
+    qtest_add_func("npcm7xx_rng/rosel", test_rosel);
+    qtest_add_func("npcm7xx_rng/continuous/monobit", test_continuous_monobit);
+    qtest_add_func("npcm7xx_rng/continuous/runs", test_continuous_runs);
+    qtest_add_func("npcm7xx_rng/first_byte/monobit", test_first_byte_monobit);
+    qtest_add_func("npcm7xx_rng/first_byte/runs", test_first_byte_runs);
+
+    qtest_start("-machine npcm750-evb");
+    ret = g_test_run();
+    qtest_end();
+
+    return ret;
+}
diff --git a/hw/misc/meson.build b/hw/misc/meson.build
index 793d45b1dc..7ffb44b587 100644
--- a/hw/misc/meson.build
+++ b/hw/misc/meson.build
@@ -59,6 +59,7 @@ softmmu_ss.add(when: 'CONFIG_MAINSTONE', if_true: files('mst_fpga.c'))
 softmmu_ss.add(when: 'CONFIG_NPCM7XX', if_true: files(
   'npcm7xx_clk.c',
   'npcm7xx_gcr.c',
+  'npcm7xx_rng.c',
 ))
 softmmu_ss.add(when: 'CONFIG_OMAP', if_true: files(
   'omap_clk.c',
diff --git a/hw/misc/trace-events b/hw/misc/trace-events
index 6054f9adf3..b2f060ad77 100644
--- a/hw/misc/trace-events
+++ b/hw/misc/trace-events
@@ -118,6 +118,10 @@ npcm7xx_clk_write(uint64_t offset, uint32_t value) "offset: 0x%04" PRIx64 " valu
 npcm7xx_gcr_read(uint64_t offset, uint32_t value) " offset: 0x%04" PRIx64 " value: 0x%08" PRIx32
 npcm7xx_gcr_write(uint64_t offset, uint32_t value) "offset: 0x%04" PRIx64 " value: 0x%08" PRIx32
 
+# npcm7xx_rng.c
+npcm7xx_rng_read(uint64_t offset, uint64_t value, unsigned size) "offset: 0x%04" PRIx64 " value: 0x%02" PRIx64 " size: %u"
+npcm7xx_rng_write(uint64_t offset, uint64_t value, unsigned size) "offset: 0x%04" PRIx64 " value: 0x%02" PRIx64 " size: %u"
+
 # stm32f4xx_syscfg.c
 stm32f4xx_syscfg_set_irq(int gpio, int line, int level) "Interupt: GPIO: %d, Line: %d; Level: %d"
 stm32f4xx_pulse_exti(int irq) "Pulse EXTI: %d"
diff --git a/tests/qtest/meson.build b/tests/qtest/meson.build
index b160c6f787..76db8f9d84 100644
--- a/tests/qtest/meson.build
+++ b/tests/qtest/meson.build
@@ -133,7 +133,10 @@ qtests_sparc64 = \
   (config_all_devices.has_key('CONFIG_ISA_TESTDEV') ? ['endianness-test'] : []) +            \
   ['prom-env-test', 'boot-serial-test']
 
-qtests_npcm7xx = ['npcm7xx_timer-test', 'npcm7xx_watchdog_timer-test']
+qtests_npcm7xx = \
+  ['npcm7xx_rng-test',
+   'npcm7xx_timer-test',
+   'npcm7xx_watchdog_timer-test']
 qtests_arm = \
   (config_all_devices.has_key('CONFIG_PFLASH_CFI02') ? ['pflash-cfi02-test'] : []) +         \
   (config_all_devices.has_key('CONFIG_NPCM7XX') ? qtests_npcm7xx : []) + \
-- 
2.29.0.rc1.297.gfa9743e501-goog



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v3 5/6] hw/arm/npcm7xx: Add EHCI and OHCI controllers
  2020-10-23 21:06 [PATCH v3 0/6] Additional NPCM7xx features, devices and tests Havard Skinnemoen via
                   ` (3 preceding siblings ...)
  2020-10-23 21:06 ` [PATCH v3 4/6] hw/misc: Add npcm7xx random number generator Havard Skinnemoen via
@ 2020-10-23 21:06 ` Havard Skinnemoen via
  2020-10-23 21:06 ` [PATCH v3 6/6] hw/gpio: Add GPIO model for Nuvoton NPCM7xx Havard Skinnemoen via
  2020-10-26 17:15 ` [PATCH v3 0/6] Additional NPCM7xx features, devices and tests Peter Maydell
  6 siblings, 0 replies; 15+ messages in thread
From: Havard Skinnemoen via @ 2020-10-23 21:06 UTC (permalink / raw)
  To: peter.maydell
  Cc: qemu-arm, qemu-devel, Avi.Fishman, kfting, venture, wuhaotsh,
	thuth, Havard Skinnemoen, Gerd Hoffmann

The NPCM730 and NPCM750 chips have a single USB host port shared between
a USB 2.0 EHCI host controller and a USB 1.1 OHCI host controller. This
adds support for both of them.

Testing notes:
  * With -device usb-kbd, qemu will automatically insert a full-speed
    hub, and the keyboard becomes controlled by the OHCI controller.
  * With -device usb-kbd,bus=usb-bus.0,port=1, the keyboard is directly
    attached to the port without any hubs, and the device becomes
    controlled by the EHCI controller since it's high speed capable.
  * With -device usb-kbd,bus=usb-bus.0,port=1,usb_version=1, the
    keyboard is directly attached to the port, but it only advertises
    itself as full-speed capable, so it becomes controlled by the OHCI
    controller.

In all cases, the keyboard device enumerates correctly.

Reviewed-by: Tyrone Ting <kfting@nuvoton.com>
Reviewed-by: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Havard Skinnemoen <hskinnemoen@google.com>
---
 docs/system/arm/nuvoton.rst |  2 +-
 hw/usb/hcd-ehci.h           |  1 +
 include/hw/arm/npcm7xx.h    |  4 ++++
 hw/arm/npcm7xx.c            | 27 +++++++++++++++++++++++++--
 hw/usb/hcd-ehci-sysbus.c    | 19 +++++++++++++++++++
 5 files changed, 50 insertions(+), 3 deletions(-)

diff --git a/docs/system/arm/nuvoton.rst b/docs/system/arm/nuvoton.rst
index 4342434df4..99fc61c740 100644
--- a/docs/system/arm/nuvoton.rst
+++ b/docs/system/arm/nuvoton.rst
@@ -39,6 +39,7 @@ Supported devices
  * OTP controllers (no protection features)
  * Flash Interface Unit (FIU; no protection features)
  * Random Number Generator (RNG)
+ * USB host (USBH)
 
 Missing devices
 ---------------
@@ -54,7 +55,6 @@ Missing devices
    * eSPI slave interface
 
  * Ethernet controllers (GMAC and EMC)
- * USB host (USBH)
  * USB device (USBD)
  * SMBus controller (SMBF)
  * Peripheral SPI controller (PSPI)
diff --git a/hw/usb/hcd-ehci.h b/hw/usb/hcd-ehci.h
index fd122dd4cd..a173707d9b 100644
--- a/hw/usb/hcd-ehci.h
+++ b/hw/usb/hcd-ehci.h
@@ -344,6 +344,7 @@ struct EHCIPCIState {
 #define TYPE_PLATFORM_EHCI "platform-ehci-usb"
 #define TYPE_EXYNOS4210_EHCI "exynos4210-ehci-usb"
 #define TYPE_AW_H3_EHCI "aw-h3-ehci-usb"
+#define TYPE_NPCM7XX_EHCI "npcm7xx-ehci-usb"
 #define TYPE_TEGRA2_EHCI "tegra2-ehci-usb"
 #define TYPE_PPC4xx_EHCI "ppc4xx-ehci-usb"
 #define TYPE_FUSBH200_EHCI "fusbh200-ehci-usb"
diff --git a/include/hw/arm/npcm7xx.h b/include/hw/arm/npcm7xx.h
index 761f9b987e..aeee1beaaa 100644
--- a/include/hw/arm/npcm7xx.h
+++ b/include/hw/arm/npcm7xx.h
@@ -25,6 +25,8 @@
 #include "hw/nvram/npcm7xx_otp.h"
 #include "hw/timer/npcm7xx_timer.h"
 #include "hw/ssi/npcm7xx_fiu.h"
+#include "hw/usb/hcd-ehci.h"
+#include "hw/usb/hcd-ohci.h"
 #include "target/arm/cpu.h"
 
 #define NPCM7XX_MAX_NUM_CPUS    (2)
@@ -77,6 +79,8 @@ typedef struct NPCM7xxState {
     NPCM7xxOTPState     fuse_array;
     NPCM7xxMCState      mc;
     NPCM7xxRNGState     rng;
+    EHCISysBusState     ehci;
+    OHCISysBusState     ohci;
     NPCM7xxFIUState     fiu[2];
 } NPCM7xxState;
 
diff --git a/hw/arm/npcm7xx.c b/hw/arm/npcm7xx.c
index cb4db41c54..c1d122576b 100644
--- a/hw/arm/npcm7xx.c
+++ b/hw/arm/npcm7xx.c
@@ -46,6 +46,10 @@
 #define NPCM7XX_MC_BA           (0xf0824000)
 #define NPCM7XX_RNG_BA          (0xf000b000)
 
+/* USB Host modules */
+#define NPCM7XX_EHCI_BA         (0xf0806000)
+#define NPCM7XX_OHCI_BA         (0xf0807000)
+
 /* Internal AHB SRAM */
 #define NPCM7XX_RAM3_BA         (0xc0008000)
 #define NPCM7XX_RAM3_SZ         (4 * KiB)
@@ -90,6 +94,8 @@ enum NPCM7xxInterrupt {
     NPCM7XX_WDG0_IRQ            = 47,   /* Timer Module 0 Watchdog */
     NPCM7XX_WDG1_IRQ,                   /* Timer Module 1 Watchdog */
     NPCM7XX_WDG2_IRQ,                   /* Timer Module 2 Watchdog */
+    NPCM7XX_EHCI_IRQ            = 61,
+    NPCM7XX_OHCI_IRQ            = 62,
 };
 
 /* Total number of GIC interrupts, including internal Cortex-A9 interrupts. */
@@ -263,6 +269,9 @@ static void npcm7xx_init(Object *obj)
         object_initialize_child(obj, "tim[*]", &s->tim[i], TYPE_NPCM7XX_TIMER);
     }
 
+    object_initialize_child(obj, "ehci", &s->ehci, TYPE_NPCM7XX_EHCI);
+    object_initialize_child(obj, "ohci", &s->ohci, TYPE_SYSBUS_OHCI);
+
     QEMU_BUILD_BUG_ON(ARRAY_SIZE(npcm7xx_fiu) != ARRAY_SIZE(s->fiu));
     for (i = 0; i < ARRAY_SIZE(s->fiu); i++) {
         object_initialize_child(obj, npcm7xx_fiu[i].name, &s->fiu[i],
@@ -380,6 +389,22 @@ static void npcm7xx_realize(DeviceState *dev, Error **errp)
     sysbus_realize(SYS_BUS_DEVICE(&s->rng), &error_abort);
     sysbus_mmio_map(SYS_BUS_DEVICE(&s->rng), 0, NPCM7XX_RNG_BA);
 
+    /* USB Host */
+    object_property_set_bool(OBJECT(&s->ehci), "companion-enable", true,
+                             &error_abort);
+    sysbus_realize(SYS_BUS_DEVICE(&s->ehci), &error_abort);
+    sysbus_mmio_map(SYS_BUS_DEVICE(&s->ehci), 0, NPCM7XX_EHCI_BA);
+    sysbus_connect_irq(SYS_BUS_DEVICE(&s->ehci), 0,
+                       npcm7xx_irq(s, NPCM7XX_EHCI_IRQ));
+
+    object_property_set_str(OBJECT(&s->ohci), "masterbus", "usb-bus.0",
+                            &error_abort);
+    object_property_set_uint(OBJECT(&s->ohci), "num-ports", 1, &error_abort);
+    sysbus_realize(SYS_BUS_DEVICE(&s->ohci), &error_abort);
+    sysbus_mmio_map(SYS_BUS_DEVICE(&s->ohci), 0, NPCM7XX_OHCI_BA);
+    sysbus_connect_irq(SYS_BUS_DEVICE(&s->ohci), 0,
+                       npcm7xx_irq(s, NPCM7XX_OHCI_IRQ));
+
     /*
      * Flash Interface Unit (FIU). Can fail if incorrect number of chip selects
      * specified, but this is a programming error.
@@ -464,8 +489,6 @@ static void npcm7xx_realize(DeviceState *dev, Error **errp)
     create_unimplemented_device("npcm7xx.mcphy",        0xf05f0000,  64 * KiB);
     create_unimplemented_device("npcm7xx.gmac1",        0xf0802000,   8 * KiB);
     create_unimplemented_device("npcm7xx.gmac2",        0xf0804000,   8 * KiB);
-    create_unimplemented_device("npcm7xx.ehci",         0xf0806000,   4 * KiB);
-    create_unimplemented_device("npcm7xx.ohci",         0xf0807000,   4 * KiB);
     create_unimplemented_device("npcm7xx.vcd",          0xf0810000,  64 * KiB);
     create_unimplemented_device("npcm7xx.ece",          0xf0820000,   8 * KiB);
     create_unimplemented_device("npcm7xx.vdma",         0xf0822000,   8 * KiB);
diff --git a/hw/usb/hcd-ehci-sysbus.c b/hw/usb/hcd-ehci-sysbus.c
index 3730736540..e3758db1b1 100644
--- a/hw/usb/hcd-ehci-sysbus.c
+++ b/hw/usb/hcd-ehci-sysbus.c
@@ -147,6 +147,24 @@ static const TypeInfo ehci_aw_h3_type_info = {
     .class_init    = ehci_aw_h3_class_init,
 };
 
+static void ehci_npcm7xx_class_init(ObjectClass *oc, void *data)
+{
+    SysBusEHCIClass *sec = SYS_BUS_EHCI_CLASS(oc);
+    DeviceClass *dc = DEVICE_CLASS(oc);
+
+    sec->capsbase = 0x0;
+    sec->opregbase = 0x10;
+    sec->portscbase = 0x44;
+    sec->portnr = 1;
+    set_bit(DEVICE_CATEGORY_USB, dc->categories);
+}
+
+static const TypeInfo ehci_npcm7xx_type_info = {
+    .name          = TYPE_NPCM7XX_EHCI,
+    .parent        = TYPE_SYS_BUS_EHCI,
+    .class_init    = ehci_npcm7xx_class_init,
+};
+
 static void ehci_tegra2_class_init(ObjectClass *oc, void *data)
 {
     SysBusEHCIClass *sec = SYS_BUS_EHCI_CLASS(oc);
@@ -269,6 +287,7 @@ static void ehci_sysbus_register_types(void)
     type_register_static(&ehci_platform_type_info);
     type_register_static(&ehci_exynos4210_type_info);
     type_register_static(&ehci_aw_h3_type_info);
+    type_register_static(&ehci_npcm7xx_type_info);
     type_register_static(&ehci_tegra2_type_info);
     type_register_static(&ehci_ppc4xx_type_info);
     type_register_static(&ehci_fusbh200_type_info);
-- 
2.29.0.rc1.297.gfa9743e501-goog



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v3 6/6] hw/gpio: Add GPIO model for Nuvoton NPCM7xx
  2020-10-23 21:06 [PATCH v3 0/6] Additional NPCM7xx features, devices and tests Havard Skinnemoen via
                   ` (4 preceding siblings ...)
  2020-10-23 21:06 ` [PATCH v3 5/6] hw/arm/npcm7xx: Add EHCI and OHCI controllers Havard Skinnemoen via
@ 2020-10-23 21:06 ` Havard Skinnemoen via
  2020-10-26 17:15 ` [PATCH v3 0/6] Additional NPCM7xx features, devices and tests Peter Maydell
  6 siblings, 0 replies; 15+ messages in thread
From: Havard Skinnemoen via @ 2020-10-23 21:06 UTC (permalink / raw)
  To: peter.maydell
  Cc: qemu-arm, qemu-devel, Avi.Fishman, kfting, venture, wuhaotsh,
	thuth, Havard Skinnemoen

The NPCM7xx chips have multiple GPIO controllers that are mostly
identical except for some minor differences like the reset values of
some registers. Each controller controls up to 32 pins.

Each individual pin is modeled as a pair of unnamed GPIOs -- one for
emitting the actual pin state, and one for driving the pin externally.
Like the nRF51 GPIO controller, a gpio level may be negative, which
means the pin is not driven, or floating.

Reviewed-by: Tyrone Ting <kfting@nuvoton.com>
Signed-off-by: Havard Skinnemoen <hskinnemoen@google.com>
---
 docs/system/arm/nuvoton.rst     |   2 +-
 include/hw/arm/npcm7xx.h        |   2 +
 include/hw/gpio/npcm7xx_gpio.h  |  55 +++++
 hw/arm/npcm7xx.c                |  80 ++++++
 hw/gpio/npcm7xx_gpio.c          | 424 ++++++++++++++++++++++++++++++++
 tests/qtest/npcm7xx_gpio-test.c | 385 +++++++++++++++++++++++++++++
 hw/gpio/meson.build             |   1 +
 hw/gpio/trace-events            |   7 +
 tests/qtest/meson.build         |   3 +-
 9 files changed, 957 insertions(+), 2 deletions(-)
 create mode 100644 include/hw/gpio/npcm7xx_gpio.h
 create mode 100644 hw/gpio/npcm7xx_gpio.c
 create mode 100644 tests/qtest/npcm7xx_gpio-test.c

diff --git a/docs/system/arm/nuvoton.rst b/docs/system/arm/nuvoton.rst
index 99fc61c740..b00d405d52 100644
--- a/docs/system/arm/nuvoton.rst
+++ b/docs/system/arm/nuvoton.rst
@@ -40,11 +40,11 @@ Supported devices
  * Flash Interface Unit (FIU; no protection features)
  * Random Number Generator (RNG)
  * USB host (USBH)
+ * GPIO controller
 
 Missing devices
 ---------------
 
- * GPIO controller
  * LPC/eSPI host-to-BMC interface, including
 
    * Keyboard and mouse controller interface (KBCI)
diff --git a/include/hw/arm/npcm7xx.h b/include/hw/arm/npcm7xx.h
index aeee1beaaa..5469247e38 100644
--- a/include/hw/arm/npcm7xx.h
+++ b/include/hw/arm/npcm7xx.h
@@ -18,6 +18,7 @@
 
 #include "hw/boards.h"
 #include "hw/cpu/a9mpcore.h"
+#include "hw/gpio/npcm7xx_gpio.h"
 #include "hw/mem/npcm7xx_mc.h"
 #include "hw/misc/npcm7xx_clk.h"
 #include "hw/misc/npcm7xx_gcr.h"
@@ -79,6 +80,7 @@ typedef struct NPCM7xxState {
     NPCM7xxOTPState     fuse_array;
     NPCM7xxMCState      mc;
     NPCM7xxRNGState     rng;
+    NPCM7xxGPIOState    gpio[8];
     EHCISysBusState     ehci;
     OHCISysBusState     ohci;
     NPCM7xxFIUState     fiu[2];
diff --git a/include/hw/gpio/npcm7xx_gpio.h b/include/hw/gpio/npcm7xx_gpio.h
new file mode 100644
index 0000000000..b1d771bd77
--- /dev/null
+++ b/include/hw/gpio/npcm7xx_gpio.h
@@ -0,0 +1,55 @@
+/*
+ * Nuvoton NPCM7xx General Purpose Input / Output (GPIO)
+ *
+ * Copyright 2020 Google LLC
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * version 2 as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+#ifndef NPCM7XX_GPIO_H
+#define NPCM7XX_GPIO_H
+
+#include "exec/memory.h"
+#include "hw/sysbus.h"
+
+/* Number of pins managed by each controller. */
+#define NPCM7XX_GPIO_NR_PINS (32)
+
+/*
+ * Number of registers in our device state structure. Don't change this without
+ * incrementing the version_id in the vmstate.
+ */
+#define NPCM7XX_GPIO_NR_REGS (0x80 / sizeof(uint32_t))
+
+typedef struct NPCM7xxGPIOState {
+    SysBusDevice parent;
+
+    /* Properties to be defined by the SoC */
+    uint32_t reset_pu;
+    uint32_t reset_pd;
+    uint32_t reset_osrc;
+    uint32_t reset_odsc;
+
+    MemoryRegion mmio;
+
+    qemu_irq irq;
+    qemu_irq output[NPCM7XX_GPIO_NR_PINS];
+
+    uint32_t pin_level;
+    uint32_t ext_level;
+    uint32_t ext_driven;
+
+    uint32_t regs[NPCM7XX_GPIO_NR_REGS];
+} NPCM7xxGPIOState;
+
+#define TYPE_NPCM7XX_GPIO "npcm7xx-gpio"
+#define NPCM7XX_GPIO(obj) \
+    OBJECT_CHECK(NPCM7xxGPIOState, (obj), TYPE_NPCM7XX_GPIO)
+
+#endif /* NPCM7XX_GPIO_H */
diff --git a/hw/arm/npcm7xx.c b/hw/arm/npcm7xx.c
index c1d122576b..47e2b6fc40 100644
--- a/hw/arm/npcm7xx.c
+++ b/hw/arm/npcm7xx.c
@@ -96,6 +96,14 @@ enum NPCM7xxInterrupt {
     NPCM7XX_WDG2_IRQ,                   /* Timer Module 2 Watchdog */
     NPCM7XX_EHCI_IRQ            = 61,
     NPCM7XX_OHCI_IRQ            = 62,
+    NPCM7XX_GPIO0_IRQ           = 116,
+    NPCM7XX_GPIO1_IRQ,
+    NPCM7XX_GPIO2_IRQ,
+    NPCM7XX_GPIO3_IRQ,
+    NPCM7XX_GPIO4_IRQ,
+    NPCM7XX_GPIO5_IRQ,
+    NPCM7XX_GPIO6_IRQ,
+    NPCM7XX_GPIO7_IRQ,
 };
 
 /* Total number of GIC interrupts, including internal Cortex-A9 interrupts. */
@@ -130,6 +138,55 @@ static const hwaddr npcm7xx_fiu3_flash_addr[] = {
     0xb8000000, /* CS3 */
 };
 
+static const struct {
+    hwaddr regs_addr;
+    uint32_t unconnected_pins;
+    uint32_t reset_pu;
+    uint32_t reset_pd;
+    uint32_t reset_osrc;
+    uint32_t reset_odsc;
+} npcm7xx_gpio[] = {
+    {
+        .regs_addr = 0xf0010000,
+        .reset_pu = 0xff03ffff,
+        .reset_pd = 0x00fc0000,
+    }, {
+        .regs_addr = 0xf0011000,
+        .unconnected_pins = 0x0000001e,
+        .reset_pu = 0xfefffe07,
+        .reset_pd = 0x010001e0,
+    }, {
+        .regs_addr = 0xf0012000,
+        .reset_pu = 0x780fffff,
+        .reset_pd = 0x07f00000,
+        .reset_odsc = 0x00700000,
+    }, {
+        .regs_addr = 0xf0013000,
+        .reset_pu = 0x00fc0000,
+        .reset_pd = 0xff000000,
+    }, {
+        .regs_addr = 0xf0014000,
+        .reset_pu = 0xffffffff,
+    }, {
+        .regs_addr = 0xf0015000,
+        .reset_pu = 0xbf83f801,
+        .reset_pd = 0x007c0000,
+        .reset_osrc = 0x000000f1,
+        .reset_odsc = 0x3f9f80f1,
+    }, {
+        .regs_addr = 0xf0016000,
+        .reset_pu = 0xfc00f801,
+        .reset_pd = 0x000007fe,
+        .reset_odsc = 0x00000800,
+    }, {
+        .regs_addr = 0xf0017000,
+        .unconnected_pins = 0xffffff00,
+        .reset_pu = 0x0000007f,
+        .reset_osrc = 0x0000007f,
+        .reset_odsc = 0x0000007f,
+    },
+};
+
 static const struct {
     const char *name;
     hwaddr regs_addr;
@@ -269,6 +326,10 @@ static void npcm7xx_init(Object *obj)
         object_initialize_child(obj, "tim[*]", &s->tim[i], TYPE_NPCM7XX_TIMER);
     }
 
+    for (i = 0; i < ARRAY_SIZE(s->gpio); i++) {
+        object_initialize_child(obj, "gpio[*]", &s->gpio[i], TYPE_NPCM7XX_GPIO);
+    }
+
     object_initialize_child(obj, "ehci", &s->ehci, TYPE_NPCM7XX_EHCI);
     object_initialize_child(obj, "ohci", &s->ohci, TYPE_SYSBUS_OHCI);
 
@@ -389,6 +450,25 @@ static void npcm7xx_realize(DeviceState *dev, Error **errp)
     sysbus_realize(SYS_BUS_DEVICE(&s->rng), &error_abort);
     sysbus_mmio_map(SYS_BUS_DEVICE(&s->rng), 0, NPCM7XX_RNG_BA);
 
+    /* GPIO modules. Cannot fail. */
+    QEMU_BUILD_BUG_ON(ARRAY_SIZE(npcm7xx_gpio) != ARRAY_SIZE(s->gpio));
+    for (i = 0; i < ARRAY_SIZE(s->gpio); i++) {
+        Object *obj = OBJECT(&s->gpio[i]);
+
+        object_property_set_uint(obj, "reset-pullup",
+                                 npcm7xx_gpio[i].reset_pu, &error_abort);
+        object_property_set_uint(obj, "reset-pulldown",
+                                 npcm7xx_gpio[i].reset_pd, &error_abort);
+        object_property_set_uint(obj, "reset-osrc",
+                                 npcm7xx_gpio[i].reset_osrc, &error_abort);
+        object_property_set_uint(obj, "reset-odsc",
+                                 npcm7xx_gpio[i].reset_odsc, &error_abort);
+        sysbus_realize(SYS_BUS_DEVICE(obj), &error_abort);
+        sysbus_mmio_map(SYS_BUS_DEVICE(obj), 0, npcm7xx_gpio[i].regs_addr);
+        sysbus_connect_irq(SYS_BUS_DEVICE(obj), 0,
+                           npcm7xx_irq(s, NPCM7XX_GPIO0_IRQ + i));
+    }
+
     /* USB Host */
     object_property_set_bool(OBJECT(&s->ehci), "companion-enable", true,
                              &error_abort);
diff --git a/hw/gpio/npcm7xx_gpio.c b/hw/gpio/npcm7xx_gpio.c
new file mode 100644
index 0000000000..3376901ab1
--- /dev/null
+++ b/hw/gpio/npcm7xx_gpio.c
@@ -0,0 +1,424 @@
+/*
+ * Nuvoton NPCM7xx General Purpose Input / Output (GPIO)
+ *
+ * Copyright 2020 Google LLC
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * version 2 as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include "qemu/osdep.h"
+
+#include "hw/gpio/npcm7xx_gpio.h"
+#include "hw/irq.h"
+#include "hw/qdev-properties.h"
+#include "migration/vmstate.h"
+#include "qapi/error.h"
+#include "qemu/log.h"
+#include "qemu/module.h"
+#include "qemu/units.h"
+#include "trace.h"
+
+/* 32-bit register indices. */
+enum NPCM7xxGPIORegister {
+    NPCM7XX_GPIO_TLOCK1,
+    NPCM7XX_GPIO_DIN,
+    NPCM7XX_GPIO_POL,
+    NPCM7XX_GPIO_DOUT,
+    NPCM7XX_GPIO_OE,
+    NPCM7XX_GPIO_OTYP,
+    NPCM7XX_GPIO_MP,
+    NPCM7XX_GPIO_PU,
+    NPCM7XX_GPIO_PD,
+    NPCM7XX_GPIO_DBNC,
+    NPCM7XX_GPIO_EVTYP,
+    NPCM7XX_GPIO_EVBE,
+    NPCM7XX_GPIO_OBL0,
+    NPCM7XX_GPIO_OBL1,
+    NPCM7XX_GPIO_OBL2,
+    NPCM7XX_GPIO_OBL3,
+    NPCM7XX_GPIO_EVEN,
+    NPCM7XX_GPIO_EVENS,
+    NPCM7XX_GPIO_EVENC,
+    NPCM7XX_GPIO_EVST,
+    NPCM7XX_GPIO_SPLCK,
+    NPCM7XX_GPIO_MPLCK,
+    NPCM7XX_GPIO_IEM,
+    NPCM7XX_GPIO_OSRC,
+    NPCM7XX_GPIO_ODSC,
+    NPCM7XX_GPIO_DOS = 0x68 / sizeof(uint32_t),
+    NPCM7XX_GPIO_DOC,
+    NPCM7XX_GPIO_OES,
+    NPCM7XX_GPIO_OEC,
+    NPCM7XX_GPIO_TLOCK2 = 0x7c / sizeof(uint32_t),
+    NPCM7XX_GPIO_REGS_END,
+};
+
+#define NPCM7XX_GPIO_REGS_SIZE (4 * KiB)
+
+#define NPCM7XX_GPIO_LOCK_MAGIC1 (0xc0defa73)
+#define NPCM7XX_GPIO_LOCK_MAGIC2 (0xc0de1248)
+
+static void npcm7xx_gpio_update_events(NPCM7xxGPIOState *s, uint32_t din_diff)
+{
+    uint32_t din_new = s->regs[NPCM7XX_GPIO_DIN];
+
+    /* Trigger on high level */
+    s->regs[NPCM7XX_GPIO_EVST] |= din_new & ~s->regs[NPCM7XX_GPIO_EVTYP];
+    /* Trigger on both edges */
+    s->regs[NPCM7XX_GPIO_EVST] |= (din_diff & s->regs[NPCM7XX_GPIO_EVTYP]
+                                   & s->regs[NPCM7XX_GPIO_EVBE]);
+    /* Trigger on rising edge */
+    s->regs[NPCM7XX_GPIO_EVST] |= (din_diff & din_new
+                                   & s->regs[NPCM7XX_GPIO_EVTYP]);
+
+    trace_npcm7xx_gpio_update_events(DEVICE(s)->canonical_path,
+                                     s->regs[NPCM7XX_GPIO_EVST],
+                                     s->regs[NPCM7XX_GPIO_EVEN]);
+    qemu_set_irq(s->irq, !!(s->regs[NPCM7XX_GPIO_EVST]
+                            & s->regs[NPCM7XX_GPIO_EVEN]));
+}
+
+static void npcm7xx_gpio_update_pins(NPCM7xxGPIOState *s, uint32_t diff)
+{
+    uint32_t drive_en;
+    uint32_t drive_lvl;
+    uint32_t not_driven;
+    uint32_t undefined;
+    uint32_t pin_diff;
+    uint32_t din_old;
+
+    /* Calculate level of each pin driven by GPIO controller. */
+    drive_lvl = s->regs[NPCM7XX_GPIO_DOUT] ^ s->regs[NPCM7XX_GPIO_POL];
+    /* If OTYP=1, only drive low (open drain) */
+    drive_en = s->regs[NPCM7XX_GPIO_OE] & ~(s->regs[NPCM7XX_GPIO_OTYP]
+                                            & drive_lvl);
+    /*
+     * If a pin is driven to opposite levels by the GPIO controller and the
+     * external driver, the result is undefined.
+     */
+    undefined = drive_en & s->ext_driven & (drive_lvl ^ s->ext_level);
+    if (undefined) {
+        qemu_log_mask(LOG_GUEST_ERROR,
+                      "%s: pins have multiple drivers: 0x%" PRIx32 "\n",
+                      DEVICE(s)->canonical_path, undefined);
+    }
+
+    not_driven = ~(drive_en | s->ext_driven);
+    pin_diff = s->pin_level;
+
+    /* Set pins to externally driven level. */
+    s->pin_level = s->ext_level & s->ext_driven;
+    /* Set internally driven pins, ignoring any conflicts. */
+    s->pin_level |= drive_lvl & drive_en;
+    /* Pull up undriven pins with internal pull-up enabled. */
+    s->pin_level |= not_driven & s->regs[NPCM7XX_GPIO_PU];
+    /* Pins not driven, pulled up or pulled down are undefined */
+    undefined |= not_driven & ~(s->regs[NPCM7XX_GPIO_PU]
+                                | s->regs[NPCM7XX_GPIO_PD]);
+
+    /* If any pins changed state, update the outgoing GPIOs. */
+    pin_diff ^= s->pin_level;
+    pin_diff |= undefined & diff;
+    if (pin_diff) {
+        int i;
+
+        for (i = 0; i < NPCM7XX_GPIO_NR_PINS; i++) {
+            uint32_t mask = BIT(i);
+            if (pin_diff & mask) {
+                int level = (undefined & mask) ? -1 : !!(s->pin_level & mask);
+                trace_npcm7xx_gpio_set_output(DEVICE(s)->canonical_path,
+                                              i, level);
+                qemu_set_irq(s->output[i], level);
+            }
+        }
+    }
+
+    /* Calculate new value of DIN after masking and polarity setting. */
+    din_old = s->regs[NPCM7XX_GPIO_DIN];
+    s->regs[NPCM7XX_GPIO_DIN] = ((s->pin_level & s->regs[NPCM7XX_GPIO_IEM])
+                                 ^ s->regs[NPCM7XX_GPIO_POL]);
+
+    /* See if any new events triggered because of all this. */
+    npcm7xx_gpio_update_events(s, din_old ^ s->regs[NPCM7XX_GPIO_DIN]);
+}
+
+static bool npcm7xx_gpio_is_locked(NPCM7xxGPIOState *s)
+{
+    return s->regs[NPCM7XX_GPIO_TLOCK1] == 1;
+}
+
+static uint64_t npcm7xx_gpio_regs_read(void *opaque, hwaddr addr,
+                                       unsigned int size)
+{
+    hwaddr reg = addr / sizeof(uint32_t);
+    NPCM7xxGPIOState *s = opaque;
+    uint64_t value = 0;
+
+    switch (reg) {
+    case NPCM7XX_GPIO_TLOCK1 ... NPCM7XX_GPIO_EVEN:
+    case NPCM7XX_GPIO_EVST ... NPCM7XX_GPIO_ODSC:
+        value = s->regs[reg];
+        break;
+
+    case NPCM7XX_GPIO_EVENS ... NPCM7XX_GPIO_EVENC:
+    case NPCM7XX_GPIO_DOS ... NPCM7XX_GPIO_TLOCK2:
+        qemu_log_mask(LOG_GUEST_ERROR,
+                      "%s: read from write-only register 0x%" HWADDR_PRIx "\n",
+                      DEVICE(s)->canonical_path, addr);
+        break;
+
+    default:
+        qemu_log_mask(LOG_GUEST_ERROR,
+                      "%s: read from invalid offset 0x%" HWADDR_PRIx "\n",
+                      DEVICE(s)->canonical_path, addr);
+        break;
+    }
+
+    trace_npcm7xx_gpio_read(DEVICE(s)->canonical_path, addr, value);
+
+    return value;
+}
+
+static void npcm7xx_gpio_regs_write(void *opaque, hwaddr addr, uint64_t v,
+                                    unsigned int size)
+{
+    hwaddr reg = addr / sizeof(uint32_t);
+    NPCM7xxGPIOState *s = opaque;
+    uint32_t value = v;
+    uint32_t diff;
+
+    trace_npcm7xx_gpio_write(DEVICE(s)->canonical_path, addr, v);
+
+    if (npcm7xx_gpio_is_locked(s)) {
+        switch (reg) {
+        case NPCM7XX_GPIO_TLOCK1:
+            if (s->regs[NPCM7XX_GPIO_TLOCK2] == NPCM7XX_GPIO_LOCK_MAGIC2 &&
+                value == NPCM7XX_GPIO_LOCK_MAGIC1) {
+                s->regs[NPCM7XX_GPIO_TLOCK1] = 0;
+                s->regs[NPCM7XX_GPIO_TLOCK2] = 0;
+            }
+            break;
+
+        case NPCM7XX_GPIO_TLOCK2:
+            s->regs[reg] = value;
+            break;
+
+        default:
+            qemu_log_mask(LOG_GUEST_ERROR,
+                          "%s: write to locked register @ 0x%" HWADDR_PRIx "\n",
+                          DEVICE(s)->canonical_path, addr);
+            break;
+        }
+
+        return;
+    }
+
+    diff = s->regs[reg] ^ value;
+
+    switch (reg) {
+    case NPCM7XX_GPIO_TLOCK1:
+    case NPCM7XX_GPIO_TLOCK2:
+        s->regs[NPCM7XX_GPIO_TLOCK1] = 1;
+        s->regs[NPCM7XX_GPIO_TLOCK2] = 0;
+        break;
+
+    case NPCM7XX_GPIO_DIN:
+        qemu_log_mask(LOG_GUEST_ERROR,
+                      "%s: write to read-only register @ 0x%" HWADDR_PRIx "\n",
+                      DEVICE(s)->canonical_path, addr);
+        break;
+
+    case NPCM7XX_GPIO_POL:
+    case NPCM7XX_GPIO_DOUT:
+    case NPCM7XX_GPIO_OE:
+    case NPCM7XX_GPIO_OTYP:
+    case NPCM7XX_GPIO_PU:
+    case NPCM7XX_GPIO_PD:
+    case NPCM7XX_GPIO_IEM:
+        s->regs[reg] = value;
+        npcm7xx_gpio_update_pins(s, diff);
+        break;
+
+    case NPCM7XX_GPIO_DOS:
+        s->regs[NPCM7XX_GPIO_DOUT] |= value;
+        npcm7xx_gpio_update_pins(s, value);
+        break;
+    case NPCM7XX_GPIO_DOC:
+        s->regs[NPCM7XX_GPIO_DOUT] &= ~value;
+        npcm7xx_gpio_update_pins(s, value);
+        break;
+    case NPCM7XX_GPIO_OES:
+        s->regs[NPCM7XX_GPIO_OE] |= value;
+        npcm7xx_gpio_update_pins(s, value);
+        break;
+    case NPCM7XX_GPIO_OEC:
+        s->regs[NPCM7XX_GPIO_OE] &= ~value;
+        npcm7xx_gpio_update_pins(s, value);
+        break;
+
+    case NPCM7XX_GPIO_EVTYP:
+    case NPCM7XX_GPIO_EVBE:
+    case NPCM7XX_GPIO_EVEN:
+        s->regs[reg] = value;
+        npcm7xx_gpio_update_events(s, 0);
+        break;
+
+    case NPCM7XX_GPIO_EVENS:
+        s->regs[NPCM7XX_GPIO_EVEN] |= value;
+        npcm7xx_gpio_update_events(s, 0);
+        break;
+    case NPCM7XX_GPIO_EVENC:
+        s->regs[NPCM7XX_GPIO_EVEN] &= ~value;
+        npcm7xx_gpio_update_events(s, 0);
+        break;
+
+    case NPCM7XX_GPIO_EVST:
+        s->regs[reg] &= ~value;
+        npcm7xx_gpio_update_events(s, 0);
+        break;
+
+    case NPCM7XX_GPIO_MP:
+    case NPCM7XX_GPIO_DBNC:
+    case NPCM7XX_GPIO_OSRC:
+    case NPCM7XX_GPIO_ODSC:
+        /* Nothing to do; just store the value. */
+        s->regs[reg] = value;
+        break;
+
+    case NPCM7XX_GPIO_OBL0:
+    case NPCM7XX_GPIO_OBL1:
+    case NPCM7XX_GPIO_OBL2:
+    case NPCM7XX_GPIO_OBL3:
+        s->regs[reg] = value;
+        qemu_log_mask(LOG_UNIMP, "%s: Blinking is not implemented\n",
+                      __func__);
+        break;
+
+    case NPCM7XX_GPIO_SPLCK:
+    case NPCM7XX_GPIO_MPLCK:
+        qemu_log_mask(LOG_UNIMP, "%s: Per-pin lock is not implemented\n",
+                      __func__);
+        break;
+
+    default:
+        qemu_log_mask(LOG_GUEST_ERROR,
+                      "%s: write to invalid offset 0x%" HWADDR_PRIx "\n",
+                      DEVICE(s)->canonical_path, addr);
+        break;
+    }
+}
+
+static const MemoryRegionOps npcm7xx_gpio_regs_ops = {
+    .read = npcm7xx_gpio_regs_read,
+    .write = npcm7xx_gpio_regs_write,
+    .endianness = DEVICE_NATIVE_ENDIAN,
+    .valid = {
+        .min_access_size = 4,
+        .max_access_size = 4,
+        .unaligned = false,
+    },
+};
+
+static void npcm7xx_gpio_set_input(void *opaque, int line, int level)
+{
+    NPCM7xxGPIOState *s = opaque;
+
+    trace_npcm7xx_gpio_set_input(DEVICE(s)->canonical_path, line, level);
+
+    g_assert(line >= 0 && line < NPCM7XX_GPIO_NR_PINS);
+
+    s->ext_driven = deposit32(s->ext_driven, line, 1, level >= 0);
+    s->ext_level = deposit32(s->ext_level, line, 1, level > 0);
+
+    npcm7xx_gpio_update_pins(s, BIT(line));
+}
+
+static void npcm7xx_gpio_enter_reset(Object *obj, ResetType type)
+{
+    NPCM7xxGPIOState *s = NPCM7XX_GPIO(obj);
+
+    memset(s->regs, 0, sizeof(s->regs));
+
+    s->regs[NPCM7XX_GPIO_PU] = s->reset_pu;
+    s->regs[NPCM7XX_GPIO_PD] = s->reset_pd;
+    s->regs[NPCM7XX_GPIO_OSRC] = s->reset_osrc;
+    s->regs[NPCM7XX_GPIO_ODSC] = s->reset_odsc;
+}
+
+static void npcm7xx_gpio_hold_reset(Object *obj)
+{
+    NPCM7xxGPIOState *s = NPCM7XX_GPIO(obj);
+
+    npcm7xx_gpio_update_pins(s, -1);
+}
+
+static void npcm7xx_gpio_init(Object *obj)
+{
+    NPCM7xxGPIOState *s = NPCM7XX_GPIO(obj);
+    DeviceState *dev = DEVICE(obj);
+
+    memory_region_init_io(&s->mmio, obj, &npcm7xx_gpio_regs_ops, s,
+                          "regs", NPCM7XX_GPIO_REGS_SIZE);
+    sysbus_init_mmio(SYS_BUS_DEVICE(obj), &s->mmio);
+    sysbus_init_irq(SYS_BUS_DEVICE(obj), &s->irq);
+
+    qdev_init_gpio_in(dev, npcm7xx_gpio_set_input, NPCM7XX_GPIO_NR_PINS);
+    qdev_init_gpio_out(dev, s->output, NPCM7XX_GPIO_NR_PINS);
+}
+
+static const VMStateDescription vmstate_npcm7xx_gpio = {
+    .name = "npcm7xx-gpio",
+    .version_id = 0,
+    .minimum_version_id = 0,
+    .fields = (VMStateField[]) {
+        VMSTATE_UINT32(pin_level, NPCM7xxGPIOState),
+        VMSTATE_UINT32(ext_level, NPCM7xxGPIOState),
+        VMSTATE_UINT32(ext_driven, NPCM7xxGPIOState),
+        VMSTATE_UINT32_ARRAY(regs, NPCM7xxGPIOState, NPCM7XX_GPIO_NR_REGS),
+        VMSTATE_END_OF_LIST(),
+    },
+};
+
+static Property npcm7xx_gpio_properties[] = {
+    /* Bit n set => pin n has pullup enabled by default. */
+    DEFINE_PROP_UINT32("reset-pullup", NPCM7xxGPIOState, reset_pu, 0),
+    /* Bit n set => pin n has pulldown enabled by default. */
+    DEFINE_PROP_UINT32("reset-pulldown", NPCM7xxGPIOState, reset_pd, 0),
+    /* Bit n set => pin n has high slew rate by default. */
+    DEFINE_PROP_UINT32("reset-osrc", NPCM7xxGPIOState, reset_osrc, 0),
+    /* Bit n set => pin n has high drive strength by default. */
+    DEFINE_PROP_UINT32("reset-odsc", NPCM7xxGPIOState, reset_odsc, 0),
+    DEFINE_PROP_END_OF_LIST(),
+};
+
+static void npcm7xx_gpio_class_init(ObjectClass *klass, void *data)
+{
+    ResettableClass *reset = RESETTABLE_CLASS(klass);
+    DeviceClass *dc = DEVICE_CLASS(klass);
+
+    QEMU_BUILD_BUG_ON(NPCM7XX_GPIO_REGS_END > NPCM7XX_GPIO_NR_REGS);
+
+    dc->desc = "NPCM7xx GPIO Controller";
+    dc->vmsd = &vmstate_npcm7xx_gpio;
+    reset->phases.enter = npcm7xx_gpio_enter_reset;
+    reset->phases.hold = npcm7xx_gpio_hold_reset;
+    device_class_set_props(dc, npcm7xx_gpio_properties);
+}
+
+static const TypeInfo npcm7xx_gpio_types[] = {
+    {
+        .name = TYPE_NPCM7XX_GPIO,
+        .parent = TYPE_SYS_BUS_DEVICE,
+        .instance_size = sizeof(NPCM7xxGPIOState),
+        .class_init = npcm7xx_gpio_class_init,
+        .instance_init = npcm7xx_gpio_init,
+    },
+};
+DEFINE_TYPES(npcm7xx_gpio_types);
diff --git a/tests/qtest/npcm7xx_gpio-test.c b/tests/qtest/npcm7xx_gpio-test.c
new file mode 100644
index 0000000000..1004cef812
--- /dev/null
+++ b/tests/qtest/npcm7xx_gpio-test.c
@@ -0,0 +1,385 @@
+/*
+ * QTest testcase for the Nuvoton NPCM7xx GPIO modules.
+ *
+ * Copyright 2020 Google LLC
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * for more details.
+ */
+
+#include "qemu/osdep.h"
+#include "libqtest-single.h"
+
+#define NR_GPIO_DEVICES (8)
+#define GPIO(x)         (0xf0010000 + (x) * 0x1000)
+#define GPIO_IRQ(x)     (116 + (x))
+
+/* GPIO registers */
+#define GP_N_TLOCK1     0x00
+#define GP_N_DIN        0x04 /* Data IN */
+#define GP_N_POL        0x08 /* Polarity */
+#define GP_N_DOUT       0x0c /* Data OUT */
+#define GP_N_OE         0x10 /* Output Enable */
+#define GP_N_OTYP       0x14
+#define GP_N_MP         0x18
+#define GP_N_PU         0x1c /* Pull-up */
+#define GP_N_PD         0x20 /* Pull-down */
+#define GP_N_DBNC       0x24 /* Debounce */
+#define GP_N_EVTYP      0x28 /* Event Type */
+#define GP_N_EVBE       0x2c /* Event Both Edge */
+#define GP_N_OBL0       0x30
+#define GP_N_OBL1       0x34
+#define GP_N_OBL2       0x38
+#define GP_N_OBL3       0x3c
+#define GP_N_EVEN       0x40 /* Event Enable */
+#define GP_N_EVENS      0x44 /* Event Set (enable) */
+#define GP_N_EVENC      0x48 /* Event Clear (disable) */
+#define GP_N_EVST       0x4c /* Event Status */
+#define GP_N_SPLCK      0x50
+#define GP_N_MPLCK      0x54
+#define GP_N_IEM        0x58 /* Input Enable */
+#define GP_N_OSRC       0x5c
+#define GP_N_ODSC       0x60
+#define GP_N_DOS        0x68 /* Data OUT Set */
+#define GP_N_DOC        0x6c /* Data OUT Clear */
+#define GP_N_OES        0x70 /* Output Enable Set */
+#define GP_N_OEC        0x74 /* Output Enable Clear */
+#define GP_N_TLOCK2     0x7c
+
+static void gpio_unlock(int n)
+{
+    if (readl(GPIO(n) + GP_N_TLOCK1) != 0) {
+        writel(GPIO(n) + GP_N_TLOCK2, 0xc0de1248);
+        writel(GPIO(n) + GP_N_TLOCK1, 0xc0defa73);
+    }
+}
+
+/* Restore the GPIO controller to a sensible default state. */
+static void gpio_reset(int n)
+{
+    gpio_unlock(0);
+
+    writel(GPIO(n) + GP_N_EVEN, 0x00000000);
+    writel(GPIO(n) + GP_N_EVST, 0xffffffff);
+    writel(GPIO(n) + GP_N_POL, 0x00000000);
+    writel(GPIO(n) + GP_N_DOUT, 0x00000000);
+    writel(GPIO(n) + GP_N_OE, 0x00000000);
+    writel(GPIO(n) + GP_N_OTYP, 0x00000000);
+    writel(GPIO(n) + GP_N_PU, 0xffffffff);
+    writel(GPIO(n) + GP_N_PD, 0x00000000);
+    writel(GPIO(n) + GP_N_IEM, 0xffffffff);
+}
+
+static void test_dout_to_din(void)
+{
+    gpio_reset(0);
+
+    /* When output is enabled, DOUT should be reflected on DIN. */
+    writel(GPIO(0) + GP_N_OE, 0xffffffff);
+    /* PU and PD shouldn't have any impact on DIN. */
+    writel(GPIO(0) + GP_N_PU, 0xffff0000);
+    writel(GPIO(0) + GP_N_PD, 0x0000ffff);
+    writel(GPIO(0) + GP_N_DOUT, 0x12345678);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_DOUT), ==, 0x12345678);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_DIN), ==, 0x12345678);
+}
+
+static void test_pullup_pulldown(void)
+{
+    gpio_reset(0);
+
+    /*
+     * When output is disabled, and PD is the inverse of PU, PU should be
+     * reflected on DIN. If PD is not the inverse of PU, the state of DIN is
+     * undefined, so we don't test that.
+     */
+    writel(GPIO(0) + GP_N_OE, 0x00000000);
+    /* DOUT shouldn't have any impact on DIN. */
+    writel(GPIO(0) + GP_N_DOUT, 0xffff0000);
+    writel(GPIO(0) + GP_N_PU, 0x23456789);
+    writel(GPIO(0) + GP_N_PD, ~0x23456789U);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_PU), ==, 0x23456789);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_PD), ==, ~0x23456789U);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_DIN), ==, 0x23456789);
+}
+
+static void test_output_enable(void)
+{
+    gpio_reset(0);
+
+    /*
+     * With all pins weakly pulled down, and DOUT all-ones, OE should be
+     * reflected on DIN.
+     */
+    writel(GPIO(0) + GP_N_DOUT, 0xffffffff);
+    writel(GPIO(0) + GP_N_PU, 0x00000000);
+    writel(GPIO(0) + GP_N_PD, 0xffffffff);
+    writel(GPIO(0) + GP_N_OE, 0x3456789a);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_OE), ==, 0x3456789a);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_DIN), ==, 0x3456789a);
+
+    writel(GPIO(0) + GP_N_OEC, 0x00030002);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_OE), ==, 0x34547898);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_DIN), ==, 0x34547898);
+
+    writel(GPIO(0) + GP_N_OES, 0x0000f001);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_OE), ==, 0x3454f899);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_DIN), ==, 0x3454f899);
+}
+
+static void test_open_drain(void)
+{
+    gpio_reset(0);
+
+    /*
+     * Upper half of DOUT drives a 1 only if the corresponding bit in OTYP is
+     * not set. If OTYP is set, DIN is determined by PU/PD. Lower half of
+     * DOUT always drives a 0 regardless of OTYP; PU/PD have no effect.  When
+     * OE is 0, output is determined by PU/PD; OTYP has no effect.
+     */
+    writel(GPIO(0) + GP_N_OTYP, 0x456789ab);
+    writel(GPIO(0) + GP_N_OE, 0xf0f0f0f0);
+    writel(GPIO(0) + GP_N_DOUT, 0xffff0000);
+    writel(GPIO(0) + GP_N_PU, 0xff00ff00);
+    writel(GPIO(0) + GP_N_PD, 0x00ff00ff);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_OTYP), ==, 0x456789ab);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_DIN), ==, 0xff900f00);
+}
+
+static void test_polarity(void)
+{
+    gpio_reset(0);
+
+    /*
+     * In push-pull mode, DIN should reflect DOUT because the signal is
+     * inverted in both directions.
+     */
+    writel(GPIO(0) + GP_N_OTYP, 0x00000000);
+    writel(GPIO(0) + GP_N_OE, 0xffffffff);
+    writel(GPIO(0) + GP_N_DOUT, 0x56789abc);
+    writel(GPIO(0) + GP_N_POL, 0x6789abcd);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_POL), ==, 0x6789abcd);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_DIN), ==, 0x56789abc);
+
+    /*
+     * When turning off the drivers, DIN should reflect the inverse of the
+     * pulled-up lines.
+     */
+    writel(GPIO(0) + GP_N_OE, 0x00000000);
+    writel(GPIO(0) + GP_N_POL, 0xffffffff);
+    writel(GPIO(0) + GP_N_PU, 0x789abcde);
+    writel(GPIO(0) + GP_N_PD, ~0x789abcdeU);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_DIN), ==, ~0x789abcdeU);
+
+    /*
+     * In open-drain mode, DOUT=1 will appear to drive the pin high (since DIN
+     * is inverted), while DOUT=0 will leave the pin floating.
+     */
+    writel(GPIO(0) + GP_N_OTYP, 0xffffffff);
+    writel(GPIO(0) + GP_N_OE, 0xffffffff);
+    writel(GPIO(0) + GP_N_PU, 0xffff0000);
+    writel(GPIO(0) + GP_N_PD, 0x0000ffff);
+    writel(GPIO(0) + GP_N_DOUT, 0xff00ff00);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_DIN), ==, 0xff00ffff);
+}
+
+static void test_input_mask(void)
+{
+    gpio_reset(0);
+
+    /* IEM=0 forces the input to zero before polarity inversion. */
+    writel(GPIO(0) + GP_N_OE, 0xffffffff);
+    writel(GPIO(0) + GP_N_DOUT, 0xff00ff00);
+    writel(GPIO(0) + GP_N_POL, 0xffff0000);
+    writel(GPIO(0) + GP_N_IEM, 0x87654321);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_DIN), ==, 0xff9a4300);
+}
+
+static void test_temp_lock(void)
+{
+    gpio_reset(0);
+
+    writel(GPIO(0) + GP_N_DOUT, 0x98765432);
+
+    /* Make sure we're unlocked initially. */
+    g_assert_cmphex(readl(GPIO(0) + GP_N_TLOCK1), ==, 0);
+    /* Writing any value to TLOCK1 will lock. */
+    writel(GPIO(0) + GP_N_TLOCK1, 0);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_TLOCK1), ==, 1);
+    writel(GPIO(0) + GP_N_DOUT, 0xa9876543);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_DOUT), ==, 0x98765432);
+    /* Now, try to unlock. */
+    gpio_unlock(0);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_TLOCK1), ==, 0);
+    writel(GPIO(0) + GP_N_DOUT, 0xa9876543);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_DOUT), ==, 0xa9876543);
+
+    /* Try it again, but write TLOCK2 to lock. */
+    writel(GPIO(0) + GP_N_TLOCK2, 0);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_TLOCK1), ==, 1);
+    writel(GPIO(0) + GP_N_DOUT, 0x98765432);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_DOUT), ==, 0xa9876543);
+    /* Now, try to unlock. */
+    gpio_unlock(0);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_TLOCK1), ==, 0);
+    writel(GPIO(0) + GP_N_DOUT, 0x98765432);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_DOUT), ==, 0x98765432);
+}
+
+static void test_events_level(void)
+{
+    gpio_reset(0);
+
+    writel(GPIO(0) + GP_N_EVTYP, 0x00000000);
+    writel(GPIO(0) + GP_N_DOUT, 0xba987654);
+    writel(GPIO(0) + GP_N_OE, 0xffffffff);
+    writel(GPIO(0) + GP_N_EVST, 0xffffffff);
+
+    g_assert_cmphex(readl(GPIO(0) + GP_N_EVST), ==, 0xba987654);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(0)));
+    writel(GPIO(0) + GP_N_DOUT, 0x00000000);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_EVST), ==, 0xba987654);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(0)));
+    writel(GPIO(0) + GP_N_EVST, 0x00007654);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_EVST), ==, 0xba980000);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(0)));
+    writel(GPIO(0) + GP_N_EVST, 0xba980000);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_EVST), ==, 0x00000000);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(0)));
+}
+
+static void test_events_rising_edge(void)
+{
+    gpio_reset(0);
+
+    writel(GPIO(0) + GP_N_EVTYP, 0xffffffff);
+    writel(GPIO(0) + GP_N_EVBE, 0x00000000);
+    writel(GPIO(0) + GP_N_DOUT, 0xffff0000);
+    writel(GPIO(0) + GP_N_OE, 0xffffffff);
+    writel(GPIO(0) + GP_N_EVST, 0xffffffff);
+
+    g_assert_cmphex(readl(GPIO(0) + GP_N_EVST), ==, 0x00000000);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(0)));
+    writel(GPIO(0) + GP_N_DOUT, 0xff00ff00);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_EVST), ==, 0x0000ff00);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(0)));
+    writel(GPIO(0) + GP_N_DOUT, 0x00ff0000);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_EVST), ==, 0x00ffff00);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(0)));
+    writel(GPIO(0) + GP_N_EVST, 0x0000f000);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_EVST), ==, 0x00ff0f00);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(0)));
+    writel(GPIO(0) + GP_N_EVST, 0x00ff0f00);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_EVST), ==, 0x00000000);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(0)));
+}
+
+static void test_events_both_edges(void)
+{
+    gpio_reset(0);
+
+    writel(GPIO(0) + GP_N_EVTYP, 0xffffffff);
+    writel(GPIO(0) + GP_N_EVBE, 0xffffffff);
+    writel(GPIO(0) + GP_N_DOUT, 0xffff0000);
+    writel(GPIO(0) + GP_N_OE, 0xffffffff);
+    writel(GPIO(0) + GP_N_EVST, 0xffffffff);
+
+    g_assert_cmphex(readl(GPIO(0) + GP_N_EVST), ==, 0x00000000);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(0)));
+    writel(GPIO(0) + GP_N_DOUT, 0xff00ff00);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_EVST), ==, 0x00ffff00);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(0)));
+    writel(GPIO(0) + GP_N_DOUT, 0xef00ff08);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_EVST), ==, 0x10ffff08);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(0)));
+    writel(GPIO(0) + GP_N_EVST, 0x0000f000);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_EVST), ==, 0x10ff0f08);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(0)));
+    writel(GPIO(0) + GP_N_EVST, 0x10ff0f08);
+    g_assert_cmphex(readl(GPIO(0) + GP_N_EVST), ==, 0x00000000);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(0)));
+}
+
+static void test_gpion_irq(gconstpointer test_data)
+{
+    intptr_t n = (intptr_t)test_data;
+
+    gpio_reset(n);
+
+    writel(GPIO(n) + GP_N_EVTYP, 0x00000000);
+    writel(GPIO(n) + GP_N_DOUT, 0x00000000);
+    writel(GPIO(n) + GP_N_OE, 0xffffffff);
+    writel(GPIO(n) + GP_N_EVST, 0xffffffff);
+    writel(GPIO(n) + GP_N_EVEN, 0x00000000);
+
+    /* Trigger an event; interrupts are masked. */
+    g_assert_cmphex(readl(GPIO(n) + GP_N_EVST), ==, 0x00000000);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(n)));
+    writel(GPIO(n) + GP_N_DOS, 0x00008000);
+    g_assert_cmphex(readl(GPIO(n) + GP_N_EVST), ==, 0x00008000);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(n)));
+
+    /* Unmask all event interrupts; verify that the interrupt fired. */
+    writel(GPIO(n) + GP_N_EVEN, 0xffffffff);
+    g_assert_true(qtest_get_irq(global_qtest, GPIO_IRQ(n)));
+
+    /* Clear the current bit, set a new bit, irq stays asserted. */
+    writel(GPIO(n) + GP_N_DOC, 0x00008000);
+    g_assert_true(qtest_get_irq(global_qtest, GPIO_IRQ(n)));
+    writel(GPIO(n) + GP_N_DOS, 0x00000200);
+    g_assert_true(qtest_get_irq(global_qtest, GPIO_IRQ(n)));
+    writel(GPIO(n) + GP_N_EVST, 0x00008000);
+    g_assert_true(qtest_get_irq(global_qtest, GPIO_IRQ(n)));
+
+    /* Mask/unmask the event that's currently active. */
+    writel(GPIO(n) + GP_N_EVENC, 0x00000200);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(n)));
+    writel(GPIO(n) + GP_N_EVENS, 0x00000200);
+    g_assert_true(qtest_get_irq(global_qtest, GPIO_IRQ(n)));
+
+    /* Clear the input and the status bit, irq is deasserted. */
+    writel(GPIO(n) + GP_N_DOC, 0x00000200);
+    g_assert_true(qtest_get_irq(global_qtest, GPIO_IRQ(n)));
+    writel(GPIO(n) + GP_N_EVST, 0x00000200);
+    g_assert_false(qtest_get_irq(global_qtest, GPIO_IRQ(n)));
+}
+
+int main(int argc, char **argv)
+{
+    int ret;
+    int i;
+
+    g_test_init(&argc, &argv, NULL);
+    g_test_set_nonfatal_assertions();
+
+    qtest_add_func("/npcm7xx_gpio/dout_to_din", test_dout_to_din);
+    qtest_add_func("/npcm7xx_gpio/pullup_pulldown", test_pullup_pulldown);
+    qtest_add_func("/npcm7xx_gpio/output_enable", test_output_enable);
+    qtest_add_func("/npcm7xx_gpio/open_drain", test_open_drain);
+    qtest_add_func("/npcm7xx_gpio/polarity", test_polarity);
+    qtest_add_func("/npcm7xx_gpio/input_mask", test_input_mask);
+    qtest_add_func("/npcm7xx_gpio/temp_lock", test_temp_lock);
+    qtest_add_func("/npcm7xx_gpio/events/level", test_events_level);
+    qtest_add_func("/npcm7xx_gpio/events/rising_edge", test_events_rising_edge);
+    qtest_add_func("/npcm7xx_gpio/events/both_edges", test_events_both_edges);
+
+    for (i = 0; i < NR_GPIO_DEVICES; i++) {
+        g_autofree char *test_name =
+            g_strdup_printf("/npcm7xx_gpio/gpio[%d]/irq", i);
+        qtest_add_data_func(test_name, (void *)(intptr_t)i, test_gpion_irq);
+    }
+
+    qtest_start("-machine npcm750-evb");
+    qtest_irq_intercept_in(global_qtest, "/machine/soc/a9mpcore/gic");
+    ret = g_test_run();
+    qtest_end();
+
+    return ret;
+}
diff --git a/hw/gpio/meson.build b/hw/gpio/meson.build
index 86cae9a0f3..5c0a7d7b95 100644
--- a/hw/gpio/meson.build
+++ b/hw/gpio/meson.build
@@ -6,6 +6,7 @@ softmmu_ss.add(when: 'CONFIG_PUV3', if_true: files('puv3_gpio.c'))
 softmmu_ss.add(when: 'CONFIG_ZAURUS', if_true: files('zaurus.c'))
 
 softmmu_ss.add(when: 'CONFIG_IMX', if_true: files('imx_gpio.c'))
+softmmu_ss.add(when: 'CONFIG_NPCM7XX', if_true: files('npcm7xx_gpio.c'))
 softmmu_ss.add(when: 'CONFIG_NRF51_SOC', if_true: files('nrf51_gpio.c'))
 softmmu_ss.add(when: 'CONFIG_OMAP', if_true: files('omap_gpio.c'))
 softmmu_ss.add(when: 'CONFIG_RASPI', if_true: files('bcm2835_gpio.c'))
diff --git a/hw/gpio/trace-events b/hw/gpio/trace-events
index 6e3f048745..46ab9323bd 100644
--- a/hw/gpio/trace-events
+++ b/hw/gpio/trace-events
@@ -1,5 +1,12 @@
 # See docs/devel/tracing.txt for syntax documentation.
 
+# npcm7xx_gpio.c
+npcm7xx_gpio_read(const char *id, uint64_t offset, uint64_t value) " %s offset: 0x%04" PRIx64 " value 0x%08" PRIx64
+npcm7xx_gpio_write(const char *id, uint64_t offset, uint64_t value) "%s offset: 0x%04" PRIx64 " value 0x%08" PRIx64
+npcm7xx_gpio_set_input(const char *id, int32_t line, int32_t level) "%s line: %" PRIi32 " level: %" PRIi32
+npcm7xx_gpio_set_output(const char *id, int32_t line, int32_t level) "%s line: %" PRIi32 " level: %" PRIi32
+npcm7xx_gpio_update_events(const char *id, uint32_t evst, uint32_t even) "%s evst: 0x%08" PRIx32 " even: 0x%08" PRIx32
+
 # nrf51_gpio.c
 nrf51_gpio_read(uint64_t offset, uint64_t r) "offset 0x%" PRIx64 " value 0x%" PRIx64
 nrf51_gpio_write(uint64_t offset, uint64_t value) "offset 0x%" PRIx64 " value 0x%" PRIx64
diff --git a/tests/qtest/meson.build b/tests/qtest/meson.build
index 76db8f9d84..1cc0f18249 100644
--- a/tests/qtest/meson.build
+++ b/tests/qtest/meson.build
@@ -134,7 +134,8 @@ qtests_sparc64 = \
   ['prom-env-test', 'boot-serial-test']
 
 qtests_npcm7xx = \
-  ['npcm7xx_rng-test',
+  ['npcm7xx_gpio-test',
+   'npcm7xx_rng-test',
    'npcm7xx_timer-test',
    'npcm7xx_watchdog_timer-test']
 qtests_arm = \
-- 
2.29.0.rc1.297.gfa9743e501-goog



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* Re: [PATCH v3 1/6] tests/qtest: Make npcm7xx_timer-test conditional on CONFIG_NPCM7XX
  2020-10-23 21:06 ` [PATCH v3 1/6] tests/qtest: Make npcm7xx_timer-test conditional on CONFIG_NPCM7XX Havard Skinnemoen via
@ 2020-10-24  5:26   ` Thomas Huth
  0 siblings, 0 replies; 15+ messages in thread
From: Thomas Huth @ 2020-10-24  5:26 UTC (permalink / raw)
  To: Havard Skinnemoen, peter.maydell
  Cc: venture, qemu-devel, wuhaotsh, kfting, qemu-arm, Avi.Fishman

On 23/10/2020 23.06, Havard Skinnemoen wrote:
> This test won't work if qemu was compiled without CONFIG_NPCM7XX, as
> pointed out by Thomas Huth on a different patch.
> 
> Signed-off-by: Havard Skinnemoen <hskinnemoen@google.com>
> ---
>  tests/qtest/meson.build | 3 ++-
>  1 file changed, 2 insertions(+), 1 deletion(-)
> 
> diff --git a/tests/qtest/meson.build b/tests/qtest/meson.build
> index 28d4068718..7e0ecaa2c5 100644
> --- a/tests/qtest/meson.build
> +++ b/tests/qtest/meson.build
> @@ -133,12 +133,13 @@ qtests_sparc64 = \
>    (config_all_devices.has_key('CONFIG_ISA_TESTDEV') ? ['endianness-test'] : []) +            \
>    ['prom-env-test', 'boot-serial-test']
>  
> +qtests_npcm7xx = ['npcm7xx_timer-test']
>  qtests_arm = \
>    (config_all_devices.has_key('CONFIG_PFLASH_CFI02') ? ['pflash-cfi02-test'] : []) +         \
> +  (config_all_devices.has_key('CONFIG_NPCM7XX') ? qtests_npcm7xx : []) + \
>    ['arm-cpu-features',
>     'microbit-test',
>     'm25p80-test',
> -   'npcm7xx_timer-test',
>     'test-arm-mptimer',
>     'boot-serial-test',
>     'hexloader-test']
> 

Reviewed-by: Thomas Huth <thuth@redhat.com>



^ permalink raw reply	[flat|nested] 15+ messages in thread

* Re: [PATCH v3 0/6] Additional NPCM7xx features, devices and tests
  2020-10-23 21:06 [PATCH v3 0/6] Additional NPCM7xx features, devices and tests Havard Skinnemoen via
                   ` (5 preceding siblings ...)
  2020-10-23 21:06 ` [PATCH v3 6/6] hw/gpio: Add GPIO model for Nuvoton NPCM7xx Havard Skinnemoen via
@ 2020-10-26 17:15 ` Peter Maydell
  6 siblings, 0 replies; 15+ messages in thread
From: Peter Maydell @ 2020-10-26 17:15 UTC (permalink / raw)
  To: Havard Skinnemoen
  Cc: Thomas Huth, venture, QEMU Developers, Hao Wu, CS20 KFTing,
	qemu-arm, IS20 Avi Fishman

On Fri, 23 Oct 2020 at 22:06, Havard Skinnemoen <hskinnemoen@google.com> wrote:
>
> This is an update to the initial NPCM7xx patch series adding
>
>   - Watchdog timer support. This makes the reboot command work.
>   - Random Number Generator device.
>   - USB Host Controllers.
>   - GPIO Controllers.
>
> The watchdog was implemented by my new teammate Hao Wu. Expect to see more
> patches from him in the near future.
>
> This series has also been pushed to the npcm7xx-5.2-update branch of my github
> repository at
>
>   https://github.com/hskinnemoen/qemu



Applied to target-arm.next, thanks. (I fixed a stray blank line at
the end of npcm_watchdog_timer-test.c because 'git am' happened
to complain about it.)

-- PMM


^ permalink raw reply	[flat|nested] 15+ messages in thread

* Re: [PATCH v3 4/6] hw/misc: Add npcm7xx random number generator
  2020-10-23 21:06 ` [PATCH v3 4/6] hw/misc: Add npcm7xx random number generator Havard Skinnemoen via
@ 2020-10-30 13:34   ` Peter Maydell
  2020-10-30 15:43     ` Havard Skinnemoen
  2020-11-02 11:36   ` Peter Maydell
  1 sibling, 1 reply; 15+ messages in thread
From: Peter Maydell @ 2020-10-30 13:34 UTC (permalink / raw)
  To: Havard Skinnemoen
  Cc: Thomas Huth, Patrick Venture, QEMU Developers, Hao Wu,
	CS20 KFTing, qemu-arm, IS20 Avi Fishman

On Fri, 23 Oct 2020 at 22:06, Havard Skinnemoen <hskinnemoen@google.com> wrote:
>
> The RNG module returns a byte of randomness when the Data Valid bit is
> set.
>
> This implementation ignores the prescaler setting, and loads a new value
> into RNGD every time RNGCS is read while the RNG is enabled and random
> data is available.
>
> A qtest featuring some simple randomness tests is included.
>
> Reviewed-by: Tyrone Ting <kfting@nuvoton.com>
> Reviewed-by: Peter Maydell <peter.maydell@linaro.org>
> Signed-off-by: Havard Skinnemoen <hskinnemoen@google.com>

I've just seen some intermittent failures on the rng tests
in this patch:

PASS 1 qtest-arm/npcm7xx_rng-test /arm/npcm7xx_rng/enable_disable
PASS 2 qtest-arm/npcm7xx_rng-test /arm/npcm7xx_rng/rosel
**
ERROR:../../tests/qtest/npcm7xx_rng-test.c:190:test_continuous_monobit:
assertion failed (calc_monobit_p(buf, sizeof(buf)) > 0.01):
(0.00800994233 > 0.01)

(on OSX)

and (on x86-64 Linux):

MALLOC_PERTURB_=${MALLOC_PERTURB_:-$(( ${RANDOM:-0} % 255 + 1))}
QTEST_QEMU_IMG=./qemu-img G_TEST_DBUS_DAEMON=/home/petmay01/li
naro/qemu-for-merges/tests/dbus-vmstate-daemon.sh
QTEST_QEMU_BINARY=./qemu-system-arm tests/qtest/npcm7xx_rng-test --tap
-k
PASS 1 qtest-arm/npcm7xx_rng-test /arm/npcm7xx_rng/enable_disable
PASS 2 qtest-arm/npcm7xx_rng-test /arm/npcm7xx_rng/rosel
PASS 3 qtest-arm/npcm7xx_rng-test /arm/npcm7xx_rng/continuous/monobit
**
ERROR:../../tests/qtest/npcm7xx_rng-test.c:211:test_continuous_runs:
assertion failed (calc_runs_p(buf.l, sizeof(buf) * BITS_PER_BYTE) >
0.01): (0.00198053202 > 0.01)


Are these just "we got a bit unlucky in the values we got from
the RNG" ?

If so, we probably need to disable these tests from the set
that we run in "make check" -- we can't really have "there's
a non-zero chance that the test fails" tests in our CI loop...

thanks
-- PMM


^ permalink raw reply	[flat|nested] 15+ messages in thread

* Re: [PATCH v3 4/6] hw/misc: Add npcm7xx random number generator
  2020-10-30 13:34   ` Peter Maydell
@ 2020-10-30 15:43     ` Havard Skinnemoen
  0 siblings, 0 replies; 15+ messages in thread
From: Havard Skinnemoen @ 2020-10-30 15:43 UTC (permalink / raw)
  To: Peter Maydell
  Cc: qemu-arm, QEMU Developers, IS20 Avi Fishman, CS20 KFTing,
	Patrick Venture, Hao Wu, Thomas Huth

On Fri, Oct 30, 2020 at 6:34 AM Peter Maydell <peter.maydell@linaro.org> wrote:
>
> On Fri, 23 Oct 2020 at 22:06, Havard Skinnemoen <hskinnemoen@google.com> wrote:
> >
> > The RNG module returns a byte of randomness when the Data Valid bit is
> > set.
> >
> > This implementation ignores the prescaler setting, and loads a new value
> > into RNGD every time RNGCS is read while the RNG is enabled and random
> > data is available.
> >
> > A qtest featuring some simple randomness tests is included.
> >
> > Reviewed-by: Tyrone Ting <kfting@nuvoton.com>
> > Reviewed-by: Peter Maydell <peter.maydell@linaro.org>
> > Signed-off-by: Havard Skinnemoen <hskinnemoen@google.com>
>
> I've just seen some intermittent failures on the rng tests
> in this patch:
>
> PASS 1 qtest-arm/npcm7xx_rng-test /arm/npcm7xx_rng/enable_disable
> PASS 2 qtest-arm/npcm7xx_rng-test /arm/npcm7xx_rng/rosel
> **
> ERROR:../../tests/qtest/npcm7xx_rng-test.c:190:test_continuous_monobit:
> assertion failed (calc_monobit_p(buf, sizeof(buf)) > 0.01):
> (0.00800994233 > 0.01)
>
> (on OSX)
>
> and (on x86-64 Linux):
>
> MALLOC_PERTURB_=${MALLOC_PERTURB_:-$(( ${RANDOM:-0} % 255 + 1))}
> QTEST_QEMU_IMG=./qemu-img G_TEST_DBUS_DAEMON=/home/petmay01/li
> naro/qemu-for-merges/tests/dbus-vmstate-daemon.sh
> QTEST_QEMU_BINARY=./qemu-system-arm tests/qtest/npcm7xx_rng-test --tap
> -k
> PASS 1 qtest-arm/npcm7xx_rng-test /arm/npcm7xx_rng/enable_disable
> PASS 2 qtest-arm/npcm7xx_rng-test /arm/npcm7xx_rng/rosel
> PASS 3 qtest-arm/npcm7xx_rng-test /arm/npcm7xx_rng/continuous/monobit
> **
> ERROR:../../tests/qtest/npcm7xx_rng-test.c:211:test_continuous_runs:
> assertion failed (calc_runs_p(buf.l, sizeof(buf) * BITS_PER_BYTE) >
> 0.01): (0.00198053202 > 0.01)
>
>
> Are these just "we got a bit unlucky in the values we got from
> the RNG" ?

Yes, it looks like the randomness is a little low.

> If so, we probably need to disable these tests from the set
> that we run in "make check" -- we can't really have "there's
> a non-zero chance that the test fails" tests in our CI loop...

Agree. Is there a way to disable the test by default, or should I send
a patch to remove it?

Havard


^ permalink raw reply	[flat|nested] 15+ messages in thread

* Re: [PATCH v3 4/6] hw/misc: Add npcm7xx random number generator
  2020-10-23 21:06 ` [PATCH v3 4/6] hw/misc: Add npcm7xx random number generator Havard Skinnemoen via
  2020-10-30 13:34   ` Peter Maydell
@ 2020-11-02 11:36   ` Peter Maydell
  2020-11-02 16:50     ` Havard Skinnemoen
  1 sibling, 1 reply; 15+ messages in thread
From: Peter Maydell @ 2020-11-02 11:36 UTC (permalink / raw)
  To: Havard Skinnemoen
  Cc: Thomas Huth, Patrick Venture, QEMU Developers, Hao Wu,
	CS20 KFTing, qemu-arm, IS20 Avi Fishman

On Fri, 23 Oct 2020 at 22:06, Havard Skinnemoen <hskinnemoen@google.com> wrote:
>
> The RNG module returns a byte of randomness when the Data Valid bit is
> set.
>
> This implementation ignores the prescaler setting, and loads a new value
> into RNGD every time RNGCS is read while the RNG is enabled and random
> data is available.
>
> A qtest featuring some simple randomness tests is included.

> +int main(int argc, char **argv)
> +{
> +    int ret;
> +
> +    g_test_init(&argc, &argv, NULL);
> +    g_test_set_nonfatal_assertions();

While I was looking at this test case I noticed that it
calls g_test_set_nonfatal_assertions(). Why does it do that?
In our entire set of tests, only the npcm7xx test cases call
that function, and they don't explain why they're a special
case that needs to do so.

thanks
-- PMM


^ permalink raw reply	[flat|nested] 15+ messages in thread

* Re: [PATCH v3 4/6] hw/misc: Add npcm7xx random number generator
  2020-11-02 11:36   ` Peter Maydell
@ 2020-11-02 16:50     ` Havard Skinnemoen
  2020-11-02 17:13       ` Peter Maydell
  0 siblings, 1 reply; 15+ messages in thread
From: Havard Skinnemoen @ 2020-11-02 16:50 UTC (permalink / raw)
  To: Peter Maydell
  Cc: qemu-arm, QEMU Developers, IS20 Avi Fishman, CS20 KFTing,
	Patrick Venture, Hao Wu, Thomas Huth

On Mon, Nov 2, 2020 at 3:36 AM Peter Maydell <peter.maydell@linaro.org> wrote:
>
> On Fri, 23 Oct 2020 at 22:06, Havard Skinnemoen <hskinnemoen@google.com> wrote:
> >
> > The RNG module returns a byte of randomness when the Data Valid bit is
> > set.
> >
> > This implementation ignores the prescaler setting, and loads a new value
> > into RNGD every time RNGCS is read while the RNG is enabled and random
> > data is available.
> >
> > A qtest featuring some simple randomness tests is included.
>
> > +int main(int argc, char **argv)
> > +{
> > +    int ret;
> > +
> > +    g_test_init(&argc, &argv, NULL);
> > +    g_test_set_nonfatal_assertions();
>
> While I was looking at this test case I noticed that it
> calls g_test_set_nonfatal_assertions(). Why does it do that?
> In our entire set of tests, only the npcm7xx test cases call
> that function, and they don't explain why they're a special
> case that needs to do so.

It's often useful to see more than the first failure when debugging
tests. Using the randomness flakiness as an example, it's very useful
to know if more than just one of the randomness tests fail. If I
remove g_test_set_nonfatal_assertions, I get:

**
ERROR:../../../tests/qtest/npcm7xx_rng-test.c:256:test_first_byte_runs:
assertion failed (calc_runs_p(buf.l, sizeof(buf) * BITS_PER_BYTE) >
0.01): (0.00204666737 > 0.01)
Bail out! ERROR:../../../tests/qtest/npcm7xx_rng-test.c:256:test_first_byte_runs:
assertion failed (calc_runs_p(buf.l, sizeof(buf) * BITS_PER_BYTE) >
0.01): (0.00204666737 > 0.01)
Aborted

which doesn't even tell me the name of the test that failed, let alone
anything about whether any subsequent tests passed.

Also note that it doesn't provide a clear "not ok" signal, which makes
life difficult for any downstream processing of the TAP output. It
looks like the test unexpectedly crashed.

Compare this to the output with g_test_set_nonfatal_assertions:

**
ERROR:../../../tests/qtest/npcm7xx_rng-test.c:232:test_first_byte_monobit:
assertion failed (calc_monobit_p(buf, sizeof(buf)) > 0.01):
(4.78548397e-05 > 0.01)
# ERROR:../../../tests/qtest/npcm7xx_rng-test.c:232:test_first_byte_monobit:
assertion failed (calc_monobit_p(buf, sizeof(buf)) > 0.01):
(4.78548397e-05 > 0.01)
not ok 5 /arm/npcm7xx_rng/first_byte/monobit
ok 6 /arm/npcm7xx_rng/first_byte/runs

which clearly shows that the "first_byte/monobit" test failed, and the
subsequent "first_byte/runs" test passed.

But none of this is really specific to the RNG test, so I can remove
it if you prefer for consistency.

Havard


^ permalink raw reply	[flat|nested] 15+ messages in thread

* Re: [PATCH v3 4/6] hw/misc: Add npcm7xx random number generator
  2020-11-02 16:50     ` Havard Skinnemoen
@ 2020-11-02 17:13       ` Peter Maydell
  2020-11-02 18:21         ` Havard Skinnemoen
  0 siblings, 1 reply; 15+ messages in thread
From: Peter Maydell @ 2020-11-02 17:13 UTC (permalink / raw)
  To: Havard Skinnemoen
  Cc: Thomas Huth, Patrick Venture, QEMU Developers, Hao Wu,
	CS20 KFTing, qemu-arm, IS20 Avi Fishman

On Mon, 2 Nov 2020 at 16:50, Havard Skinnemoen <hskinnemoen@google.com> wrote:
> But none of this is really specific to the RNG test, so I can remove
> it if you prefer for consistency.

I would prefer us to be consistent. If you want to propose
don't-stop-on-asserts then we should set that consistently
at some higher level of the test suite, not in every
individual test.

thanks
-- PMM


^ permalink raw reply	[flat|nested] 15+ messages in thread

* Re: [PATCH v3 4/6] hw/misc: Add npcm7xx random number generator
  2020-11-02 17:13       ` Peter Maydell
@ 2020-11-02 18:21         ` Havard Skinnemoen
  0 siblings, 0 replies; 15+ messages in thread
From: Havard Skinnemoen @ 2020-11-02 18:21 UTC (permalink / raw)
  To: Peter Maydell
  Cc: qemu-arm, QEMU Developers, IS20 Avi Fishman, CS20 KFTing,
	Patrick Venture, Hao Wu, Thomas Huth

On Mon, Nov 2, 2020 at 9:14 AM Peter Maydell <peter.maydell@linaro.org> wrote:
>
> On Mon, 2 Nov 2020 at 16:50, Havard Skinnemoen <hskinnemoen@google.com> wrote:
> > But none of this is really specific to the RNG test, so I can remove
> > it if you prefer for consistency.
>
> I would prefer us to be consistent. If you want to propose
> don't-stop-on-asserts then we should set that consistently
> at some higher level of the test suite, not in every
> individual test.

OK, I will remove g_test_set_nonfatal_assertions from all the tests
I've submitted.

As for the randomness failures, I did find a bug in the runs test, but
fixing it doesn't make much of an impact on the flakiness.

I've seen failures from both monobit and runs, both first_bit and
continuous. So it doesn't look like there's a systemic problem
anywhere.

I dumped the random data on failure and put it through the
https://github.com/Honno/coinflip/ implementation of monobit and runs,
and after fixing the runs bug, they consistently produce the same P
value. Here's one example that failed the qtest with P=0.000180106965:

$ ./randomness_test.py e1 ec cc 55  29 5d c9 ac  85 45 ed 4b  b6 96 56 ab
Monobit test:
normalised diff  0.53
p-value          0.596
┌───────┬───────┐
│ value │ count │
├───────┼───────┤
│ 1     │    67 │
│ 0     │    61 │
└───────┴───────┘

Runs test:
no. of runs  85
p-value       0.0

You can find the script at
https://gist.github.com/hskinnemoen/41f7513ca228c2bac959c3b14e87025f

Apparently, successive bits are toggling too often, producing too many
runs of 1s or 0s. This will of course happen from time to time since
the input is random. And the monobit test will fail if there are too
many or too few 1s compared to zeroes, which is also something that
can't really be prevented.

While we can always tune this to happen less often, e.g. by dropping
the P-value threshold or running the tests multiple times, we can
never guarantee that a randomness test won't fail. So I suspect we
should keep these tests disabled by default, but keep them available
so that we can easily do a randomness test if there's any suspicion
that the emulated RNG device produces bad data. Does that make sense?

Havard


^ permalink raw reply	[flat|nested] 15+ messages in thread

end of thread, other threads:[~2020-11-02 18:23 UTC | newest]

Thread overview: 15+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2020-10-23 21:06 [PATCH v3 0/6] Additional NPCM7xx features, devices and tests Havard Skinnemoen via
2020-10-23 21:06 ` [PATCH v3 1/6] tests/qtest: Make npcm7xx_timer-test conditional on CONFIG_NPCM7XX Havard Skinnemoen via
2020-10-24  5:26   ` Thomas Huth
2020-10-23 21:06 ` [PATCH v3 2/6] Move npcm7xx_timer_reached_zero call out of npcm7xx_timer_pause Havard Skinnemoen via
2020-10-23 21:06 ` [PATCH v3 3/6] hw/timer: Adding watchdog for NPCM7XX Timer Havard Skinnemoen via
2020-10-23 21:06 ` [PATCH v3 4/6] hw/misc: Add npcm7xx random number generator Havard Skinnemoen via
2020-10-30 13:34   ` Peter Maydell
2020-10-30 15:43     ` Havard Skinnemoen
2020-11-02 11:36   ` Peter Maydell
2020-11-02 16:50     ` Havard Skinnemoen
2020-11-02 17:13       ` Peter Maydell
2020-11-02 18:21         ` Havard Skinnemoen
2020-10-23 21:06 ` [PATCH v3 5/6] hw/arm/npcm7xx: Add EHCI and OHCI controllers Havard Skinnemoen via
2020-10-23 21:06 ` [PATCH v3 6/6] hw/gpio: Add GPIO model for Nuvoton NPCM7xx Havard Skinnemoen via
2020-10-26 17:15 ` [PATCH v3 0/6] Additional NPCM7xx features, devices and tests Peter Maydell

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.