repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
cheriot-rtos | github_2023 | cpp | 473 | CHERIoT-Platform | nwf | @@ -67,10 +67,14 @@ __always_inline static int futex_wait(const uint32_t *address,
* Wakes up to `count` threads that are sleeping with `futex[_timed]_wait` on
* `address`.
*
- * The `address` argument must permit storing four bytes of data after the
- * address. This call does not store to the address but requiring store
- * permission prevents a thread from waking up a futex that it cannot possibly
- * have moved to a different state.
+ * The `address` argument must have a length of at least four after the address | May be worth more fully enumerating what `check_pointer` is going to ask for: valid, unsealed, and length >= 4. |
cheriot-rtos | github_2023 | cpp | 481 | CHERIoT-Platform | rmn30 | @@ -77,11 +77,23 @@ compartment_error_handler(struct ErrorState *frame, size_t mcause, size_t mtval)
return ErrorRecoveryBehaviour::InstallContext;
}
+__attribute__((noinline, weak)) void *pcc_as_sentry()
+{
+ return __builtin_return_address(0);
+}
+
/**
* Test suite entry point. Runs all of the tests that we have defined.
*/
+[[cheriot::interrupt_state(disabled)]]
int __cheri_compartment("test_runner") run_tests()
{
+ // This is started as an interrupts-disabled thread, make sure that it really is!
+ Capability sealedPCC = pcc_as_sentry();
+ TEST((sealedPCC.type() == CheriSealTypeReturnSentryDisabling) ||
+ (sealedPCC.type() == CheriSealTypeSentryDisabling), | Shouldn't it always be a return sentry? Why do you need the `||`? |
cheriot-rtos | github_2023 | cpp | 481 | CHERIoT-Platform | rmn30 | @@ -77,11 +77,23 @@ compartment_error_handler(struct ErrorState *frame, size_t mcause, size_t mtval)
return ErrorRecoveryBehaviour::InstallContext;
}
+__attribute__((noinline, weak)) void *pcc_as_sentry()
+{
+ return __builtin_return_address(0);
+}
+
/**
* Test suite entry point. Runs all of the tests that we have defined.
*/
+[[cheriot::interrupt_state(disabled)]] | This will only apply to the top level test runner, right? All the tests that run in compartments will default to interrupts enabled? |
cheriot-rtos | github_2023 | cpp | 462 | CHERIoT-Platform | rmn30 | @@ -25,11 +25,8 @@ struct CleanupList
*/
__always_inline static inline struct CleanupList **cleanup_list_head()
{
- void *csp = __builtin_cheri_stack_get();
- ptraddr_t top = __builtin_cheri_top_get(csp);
- csp = __builtin_cheri_address_set(
- csp, top - INVOCATION_LOCAL_UNWIND_LIST_OFFSET);
- return (struct CleanupList **)csp;
+ return (struct CleanupList **)invocation_state_slot(
+ INVOCATION_LOCAL_UNWIND_LIST_OFFSET / sizeof(void *) - 1); | This seems like a very convoluted way of spelling `0`. I had to look up the definitions of both `invocation_state_slot` and `INVOCATION_LOCAL_UNWIND_LIST_OFFSET` to figure out what's going on. Maybe hide it in a macro `INVOCATION_LOCAL_UNWIND_SLOT` with a suitable comment? |
cheriot-rtos | github_2023 | others | 462 | CHERIoT-Platform | davidchisnall | @@ -1407,7 +1407,7 @@ namespace CHERI
};
/**
- * Register numbers as reported in cap idx field of `mtval` CSR when
+ * Register numbers as reported in cap idx field of `mtval` CSR when | ```suggestion
* Register numbers as reported in the cap idx field of `mtval` CSR when
``` |
cheriot-rtos | github_2023 | cpp | 474 | CHERIoT-Platform | rmn30 | @@ -363,5 +368,10 @@ int test_misc()
4,
{Permission::Global, Permission::Load});
check_odd_memcmp();
+ TEST_EQUAL(
+ strnlen(*volatileString, 3), 3, "Incorrect length from short strnlen");
+ TEST_EQUAL(strnlen(*volatileString, SIZE_MAX),
+ 11,
+ "Incorrect length from short strnlen"); | ```suggestion
"Incorrect length from SIZE_MAX strnlen");
``` |
cheriot-rtos | github_2023 | cpp | 464 | CHERIoT-Platform | nwf | @@ -238,4 +238,18 @@ __always_inline T *token_unseal(SKey key, Sealed<T> sealed)
{
return static_cast<T *>(token_obj_unseal(key, sealed));
}
+
#endif // __cplusplus
+
+#if __has_extension(cheri_sealed_pointers)
+# ifdef __cplusplus
+template<typename T>
+__always_inline T *token_unseal(SKey key, T *__sealed_capability sealed)
+{
+ return static_cast<T *>(token_obj_unseal(key, sealed));
+}
+# else
+# define token_unseal(key, sealed) /*NOLINT*/ \ | Why won't this clash with the `token_unseal` function above, since its `T` is inferrable and so its invocations can be spelled without wakas before parens? |
cheriot-rtos | github_2023 | cpp | 414 | CHERIoT-Platform | nwf | @@ -73,7 +73,7 @@ namespace
{
assert(high == LockBit);
high = 0;
- futex_wake(&high, std::numeric_limits<uint32_t>::max());
+ (void)futex_wake(&high, std::numeric_limits<uint32_t>::max()); | This is https://github.com/CHERIoT-Platform/cheriot-rtos/pull/404 |
cheriot-rtos | github_2023 | cpp | 414 | CHERIoT-Platform | nwf | @@ -2,18 +2,20 @@
// SPDX-License-Identifier: MIT
#include "hello.h"
+#include <debug.hh>
#include <fail-simulator-on-error.h>
/// Thread entry point.
-void __cheri_compartment("hello") entry()
+int __cheri_compartment("hello") entry()
{
// Try writing a string with a missing null terminator
char maliciousString[] = {'h', 'e', 'l', 'l', 'o'};
- write(maliciousString);
+ (void)write(maliciousString); | Should this check for `ECOMPARTMENTFAIL`? |
cheriot-rtos | github_2023 | cpp | 414 | CHERIoT-Platform | nwf | @@ -34,7 +35,10 @@ void __cheri_compartment("allocbench") run()
auto quota = heap_quota_remaining(MALLOC_CAPABILITY);
Debug::Invariant(quota == MALLOC_QUOTA, "Quota remaining {}, should be {}", quota, MALLOC_QUOTA);
Debug::log("Flushing quarantine");
- heap_quarantine_empty();
+ Debug::Invariant(heap_quarantine_empty() >= 0, | I think in _benchmark_ code, these might want to be `Debug::Assert`, so that they compile away in release mode when we're measuring cycles? |
cheriot-rtos | github_2023 | cpp | 414 | CHERIoT-Platform | nwf | @@ -34,7 +35,10 @@ void __cheri_compartment("allocbench") run()
auto quota = heap_quota_remaining(MALLOC_CAPABILITY);
Debug::Invariant(quota == MALLOC_QUOTA, "Quota remaining {}, should be {}", quota, MALLOC_QUOTA);
Debug::log("Flushing quarantine");
- heap_quarantine_empty();
+ Debug::Invariant(heap_quarantine_empty() >= 0,
+ "Unable to call heap_quarantine_empty"); | Hm. I worry that "Unable to call" is potentially misleading... In many cases, the callees indeed cannot fail, so it's accurate, but in the case where they _can_ fail? |
cheriot-rtos | github_2023 | cpp | 414 | CHERIoT-Platform | rmn30 | @@ -9,12 +9,13 @@ using Debug = ConditionalDebug<DEBUG_ALLOCBENCH, "Allocator benchmark">;
* Try allocating 1 MiB of memory in allocation sizes ranging from 32 - 4096
* bytes, report how long it takes.
*/
-void __cheri_compartment("allocbench") run()
+int __cheri_compartment("allocbench") run()
{
// Make sure sail doesn't print annoying log messages in the middle of the
// output the first time that allocation happens.
free(malloc(16));
- heap_quarantine_empty();
+ Debug::Invariant(heap_quarantine_empty() != -ECOMPARTMENTFAIL, | ```suggestion
Debug::Invariant(heap_quarantine_empty() == 0,
```
This invariant is not strong enough as, according to the comment on `heap_quarantine_empty`, other failures such as `ENOTENOUGHSTACK` and `ENOTENOUGHTRUSTEDSTACK` are possible. This applies to all other calls to this and perhaps other compartment calls? |
cheriot-rtos | github_2023 | cpp | 414 | CHERIoT-Platform | rmn30 | @@ -271,7 +272,8 @@ namespace
* failure we see below isn't because we aren't allowing the revocation
* state machine to advance.
*/
- heap_quarantine_empty();
+ TEST(heap_quarantine_empty() != -ECOMPARTMENTFAIL,
+ "Compartment call to heap_quarantine_empty failed"); | ```suggestion
TEST_EQUAL(heap_quarantine_empty(), 0, "Compartment call to heap_quarantine_empty failed");
```
As per previous comment but in the test suite we have this handy macro. |
cheriot-rtos | github_2023 | cpp | 448 | CHERIoT-Platform | davidchisnall | @@ -94,7 +94,7 @@ using _Bool = bool;
* other places) to avoid the namespace pollution from including `string.h` but
* is either constant folded in the front end or expanded to a libcall.
*/
-unsigned __builtin_strlen(const char *str) __asm__("_Z6strlenPKc");
+unsigned __builtin_strlen(const char *str); | I believe you can remove this declaration entirely. Without it, clang will use the built-in definition. |
cheriot-rtos | github_2023 | cpp | 448 | CHERIoT-Platform | davidchisnall | @@ -6,27 +6,37 @@
#include <stddef.h>
#include <stdint.h>
-int __cheri_libcall memcmp(const void *str1,
- const void *str2,
- size_t count) __asm__("memcmp");
-void *__cheri_libcall memcpy(void *dest,
- const void *src,
- size_t n) __asm__("memcpy");
-void *__cheri_libcall memset(void *, int, size_t) __asm__("memset");
-void *__cheri_libcall memmove(void *dest,
- const void *src,
- size_t n) __asm__("memmove");
-void *__cheri_libcall memchr(const void *, int, size_t);
-void *__cheri_libcall memrchr(const void *, int, size_t);
-size_t __cheri_libcall strlen(const char *str);
-int __cheri_libcall strncmp(const char *s1, const char *s2, size_t n);
-char *__cheri_libcall strncpy(char *dest, const char *src, size_t n);
-int __cheri_libcall strcmp(const char *s1, const char *s2);
-char *__cheri_libcall strnstr(const char *haystack,
- const char *needle,
- size_t haystackLength);
-char *__cheri_libcall strchr(const char *s, int c);
-size_t __cheri_libcall strlcpy(char *dest, const char *src, size_t n);
+#define DECLARE_STRING_LIBCALL(rtype, name, ...) \ | It would be good to have a comment here for what this is doing (declaring libcall functions with unmangled names) and why it exists (to permit compiler optimisations).
Minor naming nit, but are all of the things where we care about compiler libcalls optimisations string functions? If not, we should maybe call this `DECLARE_STANDARD_LIBCALL` or similar. |
cheriot-rtos | github_2023 | cpp | 448 | CHERIoT-Platform | davidchisnall | @@ -6,27 +6,37 @@
#include <stddef.h>
#include <stdint.h>
-int __cheri_libcall memcmp(const void *str1,
- const void *str2,
- size_t count) __asm__("memcmp");
-void *__cheri_libcall memcpy(void *dest,
- const void *src,
- size_t n) __asm__("memcpy");
-void *__cheri_libcall memset(void *, int, size_t) __asm__("memset");
-void *__cheri_libcall memmove(void *dest,
- const void *src,
- size_t n) __asm__("memmove");
-void *__cheri_libcall memchr(const void *, int, size_t);
-void *__cheri_libcall memrchr(const void *, int, size_t);
-size_t __cheri_libcall strlen(const char *str);
-int __cheri_libcall strncmp(const char *s1, const char *s2, size_t n);
-char *__cheri_libcall strncpy(char *dest, const char *src, size_t n);
-int __cheri_libcall strcmp(const char *s1, const char *s2);
-char *__cheri_libcall strnstr(const char *haystack,
- const char *needle,
- size_t haystackLength);
-char *__cheri_libcall strchr(const char *s, int c);
-size_t __cheri_libcall strlcpy(char *dest, const char *src, size_t n);
+#define DECLARE_STRING_LIBCALL(rtype, name, ...) \
+ rtype __cheri_libcall name(__VA_ARGS__) __asm__(#name);
+
+DECLARE_STRING_LIBCALL(int,
+ memcmp,
+ const void *str1,
+ const void *str2,
+ size_t count)
+DECLARE_STRING_LIBCALL(int,
+ memcmp,
+ const void *str1,
+ const void *str2,
+ size_t count)
+DECLARE_STRING_LIBCALL(void *, memcpy, void *dest, const void *src, size_t n)
+DECLARE_STRING_LIBCALL(void *, memset, void *, int, size_t)
+DECLARE_STRING_LIBCALL(void *, memmove, void *dest, const void *src, size_t n)
+DECLARE_STRING_LIBCALL(void *, memchr, const void *, int, size_t)
+DECLARE_STRING_LIBCALL(void *, memrchr, const void *, int, size_t)
+DECLARE_STRING_LIBCALL(size_t, strlen, const char *str)
+DECLARE_STRING_LIBCALL(int, strncmp, const char *s1, const char *s2, size_t n)
+DECLARE_STRING_LIBCALL(char *, strncpy, char *dest, const char *src, size_t n)
+DECLARE_STRING_LIBCALL(int, strcmp, const char *s1, const char *s2)
+DECLARE_STRING_LIBCALL(char *,
+ strnstr,
+ const char *haystack,
+ const char *needle,
+ size_t haystackLength)
+DECLARE_STRING_LIBCALL(char *, strchr, const char *s, int c)
+DECLARE_STRING_LIBCALL(size_t, strlcpy, char *dest, const char *src, size_t n)
+
+#undef DECLARE_STRING_LIBCALL | If you add a CHERIOT prefix on this, we can move it into cdefs.h. There's a similar macro in lib/atomic and it would be nice to refactor that to use this one at the same time. |
cheriot-rtos | github_2023 | others | 438 | CHERIoT-Platform | rmn30 | @@ -592,26 +666,31 @@ namespace
* using Debug = ConditionalDebug<DebugFoo, "Foo">; | Does this comment need updating? |
cheriot-rtos | github_2023 | others | 438 | CHERIoT-Platform | rmn30 | @@ -592,26 +666,31 @@ namespace
* using Debug = ConditionalDebug<DebugFoo, "Foo">;
* ```
*/
- template<bool Enabled, DebugContext Context>
+ template<DebugLevelTemplateArgument Threshold, DebugContext Context>
class ConditionalDebug
{
+ static constexpr bool Enabled = Threshold != DebugLevel::None; | Where is this used? |
cheriot-rtos | github_2023 | others | 438 | CHERIoT-Platform | rmn30 | @@ -676,6 +755,7 @@ namespace
}
}
};
+
/**
* Function-like class for assertions that is expected to be used via
* the deduction guide as: | Would it be useful to give Assertions a DebugLevel, like log messages? |
cheriot-rtos | github_2023 | others | 437 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,143 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * Represents the state of the Sonata's joystick.
+ *
+ * Note, that up to three of the bits may be asserted at any given time.
+ * There may be up to two cardinal directions asserted when the joystick is
+ * pushed in a diagonal and the joystick may be pressed while being pushed in a
+ * given direction.
+ */
+enum class SonataJoystick : uint8_t
+{
+ Left = 1 << 0,
+ Up = 1 << 1,
+ Pressed = 1 << 2,
+ Down = 1 << 3,
+ Right = 1 << 4,
+};
+
+/**
+ * A Simple Driver for the Sonata's GPIO.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/sonata-system/blob/1a59633d2515d4fe186a07d53e49ff95c18d9bbf/doc/ip/gpio.md
+ *
+ * Rendered documentation is served from:
+ * https://lowrisc.org/sonata-system/doc/ip/gpio.html
+ */
+struct SonataGPIO
+{
+ uint32_t output;
+ uint32_t input;
+ uint32_t debouncedInput;
+ uint32_t debouncedThreshold;
+ uint32_t raspberryPiHeader;
+ uint32_t raspberryPiMask;
+ uint32_t arduinoShieldHeader;
+ uint32_t arduinoShieldMask;
+
+ /**
+ * Is the current target Sonata 1.0.0 or later?
+ */
+ static bool constexpr Sonata1OrLater =
+#if SONATA >= CHERIOT_VERSION_TRIPLE(1, 0, 0)
+ true
+#else
+ false
+#endif | This probably isn't needed since this is just 0.2 now. |
cheriot-rtos | github_2023 | others | 437 | CHERIoT-Platform | nwf | @@ -0,0 +1,444 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+#include <utils.hh>
+
+/**
+ * Represents the state of Sonata's joystick, where each possible input
+ * corresponds to a given bit in the General GPIO's input register.
+ *
+ * Note that up to 3 of these bits may be asserted at any given time: pressing
+ * down the joystick whilst pushing it in a diagonal direction (i.e. 2 cardinal
+ * directions).
+ *
+ */
+enum class SonataJoystick : uint16_t | Should this be within the `struct SonataGpioBoard` rather than at top-level? |
cheriot-rtos | github_2023 | others | 437 | CHERIoT-Platform | nwf | @@ -0,0 +1,444 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+#include <utils.hh>
+
+/**
+ * Represents the state of Sonata's joystick, where each possible input
+ * corresponds to a given bit in the General GPIO's input register.
+ *
+ * Note that up to 3 of these bits may be asserted at any given time: pressing
+ * down the joystick whilst pushing it in a diagonal direction (i.e. 2 cardinal
+ * directions).
+ *
+ */
+enum class SonataJoystick : uint16_t
+{
+ Left = 1u << 8,
+ Up = 1u << 9,
+ Pressed = 1u << 10,
+ Down = 1u << 11,
+ Right = 1u << 12,
+};
+
+/**
+ * A simple driver for the Sonata's GPIO. This struct represents a single
+ * GPIO instance, and the methods available to interact with that GPIO.
+ *
+ * GPIO instances can be implemented via subclass structs which optionally
+ * override the three static mask attributes and/or add their own instance-
+ * specific functionality. The subclass itself should be provided as a
+ * template class parameter when declaring inheritance.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/sonata-system/blob/9f794fe3bd4eec8d1a01ee81da97a7f2cec0b452/doc/ip/gpio.md
+ *
+ * Rendered documentation is served from:
+ * https://lowrisc.org/sonata-system/doc/ip/gpio.html
+ */
+struct SonataGpioBase : private utils::NoCopyNoMove
+{
+ uint32_t output;
+ uint32_t input;
+ uint32_t debouncedInput;
+ uint32_t outputEnable;
+
+ /**
+ * The mask of bits of the `output` register that contain meaningful
+ * GPIO output.
+ */
+ static constexpr uint32_t output_mask()
+ {
+ return 0xFFFF'FFFF;
+ }
+
+ /**
+ * The mask of bits of the `input` and `debouncedInput` registers that
+ * contain meaningful GPIO input.
+ */
+ static constexpr uint32_t input_mask()
+ {
+ return 0xFFFF'FFFF;
+ }
+
+ /**
+ * Returns the bit corresponding to a given GPIO index. Will mask out
+ * the bit if this is outside of the provided mask.
+ */
+ static constexpr uint32_t output_enable_mask()
+ {
+ return 0xFFFF'FFFF;
+ }
+
+ /**
+ * Returns the bit corresponding to a given GPIO index. Will mask out
+ * the bit if this is outside of the provided mask.
+ */
+ constexpr static uint32_t gpio_bit(uint32_t index, uint32_t mask)
+ {
+ return (1 << index) & mask;
+ }
+
+ /**
+ * Set the output bit for a given GPIO pin index to a specified value.
+ * This will only have an effect if the corresponding bit is first set
+ * to `0` (i.e. output) in the `output_enable` register, and if the pin
+ * is a valid output pin.
+ */
+ void set_output(uint32_t index, bool value) volatile
+ {
+ const uint32_t Bit = gpio_bit(index, output_mask());
+ if (value)
+ {
+ output = output | Bit;
+ }
+ else
+ {
+ output = output & ~Bit;
+ }
+ }
+
+ /**
+ * Set the output enable bit for a given GPIO pin index. If `enable` is
+ * true, the GPIO pin is set to output. If `false`, it is instead set to
+ * input mode.
+ */
+ void set_output_enable(uint32_t index, bool enable) volatile
+ {
+ const uint32_t Bit = gpio_bit(index, output_enable_mask());
+ if (enable)
+ {
+ outputEnable = outputEnable | Bit;
+ }
+ else
+ {
+ outputEnable = outputEnable & ~Bit;
+ }
+ }
+
+ /**
+ * Read the input value for a given GPIO pin index. For this to be
+ * meaningful, the corresponding pin must be configured to be an input
+ * first (set output enable to `false` for the given index). If given an
+ * invalid GPIO pin (outside the input mask), then this value will
+ * always be false.
+ */
+ bool read_input(uint32_t index) volatile
+ {
+ return (input & gpio_bit(index, input_mask())) > 0;
+ }
+
+ /**
+ * Read the debounced input value for a given GPIO pin index. FOr this
+ * to be meaningful, the corresponding pin must be configured to be an
+ * input first (set output enable to `false` for the given index). If
+ * given an invalid GPIO pin (outside the input mask), then this value
+ * will always be false.
+ */
+ bool read_debounced_input(uint32_t index) volatile
+ {
+ return (debouncedInput & gpio_bit(index, input_mask())) > 0;
+ }
+};
+
+/**
+ * A driver for Sonata's Board GPIO (instance 0).
+ *
+ * Documentation source:
+ * https://lowrisc.org/sonata-system/doc/ip/gpio.html | Perhaps examples in the documentation of the right `MMIO_CAPABILITY` invocation for these would be useful? (Or even static factory methods, since they are backed by singletons in Sonata hardware?) |
cheriot-rtos | github_2023 | others | 437 | CHERIoT-Platform | davidchisnall | @@ -138,6 +292,153 @@ struct SonataGPIO
*/
SonataJoystick read_joystick() volatile
{
- return static_cast<SonataJoystick>(input & 0x1f);
+ return static_cast<SonataJoystick>(input & Inputs::Joystick);
+ }
+};
+
+/**
+ * A driver for Sonata's Raspberry Pi HAT Header GPIO.
+ *
+ * Documentation source:
+ * https://lowrisc.org/sonata-system/doc/ip/gpio.html
+ */
+struct SonataGpioRaspberryPiHat : SonataGpioBase
+{
+ /**
+ * The mask of bits of the `output` register that contain meaningful GPIO
+ * output.
+ */
+ static constexpr uint32_t output_mask() | I think this doesn't do what you think. You probably want to either make this virtual (not ideal) or use CRTP so that the superclass can use it. |
cheriot-rtos | github_2023 | others | 437 | CHERIoT-Platform | AlexJones0 | @@ -0,0 +1,444 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+#include <utils.hh>
+
+/**
+ * Represents the state of Sonata's joystick, where each possible input
+ * corresponds to a given bit in the General GPIO's input register.
+ *
+ * Note that up to 3 of these bits may be asserted at any given time: pressing
+ * down the joystick whilst pushing it in a diagonal direction (i.e. 2 cardinal
+ * directions).
+ *
+ */
+enum class SonataJoystick : uint16_t
+{
+ Left = 1u << 8,
+ Up = 1u << 9,
+ Pressed = 1u << 10,
+ Down = 1u << 11,
+ Right = 1u << 12,
+};
+
+/**
+ * A simple driver for the Sonata's GPIO. This struct represents a single
+ * GPIO instance, and the methods available to interact with that GPIO.
+ *
+ * GPIO instances can be implemented via subclass structs which optionally
+ * override the three static mask attributes and/or add their own instance-
+ * specific functionality. The subclass itself should be provided as a
+ * template class parameter when declaring inheritance. | Nit: I think I forgot to remove this last sentence from the comment when I removed the CRTP pattern from this driver; it doesn't make sense any more. The previous sentence should also probably say "three static mask ~attributes~ methods".
*Edit: Though also see David's comment above; perhaps the CRTP needs to be re-introduced?* |
cheriot-rtos | github_2023 | others | 437 | CHERIoT-Platform | rmn30 | @@ -1,78 +1,186 @@
#pragma once
#include <cdefs.h>
#include <stdint.h>
+#include <utils.hh>
/**
- * Represents the state of the Sonata's joystick.
- *
- * Note, that up to three of the bits may be asserted at any given time.
- * There may be up to two cardinal directions asserted when the joystick is
- * pushed in a diagonal and the joystick may be pressed while being pushed in a
- * given direction.
- */
-enum class SonataJoystick : uint8_t
-{
- Left = 1 << 0,
- Up = 1 << 1,
- Pressed = 1 << 2,
- Down = 1 << 3,
- Right = 1 << 4,
-};
-
-/**
- * A Simple Driver for the Sonata's GPIO.
+ * A simple driver for the Sonata's GPIO. This struct represents a single
+ * GPIO instance, and the methods available to interact with that GPIO.
*
* Documentation source can be found at:
- * https://github.com/lowRISC/sonata-system/blob/1a59633d2515d4fe186a07d53e49ff95c18d9bbf/doc/ip/gpio.md
+ * https://github.com/lowRISC/sonata-system/blob/9f794fe3bd4eec8d1a01ee81da97a7f2cec0b452/doc/ip/gpio.md
*
* Rendered documentation is served from:
* https://lowrisc.org/sonata-system/doc/ip/gpio.html
*/
-struct SonataGPIO
+template<
+ /**
+ * The mask of bits of the `output` register that contain meaningful
+ * GPIO output.
+ */
+ uint32_t OutputMask = 0xFFFF'FFFF,
+ /**
+ * The mask of bits of the `input` and `debouncedInput` registers that
+ * contain meaningful GPIO input.
+ */
+ uint32_t InputMask = OutputMask,
+ /**
+ * Returns the bit corresponding to a given GPIO index. Will mask out
+ * the bit if this is outside of the provided mask. | This comment doesn't make sense. |
cheriot-rtos | github_2023 | others | 437 | CHERIoT-Platform | rmn30 | @@ -1,78 +1,186 @@
#pragma once
#include <cdefs.h>
#include <stdint.h>
+#include <utils.hh>
/**
- * Represents the state of the Sonata's joystick.
- *
- * Note, that up to three of the bits may be asserted at any given time.
- * There may be up to two cardinal directions asserted when the joystick is
- * pushed in a diagonal and the joystick may be pressed while being pushed in a
- * given direction.
- */
-enum class SonataJoystick : uint8_t
-{
- Left = 1 << 0,
- Up = 1 << 1,
- Pressed = 1 << 2,
- Down = 1 << 3,
- Right = 1 << 4,
-};
-
-/**
- * A Simple Driver for the Sonata's GPIO.
+ * A simple driver for the Sonata's GPIO. This struct represents a single
+ * GPIO instance, and the methods available to interact with that GPIO.
*
* Documentation source can be found at:
- * https://github.com/lowRISC/sonata-system/blob/1a59633d2515d4fe186a07d53e49ff95c18d9bbf/doc/ip/gpio.md
+ * https://github.com/lowRISC/sonata-system/blob/9f794fe3bd4eec8d1a01ee81da97a7f2cec0b452/doc/ip/gpio.md
*
* Rendered documentation is served from:
* https://lowrisc.org/sonata-system/doc/ip/gpio.html
*/
-struct SonataGPIO
+template<
+ /**
+ * The mask of bits of the `output` register that contain meaningful
+ * GPIO output.
+ */
+ uint32_t OutputMask = 0xFFFF'FFFF,
+ /**
+ * The mask of bits of the `input` and `debouncedInput` registers that
+ * contain meaningful GPIO input.
+ */
+ uint32_t InputMask = OutputMask,
+ /**
+ * Returns the bit corresponding to a given GPIO index. Will mask out
+ * the bit if this is outside of the provided mask.
+ */
+ uint32_t OutputEnableMask = OutputMask>
+struct SonataGpioBase : private utils::NoCopyNoMove
{
uint32_t output;
uint32_t input;
uint32_t debouncedInput;
- uint32_t debouncedThreshold;
- uint32_t raspberryPiHeader;
- uint32_t raspberryPiMask;
- uint32_t arduinoShieldHeader;
- uint32_t arduinoShieldMask;
+ uint32_t outputEnable;
+
+ /**
+ * Returns the bit corresponding to a given GPIO index. Will mask out
+ * the bit if this is outside of the provided mask. | ```suggestion
* Returns a mask with a single bit set corresponding to the given GPIO index
* or 0 if that bit is not set in mask.
``` |
cheriot-rtos | github_2023 | others | 437 | CHERIoT-Platform | rmn30 | @@ -1,78 +1,186 @@
#pragma once
#include <cdefs.h>
#include <stdint.h>
+#include <utils.hh>
/**
- * Represents the state of the Sonata's joystick.
- *
- * Note, that up to three of the bits may be asserted at any given time.
- * There may be up to two cardinal directions asserted when the joystick is
- * pushed in a diagonal and the joystick may be pressed while being pushed in a
- * given direction.
- */
-enum class SonataJoystick : uint8_t
-{
- Left = 1 << 0,
- Up = 1 << 1,
- Pressed = 1 << 2,
- Down = 1 << 3,
- Right = 1 << 4,
-};
-
-/**
- * A Simple Driver for the Sonata's GPIO.
+ * A simple driver for the Sonata's GPIO. This struct represents a single
+ * GPIO instance, and the methods available to interact with that GPIO.
*
* Documentation source can be found at:
- * https://github.com/lowRISC/sonata-system/blob/1a59633d2515d4fe186a07d53e49ff95c18d9bbf/doc/ip/gpio.md
+ * https://github.com/lowRISC/sonata-system/blob/9f794fe3bd4eec8d1a01ee81da97a7f2cec0b452/doc/ip/gpio.md
*
* Rendered documentation is served from:
* https://lowrisc.org/sonata-system/doc/ip/gpio.html
*/
-struct SonataGPIO
+template<
+ /**
+ * The mask of bits of the `output` register that contain meaningful
+ * GPIO output.
+ */
+ uint32_t OutputMask = 0xFFFF'FFFF,
+ /**
+ * The mask of bits of the `input` and `debouncedInput` registers that
+ * contain meaningful GPIO input.
+ */
+ uint32_t InputMask = OutputMask,
+ /**
+ * Returns the bit corresponding to a given GPIO index. Will mask out
+ * the bit if this is outside of the provided mask.
+ */
+ uint32_t OutputEnableMask = OutputMask>
+struct SonataGpioBase : private utils::NoCopyNoMove
{
uint32_t output;
uint32_t input;
uint32_t debouncedInput;
- uint32_t debouncedThreshold;
- uint32_t raspberryPiHeader;
- uint32_t raspberryPiMask;
- uint32_t arduinoShieldHeader;
- uint32_t arduinoShieldMask;
+ uint32_t outputEnable;
+
+ /**
+ * Returns the bit corresponding to a given GPIO index. Will mask out
+ * the bit if this is outside of the provided mask.
+ */
+ constexpr static uint32_t gpio_bit(uint32_t index, uint32_t mask)
+ {
+ return (1 << index) & mask;
+ }
+
+ /**
+ * Set the output bit for a given GPIO pin index to a specified value.
+ * This will only have an effect if the corresponding bit is first set
+ * to `0` (i.e. output) in the `output_enable` register, and if the pin | ```suggestion
* to `1` (i.e. output) in the `output_enable` register, and if the pin
```
This appears to contradict the comment and code for `set_output_enable` below. |
cheriot-rtos | github_2023 | others | 437 | CHERIoT-Platform | rmn30 | @@ -1,78 +1,186 @@
#pragma once
#include <cdefs.h>
#include <stdint.h>
+#include <utils.hh>
/**
- * Represents the state of the Sonata's joystick.
- *
- * Note, that up to three of the bits may be asserted at any given time.
- * There may be up to two cardinal directions asserted when the joystick is
- * pushed in a diagonal and the joystick may be pressed while being pushed in a
- * given direction.
- */
-enum class SonataJoystick : uint8_t
-{
- Left = 1 << 0,
- Up = 1 << 1,
- Pressed = 1 << 2,
- Down = 1 << 3,
- Right = 1 << 4,
-};
-
-/**
- * A Simple Driver for the Sonata's GPIO.
+ * A simple driver for the Sonata's GPIO. This struct represents a single
+ * GPIO instance, and the methods available to interact with that GPIO.
*
* Documentation source can be found at:
- * https://github.com/lowRISC/sonata-system/blob/1a59633d2515d4fe186a07d53e49ff95c18d9bbf/doc/ip/gpio.md
+ * https://github.com/lowRISC/sonata-system/blob/9f794fe3bd4eec8d1a01ee81da97a7f2cec0b452/doc/ip/gpio.md
*
* Rendered documentation is served from:
* https://lowrisc.org/sonata-system/doc/ip/gpio.html
*/
-struct SonataGPIO
+template<
+ /**
+ * The mask of bits of the `output` register that contain meaningful
+ * GPIO output.
+ */
+ uint32_t OutputMask = 0xFFFF'FFFF,
+ /**
+ * The mask of bits of the `input` and `debouncedInput` registers that
+ * contain meaningful GPIO input.
+ */
+ uint32_t InputMask = OutputMask,
+ /**
+ * Returns the bit corresponding to a given GPIO index. Will mask out
+ * the bit if this is outside of the provided mask.
+ */
+ uint32_t OutputEnableMask = OutputMask>
+struct SonataGpioBase : private utils::NoCopyNoMove
{
uint32_t output;
uint32_t input;
uint32_t debouncedInput;
- uint32_t debouncedThreshold;
- uint32_t raspberryPiHeader;
- uint32_t raspberryPiMask;
- uint32_t arduinoShieldHeader;
- uint32_t arduinoShieldMask;
+ uint32_t outputEnable;
+
+ /**
+ * Returns the bit corresponding to a given GPIO index. Will mask out
+ * the bit if this is outside of the provided mask.
+ */
+ constexpr static uint32_t gpio_bit(uint32_t index, uint32_t mask)
+ {
+ return (1 << index) & mask;
+ }
+
+ /**
+ * Set the output bit for a given GPIO pin index to a specified value.
+ * This will only have an effect if the corresponding bit is first set
+ * to `0` (i.e. output) in the `output_enable` register, and if the pin
+ * is a valid output pin.
+ */
+ void set_output(uint32_t index, bool value) volatile
+ {
+ const uint32_t Bit = gpio_bit(index, OutputMask);
+ if (value)
+ {
+ output = output | Bit;
+ }
+ else
+ {
+ output = output & ~Bit;
+ }
+ }
+
+ /**
+ * Set the output enable bit for a given GPIO pin index. If `enable` is
+ * true, the GPIO pin is set to output. If `false`, it is instead set to
+ * input mode.
+ */
+ void set_output_enable(uint32_t index, bool enable) volatile
+ {
+ const uint32_t Bit = gpio_bit(index, OutputEnableMask);
+ if (enable)
+ {
+ outputEnable = outputEnable | Bit;
+ }
+ else
+ {
+ outputEnable = outputEnable & ~Bit;
+ }
+ }
/**
- * Is the current target Sonata 1.0.0 or later?
+ * Read the input value for a given GPIO pin index. For this to be
+ * meaningful, the corresponding pin must be configured to be an input
+ * first (set output enable to `false` for the given index). If given an
+ * invalid GPIO pin (outside the input mask), then this value will
+ * always be false.
*/
- static bool constexpr Sonata1OrLater =
-#if SONATA >= CHERIOT_VERSION_TRIPLE(1, 0, 0)
- true
-#else
- false
-#endif
- ;
+ bool read_input(uint32_t index) volatile
+ {
+ return (input & gpio_bit(index, InputMask)) > 0;
+ }
+
+ /**
+ * Read the debounced input value for a given GPIO pin index. FOr this | ```suggestion
* Read the debounced input value for a given GPIO pin index. For this
``` |
cheriot-rtos | github_2023 | others | 437 | CHERIoT-Platform | rmn30 | @@ -1,78 +1,186 @@
#pragma once
#include <cdefs.h>
#include <stdint.h>
+#include <utils.hh>
/**
- * Represents the state of the Sonata's joystick.
- *
- * Note, that up to three of the bits may be asserted at any given time.
- * There may be up to two cardinal directions asserted when the joystick is
- * pushed in a diagonal and the joystick may be pressed while being pushed in a
- * given direction.
- */
-enum class SonataJoystick : uint8_t
-{
- Left = 1 << 0,
- Up = 1 << 1,
- Pressed = 1 << 2,
- Down = 1 << 3,
- Right = 1 << 4,
-};
-
-/**
- * A Simple Driver for the Sonata's GPIO.
+ * A simple driver for the Sonata's GPIO. This struct represents a single
+ * GPIO instance, and the methods available to interact with that GPIO.
*
* Documentation source can be found at:
- * https://github.com/lowRISC/sonata-system/blob/1a59633d2515d4fe186a07d53e49ff95c18d9bbf/doc/ip/gpio.md
+ * https://github.com/lowRISC/sonata-system/blob/9f794fe3bd4eec8d1a01ee81da97a7f2cec0b452/doc/ip/gpio.md
*
* Rendered documentation is served from:
* https://lowrisc.org/sonata-system/doc/ip/gpio.html
*/
-struct SonataGPIO
+template<
+ /**
+ * The mask of bits of the `output` register that contain meaningful
+ * GPIO output.
+ */
+ uint32_t OutputMask = 0xFFFF'FFFF,
+ /**
+ * The mask of bits of the `input` and `debouncedInput` registers that
+ * contain meaningful GPIO input.
+ */
+ uint32_t InputMask = OutputMask,
+ /**
+ * Returns the bit corresponding to a given GPIO index. Will mask out
+ * the bit if this is outside of the provided mask.
+ */
+ uint32_t OutputEnableMask = OutputMask>
+struct SonataGpioBase : private utils::NoCopyNoMove
{
uint32_t output;
uint32_t input;
uint32_t debouncedInput;
- uint32_t debouncedThreshold;
- uint32_t raspberryPiHeader;
- uint32_t raspberryPiMask;
- uint32_t arduinoShieldHeader;
- uint32_t arduinoShieldMask;
+ uint32_t outputEnable;
+
+ /**
+ * Returns the bit corresponding to a given GPIO index. Will mask out
+ * the bit if this is outside of the provided mask.
+ */
+ constexpr static uint32_t gpio_bit(uint32_t index, uint32_t mask)
+ {
+ return (1 << index) & mask;
+ }
+
+ /**
+ * Set the output bit for a given GPIO pin index to a specified value.
+ * This will only have an effect if the corresponding bit is first set
+ * to `0` (i.e. output) in the `output_enable` register, and if the pin
+ * is a valid output pin.
+ */
+ void set_output(uint32_t index, bool value) volatile
+ {
+ const uint32_t Bit = gpio_bit(index, OutputMask);
+ if (value)
+ {
+ output = output | Bit;
+ }
+ else
+ {
+ output = output & ~Bit;
+ }
+ }
+
+ /**
+ * Set the output enable bit for a given GPIO pin index. If `enable` is
+ * true, the GPIO pin is set to output. If `false`, it is instead set to
+ * input mode.
+ */
+ void set_output_enable(uint32_t index, bool enable) volatile
+ {
+ const uint32_t Bit = gpio_bit(index, OutputEnableMask);
+ if (enable)
+ {
+ outputEnable = outputEnable | Bit;
+ }
+ else
+ {
+ outputEnable = outputEnable & ~Bit;
+ }
+ }
/**
- * Is the current target Sonata 1.0.0 or later?
+ * Read the input value for a given GPIO pin index. For this to be
+ * meaningful, the corresponding pin must be configured to be an input
+ * first (set output enable to `false` for the given index). If given an
+ * invalid GPIO pin (outside the input mask), then this value will
+ * always be false.
*/
- static bool constexpr Sonata1OrLater =
-#if SONATA >= CHERIOT_VERSION_TRIPLE(1, 0, 0)
- true
-#else
- false
-#endif
- ;
+ bool read_input(uint32_t index) volatile
+ {
+ return (input & gpio_bit(index, InputMask)) > 0;
+ }
+
+ /**
+ * Read the debounced input value for a given GPIO pin index. FOr this
+ * to be meaningful, the corresponding pin must be configured to be an
+ * input first (set output enable to `false` for the given index). If
+ * given an invalid GPIO pin (outside the input mask), then this value
+ * will always be false.
+ */
+ bool read_debounced_input(uint32_t index) volatile
+ {
+ return (debouncedInput & gpio_bit(index, InputMask)) > 0;
+ }
+};
+
+/**
+ * A driver for Sonata's Board GPIO (instance 0).
+ *
+ * Documentation source:
+ * https://lowrisc.org/sonata-system/doc/ip/gpio.html
+ */
+struct SonataGpioBoard : SonataGpioBase<0x0000'00FF, 0x0001'FFFF, 0x0000'0000>
+{
+ /**
+ * Represents the state of Sonata's joystick, where each possible input
+ * corresponds to a given bit in the General GPIO's input register.
+ *
+ * Note that up to 3 of these bits may be asserted at any given time:
+ * pressing down the joystick whilst pushing it in a diagonal direction
+ * (i.e. 2 cardinal directions).
+ *
+ */
+ enum class SonataJoystick : uint16_t | ```suggestion
enum class [[clang::flag_enum]] SonataJoystick : uint16_t
```
As this can have more than one value we should tell the compiler that. I would also prefer the name `SonataJoystickDirection` or similar. `SonataJoystick` sounds to me like the actual GPIO register, which this isn't. |
cheriot-rtos | github_2023 | others | 437 | CHERIoT-Platform | rmn30 | @@ -1,78 +1,186 @@
#pragma once
#include <cdefs.h>
#include <stdint.h>
+#include <utils.hh>
/**
- * Represents the state of the Sonata's joystick.
- *
- * Note, that up to three of the bits may be asserted at any given time.
- * There may be up to two cardinal directions asserted when the joystick is
- * pushed in a diagonal and the joystick may be pressed while being pushed in a
- * given direction.
- */
-enum class SonataJoystick : uint8_t
-{
- Left = 1 << 0,
- Up = 1 << 1,
- Pressed = 1 << 2,
- Down = 1 << 3,
- Right = 1 << 4,
-};
-
-/**
- * A Simple Driver for the Sonata's GPIO.
+ * A simple driver for the Sonata's GPIO. This struct represents a single
+ * GPIO instance, and the methods available to interact with that GPIO.
*
* Documentation source can be found at:
- * https://github.com/lowRISC/sonata-system/blob/1a59633d2515d4fe186a07d53e49ff95c18d9bbf/doc/ip/gpio.md
+ * https://github.com/lowRISC/sonata-system/blob/9f794fe3bd4eec8d1a01ee81da97a7f2cec0b452/doc/ip/gpio.md
*
* Rendered documentation is served from:
* https://lowrisc.org/sonata-system/doc/ip/gpio.html
*/
-struct SonataGPIO
+template<
+ /**
+ * The mask of bits of the `output` register that contain meaningful
+ * GPIO output.
+ */
+ uint32_t OutputMask = 0xFFFF'FFFF,
+ /**
+ * The mask of bits of the `input` and `debouncedInput` registers that
+ * contain meaningful GPIO input.
+ */
+ uint32_t InputMask = OutputMask, | Should this be negated? |
cheriot-rtos | github_2023 | others | 437 | CHERIoT-Platform | rmn30 | @@ -138,6 +246,13 @@ struct SonataGPIO
*/
SonataJoystick read_joystick() volatile
{
- return static_cast<SonataJoystick>(input & 0x1f);
+ return static_cast<SonataJoystick>(input & Inputs::Joystick);
}
};
+
+using SonataGpioRaspberryPiHat = SonataGpioBase<0x0FFF'FFFF>;
+using SonataGpioArduinoShield = SonataGpioBase<0x0000'3FFF>;
+using SonataGpioPmod = SonataGpioBase<0x0000'00FF>;
+using SonataGpioPmod0 = SonataGpioPmod;
+using SonataGpioPmod1 = SonataGpioPmod;
+using SonataGpioPmodC = SonataGpioBase<0x0000'003F>; | Why don't these aliases specify the InputMask and OutputEnableMask? Maybe it's because the InputMask is supposed to be the negation of the OutputMask but that's not what the template does right now. |
cheriot-rtos | github_2023 | others | 437 | CHERIoT-Platform | nwf | @@ -136,8 +294,15 @@ struct SonataGPIO
/**
* Returns the state of the joystick.
*/
- SonataJoystick read_joystick() volatile
+ JoystickValue read_joystick() volatile
{
- return static_cast<SonataJoystick>(input & 0x1f);
+ return {static_cast<JoystickDirection>(input & Inputs::Joystick)};
}
};
+
+using SonataGpioRaspberryPiHat = SonataGpioBase<0x0FFF'FFFF>; | Perhaps these should be structs inheriting from their current definitions and providing static factory methods for the singletons on Sonata. I'm content to leave that for a later PR, tho'. |
cheriot-rtos | github_2023 | others | 437 | CHERIoT-Platform | nwf | @@ -1,78 +1,236 @@
#pragma once
#include <cdefs.h>
#include <stdint.h>
+#include <utils.hh>
/**
- * Represents the state of the Sonata's joystick.
+ * A simple driver for the Sonata's GPIO. This struct represents a single
+ * GPIO instance, and the methods available to interact with that GPIO.
+ * This class should usually be used via one the aliases / subclasses defined
+ * below which are specialised to the GPIO instance. e.g. see SonataGpioBoard.
*
- * Note, that up to three of the bits may be asserted at any given time.
- * There may be up to two cardinal directions asserted when the joystick is
- * pushed in a diagonal and the joystick may be pressed while being pushed in a
- * given direction.
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/sonata-system/blob/9f794fe3bd4eec8d1a01ee81da97a7f2cec0b452/doc/ip/gpio.md
+ *
+ * Rendered documentation is served from:
+ * https://lowrisc.org/sonata-system/doc/ip/gpio.html
*/
-enum class SonataJoystick : uint8_t
+template<
+ /**
+ * The mask of bits of the `output` register that contain meaningful
+ * GPIO output.
+ */
+ uint32_t OutputMask = 0xFFFF'FFFF,
+ /**
+ * The mask of bits of the `input` and `debouncedInput` registers that
+ * contain meaningful GPIO input. This is usually the same as OutputMask
+ * if the instance has the same number of input and output pins.
+ */
+ uint32_t InputMask = OutputMask,
+ /**
+ * The mask of bits for the `output_enable` register, again this is usually
+ * the same as OutputMask.
+ */
+ uint32_t OutputEnableMask = OutputMask>
+struct SonataGpioBase : private utils::NoCopyNoMove
{
- Left = 1 << 0,
- Up = 1 << 1,
- Pressed = 1 << 2,
- Down = 1 << 3,
- Right = 1 << 4,
+ uint32_t output;
+ uint32_t input;
+ uint32_t debouncedInput;
+ uint32_t outputEnable;
+
+ /**
+ * Returns a mask with a single bit set corresponding to the given GPIO
+ * index or 0 if that bit is not set in mask.
+ */
+ constexpr static uint32_t gpio_bit(uint32_t index, uint32_t mask)
+ {
+ return (1 << index) & mask;
+ }
+
+ /**
+ * Set the output bit for a given GPIO pin index to a specified value.
+ * This will only have an effect if the corresponding bit is first set
+ * to `1` (i.e. output) in the `output_enable` register, and if the pin
+ * is a valid output pin.
+ */
+ void set_output(uint32_t index, bool value) volatile
+ {
+ const uint32_t Bit = gpio_bit(index, OutputMask);
+ if (value)
+ {
+ output = output | Bit;
+ }
+ else
+ {
+ output = output & ~Bit;
+ }
+ }
+
+ /**
+ * Set the output enable bit for a given GPIO pin index. If `enable` is
+ * true, the GPIO pin is set to output. If `false`, it is instead set to
+ * input mode.
+ */
+ void set_output_enable(uint32_t index, bool enable) volatile
+ {
+ const uint32_t Bit = gpio_bit(index, OutputEnableMask);
+ if (enable)
+ {
+ outputEnable = outputEnable | Bit;
+ }
+ else
+ {
+ outputEnable = outputEnable & ~Bit;
+ }
+ }
+
+ /**
+ * Read the input value for a given GPIO pin index. For this to be
+ * meaningful, the corresponding pin must be configured to be an input
+ * first (set output enable to `false` for the given index). If given an
+ * invalid GPIO pin (outside the input mask), then this value will
+ * always be false.
+ */
+ bool read_input(uint32_t index) volatile
+ {
+ return (input & gpio_bit(index, InputMask)) > 0;
+ }
+
+ /**
+ * Read the debounced input value for a given GPIO pin index. For this
+ * to be meaningful, the corresponding pin must be configured to be an
+ * input first (set output enable to `false` for the given index). If
+ * given an invalid GPIO pin (outside the input mask), then this value
+ * will always be false.
+ */
+ bool read_debounced_input(uint32_t index) volatile
+ {
+ return (debouncedInput & gpio_bit(index, InputMask)) > 0;
+ }
};
/**
- * A Simple Driver for the Sonata's GPIO.
+ * A driver for Sonata's Board GPIO (instance 0). Example of usage:
*
- * Documentation source can be found at:
- * https://github.com/lowRISC/sonata-system/blob/1a59633d2515d4fe186a07d53e49ff95c18d9bbf/doc/ip/gpio.md
+ * ```
+ * auto gpioBoard = MMIO_CAPABILITY(SonataGpioBoard, gpio_board);
+ * bool switch0 = gpioBoard->read_sitwich(0);
+ * ```
*
- * Rendered documentation is served from:
+ * Documentation source:
* https://lowrisc.org/sonata-system/doc/ip/gpio.html
*/
-struct SonataGPIO
+struct SonataGpioBoard : SonataGpioBase<0x0000'00FF, 0x0001'FFFF, 0x0000'0000>
{
- uint32_t output;
- uint32_t input;
- uint32_t debouncedInput;
- uint32_t debouncedThreshold;
- uint32_t raspberryPiHeader;
- uint32_t raspberryPiMask;
- uint32_t arduinoShieldHeader;
- uint32_t arduinoShieldMask;
+ /**
+ * Represents the state of Sonata's joystick, where each possible input
+ * corresponds to a given bit in the General GPIO's input register.
+ *
+ * Note that up to 3 of these bits may be asserted at any given time:
+ * pressing down the joystick whilst pushing it in a diagonal direction
+ * (i.e. 2 cardinal directions).
+ *
+ */
+ enum [[clang::flag_enum]] JoystickDirection : uint16_t
+ {
+ Left = 1u << 8,
+ Up = 1u << 9,
+ Pressed = 1u << 10,
+ Down = 1u << 11,
+ Right = 1u << 12,
+ };
+
+ /**
+ * Class that wraps a JoystickDirection and provides convience wrappers
+ * to query the value.
+ */
+ class JoystickValue
+ {
+ JoystickDirection direction;
+
+ public:
+ JoystickValue(JoystickDirection direction) : direction(direction) {}
+
+ bool is_direction_enabled(JoystickDirection direction) | "enabled"? Maybe "active"? |
cheriot-rtos | github_2023 | cpp | 435 | CHERIoT-Platform | davidchisnall | @@ -19,5 +20,9 @@ int test_stdio()
TEST(strcmp(buffer, "-42") == 0,
"snprintf(\"%d\", -42) gave {}",
std::string_view{buffer, BufferSize});
+ sprintf(buffer, "%x", 6 * 9);
+ TEST(strcmp(buffer, "36") == 0,
+ "sprintf(\"%x\", 6 * 9) gave {}",
+ std::string_view{buffer, BufferSize}); | If you're going to create a string view anyway, you can just use operator == in the comparison rather than strcmp. |
cheriot-rtos | github_2023 | others | 425 | CHERIoT-Platform | nwf | @@ -568,7 +568,22 @@ rule("firmware")
mmio = format("__mmio_region_start = 0x%x;\n%s__mmio_region_end = 0x%x;\n__export_mem_heap_end = 0x%x;\n",
mmio_start, mmio, mmio_end, board.heap["end"])
- local code_start = format("0x%x", board.instruction_memory.start)
+ local code_start = format("0x%x", board.instruction_memory.start);
+ -- Put the data either at the specified address if given, or directly after code
+ local data_start = board.data_memory and format("0x%x", board.data_memory.start) or '.';
+ local rwdata_ldscript = "build/" .. target:name() .. "-firmware.rwdata.ldscript";
+ local rocode_ldscript = "build/" .. target:name() .. "-firmware.rocode.ldscript" | ```suggestion
local rwdata_ldscript = path.join(config.buildir(), target:name() .. "-firmware.rwdata.ldscript")
local rocode_ldscript = path.join(config.buildir(), target:name() .. "-firmware.rocode.ldscript")
```
with `import("core.project.config")` up after line 457. |
cheriot-rtos | github_2023 | others | 425 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1 @@
+All tests finished | This file won't be needed after rebase on #428 |
cheriot-rtos | github_2023 | others | 428 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,25 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+#pragma once
+
+#ifdef SIMULATION
+# include <stdint.h>
+# include <platform-uart.hh>
+# include <string_view>
+
+static void platform_simulation_exit(uint32_t code)
+{
+# if DEVICE_EXISTS(uart0)
+ auto uart = MMIO_CAPABILITY(Uart, uart0);
+# elif DEVICE_EXISTS(uart)
+ auto uart = MMIO_CAPABILITY(Uart, uart);
+# endif | Our normal style for this is to move the `auto UART=` out of the ifdef block. This makes it clearer that the existence of the variable is not conditional. |
cheriot-rtos | github_2023 | others | 428 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,25 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+#pragma once
+
+#ifdef SIMULATION
+# include <stdint.h>
+# include <platform-uart.hh>
+# include <string_view>
+
+static void platform_simulation_exit(uint32_t code)
+{
+# if DEVICE_EXISTS(uart0)
+ auto uart = MMIO_CAPABILITY(Uart, uart0);
+# elif DEVICE_EXISTS(uart)
+ auto uart = MMIO_CAPABILITY(Uart, uart);
+# endif
+ // The following magic string will cause sonata simulator to exit.
+ using namespace std::string_view_literals; | I am not convinced that this is more readable (it’s definitely longer) than just using the long-form constructor. |
cheriot-rtos | github_2023 | others | 428 | CHERIoT-Platform | davidchisnall | @@ -25,27 +25,20 @@ fi
# Remove old uart log
rm -f "${SONATA_SIMULATOR_UART_LOG}"
-# If a second argument is provided, check content of UART log.
-if [ -n "$2" ] ; then
- # Run the simulator in the background.
- ${SONATA_SIMULATOR} -E "${SONATA_SIMULATOR_BOOT_STUB}" -E "$1" &
- LOOP_TRACKER=0
- while (( LOOP_TRACKER <= 60 ))
- do
- sleep 1s
- # Returns 0 if found and 1 if not.
- MATCH_FOUND=$(grep -q -F -f "$2" "${SONATA_SIMULATOR_UART_LOG}"; echo $?)
- if (( MATCH_FOUND == 0 )) ; then
- # Match was found so exit with success
- pkill -P $$
- exit 0
- fi
- LOOP_TRACKER=$((LOOP_TRACKER+1))
- done
- # Timeout was hit so no success.
- pkill -P $$
+# Run the simulator with a timeout and capture the exit status. The || is needed so that set -e doesn't kill us if this fails
+# and we can report the error gracefully. The timeout is chosen so that the testsuite can run in CI. It's probably
+# be a bit long for other purposes.
+result=0
+timeout --foreground 20m ${SONATA_SIMULATOR} -E "${SONATA_SIMULATOR_BOOT_STUB}" -E "$1" || result=$? | Please don't depend on non-POSIX things. If we need to use timeout in CI, that's fine (it's a known environment) but requiring developers to install GPLv3 things is mean. |
cheriot-rtos | github_2023 | others | 337 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,633 @@
+#pragma once | Please can you add the license header? |
cheriot-rtos | github_2023 | others | 337 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,633 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+#include <utils.hh>
+
+/**
+ * A driver for OpenTitan USB Device, which is used in the Sonata system.
+ *
+ * This peripheral's source and documentation can be found at:
+ * https://github.com/lowRISC/opentitan/tree/ab878b5d3578939a04db72d4ed966a56a869b2ed/hw/ip/usbdev
+ *
+ * With rendered register documentation served at:
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html
+ */
+class OpenTitanUsbdev : private utils::NoCopyNoMove
+{
+ public:
+ /// Supported sizes for the USB Device.
+ static constexpr uint8_t MaxPacketLength = 64u;
+ static constexpr uint8_t BufferCount = 32u;
+ static constexpr uint8_t MaxEndpoints = 12u;
+
+ /**
+ * The offset from the start of the USB Device MMIO region at which
+ * packet buffer memory begins.
+ */
+ static constexpr uint32_t BufferStartAddress = 0x800u;
+
+ /// Device Registers
+ uint32_t interruptState;
+ uint32_t interruptEnable;
+ uint32_t interruptTest;
+ uint32_t alertTest;
+ uint32_t usbControl;
+ uint32_t endpointOutEnable;
+ uint32_t endpointInEnable;
+ uint32_t usbStatus;
+ uint32_t availableOutBuffer;
+ uint32_t availableSetupBuffer;
+ uint32_t receiveBuffer;
+ /// Register to enable receive SETUP transactions
+ uint32_t receiveEnableSetup;
+ /// Register to enable receive OUT transactions
+ uint32_t receiveEnableOut;
+ /// Register to set NAK (Not/Negated Acknowledge) after OUT transactions
+ uint32_t setNotAcknowledgeOut;
+ /// Register showing ACK receival to indicate a successful IN send
+ uint32_t inSent;
+ /// Registers for controlling the stalling of OUT and IN endpoints
+ uint32_t outStall;
+ uint32_t inStall;
+ /**
+ * IN transaction configuration registers. There is one register per
+ * endpoint for the USB device.
+ */
+ uint32_t configIn[MaxEndpoints];
+ /**
+ * Registers for configuring which endpoints should be treated as
+ * isochronous endpoints. This means that if the corresponding bit is set,
+ * then that no handshake packet will be sent for an OUT/IN transaction on
+ * that endpoint.
+ */
+ uint32_t outIsochronous;
+ uint32_t inIsochronous;
+ /// Registers for configuring if endpoints data toggle on transactions
+ uint32_t outDataToggle;
+ uint32_t inDataToggle;
+
+ private:
+ /**
+ * Registers to sense/drive the USB PHY pins. That is, these registers can
+ * be used to respectively read out the state of the USB device inputs and
+ * outputs, or to control the inputs and outputs from software. These
+ * registers are kept private as they are intended to be used for debugging
+ * purposes or during chip testing, and not in actual software.
+ */ | It's a shame that they aren't at the end, or you'd be able to expose USB and debugUSB in the board description JSON, where one is a subset of the other and audit whether anyone is using the debug one. |
cheriot-rtos | github_2023 | others | 337 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,633 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+#include <utils.hh>
+
+/**
+ * A driver for OpenTitan USB Device, which is used in the Sonata system.
+ *
+ * This peripheral's source and documentation can be found at:
+ * https://github.com/lowRISC/opentitan/tree/ab878b5d3578939a04db72d4ed966a56a869b2ed/hw/ip/usbdev
+ *
+ * With rendered register documentation served at:
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html
+ */
+class OpenTitanUsbdev : private utils::NoCopyNoMove
+{
+ public:
+ /// Supported sizes for the USB Device.
+ static constexpr uint8_t MaxPacketLength = 64u;
+ static constexpr uint8_t BufferCount = 32u;
+ static constexpr uint8_t MaxEndpoints = 12u;
+
+ /**
+ * The offset from the start of the USB Device MMIO region at which
+ * packet buffer memory begins.
+ */
+ static constexpr uint32_t BufferStartAddress = 0x800u;
+
+ /// Device Registers
+ uint32_t interruptState;
+ uint32_t interruptEnable;
+ uint32_t interruptTest;
+ uint32_t alertTest;
+ uint32_t usbControl;
+ uint32_t endpointOutEnable;
+ uint32_t endpointInEnable;
+ uint32_t usbStatus;
+ uint32_t availableOutBuffer;
+ uint32_t availableSetupBuffer;
+ uint32_t receiveBuffer;
+ /// Register to enable receive SETUP transactions
+ uint32_t receiveEnableSetup;
+ /// Register to enable receive OUT transactions
+ uint32_t receiveEnableOut;
+ /// Register to set NAK (Not/Negated Acknowledge) after OUT transactions
+ uint32_t setNotAcknowledgeOut;
+ /// Register showing ACK receival to indicate a successful IN send
+ uint32_t inSent;
+ /// Registers for controlling the stalling of OUT and IN endpoints
+ uint32_t outStall;
+ uint32_t inStall;
+ /**
+ * IN transaction configuration registers. There is one register per
+ * endpoint for the USB device.
+ */
+ uint32_t configIn[MaxEndpoints];
+ /**
+ * Registers for configuring which endpoints should be treated as
+ * isochronous endpoints. This means that if the corresponding bit is set,
+ * then that no handshake packet will be sent for an OUT/IN transaction on
+ * that endpoint.
+ */
+ uint32_t outIsochronous;
+ uint32_t inIsochronous;
+ /// Registers for configuring if endpoints data toggle on transactions
+ uint32_t outDataToggle;
+ uint32_t inDataToggle;
+
+ private:
+ /**
+ * Registers to sense/drive the USB PHY pins. That is, these registers can
+ * be used to respectively read out the state of the USB device inputs and
+ * outputs, or to control the inputs and outputs from software. These
+ * registers are kept private as they are intended to be used for debugging
+ * purposes or during chip testing, and not in actual software.
+ */
+ [[maybe_unused]] uint32_t phyPinsSense;
+ [[maybe_unused]] uint32_t phyPinsDrive;
+
+ public:
+ /// Config register for the USB PHY pins.
+ uint32_t phyConfig;
+
+ /// Interrupt definitions for OpenTitan's USB Device.
+ enum class UsbdevInterrupt : uint32_t
+ {
+ /// Interrupt asserted whilst the receive FIFO (buffer) is not empty.
+ PacketReceived = 1u << 0,
+ /**
+ * Interrupt asserted when a packet was sent as part of an IN
+ * transaction, but not cleared from the `inSent` register.
+ */
+ PacketSent = 1u << 1,
+ /**
+ * Interrupt raised when VBUS (power supply) is lost, i.e. the link to
+ * the USB host controller has been disconnected.
+ */
+ Disconnected = 1u << 2,
+ /**
+ * Interrupt raised when the link is active, but a Start of Frame (SOF)
+ * packet has not been received within a given timeout threshold, which
+ * is set to 4.096 milliseconds.
+ */
+ HostLost = 1u << 3,
+ /**
+ * Interrupt raised when a Bus Reset condition is indicated on the link
+ * by the link being held in an SE0 state (Single Ended Zero, both lines
+ * being pulled low) for longer than 3 microseconds.
+ */
+ LinkReset = 1u << 4,
+ /**
+ * Interrupt raised when the link has entered the suspend state, due to
+ * being idle for more than 3 milliseconds.
+ */
+ LinkSuspend = 1u << 5,
+ /// Interrupt raised on link transition from suspended to non-idle.
+ LinkResume = 1u << 6,
+ /// Interrupt asserted whilst the Available OUT buffer is empty.
+ AvailableOutEmpty = 1u << 7,
+ /// Interrupt asserted whilst the Receive buffer is full.
+ ReceiveFull = 1u << 8,
+ /**
+ * Interrupt raised when the Available OUT buffer or the Available SETUP
+ * buffer overflows.
+ */
+ AvailableBufferOverflow = 1u << 9,
+ /// Interrupt raised when an error occurs during an IN transaction.
+ LinkInError = 1u << 10,
+ /**
+ * Interrupt raised when a CRC (cyclic redundancy check) error occurs on
+ * a received packet; i.e. there was an error in transmission.
+ */
+ RedundancyCheckError = 1u << 11,
+ /// Interrupt raised when an invalid Packet Identifier is received.
+ PacketIdentifierError = 1u << 12,
+ /// Interrupt raised when a bit stuffing violation is detected.
+ BitstuffingError = 1u << 13,
+ /**
+ * Interrupt raised when the USB frame number is updated with a valid
+ * SOF (Start of Frame) packet.
+ */
+ FrameUpdated = 1u << 14,
+ /// Interrupt raised when VBUS (power supply) is detected.
+ Powered = 1u << 15,
+ /// Interrupt raised when an error occurs during an OUT transaction.
+ LinkOutError = 1u << 16,
+ /// Interrupt asserted whilst the Available SETUP buffer is empty.
+ AvailableSetupEmpty = 1u << 17,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Control register
+ * (offset 0x10).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbctrl
+ */
+ enum class UsbControlField : uint32_t
+ {
+ Enable = 1u << 0,
+ ResumeLinkActive = 1u << 1,
+ DeviceAddress = 0x7Fu << 16,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Status register
+ * (offset 0x1c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbstat
+ */
+ enum class UsbStatusField : uint32_t
+ {
+ Frame = 0x7FFu << 0,
+ HostLost = 1u << 11,
+ LinkState = 0x7u << 12,
+ Sense = 1u << 15,
+ AvailableOutDepth = 0xFu << 16,
+ AvailableSetupDepth = 0x7u << 20,
+ AvailableOutFull = 1u << 23,
+ ReceiveDepth = 0xFu << 24,
+ AvailableSetupFull = 1u << 30,
+ ReceiveEmpty = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the Receive FIFO
+ * buffer register (offset 0x28).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#rxfifo
+ */
+ enum class ReceiveBufferField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Setup = 1u << 19,
+ EndpointId = 0xFu << 20,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for a Config In register
+ * (where there is one such register for each endpoint). These are
+ * the registers with offsets 0x44 up to (and not including) 0x74.
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#configin
+ */
+ enum class ConfigInField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Sending = 1u << 29,
+ Pending = 1u << 30,
+ Ready = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the PHY Config
+ * Register (offset 0x8c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#phy_config
+ */
+ enum class PhyConfigField : uint32_t
+ {
+ UseDifferentialReceiver = 1u << 0,
+ // Other PHY Configuration fields are omitted.
+ };
+
+ /**
+ * Ensure that the Available OUT and Available SETUP buffers are kept
+ * supplied with buffers for packet reception.
+ *
+ * @param bufferBitmap A bitmap of the buffers that are not currently
+ * committed (where 1 corresponds to not in use).
+ * @returns The updated bitmap after supplying buffers.
+ */
+ [[nodiscard]] uint64_t supply_buffers(uint64_t bufferBitmap) volatile
+ {
+ constexpr uint32_t SetupFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableSetupFull); | ```suggestion
constexpr uint32_t SetupFullBit =
uint32_t(UsbStatusField::AvailableSetupFull);
```
Same below. Cosmetic, but I find reading less makes it easier to read. |
cheriot-rtos | github_2023 | others | 337 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,633 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+#include <utils.hh>
+
+/**
+ * A driver for OpenTitan USB Device, which is used in the Sonata system.
+ *
+ * This peripheral's source and documentation can be found at:
+ * https://github.com/lowRISC/opentitan/tree/ab878b5d3578939a04db72d4ed966a56a869b2ed/hw/ip/usbdev
+ *
+ * With rendered register documentation served at:
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html
+ */ | I think this would benefit from a bit of high-level detail. I think, from reading the code, that the USB device has a pool of buffers that can be configured for sending and receiving, and you can read / write data from them, mark them as ready to send / receive, and get an interrupt when that's happened. The buffers are MMIO regions. Is that correct? |
cheriot-rtos | github_2023 | others | 337 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,633 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+#include <utils.hh>
+
+/**
+ * A driver for OpenTitan USB Device, which is used in the Sonata system.
+ *
+ * This peripheral's source and documentation can be found at:
+ * https://github.com/lowRISC/opentitan/tree/ab878b5d3578939a04db72d4ed966a56a869b2ed/hw/ip/usbdev
+ *
+ * With rendered register documentation served at:
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html
+ */
+class OpenTitanUsbdev : private utils::NoCopyNoMove
+{
+ public:
+ /// Supported sizes for the USB Device.
+ static constexpr uint8_t MaxPacketLength = 64u;
+ static constexpr uint8_t BufferCount = 32u;
+ static constexpr uint8_t MaxEndpoints = 12u;
+
+ /**
+ * The offset from the start of the USB Device MMIO region at which
+ * packet buffer memory begins.
+ */
+ static constexpr uint32_t BufferStartAddress = 0x800u;
+
+ /// Device Registers
+ uint32_t interruptState;
+ uint32_t interruptEnable;
+ uint32_t interruptTest;
+ uint32_t alertTest;
+ uint32_t usbControl;
+ uint32_t endpointOutEnable;
+ uint32_t endpointInEnable;
+ uint32_t usbStatus;
+ uint32_t availableOutBuffer;
+ uint32_t availableSetupBuffer;
+ uint32_t receiveBuffer;
+ /// Register to enable receive SETUP transactions
+ uint32_t receiveEnableSetup;
+ /// Register to enable receive OUT transactions
+ uint32_t receiveEnableOut;
+ /// Register to set NAK (Not/Negated Acknowledge) after OUT transactions
+ uint32_t setNotAcknowledgeOut;
+ /// Register showing ACK receival to indicate a successful IN send
+ uint32_t inSent;
+ /// Registers for controlling the stalling of OUT and IN endpoints
+ uint32_t outStall;
+ uint32_t inStall;
+ /**
+ * IN transaction configuration registers. There is one register per
+ * endpoint for the USB device.
+ */
+ uint32_t configIn[MaxEndpoints];
+ /**
+ * Registers for configuring which endpoints should be treated as
+ * isochronous endpoints. This means that if the corresponding bit is set,
+ * then that no handshake packet will be sent for an OUT/IN transaction on
+ * that endpoint.
+ */
+ uint32_t outIsochronous;
+ uint32_t inIsochronous;
+ /// Registers for configuring if endpoints data toggle on transactions
+ uint32_t outDataToggle;
+ uint32_t inDataToggle;
+
+ private:
+ /**
+ * Registers to sense/drive the USB PHY pins. That is, these registers can
+ * be used to respectively read out the state of the USB device inputs and
+ * outputs, or to control the inputs and outputs from software. These
+ * registers are kept private as they are intended to be used for debugging
+ * purposes or during chip testing, and not in actual software.
+ */
+ [[maybe_unused]] uint32_t phyPinsSense;
+ [[maybe_unused]] uint32_t phyPinsDrive;
+
+ public:
+ /// Config register for the USB PHY pins.
+ uint32_t phyConfig;
+
+ /// Interrupt definitions for OpenTitan's USB Device.
+ enum class UsbdevInterrupt : uint32_t
+ {
+ /// Interrupt asserted whilst the receive FIFO (buffer) is not empty.
+ PacketReceived = 1u << 0,
+ /**
+ * Interrupt asserted when a packet was sent as part of an IN
+ * transaction, but not cleared from the `inSent` register.
+ */
+ PacketSent = 1u << 1,
+ /**
+ * Interrupt raised when VBUS (power supply) is lost, i.e. the link to
+ * the USB host controller has been disconnected.
+ */
+ Disconnected = 1u << 2,
+ /**
+ * Interrupt raised when the link is active, but a Start of Frame (SOF)
+ * packet has not been received within a given timeout threshold, which
+ * is set to 4.096 milliseconds.
+ */
+ HostLost = 1u << 3,
+ /**
+ * Interrupt raised when a Bus Reset condition is indicated on the link
+ * by the link being held in an SE0 state (Single Ended Zero, both lines
+ * being pulled low) for longer than 3 microseconds.
+ */
+ LinkReset = 1u << 4,
+ /**
+ * Interrupt raised when the link has entered the suspend state, due to
+ * being idle for more than 3 milliseconds.
+ */
+ LinkSuspend = 1u << 5,
+ /// Interrupt raised on link transition from suspended to non-idle.
+ LinkResume = 1u << 6,
+ /// Interrupt asserted whilst the Available OUT buffer is empty.
+ AvailableOutEmpty = 1u << 7,
+ /// Interrupt asserted whilst the Receive buffer is full.
+ ReceiveFull = 1u << 8,
+ /**
+ * Interrupt raised when the Available OUT buffer or the Available SETUP
+ * buffer overflows.
+ */
+ AvailableBufferOverflow = 1u << 9,
+ /// Interrupt raised when an error occurs during an IN transaction.
+ LinkInError = 1u << 10,
+ /**
+ * Interrupt raised when a CRC (cyclic redundancy check) error occurs on
+ * a received packet; i.e. there was an error in transmission.
+ */
+ RedundancyCheckError = 1u << 11,
+ /// Interrupt raised when an invalid Packet Identifier is received.
+ PacketIdentifierError = 1u << 12,
+ /// Interrupt raised when a bit stuffing violation is detected.
+ BitstuffingError = 1u << 13,
+ /**
+ * Interrupt raised when the USB frame number is updated with a valid
+ * SOF (Start of Frame) packet.
+ */
+ FrameUpdated = 1u << 14,
+ /// Interrupt raised when VBUS (power supply) is detected.
+ Powered = 1u << 15,
+ /// Interrupt raised when an error occurs during an OUT transaction.
+ LinkOutError = 1u << 16,
+ /// Interrupt asserted whilst the Available SETUP buffer is empty.
+ AvailableSetupEmpty = 1u << 17,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Control register
+ * (offset 0x10).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbctrl
+ */
+ enum class UsbControlField : uint32_t
+ {
+ Enable = 1u << 0,
+ ResumeLinkActive = 1u << 1,
+ DeviceAddress = 0x7Fu << 16,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Status register
+ * (offset 0x1c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbstat
+ */
+ enum class UsbStatusField : uint32_t
+ {
+ Frame = 0x7FFu << 0,
+ HostLost = 1u << 11,
+ LinkState = 0x7u << 12,
+ Sense = 1u << 15,
+ AvailableOutDepth = 0xFu << 16,
+ AvailableSetupDepth = 0x7u << 20,
+ AvailableOutFull = 1u << 23,
+ ReceiveDepth = 0xFu << 24,
+ AvailableSetupFull = 1u << 30,
+ ReceiveEmpty = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the Receive FIFO
+ * buffer register (offset 0x28).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#rxfifo
+ */
+ enum class ReceiveBufferField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Setup = 1u << 19,
+ EndpointId = 0xFu << 20,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for a Config In register
+ * (where there is one such register for each endpoint). These are
+ * the registers with offsets 0x44 up to (and not including) 0x74.
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#configin
+ */
+ enum class ConfigInField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Sending = 1u << 29,
+ Pending = 1u << 30,
+ Ready = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the PHY Config
+ * Register (offset 0x8c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#phy_config
+ */
+ enum class PhyConfigField : uint32_t
+ {
+ UseDifferentialReceiver = 1u << 0,
+ // Other PHY Configuration fields are omitted.
+ };
+
+ /**
+ * Ensure that the Available OUT and Available SETUP buffers are kept
+ * supplied with buffers for packet reception.
+ *
+ * @param bufferBitmap A bitmap of the buffers that are not currently
+ * committed (where 1 corresponds to not in use).
+ * @returns The updated bitmap after supplying buffers.
+ */
+ [[nodiscard]] uint64_t supply_buffers(uint64_t bufferBitmap) volatile
+ {
+ constexpr uint32_t SetupFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableSetupFull);
+ constexpr uint32_t OutFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableOutFull);
+
+ for (uint8_t index = 0; index < BufferCount; index++)
+ {
+ const uint32_t Buffer = (1u << index);
+ if (!(bufferBitmap & Buffer))
+ {
+ continue; // Skip buffers that are not available
+ }
+
+ // If a buffer is available, and either Available SETUP or OUT are
+ // not yet full, then commit that buffer and mark it as in use.
+ if (usbStatus & SetupFullBit)
+ {
+ if (usbStatus & OutFullBit)
+ {
+ break; // Both are full - stop trying to supply buffers.
+ }
+ availableOutBuffer = index;
+ }
+ else
+ {
+ availableSetupBuffer = index;
+ }
+ bufferBitmap &= ~Buffer;
+ }
+ return bufferBitmap;
+ }
+
+ /**
+ * Enable a specified interrupt / interrupts.
+ */
+ void interrupt_enable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable | static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Disable a specified interrupt / interrupts.
+ */
+ void interrupt_disable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable & ~static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Initialise the USB device, ensuring that packet buffers are available for
+ * reception and that the PHY has been appropriately configured. Note that
+ * at this stage, endpoints have not been configured and the device has not
+ * been connected to the USB.
+ *
+ * @param bufferBitmap An out-parameter, to initialise a bitmap of the
+ * buffers that are not currently commited (1 corresponds to not in use).
+ *
+ * @returns 0 if initialisation is sucessful, and non-zero otherwise.
+ */
+ [[nodiscard]] int init(uint64_t &bufferBitmap) volatile
+ {
+ bufferBitmap =
+ supply_buffers((static_cast<uint64_t>(1u) << BufferCount) - 1u);
+ phyConfig =
+ static_cast<uint32_t>(PhyConfigField::UseDifferentialReceiver);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an OUT endpoint for the USB device. | Setup is a noun. I think you mean 'Set up' |
cheriot-rtos | github_2023 | others | 337 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,633 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+#include <utils.hh>
+
+/**
+ * A driver for OpenTitan USB Device, which is used in the Sonata system.
+ *
+ * This peripheral's source and documentation can be found at:
+ * https://github.com/lowRISC/opentitan/tree/ab878b5d3578939a04db72d4ed966a56a869b2ed/hw/ip/usbdev
+ *
+ * With rendered register documentation served at:
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html
+ */
+class OpenTitanUsbdev : private utils::NoCopyNoMove
+{
+ public:
+ /// Supported sizes for the USB Device.
+ static constexpr uint8_t MaxPacketLength = 64u;
+ static constexpr uint8_t BufferCount = 32u;
+ static constexpr uint8_t MaxEndpoints = 12u;
+
+ /**
+ * The offset from the start of the USB Device MMIO region at which
+ * packet buffer memory begins.
+ */
+ static constexpr uint32_t BufferStartAddress = 0x800u;
+
+ /// Device Registers
+ uint32_t interruptState;
+ uint32_t interruptEnable;
+ uint32_t interruptTest;
+ uint32_t alertTest;
+ uint32_t usbControl;
+ uint32_t endpointOutEnable;
+ uint32_t endpointInEnable;
+ uint32_t usbStatus;
+ uint32_t availableOutBuffer;
+ uint32_t availableSetupBuffer;
+ uint32_t receiveBuffer;
+ /// Register to enable receive SETUP transactions
+ uint32_t receiveEnableSetup;
+ /// Register to enable receive OUT transactions
+ uint32_t receiveEnableOut;
+ /// Register to set NAK (Not/Negated Acknowledge) after OUT transactions
+ uint32_t setNotAcknowledgeOut;
+ /// Register showing ACK receival to indicate a successful IN send
+ uint32_t inSent;
+ /// Registers for controlling the stalling of OUT and IN endpoints
+ uint32_t outStall;
+ uint32_t inStall;
+ /**
+ * IN transaction configuration registers. There is one register per
+ * endpoint for the USB device.
+ */
+ uint32_t configIn[MaxEndpoints];
+ /**
+ * Registers for configuring which endpoints should be treated as
+ * isochronous endpoints. This means that if the corresponding bit is set,
+ * then that no handshake packet will be sent for an OUT/IN transaction on
+ * that endpoint.
+ */
+ uint32_t outIsochronous;
+ uint32_t inIsochronous;
+ /// Registers for configuring if endpoints data toggle on transactions
+ uint32_t outDataToggle;
+ uint32_t inDataToggle;
+
+ private:
+ /**
+ * Registers to sense/drive the USB PHY pins. That is, these registers can
+ * be used to respectively read out the state of the USB device inputs and
+ * outputs, or to control the inputs and outputs from software. These
+ * registers are kept private as they are intended to be used for debugging
+ * purposes or during chip testing, and not in actual software.
+ */
+ [[maybe_unused]] uint32_t phyPinsSense;
+ [[maybe_unused]] uint32_t phyPinsDrive;
+
+ public:
+ /// Config register for the USB PHY pins.
+ uint32_t phyConfig;
+
+ /// Interrupt definitions for OpenTitan's USB Device.
+ enum class UsbdevInterrupt : uint32_t
+ {
+ /// Interrupt asserted whilst the receive FIFO (buffer) is not empty.
+ PacketReceived = 1u << 0,
+ /**
+ * Interrupt asserted when a packet was sent as part of an IN
+ * transaction, but not cleared from the `inSent` register.
+ */
+ PacketSent = 1u << 1,
+ /**
+ * Interrupt raised when VBUS (power supply) is lost, i.e. the link to
+ * the USB host controller has been disconnected.
+ */
+ Disconnected = 1u << 2,
+ /**
+ * Interrupt raised when the link is active, but a Start of Frame (SOF)
+ * packet has not been received within a given timeout threshold, which
+ * is set to 4.096 milliseconds.
+ */
+ HostLost = 1u << 3,
+ /**
+ * Interrupt raised when a Bus Reset condition is indicated on the link
+ * by the link being held in an SE0 state (Single Ended Zero, both lines
+ * being pulled low) for longer than 3 microseconds.
+ */
+ LinkReset = 1u << 4,
+ /**
+ * Interrupt raised when the link has entered the suspend state, due to
+ * being idle for more than 3 milliseconds.
+ */
+ LinkSuspend = 1u << 5,
+ /// Interrupt raised on link transition from suspended to non-idle.
+ LinkResume = 1u << 6,
+ /// Interrupt asserted whilst the Available OUT buffer is empty.
+ AvailableOutEmpty = 1u << 7,
+ /// Interrupt asserted whilst the Receive buffer is full.
+ ReceiveFull = 1u << 8,
+ /**
+ * Interrupt raised when the Available OUT buffer or the Available SETUP
+ * buffer overflows.
+ */
+ AvailableBufferOverflow = 1u << 9,
+ /// Interrupt raised when an error occurs during an IN transaction.
+ LinkInError = 1u << 10,
+ /**
+ * Interrupt raised when a CRC (cyclic redundancy check) error occurs on
+ * a received packet; i.e. there was an error in transmission.
+ */
+ RedundancyCheckError = 1u << 11,
+ /// Interrupt raised when an invalid Packet Identifier is received.
+ PacketIdentifierError = 1u << 12,
+ /// Interrupt raised when a bit stuffing violation is detected.
+ BitstuffingError = 1u << 13,
+ /**
+ * Interrupt raised when the USB frame number is updated with a valid
+ * SOF (Start of Frame) packet.
+ */
+ FrameUpdated = 1u << 14,
+ /// Interrupt raised when VBUS (power supply) is detected.
+ Powered = 1u << 15,
+ /// Interrupt raised when an error occurs during an OUT transaction.
+ LinkOutError = 1u << 16,
+ /// Interrupt asserted whilst the Available SETUP buffer is empty.
+ AvailableSetupEmpty = 1u << 17,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Control register
+ * (offset 0x10).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbctrl
+ */
+ enum class UsbControlField : uint32_t
+ {
+ Enable = 1u << 0,
+ ResumeLinkActive = 1u << 1,
+ DeviceAddress = 0x7Fu << 16,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Status register
+ * (offset 0x1c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbstat
+ */
+ enum class UsbStatusField : uint32_t
+ {
+ Frame = 0x7FFu << 0,
+ HostLost = 1u << 11,
+ LinkState = 0x7u << 12,
+ Sense = 1u << 15,
+ AvailableOutDepth = 0xFu << 16,
+ AvailableSetupDepth = 0x7u << 20,
+ AvailableOutFull = 1u << 23,
+ ReceiveDepth = 0xFu << 24,
+ AvailableSetupFull = 1u << 30,
+ ReceiveEmpty = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the Receive FIFO
+ * buffer register (offset 0x28).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#rxfifo
+ */
+ enum class ReceiveBufferField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Setup = 1u << 19,
+ EndpointId = 0xFu << 20,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for a Config In register
+ * (where there is one such register for each endpoint). These are
+ * the registers with offsets 0x44 up to (and not including) 0x74.
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#configin
+ */
+ enum class ConfigInField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Sending = 1u << 29,
+ Pending = 1u << 30,
+ Ready = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the PHY Config
+ * Register (offset 0x8c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#phy_config
+ */
+ enum class PhyConfigField : uint32_t
+ {
+ UseDifferentialReceiver = 1u << 0,
+ // Other PHY Configuration fields are omitted.
+ };
+
+ /**
+ * Ensure that the Available OUT and Available SETUP buffers are kept
+ * supplied with buffers for packet reception.
+ *
+ * @param bufferBitmap A bitmap of the buffers that are not currently
+ * committed (where 1 corresponds to not in use).
+ * @returns The updated bitmap after supplying buffers.
+ */
+ [[nodiscard]] uint64_t supply_buffers(uint64_t bufferBitmap) volatile
+ {
+ constexpr uint32_t SetupFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableSetupFull);
+ constexpr uint32_t OutFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableOutFull);
+
+ for (uint8_t index = 0; index < BufferCount; index++)
+ {
+ const uint32_t Buffer = (1u << index);
+ if (!(bufferBitmap & Buffer))
+ {
+ continue; // Skip buffers that are not available
+ }
+
+ // If a buffer is available, and either Available SETUP or OUT are
+ // not yet full, then commit that buffer and mark it as in use.
+ if (usbStatus & SetupFullBit)
+ {
+ if (usbStatus & OutFullBit)
+ {
+ break; // Both are full - stop trying to supply buffers.
+ }
+ availableOutBuffer = index;
+ }
+ else
+ {
+ availableSetupBuffer = index;
+ }
+ bufferBitmap &= ~Buffer;
+ }
+ return bufferBitmap;
+ }
+
+ /**
+ * Enable a specified interrupt / interrupts.
+ */
+ void interrupt_enable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable | static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Disable a specified interrupt / interrupts.
+ */
+ void interrupt_disable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable & ~static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Initialise the USB device, ensuring that packet buffers are available for
+ * reception and that the PHY has been appropriately configured. Note that
+ * at this stage, endpoints have not been configured and the device has not
+ * been connected to the USB.
+ *
+ * @param bufferBitmap An out-parameter, to initialise a bitmap of the
+ * buffers that are not currently commited (1 corresponds to not in use).
+ *
+ * @returns 0 if initialisation is sucessful, and non-zero otherwise.
+ */
+ [[nodiscard]] int init(uint64_t &bufferBitmap) volatile
+ {
+ bufferBitmap =
+ supply_buffers((static_cast<uint64_t>(1u) << BufferCount) - 1u);
+ phyConfig =
+ static_cast<uint32_t>(PhyConfigField::UseDifferentialReceiver);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an OUT endpoint for the USB device.
+ *
+ * @param endpointId The ID of the OUT endpoint to configure.
+ * @param enabled Whether the OUT endpoint should be enabled or not.
+ * @param setup Whether SETUP transactions should be enabled for the
+ * endpoint.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_out_endpoint(uint8_t endpointId,
+ bool enabled,
+ bool setup,
+ bool isochronous) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ endpointOutEnable = (endpointOutEnable & ~Mask) | (enabled ? Mask : 0u);
+ outIsochronous = (outIsochronous & ~Mask) | (isochronous ? Mask : 0u);
+ receiveEnableSetup = (receiveEnableSetup & ~Mask) | (setup ? Mask : 0u);
+ receiveEnableOut = (receiveEnableOut & ~Mask) | (enabled ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an IN endpoint for the USB device. | As above. |
cheriot-rtos | github_2023 | others | 337 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,633 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+#include <utils.hh>
+
+/**
+ * A driver for OpenTitan USB Device, which is used in the Sonata system.
+ *
+ * This peripheral's source and documentation can be found at:
+ * https://github.com/lowRISC/opentitan/tree/ab878b5d3578939a04db72d4ed966a56a869b2ed/hw/ip/usbdev
+ *
+ * With rendered register documentation served at:
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html
+ */
+class OpenTitanUsbdev : private utils::NoCopyNoMove
+{
+ public:
+ /// Supported sizes for the USB Device.
+ static constexpr uint8_t MaxPacketLength = 64u;
+ static constexpr uint8_t BufferCount = 32u;
+ static constexpr uint8_t MaxEndpoints = 12u;
+
+ /**
+ * The offset from the start of the USB Device MMIO region at which
+ * packet buffer memory begins.
+ */
+ static constexpr uint32_t BufferStartAddress = 0x800u;
+
+ /// Device Registers
+ uint32_t interruptState;
+ uint32_t interruptEnable;
+ uint32_t interruptTest;
+ uint32_t alertTest;
+ uint32_t usbControl;
+ uint32_t endpointOutEnable;
+ uint32_t endpointInEnable;
+ uint32_t usbStatus;
+ uint32_t availableOutBuffer;
+ uint32_t availableSetupBuffer;
+ uint32_t receiveBuffer;
+ /// Register to enable receive SETUP transactions
+ uint32_t receiveEnableSetup;
+ /// Register to enable receive OUT transactions
+ uint32_t receiveEnableOut;
+ /// Register to set NAK (Not/Negated Acknowledge) after OUT transactions
+ uint32_t setNotAcknowledgeOut;
+ /// Register showing ACK receival to indicate a successful IN send
+ uint32_t inSent;
+ /// Registers for controlling the stalling of OUT and IN endpoints
+ uint32_t outStall;
+ uint32_t inStall;
+ /**
+ * IN transaction configuration registers. There is one register per
+ * endpoint for the USB device.
+ */
+ uint32_t configIn[MaxEndpoints];
+ /**
+ * Registers for configuring which endpoints should be treated as
+ * isochronous endpoints. This means that if the corresponding bit is set,
+ * then that no handshake packet will be sent for an OUT/IN transaction on
+ * that endpoint.
+ */
+ uint32_t outIsochronous;
+ uint32_t inIsochronous;
+ /// Registers for configuring if endpoints data toggle on transactions
+ uint32_t outDataToggle;
+ uint32_t inDataToggle;
+
+ private:
+ /**
+ * Registers to sense/drive the USB PHY pins. That is, these registers can
+ * be used to respectively read out the state of the USB device inputs and
+ * outputs, or to control the inputs and outputs from software. These
+ * registers are kept private as they are intended to be used for debugging
+ * purposes or during chip testing, and not in actual software.
+ */
+ [[maybe_unused]] uint32_t phyPinsSense;
+ [[maybe_unused]] uint32_t phyPinsDrive;
+
+ public:
+ /// Config register for the USB PHY pins.
+ uint32_t phyConfig;
+
+ /// Interrupt definitions for OpenTitan's USB Device.
+ enum class UsbdevInterrupt : uint32_t
+ {
+ /// Interrupt asserted whilst the receive FIFO (buffer) is not empty.
+ PacketReceived = 1u << 0,
+ /**
+ * Interrupt asserted when a packet was sent as part of an IN
+ * transaction, but not cleared from the `inSent` register.
+ */
+ PacketSent = 1u << 1,
+ /**
+ * Interrupt raised when VBUS (power supply) is lost, i.e. the link to
+ * the USB host controller has been disconnected.
+ */
+ Disconnected = 1u << 2,
+ /**
+ * Interrupt raised when the link is active, but a Start of Frame (SOF)
+ * packet has not been received within a given timeout threshold, which
+ * is set to 4.096 milliseconds.
+ */
+ HostLost = 1u << 3,
+ /**
+ * Interrupt raised when a Bus Reset condition is indicated on the link
+ * by the link being held in an SE0 state (Single Ended Zero, both lines
+ * being pulled low) for longer than 3 microseconds.
+ */
+ LinkReset = 1u << 4,
+ /**
+ * Interrupt raised when the link has entered the suspend state, due to
+ * being idle for more than 3 milliseconds.
+ */
+ LinkSuspend = 1u << 5,
+ /// Interrupt raised on link transition from suspended to non-idle.
+ LinkResume = 1u << 6,
+ /// Interrupt asserted whilst the Available OUT buffer is empty.
+ AvailableOutEmpty = 1u << 7,
+ /// Interrupt asserted whilst the Receive buffer is full.
+ ReceiveFull = 1u << 8,
+ /**
+ * Interrupt raised when the Available OUT buffer or the Available SETUP
+ * buffer overflows.
+ */
+ AvailableBufferOverflow = 1u << 9,
+ /// Interrupt raised when an error occurs during an IN transaction.
+ LinkInError = 1u << 10,
+ /**
+ * Interrupt raised when a CRC (cyclic redundancy check) error occurs on
+ * a received packet; i.e. there was an error in transmission.
+ */
+ RedundancyCheckError = 1u << 11,
+ /// Interrupt raised when an invalid Packet Identifier is received.
+ PacketIdentifierError = 1u << 12,
+ /// Interrupt raised when a bit stuffing violation is detected.
+ BitstuffingError = 1u << 13,
+ /**
+ * Interrupt raised when the USB frame number is updated with a valid
+ * SOF (Start of Frame) packet.
+ */
+ FrameUpdated = 1u << 14,
+ /// Interrupt raised when VBUS (power supply) is detected.
+ Powered = 1u << 15,
+ /// Interrupt raised when an error occurs during an OUT transaction.
+ LinkOutError = 1u << 16,
+ /// Interrupt asserted whilst the Available SETUP buffer is empty.
+ AvailableSetupEmpty = 1u << 17,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Control register
+ * (offset 0x10).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbctrl
+ */
+ enum class UsbControlField : uint32_t
+ {
+ Enable = 1u << 0,
+ ResumeLinkActive = 1u << 1,
+ DeviceAddress = 0x7Fu << 16,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Status register
+ * (offset 0x1c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbstat
+ */
+ enum class UsbStatusField : uint32_t
+ {
+ Frame = 0x7FFu << 0,
+ HostLost = 1u << 11,
+ LinkState = 0x7u << 12,
+ Sense = 1u << 15,
+ AvailableOutDepth = 0xFu << 16,
+ AvailableSetupDepth = 0x7u << 20,
+ AvailableOutFull = 1u << 23,
+ ReceiveDepth = 0xFu << 24,
+ AvailableSetupFull = 1u << 30,
+ ReceiveEmpty = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the Receive FIFO
+ * buffer register (offset 0x28).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#rxfifo
+ */
+ enum class ReceiveBufferField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Setup = 1u << 19,
+ EndpointId = 0xFu << 20,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for a Config In register
+ * (where there is one such register for each endpoint). These are
+ * the registers with offsets 0x44 up to (and not including) 0x74.
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#configin
+ */
+ enum class ConfigInField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Sending = 1u << 29,
+ Pending = 1u << 30,
+ Ready = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the PHY Config
+ * Register (offset 0x8c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#phy_config
+ */
+ enum class PhyConfigField : uint32_t
+ {
+ UseDifferentialReceiver = 1u << 0,
+ // Other PHY Configuration fields are omitted.
+ };
+
+ /**
+ * Ensure that the Available OUT and Available SETUP buffers are kept
+ * supplied with buffers for packet reception.
+ *
+ * @param bufferBitmap A bitmap of the buffers that are not currently
+ * committed (where 1 corresponds to not in use).
+ * @returns The updated bitmap after supplying buffers.
+ */
+ [[nodiscard]] uint64_t supply_buffers(uint64_t bufferBitmap) volatile
+ {
+ constexpr uint32_t SetupFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableSetupFull);
+ constexpr uint32_t OutFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableOutFull);
+
+ for (uint8_t index = 0; index < BufferCount; index++)
+ {
+ const uint32_t Buffer = (1u << index);
+ if (!(bufferBitmap & Buffer))
+ {
+ continue; // Skip buffers that are not available
+ }
+
+ // If a buffer is available, and either Available SETUP or OUT are
+ // not yet full, then commit that buffer and mark it as in use.
+ if (usbStatus & SetupFullBit)
+ {
+ if (usbStatus & OutFullBit)
+ {
+ break; // Both are full - stop trying to supply buffers.
+ }
+ availableOutBuffer = index;
+ }
+ else
+ {
+ availableSetupBuffer = index;
+ }
+ bufferBitmap &= ~Buffer;
+ }
+ return bufferBitmap;
+ }
+
+ /**
+ * Enable a specified interrupt / interrupts.
+ */
+ void interrupt_enable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable | static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Disable a specified interrupt / interrupts.
+ */
+ void interrupt_disable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable & ~static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Initialise the USB device, ensuring that packet buffers are available for
+ * reception and that the PHY has been appropriately configured. Note that
+ * at this stage, endpoints have not been configured and the device has not
+ * been connected to the USB.
+ *
+ * @param bufferBitmap An out-parameter, to initialise a bitmap of the
+ * buffers that are not currently commited (1 corresponds to not in use).
+ *
+ * @returns 0 if initialisation is sucessful, and non-zero otherwise.
+ */
+ [[nodiscard]] int init(uint64_t &bufferBitmap) volatile
+ {
+ bufferBitmap =
+ supply_buffers((static_cast<uint64_t>(1u) << BufferCount) - 1u);
+ phyConfig =
+ static_cast<uint32_t>(PhyConfigField::UseDifferentialReceiver);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an OUT endpoint for the USB device.
+ *
+ * @param endpointId The ID of the OUT endpoint to configure.
+ * @param enabled Whether the OUT endpoint should be enabled or not.
+ * @param setup Whether SETUP transactions should be enabled for the
+ * endpoint.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_out_endpoint(uint8_t endpointId,
+ bool enabled,
+ bool setup,
+ bool isochronous) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ endpointOutEnable = (endpointOutEnable & ~Mask) | (enabled ? Mask : 0u);
+ outIsochronous = (outIsochronous & ~Mask) | (isochronous ? Mask : 0u);
+ receiveEnableSetup = (receiveEnableSetup & ~Mask) | (setup ? Mask : 0u);
+ receiveEnableOut = (receiveEnableOut & ~Mask) | (enabled ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an IN endpoint for the USB device.
+ *
+ * @param endpointId The ID of the IN endpoint to configure
+ * @param enabled Whether the IN endpoint should be enabled or not.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_in_endpoint(uint8_t endpointId, | I'm not sure how important it is, given that code using it will be quite specific to this driver, but this and the one above are not great names. We generally prefer to start with the object (endpoint) so that autocomplete finds related things. I am not a huge fan of `in` here either because it's not clear whether that's a modifier on endpoint or on the function behaviour without reading the comment. |
cheriot-rtos | github_2023 | others | 337 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,633 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+#include <utils.hh>
+
+/**
+ * A driver for OpenTitan USB Device, which is used in the Sonata system.
+ *
+ * This peripheral's source and documentation can be found at:
+ * https://github.com/lowRISC/opentitan/tree/ab878b5d3578939a04db72d4ed966a56a869b2ed/hw/ip/usbdev
+ *
+ * With rendered register documentation served at:
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html
+ */
+class OpenTitanUsbdev : private utils::NoCopyNoMove
+{
+ public:
+ /// Supported sizes for the USB Device.
+ static constexpr uint8_t MaxPacketLength = 64u;
+ static constexpr uint8_t BufferCount = 32u;
+ static constexpr uint8_t MaxEndpoints = 12u;
+
+ /**
+ * The offset from the start of the USB Device MMIO region at which
+ * packet buffer memory begins.
+ */
+ static constexpr uint32_t BufferStartAddress = 0x800u;
+
+ /// Device Registers
+ uint32_t interruptState;
+ uint32_t interruptEnable;
+ uint32_t interruptTest;
+ uint32_t alertTest;
+ uint32_t usbControl;
+ uint32_t endpointOutEnable;
+ uint32_t endpointInEnable;
+ uint32_t usbStatus;
+ uint32_t availableOutBuffer;
+ uint32_t availableSetupBuffer;
+ uint32_t receiveBuffer;
+ /// Register to enable receive SETUP transactions
+ uint32_t receiveEnableSetup;
+ /// Register to enable receive OUT transactions
+ uint32_t receiveEnableOut;
+ /// Register to set NAK (Not/Negated Acknowledge) after OUT transactions
+ uint32_t setNotAcknowledgeOut;
+ /// Register showing ACK receival to indicate a successful IN send
+ uint32_t inSent;
+ /// Registers for controlling the stalling of OUT and IN endpoints
+ uint32_t outStall;
+ uint32_t inStall;
+ /**
+ * IN transaction configuration registers. There is one register per
+ * endpoint for the USB device.
+ */
+ uint32_t configIn[MaxEndpoints];
+ /**
+ * Registers for configuring which endpoints should be treated as
+ * isochronous endpoints. This means that if the corresponding bit is set,
+ * then that no handshake packet will be sent for an OUT/IN transaction on
+ * that endpoint.
+ */
+ uint32_t outIsochronous;
+ uint32_t inIsochronous;
+ /// Registers for configuring if endpoints data toggle on transactions
+ uint32_t outDataToggle;
+ uint32_t inDataToggle;
+
+ private:
+ /**
+ * Registers to sense/drive the USB PHY pins. That is, these registers can
+ * be used to respectively read out the state of the USB device inputs and
+ * outputs, or to control the inputs and outputs from software. These
+ * registers are kept private as they are intended to be used for debugging
+ * purposes or during chip testing, and not in actual software.
+ */
+ [[maybe_unused]] uint32_t phyPinsSense;
+ [[maybe_unused]] uint32_t phyPinsDrive;
+
+ public:
+ /// Config register for the USB PHY pins.
+ uint32_t phyConfig;
+
+ /// Interrupt definitions for OpenTitan's USB Device.
+ enum class UsbdevInterrupt : uint32_t
+ {
+ /// Interrupt asserted whilst the receive FIFO (buffer) is not empty.
+ PacketReceived = 1u << 0,
+ /**
+ * Interrupt asserted when a packet was sent as part of an IN
+ * transaction, but not cleared from the `inSent` register.
+ */
+ PacketSent = 1u << 1,
+ /**
+ * Interrupt raised when VBUS (power supply) is lost, i.e. the link to
+ * the USB host controller has been disconnected.
+ */
+ Disconnected = 1u << 2,
+ /**
+ * Interrupt raised when the link is active, but a Start of Frame (SOF)
+ * packet has not been received within a given timeout threshold, which
+ * is set to 4.096 milliseconds.
+ */
+ HostLost = 1u << 3,
+ /**
+ * Interrupt raised when a Bus Reset condition is indicated on the link
+ * by the link being held in an SE0 state (Single Ended Zero, both lines
+ * being pulled low) for longer than 3 microseconds.
+ */
+ LinkReset = 1u << 4,
+ /**
+ * Interrupt raised when the link has entered the suspend state, due to
+ * being idle for more than 3 milliseconds.
+ */
+ LinkSuspend = 1u << 5,
+ /// Interrupt raised on link transition from suspended to non-idle.
+ LinkResume = 1u << 6,
+ /// Interrupt asserted whilst the Available OUT buffer is empty.
+ AvailableOutEmpty = 1u << 7,
+ /// Interrupt asserted whilst the Receive buffer is full.
+ ReceiveFull = 1u << 8,
+ /**
+ * Interrupt raised when the Available OUT buffer or the Available SETUP
+ * buffer overflows.
+ */
+ AvailableBufferOverflow = 1u << 9,
+ /// Interrupt raised when an error occurs during an IN transaction.
+ LinkInError = 1u << 10,
+ /**
+ * Interrupt raised when a CRC (cyclic redundancy check) error occurs on
+ * a received packet; i.e. there was an error in transmission.
+ */
+ RedundancyCheckError = 1u << 11,
+ /// Interrupt raised when an invalid Packet Identifier is received.
+ PacketIdentifierError = 1u << 12,
+ /// Interrupt raised when a bit stuffing violation is detected.
+ BitstuffingError = 1u << 13,
+ /**
+ * Interrupt raised when the USB frame number is updated with a valid
+ * SOF (Start of Frame) packet.
+ */
+ FrameUpdated = 1u << 14,
+ /// Interrupt raised when VBUS (power supply) is detected.
+ Powered = 1u << 15,
+ /// Interrupt raised when an error occurs during an OUT transaction.
+ LinkOutError = 1u << 16,
+ /// Interrupt asserted whilst the Available SETUP buffer is empty.
+ AvailableSetupEmpty = 1u << 17,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Control register
+ * (offset 0x10).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbctrl
+ */
+ enum class UsbControlField : uint32_t
+ {
+ Enable = 1u << 0,
+ ResumeLinkActive = 1u << 1,
+ DeviceAddress = 0x7Fu << 16,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Status register
+ * (offset 0x1c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbstat
+ */
+ enum class UsbStatusField : uint32_t
+ {
+ Frame = 0x7FFu << 0,
+ HostLost = 1u << 11,
+ LinkState = 0x7u << 12,
+ Sense = 1u << 15,
+ AvailableOutDepth = 0xFu << 16,
+ AvailableSetupDepth = 0x7u << 20,
+ AvailableOutFull = 1u << 23,
+ ReceiveDepth = 0xFu << 24,
+ AvailableSetupFull = 1u << 30,
+ ReceiveEmpty = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the Receive FIFO
+ * buffer register (offset 0x28).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#rxfifo
+ */
+ enum class ReceiveBufferField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Setup = 1u << 19,
+ EndpointId = 0xFu << 20,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for a Config In register
+ * (where there is one such register for each endpoint). These are
+ * the registers with offsets 0x44 up to (and not including) 0x74.
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#configin
+ */
+ enum class ConfigInField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Sending = 1u << 29,
+ Pending = 1u << 30,
+ Ready = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the PHY Config
+ * Register (offset 0x8c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#phy_config
+ */
+ enum class PhyConfigField : uint32_t
+ {
+ UseDifferentialReceiver = 1u << 0,
+ // Other PHY Configuration fields are omitted.
+ };
+
+ /**
+ * Ensure that the Available OUT and Available SETUP buffers are kept
+ * supplied with buffers for packet reception.
+ *
+ * @param bufferBitmap A bitmap of the buffers that are not currently
+ * committed (where 1 corresponds to not in use).
+ * @returns The updated bitmap after supplying buffers.
+ */
+ [[nodiscard]] uint64_t supply_buffers(uint64_t bufferBitmap) volatile
+ {
+ constexpr uint32_t SetupFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableSetupFull);
+ constexpr uint32_t OutFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableOutFull);
+
+ for (uint8_t index = 0; index < BufferCount; index++)
+ {
+ const uint32_t Buffer = (1u << index);
+ if (!(bufferBitmap & Buffer))
+ {
+ continue; // Skip buffers that are not available
+ }
+
+ // If a buffer is available, and either Available SETUP or OUT are
+ // not yet full, then commit that buffer and mark it as in use.
+ if (usbStatus & SetupFullBit)
+ {
+ if (usbStatus & OutFullBit)
+ {
+ break; // Both are full - stop trying to supply buffers.
+ }
+ availableOutBuffer = index;
+ }
+ else
+ {
+ availableSetupBuffer = index;
+ }
+ bufferBitmap &= ~Buffer;
+ }
+ return bufferBitmap;
+ }
+
+ /**
+ * Enable a specified interrupt / interrupts.
+ */
+ void interrupt_enable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable | static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Disable a specified interrupt / interrupts.
+ */
+ void interrupt_disable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable & ~static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Initialise the USB device, ensuring that packet buffers are available for
+ * reception and that the PHY has been appropriately configured. Note that
+ * at this stage, endpoints have not been configured and the device has not
+ * been connected to the USB.
+ *
+ * @param bufferBitmap An out-parameter, to initialise a bitmap of the
+ * buffers that are not currently commited (1 corresponds to not in use).
+ *
+ * @returns 0 if initialisation is sucessful, and non-zero otherwise.
+ */
+ [[nodiscard]] int init(uint64_t &bufferBitmap) volatile
+ {
+ bufferBitmap =
+ supply_buffers((static_cast<uint64_t>(1u) << BufferCount) - 1u);
+ phyConfig =
+ static_cast<uint32_t>(PhyConfigField::UseDifferentialReceiver);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an OUT endpoint for the USB device.
+ *
+ * @param endpointId The ID of the OUT endpoint to configure.
+ * @param enabled Whether the OUT endpoint should be enabled or not.
+ * @param setup Whether SETUP transactions should be enabled for the
+ * endpoint.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_out_endpoint(uint8_t endpointId,
+ bool enabled,
+ bool setup,
+ bool isochronous) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ endpointOutEnable = (endpointOutEnable & ~Mask) | (enabled ? Mask : 0u);
+ outIsochronous = (outIsochronous & ~Mask) | (isochronous ? Mask : 0u);
+ receiveEnableSetup = (receiveEnableSetup & ~Mask) | (setup ? Mask : 0u);
+ receiveEnableOut = (receiveEnableOut & ~Mask) | (enabled ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an IN endpoint for the USB device.
+ *
+ * @param endpointId The ID of the IN endpoint to configure
+ * @param enabled Whether the IN endpoint should be enabled or not.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_in_endpoint(uint8_t endpointId,
+ bool enabled,
+ bool isochronous) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ endpointInEnable = (endpointInEnable & ~Mask) | (enabled ? Mask : 0u);
+ inIsochronous = (inIsochronous & ~Mask) | (isochronous ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Set the STALL state of a specified endpoint pair (both IN and OUT).
+ *
+ * @param endpointId The ID of the endpoint pair to modify.
+ * @param stalling Whether the endpoints are stalling or not.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int set_endpoint_stalling(uint8_t endpointId, | As above. |
cheriot-rtos | github_2023 | others | 337 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,633 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+#include <utils.hh>
+
+/**
+ * A driver for OpenTitan USB Device, which is used in the Sonata system.
+ *
+ * This peripheral's source and documentation can be found at:
+ * https://github.com/lowRISC/opentitan/tree/ab878b5d3578939a04db72d4ed966a56a869b2ed/hw/ip/usbdev
+ *
+ * With rendered register documentation served at:
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html
+ */
+class OpenTitanUsbdev : private utils::NoCopyNoMove
+{
+ public:
+ /// Supported sizes for the USB Device.
+ static constexpr uint8_t MaxPacketLength = 64u;
+ static constexpr uint8_t BufferCount = 32u;
+ static constexpr uint8_t MaxEndpoints = 12u;
+
+ /**
+ * The offset from the start of the USB Device MMIO region at which
+ * packet buffer memory begins.
+ */
+ static constexpr uint32_t BufferStartAddress = 0x800u;
+
+ /// Device Registers
+ uint32_t interruptState;
+ uint32_t interruptEnable;
+ uint32_t interruptTest;
+ uint32_t alertTest;
+ uint32_t usbControl;
+ uint32_t endpointOutEnable;
+ uint32_t endpointInEnable;
+ uint32_t usbStatus;
+ uint32_t availableOutBuffer;
+ uint32_t availableSetupBuffer;
+ uint32_t receiveBuffer;
+ /// Register to enable receive SETUP transactions
+ uint32_t receiveEnableSetup;
+ /// Register to enable receive OUT transactions
+ uint32_t receiveEnableOut;
+ /// Register to set NAK (Not/Negated Acknowledge) after OUT transactions
+ uint32_t setNotAcknowledgeOut;
+ /// Register showing ACK receival to indicate a successful IN send
+ uint32_t inSent;
+ /// Registers for controlling the stalling of OUT and IN endpoints
+ uint32_t outStall;
+ uint32_t inStall;
+ /**
+ * IN transaction configuration registers. There is one register per
+ * endpoint for the USB device.
+ */
+ uint32_t configIn[MaxEndpoints];
+ /**
+ * Registers for configuring which endpoints should be treated as
+ * isochronous endpoints. This means that if the corresponding bit is set,
+ * then that no handshake packet will be sent for an OUT/IN transaction on
+ * that endpoint.
+ */
+ uint32_t outIsochronous;
+ uint32_t inIsochronous;
+ /// Registers for configuring if endpoints data toggle on transactions
+ uint32_t outDataToggle;
+ uint32_t inDataToggle;
+
+ private:
+ /**
+ * Registers to sense/drive the USB PHY pins. That is, these registers can
+ * be used to respectively read out the state of the USB device inputs and
+ * outputs, or to control the inputs and outputs from software. These
+ * registers are kept private as they are intended to be used for debugging
+ * purposes or during chip testing, and not in actual software.
+ */
+ [[maybe_unused]] uint32_t phyPinsSense;
+ [[maybe_unused]] uint32_t phyPinsDrive;
+
+ public:
+ /// Config register for the USB PHY pins.
+ uint32_t phyConfig;
+
+ /// Interrupt definitions for OpenTitan's USB Device.
+ enum class UsbdevInterrupt : uint32_t
+ {
+ /// Interrupt asserted whilst the receive FIFO (buffer) is not empty.
+ PacketReceived = 1u << 0,
+ /**
+ * Interrupt asserted when a packet was sent as part of an IN
+ * transaction, but not cleared from the `inSent` register.
+ */
+ PacketSent = 1u << 1,
+ /**
+ * Interrupt raised when VBUS (power supply) is lost, i.e. the link to
+ * the USB host controller has been disconnected.
+ */
+ Disconnected = 1u << 2,
+ /**
+ * Interrupt raised when the link is active, but a Start of Frame (SOF)
+ * packet has not been received within a given timeout threshold, which
+ * is set to 4.096 milliseconds.
+ */
+ HostLost = 1u << 3,
+ /**
+ * Interrupt raised when a Bus Reset condition is indicated on the link
+ * by the link being held in an SE0 state (Single Ended Zero, both lines
+ * being pulled low) for longer than 3 microseconds.
+ */
+ LinkReset = 1u << 4,
+ /**
+ * Interrupt raised when the link has entered the suspend state, due to
+ * being idle for more than 3 milliseconds.
+ */
+ LinkSuspend = 1u << 5,
+ /// Interrupt raised on link transition from suspended to non-idle.
+ LinkResume = 1u << 6,
+ /// Interrupt asserted whilst the Available OUT buffer is empty.
+ AvailableOutEmpty = 1u << 7,
+ /// Interrupt asserted whilst the Receive buffer is full.
+ ReceiveFull = 1u << 8,
+ /**
+ * Interrupt raised when the Available OUT buffer or the Available SETUP
+ * buffer overflows.
+ */
+ AvailableBufferOverflow = 1u << 9,
+ /// Interrupt raised when an error occurs during an IN transaction.
+ LinkInError = 1u << 10,
+ /**
+ * Interrupt raised when a CRC (cyclic redundancy check) error occurs on
+ * a received packet; i.e. there was an error in transmission.
+ */
+ RedundancyCheckError = 1u << 11,
+ /// Interrupt raised when an invalid Packet Identifier is received.
+ PacketIdentifierError = 1u << 12,
+ /// Interrupt raised when a bit stuffing violation is detected.
+ BitstuffingError = 1u << 13,
+ /**
+ * Interrupt raised when the USB frame number is updated with a valid
+ * SOF (Start of Frame) packet.
+ */
+ FrameUpdated = 1u << 14,
+ /// Interrupt raised when VBUS (power supply) is detected.
+ Powered = 1u << 15,
+ /// Interrupt raised when an error occurs during an OUT transaction.
+ LinkOutError = 1u << 16,
+ /// Interrupt asserted whilst the Available SETUP buffer is empty.
+ AvailableSetupEmpty = 1u << 17,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Control register
+ * (offset 0x10).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbctrl
+ */
+ enum class UsbControlField : uint32_t
+ {
+ Enable = 1u << 0,
+ ResumeLinkActive = 1u << 1,
+ DeviceAddress = 0x7Fu << 16,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Status register
+ * (offset 0x1c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbstat
+ */
+ enum class UsbStatusField : uint32_t
+ {
+ Frame = 0x7FFu << 0,
+ HostLost = 1u << 11,
+ LinkState = 0x7u << 12,
+ Sense = 1u << 15,
+ AvailableOutDepth = 0xFu << 16,
+ AvailableSetupDepth = 0x7u << 20,
+ AvailableOutFull = 1u << 23,
+ ReceiveDepth = 0xFu << 24,
+ AvailableSetupFull = 1u << 30,
+ ReceiveEmpty = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the Receive FIFO
+ * buffer register (offset 0x28).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#rxfifo
+ */
+ enum class ReceiveBufferField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Setup = 1u << 19,
+ EndpointId = 0xFu << 20,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for a Config In register
+ * (where there is one such register for each endpoint). These are
+ * the registers with offsets 0x44 up to (and not including) 0x74.
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#configin
+ */
+ enum class ConfigInField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Sending = 1u << 29,
+ Pending = 1u << 30,
+ Ready = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the PHY Config
+ * Register (offset 0x8c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#phy_config
+ */
+ enum class PhyConfigField : uint32_t
+ {
+ UseDifferentialReceiver = 1u << 0,
+ // Other PHY Configuration fields are omitted.
+ };
+
+ /**
+ * Ensure that the Available OUT and Available SETUP buffers are kept
+ * supplied with buffers for packet reception.
+ *
+ * @param bufferBitmap A bitmap of the buffers that are not currently
+ * committed (where 1 corresponds to not in use).
+ * @returns The updated bitmap after supplying buffers.
+ */
+ [[nodiscard]] uint64_t supply_buffers(uint64_t bufferBitmap) volatile
+ {
+ constexpr uint32_t SetupFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableSetupFull);
+ constexpr uint32_t OutFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableOutFull);
+
+ for (uint8_t index = 0; index < BufferCount; index++)
+ {
+ const uint32_t Buffer = (1u << index);
+ if (!(bufferBitmap & Buffer))
+ {
+ continue; // Skip buffers that are not available
+ }
+
+ // If a buffer is available, and either Available SETUP or OUT are
+ // not yet full, then commit that buffer and mark it as in use.
+ if (usbStatus & SetupFullBit)
+ {
+ if (usbStatus & OutFullBit)
+ {
+ break; // Both are full - stop trying to supply buffers.
+ }
+ availableOutBuffer = index;
+ }
+ else
+ {
+ availableSetupBuffer = index;
+ }
+ bufferBitmap &= ~Buffer;
+ }
+ return bufferBitmap;
+ }
+
+ /**
+ * Enable a specified interrupt / interrupts.
+ */
+ void interrupt_enable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable | static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Disable a specified interrupt / interrupts.
+ */
+ void interrupt_disable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable & ~static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Initialise the USB device, ensuring that packet buffers are available for
+ * reception and that the PHY has been appropriately configured. Note that
+ * at this stage, endpoints have not been configured and the device has not
+ * been connected to the USB.
+ *
+ * @param bufferBitmap An out-parameter, to initialise a bitmap of the
+ * buffers that are not currently commited (1 corresponds to not in use).
+ *
+ * @returns 0 if initialisation is sucessful, and non-zero otherwise.
+ */
+ [[nodiscard]] int init(uint64_t &bufferBitmap) volatile
+ {
+ bufferBitmap =
+ supply_buffers((static_cast<uint64_t>(1u) << BufferCount) - 1u);
+ phyConfig =
+ static_cast<uint32_t>(PhyConfigField::UseDifferentialReceiver);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an OUT endpoint for the USB device.
+ *
+ * @param endpointId The ID of the OUT endpoint to configure.
+ * @param enabled Whether the OUT endpoint should be enabled or not.
+ * @param setup Whether SETUP transactions should be enabled for the
+ * endpoint.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_out_endpoint(uint8_t endpointId,
+ bool enabled,
+ bool setup,
+ bool isochronous) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ endpointOutEnable = (endpointOutEnable & ~Mask) | (enabled ? Mask : 0u);
+ outIsochronous = (outIsochronous & ~Mask) | (isochronous ? Mask : 0u);
+ receiveEnableSetup = (receiveEnableSetup & ~Mask) | (setup ? Mask : 0u);
+ receiveEnableOut = (receiveEnableOut & ~Mask) | (enabled ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an IN endpoint for the USB device.
+ *
+ * @param endpointId The ID of the IN endpoint to configure
+ * @param enabled Whether the IN endpoint should be enabled or not.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_in_endpoint(uint8_t endpointId,
+ bool enabled,
+ bool isochronous) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ endpointInEnable = (endpointInEnable & ~Mask) | (enabled ? Mask : 0u);
+ inIsochronous = (inIsochronous & ~Mask) | (isochronous ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Set the STALL state of a specified endpoint pair (both IN and OUT).
+ *
+ * @param endpointId The ID of the endpoint pair to modify.
+ * @param stalling Whether the endpoints are stalling or not.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int set_endpoint_stalling(uint8_t endpointId,
+ bool stalling) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ outStall = (outStall & ~Mask) | (stalling ? Mask : 0u);
+ inStall = (inStall & ~Mask) | (stalling ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Connect the device to the USB, indicating its presence to the USB host
+ * controller. Endpoints must already have been configured at this point
+ * because traffic may be received imminently. | Can we assert something to check that this has happened? |
cheriot-rtos | github_2023 | others | 337 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,633 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+#include <utils.hh>
+
+/**
+ * A driver for OpenTitan USB Device, which is used in the Sonata system.
+ *
+ * This peripheral's source and documentation can be found at:
+ * https://github.com/lowRISC/opentitan/tree/ab878b5d3578939a04db72d4ed966a56a869b2ed/hw/ip/usbdev
+ *
+ * With rendered register documentation served at:
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html
+ */
+class OpenTitanUsbdev : private utils::NoCopyNoMove
+{
+ public:
+ /// Supported sizes for the USB Device.
+ static constexpr uint8_t MaxPacketLength = 64u;
+ static constexpr uint8_t BufferCount = 32u;
+ static constexpr uint8_t MaxEndpoints = 12u;
+
+ /**
+ * The offset from the start of the USB Device MMIO region at which
+ * packet buffer memory begins.
+ */
+ static constexpr uint32_t BufferStartAddress = 0x800u;
+
+ /// Device Registers
+ uint32_t interruptState;
+ uint32_t interruptEnable;
+ uint32_t interruptTest;
+ uint32_t alertTest;
+ uint32_t usbControl;
+ uint32_t endpointOutEnable;
+ uint32_t endpointInEnable;
+ uint32_t usbStatus;
+ uint32_t availableOutBuffer;
+ uint32_t availableSetupBuffer;
+ uint32_t receiveBuffer;
+ /// Register to enable receive SETUP transactions
+ uint32_t receiveEnableSetup;
+ /// Register to enable receive OUT transactions
+ uint32_t receiveEnableOut;
+ /// Register to set NAK (Not/Negated Acknowledge) after OUT transactions
+ uint32_t setNotAcknowledgeOut;
+ /// Register showing ACK receival to indicate a successful IN send
+ uint32_t inSent;
+ /// Registers for controlling the stalling of OUT and IN endpoints
+ uint32_t outStall;
+ uint32_t inStall;
+ /**
+ * IN transaction configuration registers. There is one register per
+ * endpoint for the USB device.
+ */
+ uint32_t configIn[MaxEndpoints];
+ /**
+ * Registers for configuring which endpoints should be treated as
+ * isochronous endpoints. This means that if the corresponding bit is set,
+ * then that no handshake packet will be sent for an OUT/IN transaction on
+ * that endpoint.
+ */
+ uint32_t outIsochronous;
+ uint32_t inIsochronous;
+ /// Registers for configuring if endpoints data toggle on transactions
+ uint32_t outDataToggle;
+ uint32_t inDataToggle;
+
+ private:
+ /**
+ * Registers to sense/drive the USB PHY pins. That is, these registers can
+ * be used to respectively read out the state of the USB device inputs and
+ * outputs, or to control the inputs and outputs from software. These
+ * registers are kept private as they are intended to be used for debugging
+ * purposes or during chip testing, and not in actual software.
+ */
+ [[maybe_unused]] uint32_t phyPinsSense;
+ [[maybe_unused]] uint32_t phyPinsDrive;
+
+ public:
+ /// Config register for the USB PHY pins.
+ uint32_t phyConfig;
+
+ /// Interrupt definitions for OpenTitan's USB Device.
+ enum class UsbdevInterrupt : uint32_t
+ {
+ /// Interrupt asserted whilst the receive FIFO (buffer) is not empty.
+ PacketReceived = 1u << 0,
+ /**
+ * Interrupt asserted when a packet was sent as part of an IN
+ * transaction, but not cleared from the `inSent` register.
+ */
+ PacketSent = 1u << 1,
+ /**
+ * Interrupt raised when VBUS (power supply) is lost, i.e. the link to
+ * the USB host controller has been disconnected.
+ */
+ Disconnected = 1u << 2,
+ /**
+ * Interrupt raised when the link is active, but a Start of Frame (SOF)
+ * packet has not been received within a given timeout threshold, which
+ * is set to 4.096 milliseconds.
+ */
+ HostLost = 1u << 3,
+ /**
+ * Interrupt raised when a Bus Reset condition is indicated on the link
+ * by the link being held in an SE0 state (Single Ended Zero, both lines
+ * being pulled low) for longer than 3 microseconds.
+ */
+ LinkReset = 1u << 4,
+ /**
+ * Interrupt raised when the link has entered the suspend state, due to
+ * being idle for more than 3 milliseconds.
+ */
+ LinkSuspend = 1u << 5,
+ /// Interrupt raised on link transition from suspended to non-idle.
+ LinkResume = 1u << 6,
+ /// Interrupt asserted whilst the Available OUT buffer is empty.
+ AvailableOutEmpty = 1u << 7,
+ /// Interrupt asserted whilst the Receive buffer is full.
+ ReceiveFull = 1u << 8,
+ /**
+ * Interrupt raised when the Available OUT buffer or the Available SETUP
+ * buffer overflows.
+ */
+ AvailableBufferOverflow = 1u << 9,
+ /// Interrupt raised when an error occurs during an IN transaction.
+ LinkInError = 1u << 10,
+ /**
+ * Interrupt raised when a CRC (cyclic redundancy check) error occurs on
+ * a received packet; i.e. there was an error in transmission.
+ */
+ RedundancyCheckError = 1u << 11,
+ /// Interrupt raised when an invalid Packet Identifier is received.
+ PacketIdentifierError = 1u << 12,
+ /// Interrupt raised when a bit stuffing violation is detected.
+ BitstuffingError = 1u << 13,
+ /**
+ * Interrupt raised when the USB frame number is updated with a valid
+ * SOF (Start of Frame) packet.
+ */
+ FrameUpdated = 1u << 14,
+ /// Interrupt raised when VBUS (power supply) is detected.
+ Powered = 1u << 15,
+ /// Interrupt raised when an error occurs during an OUT transaction.
+ LinkOutError = 1u << 16,
+ /// Interrupt asserted whilst the Available SETUP buffer is empty.
+ AvailableSetupEmpty = 1u << 17,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Control register
+ * (offset 0x10).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbctrl
+ */
+ enum class UsbControlField : uint32_t
+ {
+ Enable = 1u << 0,
+ ResumeLinkActive = 1u << 1,
+ DeviceAddress = 0x7Fu << 16,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Status register
+ * (offset 0x1c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbstat
+ */
+ enum class UsbStatusField : uint32_t
+ {
+ Frame = 0x7FFu << 0,
+ HostLost = 1u << 11,
+ LinkState = 0x7u << 12,
+ Sense = 1u << 15,
+ AvailableOutDepth = 0xFu << 16,
+ AvailableSetupDepth = 0x7u << 20,
+ AvailableOutFull = 1u << 23,
+ ReceiveDepth = 0xFu << 24,
+ AvailableSetupFull = 1u << 30,
+ ReceiveEmpty = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the Receive FIFO
+ * buffer register (offset 0x28).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#rxfifo
+ */
+ enum class ReceiveBufferField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Setup = 1u << 19,
+ EndpointId = 0xFu << 20,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for a Config In register
+ * (where there is one such register for each endpoint). These are
+ * the registers with offsets 0x44 up to (and not including) 0x74.
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#configin
+ */
+ enum class ConfigInField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Sending = 1u << 29,
+ Pending = 1u << 30,
+ Ready = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the PHY Config
+ * Register (offset 0x8c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#phy_config
+ */
+ enum class PhyConfigField : uint32_t
+ {
+ UseDifferentialReceiver = 1u << 0,
+ // Other PHY Configuration fields are omitted.
+ };
+
+ /**
+ * Ensure that the Available OUT and Available SETUP buffers are kept
+ * supplied with buffers for packet reception.
+ *
+ * @param bufferBitmap A bitmap of the buffers that are not currently
+ * committed (where 1 corresponds to not in use).
+ * @returns The updated bitmap after supplying buffers.
+ */
+ [[nodiscard]] uint64_t supply_buffers(uint64_t bufferBitmap) volatile
+ {
+ constexpr uint32_t SetupFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableSetupFull);
+ constexpr uint32_t OutFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableOutFull);
+
+ for (uint8_t index = 0; index < BufferCount; index++)
+ {
+ const uint32_t Buffer = (1u << index);
+ if (!(bufferBitmap & Buffer))
+ {
+ continue; // Skip buffers that are not available
+ }
+
+ // If a buffer is available, and either Available SETUP or OUT are
+ // not yet full, then commit that buffer and mark it as in use.
+ if (usbStatus & SetupFullBit)
+ {
+ if (usbStatus & OutFullBit)
+ {
+ break; // Both are full - stop trying to supply buffers.
+ }
+ availableOutBuffer = index;
+ }
+ else
+ {
+ availableSetupBuffer = index;
+ }
+ bufferBitmap &= ~Buffer;
+ }
+ return bufferBitmap;
+ }
+
+ /**
+ * Enable a specified interrupt / interrupts.
+ */
+ void interrupt_enable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable | static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Disable a specified interrupt / interrupts.
+ */
+ void interrupt_disable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable & ~static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Initialise the USB device, ensuring that packet buffers are available for
+ * reception and that the PHY has been appropriately configured. Note that
+ * at this stage, endpoints have not been configured and the device has not
+ * been connected to the USB.
+ *
+ * @param bufferBitmap An out-parameter, to initialise a bitmap of the
+ * buffers that are not currently commited (1 corresponds to not in use).
+ *
+ * @returns 0 if initialisation is sucessful, and non-zero otherwise.
+ */
+ [[nodiscard]] int init(uint64_t &bufferBitmap) volatile
+ {
+ bufferBitmap =
+ supply_buffers((static_cast<uint64_t>(1u) << BufferCount) - 1u);
+ phyConfig =
+ static_cast<uint32_t>(PhyConfigField::UseDifferentialReceiver);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an OUT endpoint for the USB device.
+ *
+ * @param endpointId The ID of the OUT endpoint to configure.
+ * @param enabled Whether the OUT endpoint should be enabled or not.
+ * @param setup Whether SETUP transactions should be enabled for the
+ * endpoint.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_out_endpoint(uint8_t endpointId,
+ bool enabled,
+ bool setup,
+ bool isochronous) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ endpointOutEnable = (endpointOutEnable & ~Mask) | (enabled ? Mask : 0u);
+ outIsochronous = (outIsochronous & ~Mask) | (isochronous ? Mask : 0u);
+ receiveEnableSetup = (receiveEnableSetup & ~Mask) | (setup ? Mask : 0u);
+ receiveEnableOut = (receiveEnableOut & ~Mask) | (enabled ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an IN endpoint for the USB device.
+ *
+ * @param endpointId The ID of the IN endpoint to configure
+ * @param enabled Whether the IN endpoint should be enabled or not.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_in_endpoint(uint8_t endpointId,
+ bool enabled,
+ bool isochronous) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ endpointInEnable = (endpointInEnable & ~Mask) | (enabled ? Mask : 0u);
+ inIsochronous = (inIsochronous & ~Mask) | (isochronous ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Set the STALL state of a specified endpoint pair (both IN and OUT).
+ *
+ * @param endpointId The ID of the endpoint pair to modify.
+ * @param stalling Whether the endpoints are stalling or not.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int set_endpoint_stalling(uint8_t endpointId,
+ bool stalling) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ outStall = (outStall & ~Mask) | (stalling ? Mask : 0u);
+ inStall = (inStall & ~Mask) | (stalling ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Connect the device to the USB, indicating its presence to the USB host
+ * controller. Endpoints must already have been configured at this point
+ * because traffic may be received imminently.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int connect() volatile
+ {
+ usbControl =
+ usbControl | static_cast<uint32_t>(UsbControlField::Enable);
+ return 0;
+ }
+
+ /**
+ * Disconnect the device from the USB.
+ *
+ * @returns 0 if successful, and non-zero otherwise. | Under what circumstances can this fail? This and `connect` look as if they unconditionally return 0? |
cheriot-rtos | github_2023 | others | 337 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,633 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+#include <utils.hh>
+
+/**
+ * A driver for OpenTitan USB Device, which is used in the Sonata system.
+ *
+ * This peripheral's source and documentation can be found at:
+ * https://github.com/lowRISC/opentitan/tree/ab878b5d3578939a04db72d4ed966a56a869b2ed/hw/ip/usbdev
+ *
+ * With rendered register documentation served at:
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html
+ */
+class OpenTitanUsbdev : private utils::NoCopyNoMove
+{
+ public:
+ /// Supported sizes for the USB Device.
+ static constexpr uint8_t MaxPacketLength = 64u;
+ static constexpr uint8_t BufferCount = 32u;
+ static constexpr uint8_t MaxEndpoints = 12u;
+
+ /**
+ * The offset from the start of the USB Device MMIO region at which
+ * packet buffer memory begins.
+ */
+ static constexpr uint32_t BufferStartAddress = 0x800u;
+
+ /// Device Registers
+ uint32_t interruptState;
+ uint32_t interruptEnable;
+ uint32_t interruptTest;
+ uint32_t alertTest;
+ uint32_t usbControl;
+ uint32_t endpointOutEnable;
+ uint32_t endpointInEnable;
+ uint32_t usbStatus;
+ uint32_t availableOutBuffer;
+ uint32_t availableSetupBuffer;
+ uint32_t receiveBuffer;
+ /// Register to enable receive SETUP transactions
+ uint32_t receiveEnableSetup;
+ /// Register to enable receive OUT transactions
+ uint32_t receiveEnableOut;
+ /// Register to set NAK (Not/Negated Acknowledge) after OUT transactions
+ uint32_t setNotAcknowledgeOut;
+ /// Register showing ACK receival to indicate a successful IN send
+ uint32_t inSent;
+ /// Registers for controlling the stalling of OUT and IN endpoints
+ uint32_t outStall;
+ uint32_t inStall;
+ /**
+ * IN transaction configuration registers. There is one register per
+ * endpoint for the USB device.
+ */
+ uint32_t configIn[MaxEndpoints];
+ /**
+ * Registers for configuring which endpoints should be treated as
+ * isochronous endpoints. This means that if the corresponding bit is set,
+ * then that no handshake packet will be sent for an OUT/IN transaction on
+ * that endpoint.
+ */
+ uint32_t outIsochronous;
+ uint32_t inIsochronous;
+ /// Registers for configuring if endpoints data toggle on transactions
+ uint32_t outDataToggle;
+ uint32_t inDataToggle;
+
+ private:
+ /**
+ * Registers to sense/drive the USB PHY pins. That is, these registers can
+ * be used to respectively read out the state of the USB device inputs and
+ * outputs, or to control the inputs and outputs from software. These
+ * registers are kept private as they are intended to be used for debugging
+ * purposes or during chip testing, and not in actual software.
+ */
+ [[maybe_unused]] uint32_t phyPinsSense;
+ [[maybe_unused]] uint32_t phyPinsDrive;
+
+ public:
+ /// Config register for the USB PHY pins.
+ uint32_t phyConfig;
+
+ /// Interrupt definitions for OpenTitan's USB Device.
+ enum class UsbdevInterrupt : uint32_t
+ {
+ /// Interrupt asserted whilst the receive FIFO (buffer) is not empty.
+ PacketReceived = 1u << 0,
+ /**
+ * Interrupt asserted when a packet was sent as part of an IN
+ * transaction, but not cleared from the `inSent` register.
+ */
+ PacketSent = 1u << 1,
+ /**
+ * Interrupt raised when VBUS (power supply) is lost, i.e. the link to
+ * the USB host controller has been disconnected.
+ */
+ Disconnected = 1u << 2,
+ /**
+ * Interrupt raised when the link is active, but a Start of Frame (SOF)
+ * packet has not been received within a given timeout threshold, which
+ * is set to 4.096 milliseconds.
+ */
+ HostLost = 1u << 3,
+ /**
+ * Interrupt raised when a Bus Reset condition is indicated on the link
+ * by the link being held in an SE0 state (Single Ended Zero, both lines
+ * being pulled low) for longer than 3 microseconds.
+ */
+ LinkReset = 1u << 4,
+ /**
+ * Interrupt raised when the link has entered the suspend state, due to
+ * being idle for more than 3 milliseconds.
+ */
+ LinkSuspend = 1u << 5,
+ /// Interrupt raised on link transition from suspended to non-idle.
+ LinkResume = 1u << 6,
+ /// Interrupt asserted whilst the Available OUT buffer is empty.
+ AvailableOutEmpty = 1u << 7,
+ /// Interrupt asserted whilst the Receive buffer is full.
+ ReceiveFull = 1u << 8,
+ /**
+ * Interrupt raised when the Available OUT buffer or the Available SETUP
+ * buffer overflows.
+ */
+ AvailableBufferOverflow = 1u << 9,
+ /// Interrupt raised when an error occurs during an IN transaction.
+ LinkInError = 1u << 10,
+ /**
+ * Interrupt raised when a CRC (cyclic redundancy check) error occurs on
+ * a received packet; i.e. there was an error in transmission.
+ */
+ RedundancyCheckError = 1u << 11,
+ /// Interrupt raised when an invalid Packet Identifier is received.
+ PacketIdentifierError = 1u << 12,
+ /// Interrupt raised when a bit stuffing violation is detected.
+ BitstuffingError = 1u << 13,
+ /**
+ * Interrupt raised when the USB frame number is updated with a valid
+ * SOF (Start of Frame) packet.
+ */
+ FrameUpdated = 1u << 14,
+ /// Interrupt raised when VBUS (power supply) is detected.
+ Powered = 1u << 15,
+ /// Interrupt raised when an error occurs during an OUT transaction.
+ LinkOutError = 1u << 16,
+ /// Interrupt asserted whilst the Available SETUP buffer is empty.
+ AvailableSetupEmpty = 1u << 17,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Control register
+ * (offset 0x10).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbctrl
+ */
+ enum class UsbControlField : uint32_t
+ {
+ Enable = 1u << 0,
+ ResumeLinkActive = 1u << 1,
+ DeviceAddress = 0x7Fu << 16,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Status register
+ * (offset 0x1c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbstat
+ */
+ enum class UsbStatusField : uint32_t
+ {
+ Frame = 0x7FFu << 0,
+ HostLost = 1u << 11,
+ LinkState = 0x7u << 12,
+ Sense = 1u << 15,
+ AvailableOutDepth = 0xFu << 16,
+ AvailableSetupDepth = 0x7u << 20,
+ AvailableOutFull = 1u << 23,
+ ReceiveDepth = 0xFu << 24,
+ AvailableSetupFull = 1u << 30,
+ ReceiveEmpty = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the Receive FIFO
+ * buffer register (offset 0x28).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#rxfifo
+ */
+ enum class ReceiveBufferField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Setup = 1u << 19,
+ EndpointId = 0xFu << 20,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for a Config In register
+ * (where there is one such register for each endpoint). These are
+ * the registers with offsets 0x44 up to (and not including) 0x74.
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#configin
+ */
+ enum class ConfigInField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Sending = 1u << 29,
+ Pending = 1u << 30,
+ Ready = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the PHY Config
+ * Register (offset 0x8c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#phy_config
+ */
+ enum class PhyConfigField : uint32_t
+ {
+ UseDifferentialReceiver = 1u << 0,
+ // Other PHY Configuration fields are omitted.
+ };
+
+ /**
+ * Ensure that the Available OUT and Available SETUP buffers are kept
+ * supplied with buffers for packet reception.
+ *
+ * @param bufferBitmap A bitmap of the buffers that are not currently
+ * committed (where 1 corresponds to not in use).
+ * @returns The updated bitmap after supplying buffers.
+ */
+ [[nodiscard]] uint64_t supply_buffers(uint64_t bufferBitmap) volatile
+ {
+ constexpr uint32_t SetupFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableSetupFull);
+ constexpr uint32_t OutFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableOutFull);
+
+ for (uint8_t index = 0; index < BufferCount; index++)
+ {
+ const uint32_t Buffer = (1u << index);
+ if (!(bufferBitmap & Buffer))
+ {
+ continue; // Skip buffers that are not available
+ }
+
+ // If a buffer is available, and either Available SETUP or OUT are
+ // not yet full, then commit that buffer and mark it as in use.
+ if (usbStatus & SetupFullBit)
+ {
+ if (usbStatus & OutFullBit)
+ {
+ break; // Both are full - stop trying to supply buffers.
+ }
+ availableOutBuffer = index;
+ }
+ else
+ {
+ availableSetupBuffer = index;
+ }
+ bufferBitmap &= ~Buffer;
+ }
+ return bufferBitmap;
+ }
+
+ /**
+ * Enable a specified interrupt / interrupts.
+ */
+ void interrupt_enable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable | static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Disable a specified interrupt / interrupts.
+ */
+ void interrupt_disable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable & ~static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Initialise the USB device, ensuring that packet buffers are available for
+ * reception and that the PHY has been appropriately configured. Note that
+ * at this stage, endpoints have not been configured and the device has not
+ * been connected to the USB.
+ *
+ * @param bufferBitmap An out-parameter, to initialise a bitmap of the
+ * buffers that are not currently commited (1 corresponds to not in use).
+ *
+ * @returns 0 if initialisation is sucessful, and non-zero otherwise.
+ */
+ [[nodiscard]] int init(uint64_t &bufferBitmap) volatile
+ {
+ bufferBitmap =
+ supply_buffers((static_cast<uint64_t>(1u) << BufferCount) - 1u);
+ phyConfig =
+ static_cast<uint32_t>(PhyConfigField::UseDifferentialReceiver);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an OUT endpoint for the USB device.
+ *
+ * @param endpointId The ID of the OUT endpoint to configure.
+ * @param enabled Whether the OUT endpoint should be enabled or not.
+ * @param setup Whether SETUP transactions should be enabled for the
+ * endpoint.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_out_endpoint(uint8_t endpointId,
+ bool enabled,
+ bool setup,
+ bool isochronous) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ endpointOutEnable = (endpointOutEnable & ~Mask) | (enabled ? Mask : 0u);
+ outIsochronous = (outIsochronous & ~Mask) | (isochronous ? Mask : 0u);
+ receiveEnableSetup = (receiveEnableSetup & ~Mask) | (setup ? Mask : 0u);
+ receiveEnableOut = (receiveEnableOut & ~Mask) | (enabled ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an IN endpoint for the USB device.
+ *
+ * @param endpointId The ID of the IN endpoint to configure
+ * @param enabled Whether the IN endpoint should be enabled or not.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_in_endpoint(uint8_t endpointId,
+ bool enabled,
+ bool isochronous) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ endpointInEnable = (endpointInEnable & ~Mask) | (enabled ? Mask : 0u);
+ inIsochronous = (inIsochronous & ~Mask) | (isochronous ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Set the STALL state of a specified endpoint pair (both IN and OUT).
+ *
+ * @param endpointId The ID of the endpoint pair to modify.
+ * @param stalling Whether the endpoints are stalling or not.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int set_endpoint_stalling(uint8_t endpointId,
+ bool stalling) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ outStall = (outStall & ~Mask) | (stalling ? Mask : 0u);
+ inStall = (inStall & ~Mask) | (stalling ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Connect the device to the USB, indicating its presence to the USB host
+ * controller. Endpoints must already have been configured at this point
+ * because traffic may be received imminently.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int connect() volatile
+ {
+ usbControl =
+ usbControl | static_cast<uint32_t>(UsbControlField::Enable);
+ return 0;
+ }
+
+ /**
+ * Disconnect the device from the USB.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int disconnect() volatile
+ {
+ usbControl =
+ usbControl & ~static_cast<uint32_t>(UsbControlField::Enable);
+ return 0;
+ }
+
+ /**
+ * Check whether the USB device is connected (i.e. pullup enabled).
+ *
+ * @returns True to indicate it is connected, and false otherwise.
+ */
+ [[nodiscard]] bool connected() volatile
+ {
+ return (usbControl & static_cast<uint32_t>(UsbControlField::Enable));
+ }
+
+ /**
+ * Set the device address on the USB; this address will have been supplied
+ * by the USB host controller in the standard `SET_ADDRESS` Control
+ * Transfer.
+ *
+ * @param address The device address to set on the USB.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int set_device_address(uint8_t address) volatile
+ {
+ if (address >= 0x80)
+ return -1; // Device addresses are only 7 bits long.
+
+ constexpr uint32_t Mask =
+ static_cast<uint32_t>(UsbControlField::DeviceAddress);
+ usbControl = (usbControl & ~Mask) | (address << 16);
+ return 0;
+ }
+
+ /**
+ * Check and retrieve the endpoint and buffer numbers of a
+ * recently-collected IN data packet. The caller is responsible for reusing
+ * or releasing the buffer.
+ *
+ * @param endpointId An out-parameter, to which the ID of the endpoint for
+ * a recently-collected IN data packet will be written.
+ * @param bufferId An out-parameter, to which the ID of the buffer for a
+ * recently-collected IN data packet will be written.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int retrieve_collected_packet(uint8_t &endpointId,
+ uint8_t &bufferId) volatile
+ {
+ constexpr uint32_t BufferIdMask =
+ static_cast<uint32_t>(ConfigInField::BufferId);
+ uint32_t sent = inSent;
+
+ // Clear the first encountered packet sent indication.
+ for (endpointId = 0; endpointId < MaxEndpoints; endpointId++)
+ {
+ const uint32_t EndpointBit = 1u << endpointId;
+ if (sent & EndpointBit)
+ {
+ // Clear the `in_sent` bit for this specific endpoint, and
+ // indicate which buffer has been released.
+ inSent = EndpointBit;
+ bufferId = (configIn[endpointId] & BufferIdMask);
+ return 0;
+ }
+ }
+
+ // If no packet sent indications were found, then fail.
+ return -1;
+ }
+
+ /**
+ * Present a packet on the specified IN endpoint for collection by the USB
+ * host controller.
+ *
+ * @param bufferId The buffer to use to store the packet.
+ * @param endpointId The IN endpoint used to send the packet.
+ * @param data The packet to be transmitted.
+ * @param size The size of the packet.
+ *
+ * @returns 0 if successful, or non-zero if not successful.
+ */
+ [[nodiscard]] int packet_send(uint8_t bufferId,
+ uint8_t endpointId,
+ const uint32_t *data,
+ uint8_t size) volatile
+ {
+ // Transmission of zero length packets is common over USB
+ if (size > 0)
+ {
+ usbdev_transfer(buffers(bufferId), data, size, true);
+ }
+
+ constexpr uint32_t ReadyBit =
+ static_cast<uint32_t>(ConfigInField::Ready);
+ configIn[endpointId] = bufferId | (size << 8);
+ configIn[endpointId] = configIn[endpointId] | ReadyBit;
+ return 0;
+ }
+
+ /**
+ * Test for and collect the next received packet.
+ *
+ * @param bufferId An out-parameter storing the buffer ID used
+ * @param endpointId An out-parameter storing the endpoint received on.
+ * @param size An out-parameter storing the size of the received packet.
+ * @param isSetup A boolean out-parameter. True means the received packet
+ * was a SETUP packet, false means it was not.
+ * @param destination A destination buffer to read the packet's data into.
+ *
+ * @returns 0 if successful, or non-zero if not successful.
+ */
+ [[nodiscard]] int packet_receive(uint8_t &bufferId,
+ uint8_t &endpointId,
+ uint16_t &size,
+ bool &isSetup,
+ uint32_t *destination) volatile | Is it possible to probe for the endpoint here? If I were writing a driver in a compartment to service multiple USB devices in other compartments, I'd want them to provide an allocation capability to hold the next packet for their stream and then, when a packet is received, wake whichever thread should handle it. |
cheriot-rtos | github_2023 | others | 337 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,633 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+#include <utils.hh>
+
+/**
+ * A driver for OpenTitan USB Device, which is used in the Sonata system.
+ *
+ * This peripheral's source and documentation can be found at:
+ * https://github.com/lowRISC/opentitan/tree/ab878b5d3578939a04db72d4ed966a56a869b2ed/hw/ip/usbdev
+ *
+ * With rendered register documentation served at:
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html
+ */
+class OpenTitanUsbdev : private utils::NoCopyNoMove
+{
+ public:
+ /// Supported sizes for the USB Device.
+ static constexpr uint8_t MaxPacketLength = 64u;
+ static constexpr uint8_t BufferCount = 32u;
+ static constexpr uint8_t MaxEndpoints = 12u;
+
+ /**
+ * The offset from the start of the USB Device MMIO region at which
+ * packet buffer memory begins.
+ */
+ static constexpr uint32_t BufferStartAddress = 0x800u;
+
+ /// Device Registers
+ uint32_t interruptState;
+ uint32_t interruptEnable;
+ uint32_t interruptTest;
+ uint32_t alertTest;
+ uint32_t usbControl;
+ uint32_t endpointOutEnable;
+ uint32_t endpointInEnable;
+ uint32_t usbStatus;
+ uint32_t availableOutBuffer;
+ uint32_t availableSetupBuffer;
+ uint32_t receiveBuffer;
+ /// Register to enable receive SETUP transactions
+ uint32_t receiveEnableSetup;
+ /// Register to enable receive OUT transactions
+ uint32_t receiveEnableOut;
+ /// Register to set NAK (Not/Negated Acknowledge) after OUT transactions
+ uint32_t setNotAcknowledgeOut;
+ /// Register showing ACK receival to indicate a successful IN send
+ uint32_t inSent;
+ /// Registers for controlling the stalling of OUT and IN endpoints
+ uint32_t outStall;
+ uint32_t inStall;
+ /**
+ * IN transaction configuration registers. There is one register per
+ * endpoint for the USB device.
+ */
+ uint32_t configIn[MaxEndpoints];
+ /**
+ * Registers for configuring which endpoints should be treated as
+ * isochronous endpoints. This means that if the corresponding bit is set,
+ * then that no handshake packet will be sent for an OUT/IN transaction on
+ * that endpoint.
+ */
+ uint32_t outIsochronous;
+ uint32_t inIsochronous;
+ /// Registers for configuring if endpoints data toggle on transactions
+ uint32_t outDataToggle;
+ uint32_t inDataToggle;
+
+ private:
+ /**
+ * Registers to sense/drive the USB PHY pins. That is, these registers can
+ * be used to respectively read out the state of the USB device inputs and
+ * outputs, or to control the inputs and outputs from software. These
+ * registers are kept private as they are intended to be used for debugging
+ * purposes or during chip testing, and not in actual software.
+ */
+ [[maybe_unused]] uint32_t phyPinsSense;
+ [[maybe_unused]] uint32_t phyPinsDrive;
+
+ public:
+ /// Config register for the USB PHY pins.
+ uint32_t phyConfig;
+
+ /// Interrupt definitions for OpenTitan's USB Device.
+ enum class UsbdevInterrupt : uint32_t
+ {
+ /// Interrupt asserted whilst the receive FIFO (buffer) is not empty.
+ PacketReceived = 1u << 0,
+ /**
+ * Interrupt asserted when a packet was sent as part of an IN
+ * transaction, but not cleared from the `inSent` register.
+ */
+ PacketSent = 1u << 1,
+ /**
+ * Interrupt raised when VBUS (power supply) is lost, i.e. the link to
+ * the USB host controller has been disconnected.
+ */
+ Disconnected = 1u << 2,
+ /**
+ * Interrupt raised when the link is active, but a Start of Frame (SOF)
+ * packet has not been received within a given timeout threshold, which
+ * is set to 4.096 milliseconds.
+ */
+ HostLost = 1u << 3,
+ /**
+ * Interrupt raised when a Bus Reset condition is indicated on the link
+ * by the link being held in an SE0 state (Single Ended Zero, both lines
+ * being pulled low) for longer than 3 microseconds.
+ */
+ LinkReset = 1u << 4,
+ /**
+ * Interrupt raised when the link has entered the suspend state, due to
+ * being idle for more than 3 milliseconds.
+ */
+ LinkSuspend = 1u << 5,
+ /// Interrupt raised on link transition from suspended to non-idle.
+ LinkResume = 1u << 6,
+ /// Interrupt asserted whilst the Available OUT buffer is empty.
+ AvailableOutEmpty = 1u << 7,
+ /// Interrupt asserted whilst the Receive buffer is full.
+ ReceiveFull = 1u << 8,
+ /**
+ * Interrupt raised when the Available OUT buffer or the Available SETUP
+ * buffer overflows.
+ */
+ AvailableBufferOverflow = 1u << 9,
+ /// Interrupt raised when an error occurs during an IN transaction.
+ LinkInError = 1u << 10,
+ /**
+ * Interrupt raised when a CRC (cyclic redundancy check) error occurs on
+ * a received packet; i.e. there was an error in transmission.
+ */
+ RedundancyCheckError = 1u << 11,
+ /// Interrupt raised when an invalid Packet Identifier is received.
+ PacketIdentifierError = 1u << 12,
+ /// Interrupt raised when a bit stuffing violation is detected.
+ BitstuffingError = 1u << 13,
+ /**
+ * Interrupt raised when the USB frame number is updated with a valid
+ * SOF (Start of Frame) packet.
+ */
+ FrameUpdated = 1u << 14,
+ /// Interrupt raised when VBUS (power supply) is detected.
+ Powered = 1u << 15,
+ /// Interrupt raised when an error occurs during an OUT transaction.
+ LinkOutError = 1u << 16,
+ /// Interrupt asserted whilst the Available SETUP buffer is empty.
+ AvailableSetupEmpty = 1u << 17,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Control register
+ * (offset 0x10).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbctrl
+ */
+ enum class UsbControlField : uint32_t
+ {
+ Enable = 1u << 0,
+ ResumeLinkActive = 1u << 1,
+ DeviceAddress = 0x7Fu << 16,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Status register
+ * (offset 0x1c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbstat
+ */
+ enum class UsbStatusField : uint32_t
+ {
+ Frame = 0x7FFu << 0,
+ HostLost = 1u << 11,
+ LinkState = 0x7u << 12,
+ Sense = 1u << 15,
+ AvailableOutDepth = 0xFu << 16,
+ AvailableSetupDepth = 0x7u << 20,
+ AvailableOutFull = 1u << 23,
+ ReceiveDepth = 0xFu << 24,
+ AvailableSetupFull = 1u << 30,
+ ReceiveEmpty = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the Receive FIFO
+ * buffer register (offset 0x28).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#rxfifo
+ */
+ enum class ReceiveBufferField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Setup = 1u << 19,
+ EndpointId = 0xFu << 20,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for a Config In register
+ * (where there is one such register for each endpoint). These are
+ * the registers with offsets 0x44 up to (and not including) 0x74.
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#configin
+ */
+ enum class ConfigInField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Sending = 1u << 29,
+ Pending = 1u << 30,
+ Ready = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the PHY Config
+ * Register (offset 0x8c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#phy_config
+ */
+ enum class PhyConfigField : uint32_t
+ {
+ UseDifferentialReceiver = 1u << 0,
+ // Other PHY Configuration fields are omitted.
+ };
+
+ /**
+ * Ensure that the Available OUT and Available SETUP buffers are kept
+ * supplied with buffers for packet reception.
+ *
+ * @param bufferBitmap A bitmap of the buffers that are not currently
+ * committed (where 1 corresponds to not in use).
+ * @returns The updated bitmap after supplying buffers.
+ */
+ [[nodiscard]] uint64_t supply_buffers(uint64_t bufferBitmap) volatile
+ {
+ constexpr uint32_t SetupFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableSetupFull);
+ constexpr uint32_t OutFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableOutFull);
+
+ for (uint8_t index = 0; index < BufferCount; index++)
+ {
+ const uint32_t Buffer = (1u << index);
+ if (!(bufferBitmap & Buffer))
+ {
+ continue; // Skip buffers that are not available
+ }
+
+ // If a buffer is available, and either Available SETUP or OUT are
+ // not yet full, then commit that buffer and mark it as in use.
+ if (usbStatus & SetupFullBit)
+ {
+ if (usbStatus & OutFullBit)
+ {
+ break; // Both are full - stop trying to supply buffers.
+ }
+ availableOutBuffer = index;
+ }
+ else
+ {
+ availableSetupBuffer = index;
+ }
+ bufferBitmap &= ~Buffer;
+ }
+ return bufferBitmap;
+ }
+
+ /**
+ * Enable a specified interrupt / interrupts.
+ */
+ void interrupt_enable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable | static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Disable a specified interrupt / interrupts.
+ */
+ void interrupt_disable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable & ~static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Initialise the USB device, ensuring that packet buffers are available for
+ * reception and that the PHY has been appropriately configured. Note that
+ * at this stage, endpoints have not been configured and the device has not
+ * been connected to the USB.
+ *
+ * @param bufferBitmap An out-parameter, to initialise a bitmap of the
+ * buffers that are not currently commited (1 corresponds to not in use).
+ *
+ * @returns 0 if initialisation is sucessful, and non-zero otherwise.
+ */
+ [[nodiscard]] int init(uint64_t &bufferBitmap) volatile
+ {
+ bufferBitmap =
+ supply_buffers((static_cast<uint64_t>(1u) << BufferCount) - 1u);
+ phyConfig =
+ static_cast<uint32_t>(PhyConfigField::UseDifferentialReceiver);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an OUT endpoint for the USB device.
+ *
+ * @param endpointId The ID of the OUT endpoint to configure.
+ * @param enabled Whether the OUT endpoint should be enabled or not.
+ * @param setup Whether SETUP transactions should be enabled for the
+ * endpoint.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_out_endpoint(uint8_t endpointId,
+ bool enabled,
+ bool setup,
+ bool isochronous) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ endpointOutEnable = (endpointOutEnable & ~Mask) | (enabled ? Mask : 0u);
+ outIsochronous = (outIsochronous & ~Mask) | (isochronous ? Mask : 0u);
+ receiveEnableSetup = (receiveEnableSetup & ~Mask) | (setup ? Mask : 0u);
+ receiveEnableOut = (receiveEnableOut & ~Mask) | (enabled ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an IN endpoint for the USB device.
+ *
+ * @param endpointId The ID of the IN endpoint to configure
+ * @param enabled Whether the IN endpoint should be enabled or not.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_in_endpoint(uint8_t endpointId,
+ bool enabled,
+ bool isochronous) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ endpointInEnable = (endpointInEnable & ~Mask) | (enabled ? Mask : 0u);
+ inIsochronous = (inIsochronous & ~Mask) | (isochronous ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Set the STALL state of a specified endpoint pair (both IN and OUT).
+ *
+ * @param endpointId The ID of the endpoint pair to modify.
+ * @param stalling Whether the endpoints are stalling or not.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int set_endpoint_stalling(uint8_t endpointId,
+ bool stalling) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ outStall = (outStall & ~Mask) | (stalling ? Mask : 0u);
+ inStall = (inStall & ~Mask) | (stalling ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Connect the device to the USB, indicating its presence to the USB host
+ * controller. Endpoints must already have been configured at this point
+ * because traffic may be received imminently.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int connect() volatile
+ {
+ usbControl =
+ usbControl | static_cast<uint32_t>(UsbControlField::Enable);
+ return 0;
+ }
+
+ /**
+ * Disconnect the device from the USB.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int disconnect() volatile
+ {
+ usbControl =
+ usbControl & ~static_cast<uint32_t>(UsbControlField::Enable);
+ return 0;
+ }
+
+ /**
+ * Check whether the USB device is connected (i.e. pullup enabled).
+ *
+ * @returns True to indicate it is connected, and false otherwise.
+ */
+ [[nodiscard]] bool connected() volatile
+ {
+ return (usbControl & static_cast<uint32_t>(UsbControlField::Enable));
+ }
+
+ /**
+ * Set the device address on the USB; this address will have been supplied
+ * by the USB host controller in the standard `SET_ADDRESS` Control
+ * Transfer.
+ *
+ * @param address The device address to set on the USB.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int set_device_address(uint8_t address) volatile
+ {
+ if (address >= 0x80)
+ return -1; // Device addresses are only 7 bits long.
+
+ constexpr uint32_t Mask =
+ static_cast<uint32_t>(UsbControlField::DeviceAddress);
+ usbControl = (usbControl & ~Mask) | (address << 16);
+ return 0;
+ }
+
+ /**
+ * Check and retrieve the endpoint and buffer numbers of a
+ * recently-collected IN data packet. The caller is responsible for reusing
+ * or releasing the buffer.
+ *
+ * @param endpointId An out-parameter, to which the ID of the endpoint for
+ * a recently-collected IN data packet will be written.
+ * @param bufferId An out-parameter, to which the ID of the buffer for a
+ * recently-collected IN data packet will be written.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int retrieve_collected_packet(uint8_t &endpointId,
+ uint8_t &bufferId) volatile
+ {
+ constexpr uint32_t BufferIdMask =
+ static_cast<uint32_t>(ConfigInField::BufferId);
+ uint32_t sent = inSent;
+
+ // Clear the first encountered packet sent indication.
+ for (endpointId = 0; endpointId < MaxEndpoints; endpointId++)
+ {
+ const uint32_t EndpointBit = 1u << endpointId;
+ if (sent & EndpointBit)
+ {
+ // Clear the `in_sent` bit for this specific endpoint, and
+ // indicate which buffer has been released.
+ inSent = EndpointBit;
+ bufferId = (configIn[endpointId] & BufferIdMask);
+ return 0;
+ }
+ }
+
+ // If no packet sent indications were found, then fail.
+ return -1;
+ }
+
+ /**
+ * Present a packet on the specified IN endpoint for collection by the USB
+ * host controller.
+ *
+ * @param bufferId The buffer to use to store the packet.
+ * @param endpointId The IN endpoint used to send the packet.
+ * @param data The packet to be transmitted.
+ * @param size The size of the packet.
+ *
+ * @returns 0 if successful, or non-zero if not successful.
+ */
+ [[nodiscard]] int packet_send(uint8_t bufferId,
+ uint8_t endpointId,
+ const uint32_t *data,
+ uint8_t size) volatile
+ {
+ // Transmission of zero length packets is common over USB
+ if (size > 0)
+ {
+ usbdev_transfer(buffers(bufferId), data, size, true);
+ }
+
+ constexpr uint32_t ReadyBit =
+ static_cast<uint32_t>(ConfigInField::Ready);
+ configIn[endpointId] = bufferId | (size << 8);
+ configIn[endpointId] = configIn[endpointId] | ReadyBit;
+ return 0;
+ }
+
+ /**
+ * Test for and collect the next received packet.
+ *
+ * @param bufferId An out-parameter storing the buffer ID used
+ * @param endpointId An out-parameter storing the endpoint received on.
+ * @param size An out-parameter storing the size of the received packet.
+ * @param isSetup A boolean out-parameter. True means the received packet
+ * was a SETUP packet, false means it was not.
+ * @param destination A destination buffer to read the packet's data into.
+ *
+ * @returns 0 if successful, or non-zero if not successful.
+ */
+ [[nodiscard]] int packet_receive(uint8_t &bufferId,
+ uint8_t &endpointId,
+ uint16_t &size,
+ bool &isSetup,
+ uint32_t *destination) volatile
+ {
+ if (!(usbStatus & static_cast<uint32_t>(UsbStatusField::ReceiveDepth)))
+ {
+ return -1; // No packets received
+ }
+
+ uint32_t received = receiveBuffer;
+
+ typedef ReceiveBufferField Reg;
+ endpointId = (received & static_cast<uint32_t>(Reg::EndpointId)) >> 20;
+ size = (received & static_cast<uint32_t>(Reg::Size)) >> 8;
+ isSetup = (received & static_cast<uint32_t>(Reg::Setup)) != 0;
+ bufferId = (received & static_cast<uint32_t>(Reg::BufferId)) >> 0;
+
+ // Reception of Zero Length Packets occurs in the Status Stage of IN
+ // Control Transfers.
+ if (size > 0)
+ {
+ usbdev_transfer(destination, buffers(bufferId), size, false);
+ }
+ return 0;
+ }
+
+ private:
+ /**
+ * Return a pointer to the given offset within the USB device register
+ * space; this is used to access the packet buffer memory.
+ *
+ * @param bufferId The buffer number to access the packet buffer memory for
+ *
+ * @returns A volatile pointer to the buffer's memory.
+ */
+ volatile uint32_t *buffers(uint8_t bufferId) volatile
+ {
+ const uint32_t Offset = BufferStartAddress + bufferId * MaxPacketLength;
+ const uintptr_t Address = reinterpret_cast<uintptr_t>(this) + Offset;
+ return reinterpret_cast<uint32_t *>(Address);
+ }
+
+ /**
+ * Perform a transfer to or from packet buffer memory. This function is
+ * hand-optimised to perform a faster, unrolled, word-based data transfer
+ * for efficiency.
+ *
+ * @param destination A pointer to transfer the source data to.
+ * @param source A pointer to the data to be transferred.
+ * @param size The size of the data pointed to by `source`.
+ * @param toDevice True if the transfer is to the device (e.g. when sending
+ * a packet), and False if not (e.g. when receiving a packet).
+ */
+ static void usbdev_transfer(volatile uint32_t *destination,
+ const volatile uint32_t *source,
+ uint8_t size,
+ bool toDevice)
+ {
+ // Unroll word transfer. Each word transfer is 4 bytes, so we must round
+ // to the closest multiple of (4 * words) when unrolling.
+ constexpr uint8_t UnrollFactor = 4u;
+ constexpr uint32_t UnrollMask = (UnrollFactor * 4u) - 1;
+
+ // Round down to the previous multiple for unrolling
+ const uint32_t UnrollSize = (size & ~UnrollMask);
+ const uint32_t *sourceEnd = reinterpret_cast<uint32_t *>(
+ reinterpret_cast<uintptr_t>(source) + UnrollSize);
+
+ // Unrolled to mitigate loop overheads.
+ // Ensure the unrolling here matches `UnrollFactor`.
+ while (source < sourceEnd)
+ {
+ destination[0] = source[0];
+ destination[1] = source[1];
+ destination[2] = source[2];
+ destination[3] = source[3];
+ destination += UnrollFactor;
+ source += UnrollFactor;
+ }
+
+ // Copy the remaining whole words.
+ for (size &= UnrollMask; size >= UnrollFactor; size -= UnrollFactor)
+ *destination++ = *source++;
+ if (size == 0)
+ return;
+ | Missing braces. |
cheriot-rtos | github_2023 | others | 337 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,633 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+#include <utils.hh>
+
+/**
+ * A driver for OpenTitan USB Device, which is used in the Sonata system.
+ *
+ * This peripheral's source and documentation can be found at:
+ * https://github.com/lowRISC/opentitan/tree/ab878b5d3578939a04db72d4ed966a56a869b2ed/hw/ip/usbdev
+ *
+ * With rendered register documentation served at:
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html
+ */
+class OpenTitanUsbdev : private utils::NoCopyNoMove
+{
+ public:
+ /// Supported sizes for the USB Device.
+ static constexpr uint8_t MaxPacketLength = 64u;
+ static constexpr uint8_t BufferCount = 32u;
+ static constexpr uint8_t MaxEndpoints = 12u;
+
+ /**
+ * The offset from the start of the USB Device MMIO region at which
+ * packet buffer memory begins.
+ */
+ static constexpr uint32_t BufferStartAddress = 0x800u;
+
+ /// Device Registers
+ uint32_t interruptState;
+ uint32_t interruptEnable;
+ uint32_t interruptTest;
+ uint32_t alertTest;
+ uint32_t usbControl;
+ uint32_t endpointOutEnable;
+ uint32_t endpointInEnable;
+ uint32_t usbStatus;
+ uint32_t availableOutBuffer;
+ uint32_t availableSetupBuffer;
+ uint32_t receiveBuffer;
+ /// Register to enable receive SETUP transactions
+ uint32_t receiveEnableSetup;
+ /// Register to enable receive OUT transactions
+ uint32_t receiveEnableOut;
+ /// Register to set NAK (Not/Negated Acknowledge) after OUT transactions
+ uint32_t setNotAcknowledgeOut;
+ /// Register showing ACK receival to indicate a successful IN send
+ uint32_t inSent;
+ /// Registers for controlling the stalling of OUT and IN endpoints
+ uint32_t outStall;
+ uint32_t inStall;
+ /**
+ * IN transaction configuration registers. There is one register per
+ * endpoint for the USB device.
+ */
+ uint32_t configIn[MaxEndpoints];
+ /**
+ * Registers for configuring which endpoints should be treated as
+ * isochronous endpoints. This means that if the corresponding bit is set,
+ * then that no handshake packet will be sent for an OUT/IN transaction on
+ * that endpoint.
+ */
+ uint32_t outIsochronous;
+ uint32_t inIsochronous;
+ /// Registers for configuring if endpoints data toggle on transactions
+ uint32_t outDataToggle;
+ uint32_t inDataToggle;
+
+ private:
+ /**
+ * Registers to sense/drive the USB PHY pins. That is, these registers can
+ * be used to respectively read out the state of the USB device inputs and
+ * outputs, or to control the inputs and outputs from software. These
+ * registers are kept private as they are intended to be used for debugging
+ * purposes or during chip testing, and not in actual software.
+ */
+ [[maybe_unused]] uint32_t phyPinsSense;
+ [[maybe_unused]] uint32_t phyPinsDrive;
+
+ public:
+ /// Config register for the USB PHY pins.
+ uint32_t phyConfig;
+
+ /// Interrupt definitions for OpenTitan's USB Device.
+ enum class UsbdevInterrupt : uint32_t
+ {
+ /// Interrupt asserted whilst the receive FIFO (buffer) is not empty.
+ PacketReceived = 1u << 0,
+ /**
+ * Interrupt asserted when a packet was sent as part of an IN
+ * transaction, but not cleared from the `inSent` register.
+ */
+ PacketSent = 1u << 1,
+ /**
+ * Interrupt raised when VBUS (power supply) is lost, i.e. the link to
+ * the USB host controller has been disconnected.
+ */
+ Disconnected = 1u << 2,
+ /**
+ * Interrupt raised when the link is active, but a Start of Frame (SOF)
+ * packet has not been received within a given timeout threshold, which
+ * is set to 4.096 milliseconds.
+ */
+ HostLost = 1u << 3,
+ /**
+ * Interrupt raised when a Bus Reset condition is indicated on the link
+ * by the link being held in an SE0 state (Single Ended Zero, both lines
+ * being pulled low) for longer than 3 microseconds.
+ */
+ LinkReset = 1u << 4,
+ /**
+ * Interrupt raised when the link has entered the suspend state, due to
+ * being idle for more than 3 milliseconds.
+ */
+ LinkSuspend = 1u << 5,
+ /// Interrupt raised on link transition from suspended to non-idle.
+ LinkResume = 1u << 6,
+ /// Interrupt asserted whilst the Available OUT buffer is empty.
+ AvailableOutEmpty = 1u << 7,
+ /// Interrupt asserted whilst the Receive buffer is full.
+ ReceiveFull = 1u << 8,
+ /**
+ * Interrupt raised when the Available OUT buffer or the Available SETUP
+ * buffer overflows.
+ */
+ AvailableBufferOverflow = 1u << 9,
+ /// Interrupt raised when an error occurs during an IN transaction.
+ LinkInError = 1u << 10,
+ /**
+ * Interrupt raised when a CRC (cyclic redundancy check) error occurs on
+ * a received packet; i.e. there was an error in transmission.
+ */
+ RedundancyCheckError = 1u << 11,
+ /// Interrupt raised when an invalid Packet Identifier is received.
+ PacketIdentifierError = 1u << 12,
+ /// Interrupt raised when a bit stuffing violation is detected.
+ BitstuffingError = 1u << 13,
+ /**
+ * Interrupt raised when the USB frame number is updated with a valid
+ * SOF (Start of Frame) packet.
+ */
+ FrameUpdated = 1u << 14,
+ /// Interrupt raised when VBUS (power supply) is detected.
+ Powered = 1u << 15,
+ /// Interrupt raised when an error occurs during an OUT transaction.
+ LinkOutError = 1u << 16,
+ /// Interrupt asserted whilst the Available SETUP buffer is empty.
+ AvailableSetupEmpty = 1u << 17,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Control register
+ * (offset 0x10).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbctrl
+ */
+ enum class UsbControlField : uint32_t
+ {
+ Enable = 1u << 0,
+ ResumeLinkActive = 1u << 1,
+ DeviceAddress = 0x7Fu << 16,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Status register
+ * (offset 0x1c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbstat
+ */
+ enum class UsbStatusField : uint32_t
+ {
+ Frame = 0x7FFu << 0,
+ HostLost = 1u << 11,
+ LinkState = 0x7u << 12,
+ Sense = 1u << 15,
+ AvailableOutDepth = 0xFu << 16,
+ AvailableSetupDepth = 0x7u << 20,
+ AvailableOutFull = 1u << 23,
+ ReceiveDepth = 0xFu << 24,
+ AvailableSetupFull = 1u << 30,
+ ReceiveEmpty = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the Receive FIFO
+ * buffer register (offset 0x28).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#rxfifo
+ */
+ enum class ReceiveBufferField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Setup = 1u << 19,
+ EndpointId = 0xFu << 20,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for a Config In register
+ * (where there is one such register for each endpoint). These are
+ * the registers with offsets 0x44 up to (and not including) 0x74.
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#configin
+ */
+ enum class ConfigInField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Sending = 1u << 29,
+ Pending = 1u << 30,
+ Ready = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the PHY Config
+ * Register (offset 0x8c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#phy_config
+ */
+ enum class PhyConfigField : uint32_t
+ {
+ UseDifferentialReceiver = 1u << 0,
+ // Other PHY Configuration fields are omitted.
+ };
+
+ /**
+ * Ensure that the Available OUT and Available SETUP buffers are kept
+ * supplied with buffers for packet reception.
+ *
+ * @param bufferBitmap A bitmap of the buffers that are not currently
+ * committed (where 1 corresponds to not in use).
+ * @returns The updated bitmap after supplying buffers.
+ */
+ [[nodiscard]] uint64_t supply_buffers(uint64_t bufferBitmap) volatile
+ {
+ constexpr uint32_t SetupFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableSetupFull);
+ constexpr uint32_t OutFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableOutFull);
+
+ for (uint8_t index = 0; index < BufferCount; index++)
+ {
+ const uint32_t Buffer = (1u << index);
+ if (!(bufferBitmap & Buffer))
+ {
+ continue; // Skip buffers that are not available
+ }
+
+ // If a buffer is available, and either Available SETUP or OUT are
+ // not yet full, then commit that buffer and mark it as in use.
+ if (usbStatus & SetupFullBit)
+ {
+ if (usbStatus & OutFullBit)
+ {
+ break; // Both are full - stop trying to supply buffers.
+ }
+ availableOutBuffer = index;
+ }
+ else
+ {
+ availableSetupBuffer = index;
+ }
+ bufferBitmap &= ~Buffer;
+ }
+ return bufferBitmap;
+ }
+
+ /**
+ * Enable a specified interrupt / interrupts.
+ */
+ void interrupt_enable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable | static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Disable a specified interrupt / interrupts.
+ */
+ void interrupt_disable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable & ~static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Initialise the USB device, ensuring that packet buffers are available for
+ * reception and that the PHY has been appropriately configured. Note that
+ * at this stage, endpoints have not been configured and the device has not
+ * been connected to the USB.
+ *
+ * @param bufferBitmap An out-parameter, to initialise a bitmap of the
+ * buffers that are not currently commited (1 corresponds to not in use).
+ *
+ * @returns 0 if initialisation is sucessful, and non-zero otherwise.
+ */
+ [[nodiscard]] int init(uint64_t &bufferBitmap) volatile
+ {
+ bufferBitmap =
+ supply_buffers((static_cast<uint64_t>(1u) << BufferCount) - 1u);
+ phyConfig =
+ static_cast<uint32_t>(PhyConfigField::UseDifferentialReceiver);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an OUT endpoint for the USB device.
+ *
+ * @param endpointId The ID of the OUT endpoint to configure.
+ * @param enabled Whether the OUT endpoint should be enabled or not.
+ * @param setup Whether SETUP transactions should be enabled for the
+ * endpoint.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_out_endpoint(uint8_t endpointId,
+ bool enabled,
+ bool setup,
+ bool isochronous) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ endpointOutEnable = (endpointOutEnable & ~Mask) | (enabled ? Mask : 0u);
+ outIsochronous = (outIsochronous & ~Mask) | (isochronous ? Mask : 0u);
+ receiveEnableSetup = (receiveEnableSetup & ~Mask) | (setup ? Mask : 0u);
+ receiveEnableOut = (receiveEnableOut & ~Mask) | (enabled ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an IN endpoint for the USB device.
+ *
+ * @param endpointId The ID of the IN endpoint to configure
+ * @param enabled Whether the IN endpoint should be enabled or not.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_in_endpoint(uint8_t endpointId,
+ bool enabled,
+ bool isochronous) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ endpointInEnable = (endpointInEnable & ~Mask) | (enabled ? Mask : 0u);
+ inIsochronous = (inIsochronous & ~Mask) | (isochronous ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Set the STALL state of a specified endpoint pair (both IN and OUT).
+ *
+ * @param endpointId The ID of the endpoint pair to modify.
+ * @param stalling Whether the endpoints are stalling or not.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int set_endpoint_stalling(uint8_t endpointId,
+ bool stalling) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ outStall = (outStall & ~Mask) | (stalling ? Mask : 0u);
+ inStall = (inStall & ~Mask) | (stalling ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Connect the device to the USB, indicating its presence to the USB host
+ * controller. Endpoints must already have been configured at this point
+ * because traffic may be received imminently.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int connect() volatile
+ {
+ usbControl =
+ usbControl | static_cast<uint32_t>(UsbControlField::Enable);
+ return 0;
+ }
+
+ /**
+ * Disconnect the device from the USB.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int disconnect() volatile
+ {
+ usbControl =
+ usbControl & ~static_cast<uint32_t>(UsbControlField::Enable);
+ return 0;
+ }
+
+ /**
+ * Check whether the USB device is connected (i.e. pullup enabled).
+ *
+ * @returns True to indicate it is connected, and false otherwise.
+ */
+ [[nodiscard]] bool connected() volatile
+ {
+ return (usbControl & static_cast<uint32_t>(UsbControlField::Enable));
+ }
+
+ /**
+ * Set the device address on the USB; this address will have been supplied
+ * by the USB host controller in the standard `SET_ADDRESS` Control
+ * Transfer.
+ *
+ * @param address The device address to set on the USB.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int set_device_address(uint8_t address) volatile
+ {
+ if (address >= 0x80)
+ return -1; // Device addresses are only 7 bits long.
+
+ constexpr uint32_t Mask =
+ static_cast<uint32_t>(UsbControlField::DeviceAddress);
+ usbControl = (usbControl & ~Mask) | (address << 16);
+ return 0;
+ }
+
+ /**
+ * Check and retrieve the endpoint and buffer numbers of a
+ * recently-collected IN data packet. The caller is responsible for reusing
+ * or releasing the buffer.
+ *
+ * @param endpointId An out-parameter, to which the ID of the endpoint for
+ * a recently-collected IN data packet will be written.
+ * @param bufferId An out-parameter, to which the ID of the buffer for a
+ * recently-collected IN data packet will be written.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int retrieve_collected_packet(uint8_t &endpointId,
+ uint8_t &bufferId) volatile
+ {
+ constexpr uint32_t BufferIdMask =
+ static_cast<uint32_t>(ConfigInField::BufferId);
+ uint32_t sent = inSent;
+
+ // Clear the first encountered packet sent indication.
+ for (endpointId = 0; endpointId < MaxEndpoints; endpointId++)
+ {
+ const uint32_t EndpointBit = 1u << endpointId;
+ if (sent & EndpointBit)
+ {
+ // Clear the `in_sent` bit for this specific endpoint, and
+ // indicate which buffer has been released.
+ inSent = EndpointBit;
+ bufferId = (configIn[endpointId] & BufferIdMask);
+ return 0;
+ }
+ }
+
+ // If no packet sent indications were found, then fail.
+ return -1;
+ }
+
+ /**
+ * Present a packet on the specified IN endpoint for collection by the USB
+ * host controller.
+ *
+ * @param bufferId The buffer to use to store the packet.
+ * @param endpointId The IN endpoint used to send the packet.
+ * @param data The packet to be transmitted.
+ * @param size The size of the packet.
+ *
+ * @returns 0 if successful, or non-zero if not successful.
+ */
+ [[nodiscard]] int packet_send(uint8_t bufferId,
+ uint8_t endpointId,
+ const uint32_t *data,
+ uint8_t size) volatile
+ {
+ // Transmission of zero length packets is common over USB
+ if (size > 0)
+ {
+ usbdev_transfer(buffers(bufferId), data, size, true);
+ }
+
+ constexpr uint32_t ReadyBit =
+ static_cast<uint32_t>(ConfigInField::Ready);
+ configIn[endpointId] = bufferId | (size << 8);
+ configIn[endpointId] = configIn[endpointId] | ReadyBit;
+ return 0;
+ }
+
+ /**
+ * Test for and collect the next received packet.
+ *
+ * @param bufferId An out-parameter storing the buffer ID used
+ * @param endpointId An out-parameter storing the endpoint received on.
+ * @param size An out-parameter storing the size of the received packet.
+ * @param isSetup A boolean out-parameter. True means the received packet
+ * was a SETUP packet, false means it was not.
+ * @param destination A destination buffer to read the packet's data into.
+ *
+ * @returns 0 if successful, or non-zero if not successful.
+ */
+ [[nodiscard]] int packet_receive(uint8_t &bufferId,
+ uint8_t &endpointId,
+ uint16_t &size,
+ bool &isSetup,
+ uint32_t *destination) volatile
+ {
+ if (!(usbStatus & static_cast<uint32_t>(UsbStatusField::ReceiveDepth)))
+ {
+ return -1; // No packets received
+ }
+
+ uint32_t received = receiveBuffer;
+
+ typedef ReceiveBufferField Reg;
+ endpointId = (received & static_cast<uint32_t>(Reg::EndpointId)) >> 20;
+ size = (received & static_cast<uint32_t>(Reg::Size)) >> 8;
+ isSetup = (received & static_cast<uint32_t>(Reg::Setup)) != 0;
+ bufferId = (received & static_cast<uint32_t>(Reg::BufferId)) >> 0;
+
+ // Reception of Zero Length Packets occurs in the Status Stage of IN
+ // Control Transfers.
+ if (size > 0)
+ {
+ usbdev_transfer(destination, buffers(bufferId), size, false);
+ }
+ return 0;
+ }
+
+ private:
+ /**
+ * Return a pointer to the given offset within the USB device register
+ * space; this is used to access the packet buffer memory.
+ *
+ * @param bufferId The buffer number to access the packet buffer memory for
+ *
+ * @returns A volatile pointer to the buffer's memory.
+ */
+ volatile uint32_t *buffers(uint8_t bufferId) volatile
+ {
+ const uint32_t Offset = BufferStartAddress + bufferId * MaxPacketLength;
+ const uintptr_t Address = reinterpret_cast<uintptr_t>(this) + Offset;
+ return reinterpret_cast<uint32_t *>(Address);
+ }
+
+ /**
+ * Perform a transfer to or from packet buffer memory. This function is
+ * hand-optimised to perform a faster, unrolled, word-based data transfer
+ * for efficiency.
+ *
+ * @param destination A pointer to transfer the source data to.
+ * @param source A pointer to the data to be transferred.
+ * @param size The size of the data pointed to by `source`.
+ * @param toDevice True if the transfer is to the device (e.g. when sending
+ * a packet), and False if not (e.g. when receiving a packet).
+ */
+ static void usbdev_transfer(volatile uint32_t *destination,
+ const volatile uint32_t *source,
+ uint8_t size,
+ bool toDevice)
+ {
+ // Unroll word transfer. Each word transfer is 4 bytes, so we must round
+ // to the closest multiple of (4 * words) when unrolling.
+ constexpr uint8_t UnrollFactor = 4u;
+ constexpr uint32_t UnrollMask = (UnrollFactor * 4u) - 1;
+
+ // Round down to the previous multiple for unrolling
+ const uint32_t UnrollSize = (size & ~UnrollMask);
+ const uint32_t *sourceEnd = reinterpret_cast<uint32_t *>(
+ reinterpret_cast<uintptr_t>(source) + UnrollSize);
+
+ // Unrolled to mitigate loop overheads.
+ // Ensure the unrolling here matches `UnrollFactor`.
+ while (source < sourceEnd)
+ {
+ destination[0] = source[0];
+ destination[1] = source[1];
+ destination[2] = source[2];
+ destination[3] = source[3];
+ destination += UnrollFactor;
+ source += UnrollFactor;
+ } | I don't really like the manual loop unrolling here. Is there a reason that this isn't just a memcpy? The memcpy loop will do each copy as a capability, so even without unrolling it will be a fairly similar speed to this.
With the current compiler, this structure actually hits one of the pathological cases for missed optimisation and so I'd expect it to be much slower. |
cheriot-rtos | github_2023 | others | 337 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,633 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+#include <utils.hh>
+
+/**
+ * A driver for OpenTitan USB Device, which is used in the Sonata system.
+ *
+ * This peripheral's source and documentation can be found at:
+ * https://github.com/lowRISC/opentitan/tree/ab878b5d3578939a04db72d4ed966a56a869b2ed/hw/ip/usbdev
+ *
+ * With rendered register documentation served at:
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html
+ */
+class OpenTitanUsbdev : private utils::NoCopyNoMove
+{
+ public:
+ /// Supported sizes for the USB Device.
+ static constexpr uint8_t MaxPacketLength = 64u;
+ static constexpr uint8_t BufferCount = 32u;
+ static constexpr uint8_t MaxEndpoints = 12u;
+
+ /**
+ * The offset from the start of the USB Device MMIO region at which
+ * packet buffer memory begins.
+ */
+ static constexpr uint32_t BufferStartAddress = 0x800u;
+
+ /// Device Registers
+ uint32_t interruptState;
+ uint32_t interruptEnable;
+ uint32_t interruptTest;
+ uint32_t alertTest;
+ uint32_t usbControl;
+ uint32_t endpointOutEnable;
+ uint32_t endpointInEnable;
+ uint32_t usbStatus;
+ uint32_t availableOutBuffer;
+ uint32_t availableSetupBuffer;
+ uint32_t receiveBuffer;
+ /// Register to enable receive SETUP transactions
+ uint32_t receiveEnableSetup;
+ /// Register to enable receive OUT transactions
+ uint32_t receiveEnableOut;
+ /// Register to set NAK (Not/Negated Acknowledge) after OUT transactions
+ uint32_t setNotAcknowledgeOut;
+ /// Register showing ACK receival to indicate a successful IN send
+ uint32_t inSent;
+ /// Registers for controlling the stalling of OUT and IN endpoints
+ uint32_t outStall;
+ uint32_t inStall;
+ /**
+ * IN transaction configuration registers. There is one register per
+ * endpoint for the USB device.
+ */
+ uint32_t configIn[MaxEndpoints];
+ /**
+ * Registers for configuring which endpoints should be treated as
+ * isochronous endpoints. This means that if the corresponding bit is set,
+ * then that no handshake packet will be sent for an OUT/IN transaction on
+ * that endpoint.
+ */
+ uint32_t outIsochronous;
+ uint32_t inIsochronous;
+ /// Registers for configuring if endpoints data toggle on transactions
+ uint32_t outDataToggle;
+ uint32_t inDataToggle;
+
+ private:
+ /**
+ * Registers to sense/drive the USB PHY pins. That is, these registers can
+ * be used to respectively read out the state of the USB device inputs and
+ * outputs, or to control the inputs and outputs from software. These
+ * registers are kept private as they are intended to be used for debugging
+ * purposes or during chip testing, and not in actual software.
+ */
+ [[maybe_unused]] uint32_t phyPinsSense;
+ [[maybe_unused]] uint32_t phyPinsDrive;
+
+ public:
+ /// Config register for the USB PHY pins.
+ uint32_t phyConfig;
+
+ /// Interrupt definitions for OpenTitan's USB Device.
+ enum class UsbdevInterrupt : uint32_t
+ {
+ /// Interrupt asserted whilst the receive FIFO (buffer) is not empty.
+ PacketReceived = 1u << 0,
+ /**
+ * Interrupt asserted when a packet was sent as part of an IN
+ * transaction, but not cleared from the `inSent` register.
+ */
+ PacketSent = 1u << 1,
+ /**
+ * Interrupt raised when VBUS (power supply) is lost, i.e. the link to
+ * the USB host controller has been disconnected.
+ */
+ Disconnected = 1u << 2,
+ /**
+ * Interrupt raised when the link is active, but a Start of Frame (SOF)
+ * packet has not been received within a given timeout threshold, which
+ * is set to 4.096 milliseconds.
+ */
+ HostLost = 1u << 3,
+ /**
+ * Interrupt raised when a Bus Reset condition is indicated on the link
+ * by the link being held in an SE0 state (Single Ended Zero, both lines
+ * being pulled low) for longer than 3 microseconds.
+ */
+ LinkReset = 1u << 4,
+ /**
+ * Interrupt raised when the link has entered the suspend state, due to
+ * being idle for more than 3 milliseconds.
+ */
+ LinkSuspend = 1u << 5,
+ /// Interrupt raised on link transition from suspended to non-idle.
+ LinkResume = 1u << 6,
+ /// Interrupt asserted whilst the Available OUT buffer is empty.
+ AvailableOutEmpty = 1u << 7,
+ /// Interrupt asserted whilst the Receive buffer is full.
+ ReceiveFull = 1u << 8,
+ /**
+ * Interrupt raised when the Available OUT buffer or the Available SETUP
+ * buffer overflows.
+ */
+ AvailableBufferOverflow = 1u << 9,
+ /// Interrupt raised when an error occurs during an IN transaction.
+ LinkInError = 1u << 10,
+ /**
+ * Interrupt raised when a CRC (cyclic redundancy check) error occurs on
+ * a received packet; i.e. there was an error in transmission.
+ */
+ RedundancyCheckError = 1u << 11,
+ /// Interrupt raised when an invalid Packet Identifier is received.
+ PacketIdentifierError = 1u << 12,
+ /// Interrupt raised when a bit stuffing violation is detected.
+ BitstuffingError = 1u << 13,
+ /**
+ * Interrupt raised when the USB frame number is updated with a valid
+ * SOF (Start of Frame) packet.
+ */
+ FrameUpdated = 1u << 14,
+ /// Interrupt raised when VBUS (power supply) is detected.
+ Powered = 1u << 15,
+ /// Interrupt raised when an error occurs during an OUT transaction.
+ LinkOutError = 1u << 16,
+ /// Interrupt asserted whilst the Available SETUP buffer is empty.
+ AvailableSetupEmpty = 1u << 17,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Control register
+ * (offset 0x10).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbctrl
+ */
+ enum class UsbControlField : uint32_t
+ {
+ Enable = 1u << 0,
+ ResumeLinkActive = 1u << 1,
+ DeviceAddress = 0x7Fu << 16,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the USB Status register
+ * (offset 0x1c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#usbstat
+ */
+ enum class UsbStatusField : uint32_t
+ {
+ Frame = 0x7FFu << 0,
+ HostLost = 1u << 11,
+ LinkState = 0x7u << 12,
+ Sense = 1u << 15,
+ AvailableOutDepth = 0xFu << 16,
+ AvailableSetupDepth = 0x7u << 20,
+ AvailableOutFull = 1u << 23,
+ ReceiveDepth = 0xFu << 24,
+ AvailableSetupFull = 1u << 30,
+ ReceiveEmpty = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the Receive FIFO
+ * buffer register (offset 0x28).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#rxfifo
+ */
+ enum class ReceiveBufferField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Setup = 1u << 19,
+ EndpointId = 0xFu << 20,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for a Config In register
+ * (where there is one such register for each endpoint). These are
+ * the registers with offsets 0x44 up to (and not including) 0x74.
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#configin
+ */
+ enum class ConfigInField : uint32_t
+ {
+ BufferId = 0x1Fu << 0,
+ Size = 0x7Fu << 8,
+ Sending = 1u << 29,
+ Pending = 1u << 30,
+ Ready = 1u << 31,
+ };
+
+ /**
+ * Definitions of fields (and their locations) for the PHY Config
+ * Register (offset 0x8c).
+ *
+ * https://opentitan.org/book/hw/ip/usbdev/doc/registers.html#phy_config
+ */
+ enum class PhyConfigField : uint32_t
+ {
+ UseDifferentialReceiver = 1u << 0,
+ // Other PHY Configuration fields are omitted.
+ };
+
+ /**
+ * Ensure that the Available OUT and Available SETUP buffers are kept
+ * supplied with buffers for packet reception.
+ *
+ * @param bufferBitmap A bitmap of the buffers that are not currently
+ * committed (where 1 corresponds to not in use).
+ * @returns The updated bitmap after supplying buffers.
+ */
+ [[nodiscard]] uint64_t supply_buffers(uint64_t bufferBitmap) volatile
+ {
+ constexpr uint32_t SetupFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableSetupFull);
+ constexpr uint32_t OutFullBit =
+ static_cast<uint32_t>(UsbStatusField::AvailableOutFull);
+
+ for (uint8_t index = 0; index < BufferCount; index++)
+ {
+ const uint32_t Buffer = (1u << index);
+ if (!(bufferBitmap & Buffer))
+ {
+ continue; // Skip buffers that are not available
+ }
+
+ // If a buffer is available, and either Available SETUP or OUT are
+ // not yet full, then commit that buffer and mark it as in use.
+ if (usbStatus & SetupFullBit)
+ {
+ if (usbStatus & OutFullBit)
+ {
+ break; // Both are full - stop trying to supply buffers.
+ }
+ availableOutBuffer = index;
+ }
+ else
+ {
+ availableSetupBuffer = index;
+ }
+ bufferBitmap &= ~Buffer;
+ }
+ return bufferBitmap;
+ }
+
+ /**
+ * Enable a specified interrupt / interrupts.
+ */
+ void interrupt_enable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable | static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Disable a specified interrupt / interrupts.
+ */
+ void interrupt_disable(UsbdevInterrupt interrupt) volatile
+ {
+ interruptEnable = interruptEnable & ~static_cast<uint32_t>(interrupt);
+ }
+
+ /**
+ * Initialise the USB device, ensuring that packet buffers are available for
+ * reception and that the PHY has been appropriately configured. Note that
+ * at this stage, endpoints have not been configured and the device has not
+ * been connected to the USB.
+ *
+ * @param bufferBitmap An out-parameter, to initialise a bitmap of the
+ * buffers that are not currently commited (1 corresponds to not in use).
+ *
+ * @returns 0 if initialisation is sucessful, and non-zero otherwise.
+ */
+ [[nodiscard]] int init(uint64_t &bufferBitmap) volatile
+ {
+ bufferBitmap =
+ supply_buffers((static_cast<uint64_t>(1u) << BufferCount) - 1u);
+ phyConfig =
+ static_cast<uint32_t>(PhyConfigField::UseDifferentialReceiver);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an OUT endpoint for the USB device.
+ *
+ * @param endpointId The ID of the OUT endpoint to configure.
+ * @param enabled Whether the OUT endpoint should be enabled or not.
+ * @param setup Whether SETUP transactions should be enabled for the
+ * endpoint.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_out_endpoint(uint8_t endpointId,
+ bool enabled,
+ bool setup,
+ bool isochronous) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ endpointOutEnable = (endpointOutEnable & ~Mask) | (enabled ? Mask : 0u);
+ outIsochronous = (outIsochronous & ~Mask) | (isochronous ? Mask : 0u);
+ receiveEnableSetup = (receiveEnableSetup & ~Mask) | (setup ? Mask : 0u);
+ receiveEnableOut = (receiveEnableOut & ~Mask) | (enabled ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Setup the configuration of an IN endpoint for the USB device.
+ *
+ * @param endpointId The ID of the IN endpoint to configure
+ * @param enabled Whether the IN endpoint should be enabled or not.
+ * @param isochronous Whether the endpoint should operate isochronously or
+ * non-isochronously.
+ *
+ * @returns 0 if configuration is successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int configure_in_endpoint(uint8_t endpointId,
+ bool enabled,
+ bool isochronous) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ endpointInEnable = (endpointInEnable & ~Mask) | (enabled ? Mask : 0u);
+ inIsochronous = (inIsochronous & ~Mask) | (isochronous ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Set the STALL state of a specified endpoint pair (both IN and OUT).
+ *
+ * @param endpointId The ID of the endpoint pair to modify.
+ * @param stalling Whether the endpoints are stalling or not.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int set_endpoint_stalling(uint8_t endpointId,
+ bool stalling) volatile
+ {
+ if (endpointId >= MaxEndpoints)
+ return -1;
+
+ const uint32_t Mask = 1u << endpointId;
+ outStall = (outStall & ~Mask) | (stalling ? Mask : 0u);
+ inStall = (inStall & ~Mask) | (stalling ? Mask : 0u);
+ return 0;
+ }
+
+ /**
+ * Connect the device to the USB, indicating its presence to the USB host
+ * controller. Endpoints must already have been configured at this point
+ * because traffic may be received imminently.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int connect() volatile
+ {
+ usbControl =
+ usbControl | static_cast<uint32_t>(UsbControlField::Enable);
+ return 0;
+ }
+
+ /**
+ * Disconnect the device from the USB.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int disconnect() volatile
+ {
+ usbControl =
+ usbControl & ~static_cast<uint32_t>(UsbControlField::Enable);
+ return 0;
+ }
+
+ /**
+ * Check whether the USB device is connected (i.e. pullup enabled).
+ *
+ * @returns True to indicate it is connected, and false otherwise.
+ */
+ [[nodiscard]] bool connected() volatile
+ {
+ return (usbControl & static_cast<uint32_t>(UsbControlField::Enable));
+ }
+
+ /**
+ * Set the device address on the USB; this address will have been supplied
+ * by the USB host controller in the standard `SET_ADDRESS` Control
+ * Transfer.
+ *
+ * @param address The device address to set on the USB.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int set_device_address(uint8_t address) volatile
+ {
+ if (address >= 0x80)
+ return -1; // Device addresses are only 7 bits long.
+
+ constexpr uint32_t Mask =
+ static_cast<uint32_t>(UsbControlField::DeviceAddress);
+ usbControl = (usbControl & ~Mask) | (address << 16);
+ return 0;
+ }
+
+ /**
+ * Check and retrieve the endpoint and buffer numbers of a
+ * recently-collected IN data packet. The caller is responsible for reusing
+ * or releasing the buffer.
+ *
+ * @param endpointId An out-parameter, to which the ID of the endpoint for
+ * a recently-collected IN data packet will be written.
+ * @param bufferId An out-parameter, to which the ID of the buffer for a
+ * recently-collected IN data packet will be written.
+ *
+ * @returns 0 if successful, and non-zero otherwise.
+ */
+ [[nodiscard]] int retrieve_collected_packet(uint8_t &endpointId,
+ uint8_t &bufferId) volatile
+ {
+ constexpr uint32_t BufferIdMask =
+ static_cast<uint32_t>(ConfigInField::BufferId);
+ uint32_t sent = inSent;
+
+ // Clear the first encountered packet sent indication.
+ for (endpointId = 0; endpointId < MaxEndpoints; endpointId++)
+ {
+ const uint32_t EndpointBit = 1u << endpointId;
+ if (sent & EndpointBit)
+ {
+ // Clear the `in_sent` bit for this specific endpoint, and
+ // indicate which buffer has been released.
+ inSent = EndpointBit;
+ bufferId = (configIn[endpointId] & BufferIdMask);
+ return 0;
+ }
+ }
+
+ // If no packet sent indications were found, then fail.
+ return -1;
+ }
+
+ /**
+ * Present a packet on the specified IN endpoint for collection by the USB
+ * host controller.
+ *
+ * @param bufferId The buffer to use to store the packet.
+ * @param endpointId The IN endpoint used to send the packet.
+ * @param data The packet to be transmitted.
+ * @param size The size of the packet.
+ *
+ * @returns 0 if successful, or non-zero if not successful.
+ */
+ [[nodiscard]] int packet_send(uint8_t bufferId,
+ uint8_t endpointId,
+ const uint32_t *data,
+ uint8_t size) volatile
+ {
+ // Transmission of zero length packets is common over USB
+ if (size > 0)
+ {
+ usbdev_transfer(buffers(bufferId), data, size, true);
+ }
+
+ constexpr uint32_t ReadyBit =
+ static_cast<uint32_t>(ConfigInField::Ready);
+ configIn[endpointId] = bufferId | (size << 8);
+ configIn[endpointId] = configIn[endpointId] | ReadyBit;
+ return 0;
+ }
+
+ /**
+ * Test for and collect the next received packet.
+ *
+ * @param bufferId An out-parameter storing the buffer ID used
+ * @param endpointId An out-parameter storing the endpoint received on.
+ * @param size An out-parameter storing the size of the received packet.
+ * @param isSetup A boolean out-parameter. True means the received packet
+ * was a SETUP packet, false means it was not.
+ * @param destination A destination buffer to read the packet's data into.
+ *
+ * @returns 0 if successful, or non-zero if not successful.
+ */
+ [[nodiscard]] int packet_receive(uint8_t &bufferId,
+ uint8_t &endpointId,
+ uint16_t &size,
+ bool &isSetup,
+ uint32_t *destination) volatile
+ {
+ if (!(usbStatus & static_cast<uint32_t>(UsbStatusField::ReceiveDepth)))
+ {
+ return -1; // No packets received
+ }
+
+ uint32_t received = receiveBuffer;
+
+ typedef ReceiveBufferField Reg;
+ endpointId = (received & static_cast<uint32_t>(Reg::EndpointId)) >> 20;
+ size = (received & static_cast<uint32_t>(Reg::Size)) >> 8;
+ isSetup = (received & static_cast<uint32_t>(Reg::Setup)) != 0;
+ bufferId = (received & static_cast<uint32_t>(Reg::BufferId)) >> 0;
+
+ // Reception of Zero Length Packets occurs in the Status Stage of IN
+ // Control Transfers.
+ if (size > 0)
+ {
+ usbdev_transfer(destination, buffers(bufferId), size, false);
+ }
+ return 0;
+ }
+
+ private:
+ /**
+ * Return a pointer to the given offset within the USB device register
+ * space; this is used to access the packet buffer memory.
+ *
+ * @param bufferId The buffer number to access the packet buffer memory for
+ *
+ * @returns A volatile pointer to the buffer's memory.
+ */
+ volatile uint32_t *buffers(uint8_t bufferId) volatile
+ {
+ const uint32_t Offset = BufferStartAddress + bufferId * MaxPacketLength;
+ const uintptr_t Address = reinterpret_cast<uintptr_t>(this) + Offset;
+ return reinterpret_cast<uint32_t *>(Address);
+ }
+
+ /**
+ * Perform a transfer to or from packet buffer memory. This function is
+ * hand-optimised to perform a faster, unrolled, word-based data transfer
+ * for efficiency.
+ *
+ * @param destination A pointer to transfer the source data to.
+ * @param source A pointer to the data to be transferred.
+ * @param size The size of the data pointed to by `source`.
+ * @param toDevice True if the transfer is to the device (e.g. when sending
+ * a packet), and False if not (e.g. when receiving a packet).
+ */
+ static void usbdev_transfer(volatile uint32_t *destination,
+ const volatile uint32_t *source, | I don't think that these actually need to be volatile. They're writes to memory-mapped buffers, not to MMIO registers, so it doesn't matter if the compiler reorders them (or even duplicates stores). |
cheriot-rtos | github_2023 | others | 423 | CHERIoT-Platform | nwf | @@ -253,21 +253,143 @@ target("cheriot.software_revoker")
target:set("cheriot.ldscript", "software_revoker.ldscript")
end)
--- Helper to get the board file for a given target
-local board_file = function(target)
- local boardfile = target:values("board")
- if not boardfile then
- raise("target " .. target:name() .. " does not define a board name")
- end
+-- Helper to find a board file given either the name of a board file or a path.
+local function board_file_for_name(boardName)
+ local boardfile = boardName
-- The directory containing the board file.
local boarddir = path.directory(boardfile);
+ -- If this isn't a path, look in the boards directory
if path.basename(boardfile) == boardfile then
boarddir = path.join(scriptdir, "boards")
- boardfile = path.join(boarddir, boardfile .. '.json')
+ local fullBoardPath = path.join(boarddir, boardfile .. '.json')
+ if not os.isfile(fullBoardPath) then
+ fullBoardPath = path.join(boarddir, boardfile .. '.patch')
+ end
+ if not os.isfile(fullBoardPath) then
+ print("unable to find board file " .. boardfile .. ". Try specifying a full path")
+ return nil
+ end
+ boardfile = fullBoardPath
end
return boarddir, boardfile
end
+-- Helper to get the board file for a given target
+local function board_file_for_target(target)
+ local boardName = target:values("board")
+ if not boardName then
+ print("target " .. target:name() .. " does not define a board name")
+ return nil
+ end
+ return board_file_for_name(boardName)
+end
+
+-- Helper to load a board file. This must be passed the json object provided
+-- by import("core.base.json") because import does not work in helper
+-- functions at the top level.
+local function load_board_file(json, boardFile)
+ if path.extension(boardFile) == ".json" then
+ return json.loadfile(boardFile)
+ end
+ if path.extension(boardFile) ~= ".patch" then
+ print("unknown extension for board file: " .. boardFile)
+ return nil
+ end
+ local patch = json.loadfile(boardFile)
+ if not patch.base then
+ print("Board file " .. boardFile .. " does not specify a base")
+ return nil
+ end
+ local _, baseFile = board_file_for_name(patch.base)
+ local base = load_board_file(json, baseFile)
+
+ -- If a string value is a number, return it as number, otherwise return it
+ -- in its original form.
+ function asNumberIfNumber(value) | Hrm. This function isn't just `tonumber(value) or value` (numeric 0 is _true_ in Lua, and `tonumber` won't return `false`) because we want to keep things Lua can't exactly represent as strings? I don't think we're likely to _notice_ the difference in practice, but defense in depth is probably a good idea. |
cheriot-rtos | github_2023 | others | 423 | CHERIoT-Platform | nwf | @@ -253,21 +253,143 @@ target("cheriot.software_revoker")
target:set("cheriot.ldscript", "software_revoker.ldscript")
end)
--- Helper to get the board file for a given target
-local board_file = function(target)
- local boardfile = target:values("board")
- if not boardfile then
- raise("target " .. target:name() .. " does not define a board name")
- end
+-- Helper to find a board file given either the name of a board file or a path.
+local function board_file_for_name(boardName)
+ local boardfile = boardName
-- The directory containing the board file.
local boarddir = path.directory(boardfile);
+ -- If this isn't a path, look in the boards directory
if path.basename(boardfile) == boardfile then
boarddir = path.join(scriptdir, "boards")
- boardfile = path.join(boarddir, boardfile .. '.json')
+ local fullBoardPath = path.join(boarddir, boardfile .. '.json')
+ if not os.isfile(fullBoardPath) then
+ fullBoardPath = path.join(boarddir, boardfile .. '.patch')
+ end
+ if not os.isfile(fullBoardPath) then
+ print("unable to find board file " .. boardfile .. ". Try specifying a full path")
+ return nil
+ end
+ boardfile = fullBoardPath
end
return boarddir, boardfile
end
+-- Helper to get the board file for a given target
+local function board_file_for_target(target)
+ local boardName = target:values("board")
+ if not boardName then
+ print("target " .. target:name() .. " does not define a board name")
+ return nil
+ end
+ return board_file_for_name(boardName)
+end
+
+-- Helper to load a board file. This must be passed the json object provided
+-- by import("core.base.json") because import does not work in helper
+-- functions at the top level.
+local function load_board_file(json, boardFile)
+ if path.extension(boardFile) == ".json" then
+ return json.loadfile(boardFile)
+ end
+ if path.extension(boardFile) ~= ".patch" then
+ print("unknown extension for board file: " .. boardFile)
+ return nil
+ end
+ local patch = json.loadfile(boardFile)
+ if not patch.base then
+ print("Board file " .. boardFile .. " does not specify a base")
+ return nil
+ end
+ local _, baseFile = board_file_for_name(patch.base)
+ local base = load_board_file(json, baseFile)
+
+ -- If a string value is a number, return it as number, otherwise return it
+ -- in its original form.
+ function asNumberIfNumber(value)
+ if tostring(tonumber(value)) == value then
+ return tonumber(value)
+ end
+ return value
+ end
+
+ -- Heuristic to tell a Lua table is probably an array in Lua
+ -- This is O(n), but n is usually very small, and this happens once per
+ -- build so this doesn't really matter.
+ function isarray(t)
+ local i = 1
+ for k, v in pairs(t) do | The manual sayeth "The order in which the indices are enumerated is not specified, _even for numeric indices_" (emphasis theirs). I think you want to test for the existence of a "border" at each `k`, and check that you've only seen one by the end of the loop. Of course, a non-numeric `k` means that this isn't a table backing a JSON array, even if Lua doesn't consider non-numeric keys to make a table a non-sequence.
_xmake_'s JSON goo in particular exports an [is_marked_as_array](https://github.com/xmake-io/xmake/blob/217d4adabedf2371f299ab1fbc456f40c24f4e23/xmake/core/base/json.lua#L252-L255) method that might be useful instead? |
cheriot-rtos | github_2023 | others | 423 | CHERIoT-Platform | nwf | @@ -253,21 +253,143 @@ target("cheriot.software_revoker")
target:set("cheriot.ldscript", "software_revoker.ldscript")
end)
--- Helper to get the board file for a given target
-local board_file = function(target)
- local boardfile = target:values("board")
- if not boardfile then
- raise("target " .. target:name() .. " does not define a board name")
- end
+-- Helper to find a board file given either the name of a board file or a path.
+local function board_file_for_name(boardName)
+ local boardfile = boardName
-- The directory containing the board file.
local boarddir = path.directory(boardfile);
+ -- If this isn't a path, look in the boards directory
if path.basename(boardfile) == boardfile then
boarddir = path.join(scriptdir, "boards")
- boardfile = path.join(boarddir, boardfile .. '.json')
+ local fullBoardPath = path.join(boarddir, boardfile .. '.json')
+ if not os.isfile(fullBoardPath) then
+ fullBoardPath = path.join(boarddir, boardfile .. '.patch')
+ end
+ if not os.isfile(fullBoardPath) then
+ print("unable to find board file " .. boardfile .. ". Try specifying a full path")
+ return nil
+ end
+ boardfile = fullBoardPath
end
return boarddir, boardfile
end
+-- Helper to get the board file for a given target
+local function board_file_for_target(target)
+ local boardName = target:values("board")
+ if not boardName then
+ print("target " .. target:name() .. " does not define a board name")
+ return nil
+ end
+ return board_file_for_name(boardName)
+end
+
+-- Helper to load a board file. This must be passed the json object provided
+-- by import("core.base.json") because import does not work in helper
+-- functions at the top level.
+local function load_board_file(json, boardFile)
+ if path.extension(boardFile) == ".json" then
+ return json.loadfile(boardFile)
+ end
+ if path.extension(boardFile) ~= ".patch" then
+ print("unknown extension for board file: " .. boardFile)
+ return nil
+ end
+ local patch = json.loadfile(boardFile)
+ if not patch.base then
+ print("Board file " .. boardFile .. " does not specify a base")
+ return nil
+ end
+ local _, baseFile = board_file_for_name(patch.base)
+ local base = load_board_file(json, baseFile)
+
+ -- If a string value is a number, return it as number, otherwise return it
+ -- in its original form.
+ function asNumberIfNumber(value)
+ if tostring(tonumber(value)) == value then
+ return tonumber(value)
+ end
+ return value
+ end
+
+ -- Heuristic to tell a Lua table is probably an array in Lua
+ -- This is O(n), but n is usually very small, and this happens once per
+ -- build so this doesn't really matter.
+ function isarray(t)
+ local i = 1
+ for k, v in pairs(t) do
+ if k ~= i then
+ return false
+ end
+ i = i+1
+ end
+ return true
+ end
+
+ for _, p in ipairs(patch.patch) do
+ if not p.op then
+ print("missing op in "..json.encode(p))
+ return nil
+ end
+ if not p.path or (type(p.path) ~= "string") then
+ print("missing or invalid path in "..json.encode(p))
+ return nil
+ end
+
+ -- Parse the JSON Pointer into an array of filed names, converting
+ -- numbers into Lua numbers if we see them. This is not quite right,
+ -- because it doesn't handle field names with / in them, but we don't
+ -- currently use those for anything. It also assumes that we really do
+ -- mean array indexes when we say numbers. If we have an object with
+ -- "3" as the key and try to replace 3, it will currently not do the
+ -- right thing. | The bit about numeric path components might be somewhat easy to solve with `is_marked_as_array`? Might not be worth doing yet, but just a comment with the name so we don't forget, perhaps. |
cheriot-rtos | github_2023 | others | 423 | CHERIoT-Platform | nwf | @@ -339,9 +460,10 @@ rule("firmware")
visit_all_dependencies_of(target, callback)
end
- local boarddir, boardfile = board_file(target);
- local board = json.loadfile(boardfile)
-
+ local boarddir, boardfile = board_file_for_target(target);
+ local board = load_board_file(json, boardfile)
+ print("Board file saved as ", target:targetfile()..".board.json")
+ json.savefile(target:targetfile()..".board.json", board) | Oh thank you. It's so obnoxious when build systems hide their computed state. :) |
cheriot-rtos | github_2023 | others | 423 | CHERIoT-Platform | rmn30 | @@ -0,0 +1,15 @@
+{
+ "base": "sonata-prerelease",
+ "patch": [
+ {
+ "op": "replace",
+ "path": "/simulation",
+ "value": true
+ },
+ {
+ "op": "replace",
+ "path": "/simulator", | Shouldn't there be a run here somewhere? |
cheriot-rtos | github_2023 | others | 410 | CHERIoT-Platform | nwf | @@ -79,6 +79,42 @@ struct DebugWriter
* Write a 64-bit signed integer.
*/
virtual void write(int64_t) = 0;
+ /**
+ * Write a single byte as hex with no leading 0x.
+ */
+ virtual void write_hex_byte(uint8_t) = 0;
+ /**
+ * Write an integer as hex.
+ */
+ template<typename T>
+ __always_inline void write_hex(T x)
+ requires(std::integral<T>)
+ {
+ if constexpr (sizeof(T) <= 4)
+ {
+ write(static_cast<uint32_t>(x)); | In order that negative values of signed types `T` narrower than `uint{32,64}_t` don't end up prefixed with a bunch of `F`s, do the signedness conversion at the same width and then zero-extend. Because we don't print leading zeros either, this should result in things appearing to be the right width.
```suggestion
write(static_cast<uint32_t>(static_cast<std::make_unsigned_t<T>>(x)));
``` |
cheriot-rtos | github_2023 | others | 391 | CHERIoT-Platform | davidchisnall | @@ -121,7 +121,11 @@ namespace Ibex
}
/**
- * Queries whether the specified revocation epoch has finished.
+ * Queries whether the specified revocation epoch has finished, or,
+ * if `AllowPartial` is true, that it has (at least) started.
+ *
+ * `epoch` must be even, as memory leaves quarantine only when
+ * revocation is not in progress.
*/
template<bool AllowPartial = false> | Do we have any users of this template parameter left? |
cheriot-rtos | github_2023 | cpp | 404 | CHERIoT-Platform | davidchisnall | @@ -1,12 +1,14 @@
// Copyright Microsoft and CHERIoT Contributors.
// SPDX-License-Identifier: MIT
-#include <cassert>
#include <cdefs.h>
+#include <debug.hh>
#include <futex.h>
#include <limits>
#include <stdint.h>
+using Debug = ConditionalDebug<DEBUG_CXXRT, "cxxrt">; | I don’t see the xmake option that sets this, so I’m a bit confused about how it compiles at all. |
cheriot-rtos | github_2023 | cpp | 404 | CHERIoT-Platform | davidchisnall | @@ -54,6 +56,8 @@ namespace
/**
* Acquire the lock.
+ *
+ * This is safe only in IRQ-deferred context. | Why? |
cheriot-rtos | github_2023 | cpp | 404 | CHERIoT-Platform | davidchisnall | @@ -62,7 +66,7 @@ namespace
{
futex_wait(&high, LockBit);
}
- assert(high == 0);
+ Debug::Assert(high == 0, "Corrupt guard word"); | It would be nice to log the address of the guard word here, so someone can look up that address. It will have a symbol name that matches the global being described. |
cheriot-rtos | github_2023 | cpp | 404 | CHERIoT-Platform | davidchisnall | @@ -71,9 +75,10 @@ namespace
*/
void unlock()
{
- assert(high == LockBit);
- high = 0;
- futex_wake(&high, std::numeric_limits<uint32_t>::max());
+ Debug::Assert(high == LockBit, "Corrupt guard word");
+ high = 0;
+ int res = futex_wake(&high, std::numeric_limits<uint32_t>::max());
+ Debug::Invariant(res == 0, "futex_wake failed; possible deadlock"); | I’m not sure I like having this as an invariant. If a compartment is single threaded or otherwise ensures that statics are not concurrently initialised, it’s fine for this to fail. In this function, we don’t know if that is the case. |
cheriot-rtos | github_2023 | cpp | 412 | CHERIoT-Platform | davidchisnall | @@ -170,243 +170,235 @@ namespace
} // namespace
-namespace sched | These things should all be moved to an anonymous namespace, not exported functions in the global namespace.
Ideally, the `priv` namespace should also be removed. |
cheriot-rtos | github_2023 | cpp | 405 | CHERIoT-Platform | rmn30 | @@ -34,5 +34,15 @@ constexpr StackCheckMode StackMode =
#endif
;
-#define STACK_CHECK(expected) \
- StackUsageCheck<StackMode, expected, __PRETTY_FUNCTION__> stackCheck
+#if __CHERIOT__ >= 20250108 | ```suggestion
#if defined(__CHERIOT__) && (__CHERIOT__ >= 20250108)
``` |
cheriot-rtos | github_2023 | cpp | 413 | CHERIoT-Platform | rmn30 | @@ -163,8 +182,22 @@ namespace
MultiWaiterInternal::wake_waiters(key, count);
count -= multiwaitersWoken;
woke += multiwaitersWoken;
- shouldYield |= (multiwaitersWoken > 0);
}
+ Debug::log("futex_wake on {} woke {} waiters", key, woke);
+
+ auto *thread = Thread::current_get();
+ FutexWakeKind shouldYield = NoYield;
+ if (!thread->is_highest_priority())
+ {
+ shouldYield = YieldNow;
+ }
+ else if (thread->has_priority_peers())
+ {
+ shouldYield =
+ thread->has_run_for_full_tick() ? YieldNow : YieldLater;
+ }
+ Debug::log("futex_wake yielding?", shouldYield); | ```suggestion
Debug::log("futex_wake yielding? {}", shouldYield);
``` |
cheriot-rtos | github_2023 | cpp | 413 | CHERIoT-Platform | nwf | @@ -530,7 +553,28 @@ __cheriot_minimum_stack(0xa0) int futex_wake(uint32_t *address, uint32_t count)
}
ptraddr_t key = Capability{address}.address();
- auto [shouldYield, shouldResetPrioirity, woke] = futex_wake(key, count);
+ auto [shouldResetPrioirity, woke] = futex_wake(key, count);
+
+ FutexWakeKind shouldYield = NoYield;
+
+ if (woke > 0)
+ {
+ auto *thread = Thread::current_get();
+ if (!thread)
+ { | Just to confirm my understanding: this is the case of `exception_entry` calling `futex_wake`? |
cheriot-rtos | github_2023 | cpp | 413 | CHERIoT-Platform | nwf | @@ -551,12 +595,19 @@ __cheriot_minimum_stack(0xa0) int futex_wake(uint32_t *address, uint32_t count)
priority_boost_for_thread(currentThread->id_get()));
// If we have dropped priority below that of another runnable thread, we
// should yield now.
- shouldYield |= !currentThread->is_highest_priority();
}
- if (shouldYield)
+ switch (shouldYield)
{
- yield();
+ case YieldLater:
+ Timer::ensure_tick();
+ break;
+ case YieldNow:
+ yield();
+ break;
+ case NoYield:
+ {
+ } | Purely a stylistic question: why not `break;`? |
cheriot-rtos | github_2023 | cpp | 413 | CHERIoT-Platform | nwf | @@ -543,6 +539,17 @@ namespace
return next != this;
}
+ /**
+ * Returns true if the thread has run for a complete tick. This must
+ * be called only on the currently running thread.
+ */
+ bool has_run_for_full_tick()
+ {
+ Debug::Assert(this == current,
+ "Only the current thread is running"); | That's a bit of a tautology, isn't it?
```suggestion
"Ask only about currently running thread");
``` |
cheriot-rtos | github_2023 | cpp | 413 | CHERIoT-Platform | nwf | @@ -564,8 +571,12 @@ namespace
///@}
/// Pointer to the list of the resource this thread is blocked on.
ThreadImpl **sleepQueue;
- /// If suspended, when will this thread expire. The maximum value is
- /// special-cased to mean blocked indefinitely.
+ /**
+ * If suspended, when will this thread expire. The maximum value is
+ * special-cased to mean blocked indefinitely.
+ *
+ * When a thread is running, this the time at which it was scheduled. | Again, just to check my understanding: Time of the _last_ scheduling event and not the time of any _upcoming_ scheduling event because there might not actually be one, if this is the only runnable thread in the system, and besides it's cheaper to not do the addition unless someone asks in `has_run...`? |
cheriot-rtos | github_2023 | cpp | 403 | CHERIoT-Platform | nwf | @@ -1364,7 +1364,7 @@ extern "C" SchedulerEntryInfo loader_entry_point(const ImgHdr &imgHdr,
build<ExportEntry>(
imgHdr.scheduler().exportTable,
LA_ABS(
- __export_sched__ZN5sched15exception_entryEP19TrustedStackGenericILj0EEjjj))
+ __export_scheduler__ZN5sched15exception_entryEP19TrustedStackGenericILj0EEjjj)) | While you're here, do you want to change the `namespace sched` in `scheduler/main.cc` to `namespace scheduler`, too? |
cheriot-rtos | github_2023 | others | 398 | CHERIoT-Platform | davidchisnall | @@ -75,6 +75,7 @@
"ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM=1",
"ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM=1"
],
+ "cflags": "-enable-machine-outliner=never", | I *think* this is not needed on 0.2. I'll check, but I believe 0.2 has an old enough version of Ibex that it doesn't introduce the problem that the latest one fixes. |
cheriot-rtos | github_2023 | cpp | 401 | CHERIoT-Platform | davidchisnall | @@ -1183,7 +1190,11 @@ __cheriot_minimum_stack(0x280) SObj
return sealed; | ```suggestion
``` |
cheriot-rtos | github_2023 | cpp | 401 | CHERIoT-Platform | davidchisnall | @@ -1183,7 +1190,11 @@ __cheriot_minimum_stack(0x280) SObj
return sealed;
}
}
- heap_free(heapCapability, obj);
+ /*
+ * We get here only if we have failed to store the unsealed handle through
+ * the out parameter. Destroy the allocation we just made.
+ */
+ token_obj_destroy(heapCapability, key, sealed);
return INVALID_SOBJ; | ```suggestion
return sealed;
``` |
cheriot-rtos | github_2023 | cpp | 401 | CHERIoT-Platform | rmn30 | @@ -1175,16 +1175,24 @@ __cheriot_minimum_stack(0x280) SObj
auto [sealed, obj] = allocate_sealed_unsealed(
timeout, heapCapability, key, sz, {Permission::Seal, Permission::Unseal});
{
+ /*
+ * Write the unsealed capability through the out parameter, while
+ * holding the allocator lock. That's a little heavy-handed, but it
+ * suffices to ensure that it won't be freed out from under us, so
+ * if it passes `check_pointer`, then the store won't trap.
+ */
LockGuard g{lock};
if (check_pointer<PermissionSet{
Permission::Store, Permission::LoadStoreCapability}>(unsealed))
{
*unsealed = obj;
- return sealed;
}
}
- heap_free(heapCapability, obj);
- return INVALID_SOBJ;
+ /*
+ * We get here only if we have failed to store the unsealed handle through | What am I missing? This doesn't seem right. |
cheriot-rtos | github_2023 | cpp | 379 | CHERIoT-Platform | davidchisnall | @@ -1183,7 +1192,7 @@ __cheriot_minimum_stack(0x280) SObj
return sealed;
}
}
- heap_free(heapCapability, obj);
+ (void)heap_free(heapCapability, obj); | Would be nice to have a comment here. This can happen only if the caller gives us a malicious output value. Actually, we probably can elide this and return sealed unconditionally. If you give us a valid `unsealed` pointer and we don't write through it, you can still free with the sealed pointer. |
cheriot-rtos | github_2023 | cpp | 379 | CHERIoT-Platform | davidchisnall | @@ -1460,6 +1460,7 @@ extern "C" SchedulerEntryInfo loader_entry_point(const ImgHdr &imgHdr,
// invoke the exception entry point.
auto exportEntry = build<ExportEntry>(
imgHdr.scheduler().exportTable,
+ // XXX NWF | ??? |
cheriot-rtos | github_2023 | cpp | 379 | CHERIoT-Platform | davidchisnall | @@ -31,9 +31,10 @@ using namespace CHERI;
/**
* Exit simulation, reporting the error code given as the argument.
*/
-void simulation_exit(uint32_t code)
+int simulation_exit(uint32_t code) | Why is this an `int`? I don't think any code should ever be expected to handle this returning. The fallback mode should probably be to infinite loop. |
cheriot-rtos | github_2023 | cpp | 379 | CHERIoT-Platform | davidchisnall | @@ -67,7 +67,7 @@ compartment_error_handler(ErrorState *frame, size_t mcause, size_t mtval)
DebugErrorHandler::log("Unhandled error {} at {}", mcause, frame->pcc);
}
- simulation_exit(1);
+ (void)simulation_exit(1); | As above, so far every call to this function has discarded the return result. It either exits (and doesn't return) or doesn't exit (and we're not in a simulator that can exit). We get no information from the non-void return. |
cheriot-rtos | github_2023 | cpp | 379 | CHERIoT-Platform | davidchisnall | @@ -3,14 +3,18 @@
#pragma once
#include <compartment.h>
+#include <errno.h>
#include <stdint.h>
#ifdef SIMULATION
/**
* Exit simulation, reporting the error code given as the argument.
*/
-[[cheri::interrupt_state(disabled)]] void __cheri_compartment("sched")
+[[cheri::interrupt_state(disabled)]] int __cheri_compartment("sched") | We can just silence the warning here, I think. Or we can rename this to `scheduler_exit_simulation` and have a `void` wrapper that calls it. |
cheriot-rtos | github_2023 | cpp | 379 | CHERIoT-Platform | davidchisnall | @@ -282,7 +282,7 @@ ssize_t __cheri_compartment("alloc")
* state. It can block indefinitely if another thread is allocating and
* freeing memory while this runs.
*/
-void __cheri_compartment("alloc") heap_quarantine_empty(void);
+int __cheri_compartment("alloc") heap_quarantine_empty(void); | Please update the comment to say that this returns 0 or -ECOMPARTMENTFAIL. |
cheriot-rtos | github_2023 | cpp | 379 | CHERIoT-Platform | davidchisnall | @@ -72,8 +72,9 @@ namespace
void unlock()
{
assert(high == LockBit);
- high = 0;
- futex_wake(&high, std::numeric_limits<uint32_t>::max());
+ high = 0;
+ int res = futex_wake(&high, std::numeric_limits<uint32_t>::max());
+ assert(res >= 0); | Please don't use `assert`, I don't think we use it anywhere else in the codebase. It is there *purely* because C99 requires it, not because we should use it. |
cheriot-rtos | github_2023 | cpp | 379 | CHERIoT-Platform | rmn30 | @@ -224,7 +224,10 @@ namespace
// Release the lock before sleeping
g.unlock();
Timeout smallSleep{1};
- thread_sleep(&smallSleep);
+ if (thread_sleep(&smallSleep) < 0) | Not going to block merge but would be nice to have a union type for this. Did you audit all calls to `thread_sleep`, even ones that didn't trigger the `nodiscard` warning? |
cheriot-rtos | github_2023 | cpp | 379 | CHERIoT-Platform | rmn30 | @@ -9,7 +9,7 @@
* revocation pass, it will scan a region of memory and then return. | Ought to have a comment here describing the return value. Not a blocker. |
cheriot-rtos | github_2023 | cpp | 379 | CHERIoT-Platform | rmn30 | @@ -159,15 +159,17 @@ namespace
} // namespace
-void revoker_tick()
+int revoker_tick()
{
// If we've been asked to run, make sure that we're running.
if (state == State::NotRunning)
{
advance();
}
// Do some work.
- return scan_range(); | Why was there a return in a void function!? |
cheriot-rtos | github_2023 | cpp | 379 | CHERIoT-Platform | rmn30 | @@ -94,7 +94,14 @@ namespace thread_pool
return;
}
(*fn)();
- token_obj_destroy(MALLOC_CAPABILITY, key, static_cast<SObj>(rawFn));
+ /*
+ * This fails only if the thread pool runner compartment can't make
+ * cross-compartment calls to the allocator at all, since we're
+ * in its initial trusted activation frame and near the beginning
+ * (highest address) of its stack.
+ */
+ (void)token_obj_destroy( | Worthy of a debug assertion? |
cheriot-rtos | github_2023 | cpp | 379 | CHERIoT-Platform | rmn30 | @@ -471,21 +499,19 @@ namespace
ptr2);
state = 2;
// Yield to allow the hazards to be dropped.
- Timeout t{1};
- thread_sleep(&t);
+ TEST(sleep(1) >= 0, "Failed to yield to drop hazards");
// Try a double free. This may logically succeed, but should not affect
// our quota.
- heap_free(SECOND_HEAP, ptr);
+ (void)heap_free(SECOND_HEAP, ptr); | Why doesn't this one test the return value of `heap_free`? |
cheriot-rtos | github_2023 | cpp | 400 | CHERIoT-Platform | davidchisnall | @@ -34,5 +34,12 @@ constexpr StackCheckMode StackMode =
#endif
;
-#define STACK_CHECK(expected) \
- StackUsageCheck<StackMode, expected, __PRETTY_FUNCTION__> stackCheck
+
+#if __CHERIOT__ >= 20250102 | ```suggestion
#if __has_builtin(__builtin_cheriot_get_specified_minimum_stack)
``` |
cheriot-rtos | github_2023 | cpp | 400 | CHERIoT-Platform | davidchisnall | @@ -34,5 +34,12 @@ constexpr StackCheckMode StackMode =
#endif
;
-#define STACK_CHECK(expected) \
- StackUsageCheck<StackMode, expected, __PRETTY_FUNCTION__> stackCheck
+
+#if __CHERIOT__ >= 20250102
+ #define STACK_CHECK(expected) \
+ assert(__builtin_cheriot_get_specified_minimum_stack() == expected); \ | ```suggestion
static_assert(__builtin_cheriot_get_specified_minimum_stack() == expected, "expected value does not match value provided as function argument"); \
``` |
cheriot-rtos | github_2023 | others | 400 | CHERIoT-Platform | nwf | @@ -819,20 +819,20 @@ namespace
* StackUsageCheck<DebugFlag, 128, __PRETTY_FUNCTION__> stackCheck;
* ```
*/
- template<StackCheckMode Mode, size_t Expected, DebugContext Fn>
+ template<StackCheckMode Mode, DebugContext Fn>
class StackUsageCheck
{
/**
* The expected maximum. This class is templated on the function name
* and so there is one copy of this per function.
*/
- static inline size_t stackUsage = Expected;
+ static inline size_t stackUsage; | ```suggestion
size_t stackUsage;
```
The change from a template parameter to a constructor parameter is... incomplete? On both the "old" llvm-13 and new compiler, as it stands, this PR...
1. creates and *mutates* a `static` object in globals, and
2. stores a pointer to that static object on the stack, which is why CI is balking.
Here's the prolog of `heap_quota_remaining`, before (`-`) and after (`+`):
```
800039b0 <heap_quota_remaining(SObjStruct*)>:
; heap_quota_remaining(SObjStruct*)():
; /home/cheriot/cheriot-rtos/tests/../sdk/core/allocator/main.cc:844
; {
-800039b0: 79 71 cincoffset csp, csp, -48
-800039b2: 06 f4 csc cra, 40(csp)
-800039b4: 22 f0 csc cs0, 32(csp)
-800039b6: 26 ec csc cs1, 24(csp)
+800039b0: 39 71 cincoffset csp, csp, -64
+800039b2: 06 fc csc cra, 56(csp)
+800039b4: 22 f8 csc cs0, 48(csp)
+800039b6: 26 f4 csc cs1, 40(csp)
800039b8: db 04 a5 fe cmove cs1, ca0
-800039bc: 28 00 cincoffset ca0, csp, 8
-800039be: 5b 24 05 01 csetbounds cs0, ca0, 16
-800039c2 <.LBB0_6>:
+800039bc <.LBB0_6>:
; .LBB0_6():
+; /home/cheriot/cheriot-rtos/sdk/include/debug.hh:835
+; constexpr inline explicit StackUsageCheck(size_t Expected) { stackUsage = Expected; }
+800039bc: db 95 c1 ff cincoffset ca1, cgp, -4
+800039c0: 13 05 00 09 addi a0, zero, 144
+800039c4: 2e e4 csc ca1, 8(csp)
+800039c6: 88 c1 csw a0, 0(ca1)
```
Dropping the `static inline` on `stackUsage` undoes that change, presumably because the compiler has better visibility into all references to it. The new compiler still won't pass CI yet until we bump some limits, but it is definitely _worse_ with the `static inline` on `stackUsage` than without. |
cheriot-rtos | github_2023 | others | 357 | CHERIoT-Platform | nwf | @@ -0,0 +1,403 @@
+#pragma once
+#include <cdefs.h>
+#include <debug.hh>
+#include <stdint.h>
+#include <utils.hh>
+
+namespace SonataSpi
+{
+ /// Sonata SPI Interrupts
+ typedef enum [[clang::flag_enum]]
+ : uint32_t{
+ /// Raised when a SPI operation completes and the block has become idle.
+ InterruptComplete = 1 << 4,
+ /// Asserted whilst the transmit FIFO level is at or above the
+ /// watermark.
+ InterruptTransmitWatermark = 1 << 3,
+ /// Asserted whilst the transmit FIFO is empty.
+ InterruptTransmitEmpty = 1 << 2,
+ /// Asserted whilst the receive FIFO level is at or below the watermark.
+ InterruptReceiveWatermark = 1 << 1,
+ /// Asserted whilst the receive FIFO is full.
+ InterruptReceiveFull = 1 << 0,
+ } Interrupt; | Er, perhaps this is just a polarity thing, but I'd expect the `InterruptTransmitWatermark` to fire when the transmit FIFO is _below_ its watermark (that is, it has room to accept a positive natural number of bytes before overflow) and, dually, `InterruptReceiveWatermakr` to fire when the receive FIFO is _above_ its watermark (that is, it can source at least watermark-many bytes). |
cheriot-rtos | github_2023 | others | 357 | CHERIoT-Platform | nwf | @@ -0,0 +1,403 @@
+#pragma once
+#include <cdefs.h>
+#include <debug.hh>
+#include <stdint.h>
+#include <utils.hh>
+
+namespace SonataSpi
+{
+ /// Sonata SPI Interrupts
+ typedef enum [[clang::flag_enum]]
+ : uint32_t{
+ /// Raised when a SPI operation completes and the block has become idle.
+ InterruptComplete = 1 << 4,
+ /// Asserted whilst the transmit FIFO level is at or above the
+ /// watermark.
+ InterruptTransmitWatermark = 1 << 3,
+ /// Asserted whilst the transmit FIFO is empty.
+ InterruptTransmitEmpty = 1 << 2,
+ /// Asserted whilst the receive FIFO level is at or below the watermark.
+ InterruptReceiveWatermark = 1 << 1,
+ /// Asserted whilst the receive FIFO is full.
+ InterruptReceiveFull = 1 << 0,
+ } Interrupt;
+
+ /// Configuration Register Fields
+ enum : uint32_t
+ {
+ /**
+ * The length of a half period (i.e. positive edge to negative edge) of
+ * the SPI clock, measured in system clock cycles reduced by 1. For
+ * example, at a 50 MHz system clock, a value of 0 gives a 25 MHz SPI
+ * clock, a value of 1 gives a 12.5 MHz SPI clock, a value of 2 gives
+ * a 8.33 MHz SPI clock and so on.
+ */
+ ConfigurationHalfClockPeriodMask = 0xffu << 0,
+ /*
+ * When set the most significant bit (MSB) is the first bit sent and
+ * received with each byte
+ */
+ ConfigurationMSBFirst = 1u << 29,
+ /*
+ * The phase of the spi_clk signal. when clockphase is 0, data is
+ * sampled on the leading edge and changes on the trailing edge. The
+ * first data bit is immediately available before the first leading edge
+ * of the clock when transmission begins. When clockphase is 1, data is
+ * sampled on the trailing edge and change on the leading edge.
+ */
+ ConfigurationClockPhase = 1u << 30,
+ /*
+ * The polarity of the spi_clk signal. When ClockPolarity is 0, clock is
+ * low when idle and the leading edge is positive. When ClkPolarity is
+ * 1, clock is high when idle and the leading edge is negative
+ */
+ ConfigurationClockPolarity = 1u << 31,
+ };
+
+ /// Control Register Fields
+ enum : uint32_t
+ {
+ /// Write 1 to clear the transmit FIFO.
+ ControlTransmitClear = 1 << 0,
+ /// Write 1 to clear the receive FIFO.
+ ControlReceiveClear = 1 << 1,
+ /**
+ * When set bytes from the transmit FIFO are sent. When clear the state
+ * of the outgoing spi_cipo is undefined whilst the SPI clock is
+ * running.
+ */
+ ControlTransmitEnable = 1 << 2,
+ /**
+ * When set incoming bits are written to the receive FIFO. When clear
+ * incoming bits are ignored.
+ */
+ ControlReceiveEnable = 1 << 3,
+ /**
+ * The watermark level for the transmit FIFO, depending on the value
+ * the interrupt will trigger at different points
+ */
+ ControlTransmitWatermarkMask = 0xf << 4,
+ /**
+ * The watermark level for the receive FIFO, depending on the value the
+ * interrupt will trigger at different points
+ */
+ ControlReceiveWatermarkMask = 0xf << 8,
+ /**
+ * Internal loopback function enabled when set to 1.
+ */
+ ControlInternalLoopback = 1 << 30,
+ /**
+ * Software reset performed when written as 1.
+ */
+ ControlSoftwareReset = 1u << 31,
+ };
+
+ /// Status Register Fields
+ enum : uint32_t
+ {
+ /// Number of items in the transmit FIFO.
+ StatusTxFifoLevel = 0xffu << 0,
+ /// Number of items in the receive FIFO.
+ StatusRxFifoLevel = 0xffu << 8,
+ /**
+ * When set the transmit FIFO is full and any data written to it will
+ * be ignored.
+ */
+ StatusTxFifoFull = 1u << 16,
+ /**
+ * When set the receive FIFO is empty and any data read from it will be
+ * undefined.
+ */
+ StatusRxFifoEmpty = 1u << 17,
+ /// When set the SPI block is idle and can accept a new start command.
+ StatusIdle = 1u << 18,
+ };
+
+ /// Start Register Fields
+ enum : uint32_t
+ {
+ /// Number of bytes to receive/transmit in the SPI operation
+ StartByteCountMask = 0x7ffu,
+ };
+
+ /// Info Register Fields
+ enum : uint32_t
+ {
+ /// Maximum number of items in the transmit FIFO.
+ InfoTxFifoDepth = 0xffu << 0,
+ /// Maximum number of items in the receive FIFO.
+ InfoRxFifoDepth = 0xffu << 8,
+ };
+
+ /**
+ * A driver for the Sonata's SPI device block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/sonata-system/blob/1a59633d2515d4fe186a07d53e49ff95c18d9bbf/doc/ip/spi.md
+ *
+ * Rendered documentation is served from:
+ * https://lowrisc.org/sonata-system/doc/ip/spi.html
+ */
+ template<size_t NumChipSelects = 4>
+ struct Generic : private utils::NoCopyNoMove
+ {
+ /**
+ * The Sonata SPI block doesn't currently have support for interrupts.
+ * The following registers are reserved for future use.
+ */ | Stale comment, given the code below? |
cheriot-rtos | github_2023 | others | 357 | CHERIoT-Platform | nwf | @@ -0,0 +1,403 @@
+#pragma once
+#include <cdefs.h>
+#include <debug.hh>
+#include <stdint.h>
+#include <utils.hh>
+
+namespace SonataSpi
+{
+ /// Sonata SPI Interrupts
+ typedef enum [[clang::flag_enum]]
+ : uint32_t{
+ /// Raised when a SPI operation completes and the block has become idle.
+ InterruptComplete = 1 << 4,
+ /// Asserted whilst the transmit FIFO level is at or above the
+ /// watermark.
+ InterruptTransmitWatermark = 1 << 3,
+ /// Asserted whilst the transmit FIFO is empty.
+ InterruptTransmitEmpty = 1 << 2,
+ /// Asserted whilst the receive FIFO level is at or below the watermark.
+ InterruptReceiveWatermark = 1 << 1,
+ /// Asserted whilst the receive FIFO is full.
+ InterruptReceiveFull = 1 << 0,
+ } Interrupt;
+
+ /// Configuration Register Fields
+ enum : uint32_t
+ {
+ /**
+ * The length of a half period (i.e. positive edge to negative edge) of
+ * the SPI clock, measured in system clock cycles reduced by 1. For
+ * example, at a 50 MHz system clock, a value of 0 gives a 25 MHz SPI
+ * clock, a value of 1 gives a 12.5 MHz SPI clock, a value of 2 gives
+ * a 8.33 MHz SPI clock and so on.
+ */
+ ConfigurationHalfClockPeriodMask = 0xffu << 0,
+ /*
+ * When set the most significant bit (MSB) is the first bit sent and
+ * received with each byte
+ */
+ ConfigurationMSBFirst = 1u << 29,
+ /*
+ * The phase of the spi_clk signal. when clockphase is 0, data is
+ * sampled on the leading edge and changes on the trailing edge. The
+ * first data bit is immediately available before the first leading edge
+ * of the clock when transmission begins. When clockphase is 1, data is
+ * sampled on the trailing edge and change on the leading edge.
+ */
+ ConfigurationClockPhase = 1u << 30,
+ /*
+ * The polarity of the spi_clk signal. When ClockPolarity is 0, clock is
+ * low when idle and the leading edge is positive. When ClkPolarity is
+ * 1, clock is high when idle and the leading edge is negative
+ */
+ ConfigurationClockPolarity = 1u << 31,
+ };
+
+ /// Control Register Fields
+ enum : uint32_t
+ {
+ /// Write 1 to clear the transmit FIFO.
+ ControlTransmitClear = 1 << 0,
+ /// Write 1 to clear the receive FIFO.
+ ControlReceiveClear = 1 << 1,
+ /**
+ * When set bytes from the transmit FIFO are sent. When clear the state
+ * of the outgoing spi_cipo is undefined whilst the SPI clock is
+ * running.
+ */
+ ControlTransmitEnable = 1 << 2,
+ /**
+ * When set incoming bits are written to the receive FIFO. When clear
+ * incoming bits are ignored.
+ */
+ ControlReceiveEnable = 1 << 3,
+ /**
+ * The watermark level for the transmit FIFO, depending on the value
+ * the interrupt will trigger at different points
+ */
+ ControlTransmitWatermarkMask = 0xf << 4,
+ /**
+ * The watermark level for the receive FIFO, depending on the value the
+ * interrupt will trigger at different points
+ */
+ ControlReceiveWatermarkMask = 0xf << 8,
+ /**
+ * Internal loopback function enabled when set to 1.
+ */
+ ControlInternalLoopback = 1 << 30,
+ /**
+ * Software reset performed when written as 1.
+ */
+ ControlSoftwareReset = 1u << 31,
+ };
+
+ /// Status Register Fields
+ enum : uint32_t
+ {
+ /// Number of items in the transmit FIFO.
+ StatusTxFifoLevel = 0xffu << 0,
+ /// Number of items in the receive FIFO.
+ StatusRxFifoLevel = 0xffu << 8,
+ /**
+ * When set the transmit FIFO is full and any data written to it will
+ * be ignored.
+ */
+ StatusTxFifoFull = 1u << 16,
+ /**
+ * When set the receive FIFO is empty and any data read from it will be
+ * undefined.
+ */
+ StatusRxFifoEmpty = 1u << 17,
+ /// When set the SPI block is idle and can accept a new start command.
+ StatusIdle = 1u << 18,
+ };
+
+ /// Start Register Fields
+ enum : uint32_t
+ {
+ /// Number of bytes to receive/transmit in the SPI operation
+ StartByteCountMask = 0x7ffu,
+ };
+
+ /// Info Register Fields
+ enum : uint32_t
+ {
+ /// Maximum number of items in the transmit FIFO.
+ InfoTxFifoDepth = 0xffu << 0,
+ /// Maximum number of items in the receive FIFO.
+ InfoRxFifoDepth = 0xffu << 8,
+ };
+
+ /**
+ * A driver for the Sonata's SPI device block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/sonata-system/blob/1a59633d2515d4fe186a07d53e49ff95c18d9bbf/doc/ip/spi.md
+ *
+ * Rendered documentation is served from:
+ * https://lowrisc.org/sonata-system/doc/ip/spi.html
+ */
+ template<size_t NumChipSelects = 4>
+ struct Generic : private utils::NoCopyNoMove
+ {
+ /**
+ * The Sonata SPI block doesn't currently have support for interrupts.
+ * The following registers are reserved for future use.
+ */
+ uint32_t interruptState;
+ uint32_t interruptEnable;
+ uint32_t interruptTest;
+ /**
+ * Configuration register. Controls how the SPI block transmits and
+ * receives data. This register can be modified only whilst the SPI
+ * block is idle.
+ */
+ uint32_t configuration;
+ /**
+ * Controls the operation of the SPI block. This register can
+ * be modified only whilst the SPI block is idle.
+ */
+ uint32_t control;
+ /// Status information about the SPI block
+ uint32_t status;
+ /**
+ * Writes to this begin an SPI operation.
+ * Writes are ignored when the SPI block is active.
+ */
+ uint32_t start;
+ /**
+ * Data from the receive FIFO. When read the data is popped from the
+ * FIFO. If the FIFO is empty data read is undefined.
+ */
+ uint32_t receiveFifo;
+ /**
+ * Bytes written here are pushed to the transmit FIFO. If the FIFO is
+ * full writes are ignored.
+ */
+ uint32_t transmitFifo;
+ /**
+ * Information about the SPI controller. This register reports the
+ * depths of the transmit and receive FIFOs within the controller.
+ */
+ uint32_t info;
+ /**
+ * Chip Select lines; clear a bit to transmit/receive to/from the
+ * corresponding peripheral.
+ */ | What happens if this has a population count other than 1? |
cheriot-rtos | github_2023 | others | 395 | CHERIoT-Platform | davidchisnall | @@ -6,9 +6,6 @@ resources:
- pipeline: LLVM
project: CHERI-MCU
source: LLVM | I think we can lose this file entirely. |
cheriot-rtos | github_2023 | cpp | 377 | CHERIoT-Platform | davidchisnall | @@ -2807,4 +2807,155 @@ class MState
{
ABORT();
}
+
+#ifndef NDEBUG | Please don't gate things on this macro. Use feature flags. |
cheriot-rtos | github_2023 | cpp | 377 | CHERIoT-Platform | davidchisnall | @@ -1268,3 +1268,10 @@ size_t heap_available()
{
return gm->heapFreeSize;
}
+
+#ifndef NDEBUG | Same here. This should be controlled by an option, not a global flag that we don't use for any other purpose but that is defined by the C spec. |
cheriot-rtos | github_2023 | cpp | 377 | CHERIoT-Platform | rmn30 | @@ -2811,4 +2811,163 @@ class MState
{
ABORT();
}
+
+#if HEAP_RENDER
+ public:
+ /**
+ * "Render" the heap for debugging.
+ */
+ template<bool Asserts = false, bool Chatty = true> | I think Asserts should default to `true`. They don't look that expensive compared to the debug logs (I guess `ds::linked_list::is_well_formed` may be linear in length of list?). |
cheriot-rtos | github_2023 | cpp | 363 | CHERIoT-Platform | rmn30 | @@ -240,13 +240,56 @@ namespace
}
} // namespace
+void check_sealed_scoping()
+{
+ Capability<void> o{switcher_current_thread()};
+ TEST(o.is_valid() && (o.type() == CheriSealTypeSealedTrustedStacks),
+ "Shared object cap not as expected: {}",
+ o);
+
+ // Take the address of the o cap, requiring that it go out to memory.
+ Capability<Capability<void>> oP{&o};
+
+ /*
+ * Load a copy of our sealed o cap through an authority that lacks
+ * LoadGlobal permission. The result should be identical to the original
+ * but without global permission.
+ */
+ Capability<Capability<void>> oPNoLoadGlobal = oP;
+ oPNoLoadGlobal.permissions() &=
+ PermissionSet::omnipotent().without(Permission::LoadGlobal);
+ Capability<void> oLocal1 = *oPNoLoadGlobal;
+
+ TEST(
+ oLocal1.is_valid() && (oLocal1.type() == o.type()) && | I would suggest separating clauses into differnt `TEST` / `TEST_EQUAL` as that will provide a clearer error if anything goes wrong. |
cheriot-rtos | github_2023 | cpp | 363 | CHERIoT-Platform | rmn30 | @@ -240,13 +240,56 @@ namespace
}
} // namespace
+void check_sealed_scoping()
+{
+ Capability<void> o{switcher_current_thread()};
+ TEST(o.is_valid() && (o.type() == CheriSealTypeSealedTrustedStacks),
+ "Shared object cap not as expected: {}",
+ o);
+
+ // Take the address of the o cap, requiring that it go out to memory.
+ Capability<Capability<void>> oP{&o};
+
+ /*
+ * Load a copy of our sealed o cap through an authority that lacks
+ * LoadGlobal permission. The result should be identical to the original
+ * but without global permission.
+ */
+ Capability<Capability<void>> oPNoLoadGlobal = oP;
+ oPNoLoadGlobal.permissions() &=
+ PermissionSet::omnipotent().without(Permission::LoadGlobal);
+ Capability<void> oLocal1 = *oPNoLoadGlobal;
+
+ TEST(
+ oLocal1.is_valid() && (oLocal1.type() == o.type()) &&
+ (oLocal1.permissions() == o.permissions().without(Permission::Global)),
+ "Loading global sealed cap through non-LoadGlobal authority gone wrong: "
+ "{} {}",
+ o,
+ oLocal1);
+
+ /*
+ * Use CAndPerm to shed Global from our o cap.
+ * Spell this a little oddly to make sure we get CAndPerm with a mask of | I think we should add a `drop_perms` method to `Capability` to do this. The architectural permissions were ordered to optimize dropping specific permissions in this way for common permissions to drop (e.g. LM, LG). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.