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 | others | 264 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,125 @@
+Safe Configuration Management
+=============================
+
+This example shows how dynamic configuration changes can be made to compartments using the ChERIoT features of static sealed capabilities, memory claims, a futex, and a sandbox compartment for validating untrusted data.
+
+In this model a configuration item is a named blob of data. There are compartments which supply configuration items (for example received by them via the network) and other compartments that need to receive specific configuration items when ever they change. None of these compartments know about or trust each other; keeping them decoupled helps to keep the system simple, and make it easy to add new items and compartments with a minimal amount of development. | We try to follow a convention in Markdown of one sentence per line. It makes it easier to review diffs because changing one sentence doesn't affect the rest of the paragraph. |
cheriot-rtos | github_2023 | others | 264 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,125 @@
+Safe Configuration Management
+=============================
+
+This example shows how dynamic configuration changes can be made to compartments using the ChERIoT features of static sealed capabilities, memory claims, a futex, and a sandbox compartment for validating untrusted data.
+
+In this model a configuration item is a named blob of data. There are compartments which supply configuration items (for example received by them via the network) and other compartments that need to receive specific configuration items when ever they change. None of these compartments know about or trust each other; keeping them decoupled helps to keep the system simple, and make it easy to add new items and compartments with a minimal amount of development.
+
+## Overview
+
+The model is is similar to a pub/sub architecture with a single retained message for each item and a security policy defined at build time though static sealed capabilities. The configuration data is declarative so there is no need or value in maintaining a full sequence of updates. Providing the role of the broker is a config_broker compartment, which has the unsealing key. Aligned the pub/sub model publishing items and subscribing for items can happen in any sequence; a subscriber will receive any data that is already published, and any subsequent updates. This avoids any timing issues during system startup.
+
+By defining static sealed capabilities we can control at build time:
+* Which compartments are allowed to update which items
+* Which compartments are allowed to receives which items
+
+In addition the example shows how memory claims can be used to ensure that heap allocations made in one compartment (publishers) remains available to the subscribers outside of the context of the call in which it was delivered.
+
+And finally the example shows how a separate sandpit compartment can be used by a subscriber to safely validate new data and gain trust in its content without exposing it own stack and heap.
+
+## Compartments in the example
+
+### Config Source (Publisher)
+The **Config Source** compartment provides the publisher of configuration data. In a real system this would receive updates from the network, although its possible that some compartments might also need to publish internal configuration updates. For this example it simple creates new updates to two items, "config1"and "config2" on a periodic basis (for simplicity both items share the same structure).
+
+### Config Broker (Broker)
+The **config broker** exposes two cross compartment methods, set_config() to publish and on_config() to subscribe. Internally it maintains the most recently published value of each item and the list of subscribers. Importantly it has no predefined knowledge of which items, publishers, or subscribes exist, and it's only level of trust is provided by the static sealed capabilities that only it can inspect.
+
+### Compartment[1-3] (Subscribers)
+These compartments provide the role of subscribers; Compartment 1 is allowed to receive "config1", Compartment 2 is allowed receive "config2", and Compartment 3 is allowed to receive both "config1" and "config2".
+
+### Validator
+This compartment provides a sandpit in which a compartment can validate a configuration update without exposing its own stack or context; It is prevented from making any heap allocations of its own. This is consistent with the principle that incoming data should be treated as being not only unsafe in content, but potentially even unsafe to parse. It exposes a single cross compartment method to validate the configuration struct used in the example; in practice each config item would need its own validation method. The validation used here is very basic, and implemented in a way to deliberately expose it to bound violations.
+
+## Threads in the example
+A number of thread are used to provide the dynamic behaviour. They are described in the context of the compartments where they start and execute their idle loops, although of course they also perform cross compartment calls.
+
+A thread in the Config Source compartment periodically makes updates to both of the configuration items. A separate thread in Config Source compartment occasionally generates an invalid structure for "config1" which triggers a bounds violation in the validator.
+
+A thread in the Config Broker invokes the callbacks when a configuration item is changed. It uses a _futex_ to sleep until updates are available. Decoupling the arrival of new data from its delivery to subscribers ensures that the thread which is making the updated (which may be part of a network stack) isn't blocked until all of the subscribers have processed it. | Note that this still means that subscribers *are* trusted for availability. They can infinite loop in the callback and that will prevent any other notifications being delivered. You could avoid this by exposing a read-only capability to a `uint32_t` that they then did a futex wait on (for C++, using `std::atomic<uint32_t>` and its `notify_*` / `wait` overloads is a nicer interface than using `futex_*` directly). They could then call back in to query the new value.
You could actually avoid all cross-compartment calls if you handed everyone a read+cap object that is:
```c++
struct PublishedObject
{
std::atomic<uint32_t> version;
void *value;
};
```
They could then block on the futex changing and, when it did, read and `heap_claim_fast` the value. The read function would look something like this:
```c++
bool wait(Timeout *t, PublishedObject &object, uint32_t oldVersion)
{
object.wait(t, oldVersion);
return object.load() != oldVersion;
}
int read(Timeout *t, PublishedObject &object, auto callback)
{
void* value = object.value;
if (int ret = heap_claim_fast(t, value); ret != 0))
{
return ret;
}
callback(value);
}
```
You'd then use `wait` to poll (blocking as determined with the timeout parameter) for changes and then use `read` to read the new value. There's a little bit of fragility in `read`: it can't do any cross-compartment calls or the value may disappear out from under it. |
cheriot-rtos | github_2023 | others | 264 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,125 @@
+Safe Configuration Management
+=============================
+
+This example shows how dynamic configuration changes can be made to compartments using the ChERIoT features of static sealed capabilities, memory claims, a futex, and a sandbox compartment for validating untrusted data.
+
+In this model a configuration item is a named blob of data. There are compartments which supply configuration items (for example received by them via the network) and other compartments that need to receive specific configuration items when ever they change. None of these compartments know about or trust each other; keeping them decoupled helps to keep the system simple, and make it easy to add new items and compartments with a minimal amount of development.
+
+## Overview
+
+The model is is similar to a pub/sub architecture with a single retained message for each item and a security policy defined at build time though static sealed capabilities. The configuration data is declarative so there is no need or value in maintaining a full sequence of updates. Providing the role of the broker is a config_broker compartment, which has the unsealing key. Aligned the pub/sub model publishing items and subscribing for items can happen in any sequence; a subscriber will receive any data that is already published, and any subsequent updates. This avoids any timing issues during system startup.
+
+By defining static sealed capabilities we can control at build time:
+* Which compartments are allowed to update which items
+* Which compartments are allowed to receives which items
+
+In addition the example shows how memory claims can be used to ensure that heap allocations made in one compartment (publishers) remains available to the subscribers outside of the context of the call in which it was delivered.
+
+And finally the example shows how a separate sandpit compartment can be used by a subscriber to safely validate new data and gain trust in its content without exposing it own stack and heap.
+
+## Compartments in the example
+
+### Config Source (Publisher)
+The **Config Source** compartment provides the publisher of configuration data. In a real system this would receive updates from the network, although its possible that some compartments might also need to publish internal configuration updates. For this example it simple creates new updates to two items, "config1"and "config2" on a periodic basis (for simplicity both items share the same structure).
+
+### Config Broker (Broker)
+The **config broker** exposes two cross compartment methods, set_config() to publish and on_config() to subscribe. Internally it maintains the most recently published value of each item and the list of subscribers. Importantly it has no predefined knowledge of which items, publishers, or subscribes exist, and it's only level of trust is provided by the static sealed capabilities that only it can inspect.
+
+### Compartment[1-3] (Subscribers)
+These compartments provide the role of subscribers; Compartment 1 is allowed to receive "config1", Compartment 2 is allowed receive "config2", and Compartment 3 is allowed to receive both "config1" and "config2".
+
+### Validator
+This compartment provides a sandpit in which a compartment can validate a configuration update without exposing its own stack or context; It is prevented from making any heap allocations of its own. This is consistent with the principle that incoming data should be treated as being not only unsafe in content, but potentially even unsafe to parse. It exposes a single cross compartment method to validate the configuration struct used in the example; in practice each config item would need its own validation method. The validation used here is very basic, and implemented in a way to deliberately expose it to bound violations.
+
+## Threads in the example
+A number of thread are used to provide the dynamic behaviour. They are described in the context of the compartments where they start and execute their idle loops, although of course they also perform cross compartment calls.
+
+A thread in the Config Source compartment periodically makes updates to both of the configuration items. A separate thread in Config Source compartment occasionally generates an invalid structure for "config1" which triggers a bounds violation in the validator.
+
+A thread in the Config Broker invokes the callbacks when a configuration item is changed. It uses a _futex_ to sleep until updates are available. Decoupling the arrival of new data from its delivery to subscribers ensures that the thread which is making the updated (which may be part of a network stack) isn't blocked until all of the subscribers have processed it.
+
+A thread in each of the subscribing compartments registers for configuration updates, and then sits in a loop periodically printing the configuration values the compartment has received and validated. The main reason for having this thread is to show that the value remains available after it has been freed by the Config Source. It also provides a convenient way to perform the initial subscription for each compartment.
+
+## Use of Sealed Capabilities
+The CONFIG_CAPABILITY in each compartment holds a list of configuration item names and boolean which defines if the compartment is allowed to be a publisher.
+
+Publishers define their capability with:
+```c++
+DEFINE_CONFIG_SOURCE_CAPABILITY("config1", "config2")
+```
+whereas subscribers define theirs with
+```c++
+DEFINE_CONFIG_CAPABILITY("config1")
+```
+In both cases the macro can take up to 8 names, which are defines in the example to be char[16]. The difference between the macros is value they supply for the is_source element.
+
+Both methods exposed by the Config Broker require the calling compartments capability. The set_config() method also takes name and data values, and the Config Broker checks the name against the list in the unsealed capability along with the is_source value. The on_config() method takes a cheri_callback parameter, which is registers against all of the names in the capability. Although it may seem more obvious to allow a subscriber to register separate callbacks for each item (since they will have different data structures) this approach ensures that a compartment always receives all of the values it is allowed, and the name is passed to the callback to allow simple conditional logic in the callback.
+
+Using the same pattern as the allocator the Config Broker assigns an id to each capability the first time it is presented, which is used to track the association between callback function and capability in the callback lists for each item. If a compartment calls on_config() a second time then the previous callback is replaced.
+
+## Memory Management
+In the example the ConfigSource allocates a new heap object for each updated, and frees it immediately after the call to set_config() - which is prototypical of something working from a network stack and ensured that new values do not overwrite existing ones until they have been validated.
+
+Subscribers can not be allowed to change the configuration data (it may be shared with other compartments) so the Config Broker cderives a Read Only capability to pass to subscribers.
+
+The Config Broker also need to ensure that it can provide the data to any current and future subscribers, so it adds its own claim to the object, which it only releases when it gets a new object for that item. The claim is made against the derived read only capability.
+
+Any subscribers which need to have access the configuration data beyond the scope of the callback can also make their own claim on the object, and release it on the next update.
+
+## Sandpit Compartment
+Although the static sealed capabilities provide protection over who can update and receive configuration items, they can not offer any assurance over the content. To treat the data as initially untrusted we have to assume that not only may it contain invalid values, but that it may be constructed so as to cause harm when it is being parsed. In the example the first action of each callback is to pass the received value to a valuation method in a sandpit container, which has no access to the callers stack or context and cannot allocate any additional heap. An error handler in the validator compartment traps any violations, and if the validator does not return a success value the compartment simply ignores the update and keeps its claim on the previous object. | You probably don't need the error handler in the validator to do anything. If it returns `int`, errors will be reported as `-ECOMPARTMENTFAIL`. |
cheriot-rtos | github_2023 | others | 264 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,125 @@
+Safe Configuration Management
+=============================
+
+This example shows how dynamic configuration changes can be made to compartments using the ChERIoT features of static sealed capabilities, memory claims, a futex, and a sandbox compartment for validating untrusted data.
+
+In this model a configuration item is a named blob of data. There are compartments which supply configuration items (for example received by them via the network) and other compartments that need to receive specific configuration items when ever they change. None of these compartments know about or trust each other; keeping them decoupled helps to keep the system simple, and make it easy to add new items and compartments with a minimal amount of development.
+
+## Overview
+
+The model is is similar to a pub/sub architecture with a single retained message for each item and a security policy defined at build time though static sealed capabilities. The configuration data is declarative so there is no need or value in maintaining a full sequence of updates. Providing the role of the broker is a config_broker compartment, which has the unsealing key. Aligned the pub/sub model publishing items and subscribing for items can happen in any sequence; a subscriber will receive any data that is already published, and any subsequent updates. This avoids any timing issues during system startup.
+
+By defining static sealed capabilities we can control at build time:
+* Which compartments are allowed to update which items
+* Which compartments are allowed to receives which items
+
+In addition the example shows how memory claims can be used to ensure that heap allocations made in one compartment (publishers) remains available to the subscribers outside of the context of the call in which it was delivered.
+
+And finally the example shows how a separate sandpit compartment can be used by a subscriber to safely validate new data and gain trust in its content without exposing it own stack and heap.
+
+## Compartments in the example
+
+### Config Source (Publisher)
+The **Config Source** compartment provides the publisher of configuration data. In a real system this would receive updates from the network, although its possible that some compartments might also need to publish internal configuration updates. For this example it simple creates new updates to two items, "config1"and "config2" on a periodic basis (for simplicity both items share the same structure).
+
+### Config Broker (Broker)
+The **config broker** exposes two cross compartment methods, set_config() to publish and on_config() to subscribe. Internally it maintains the most recently published value of each item and the list of subscribers. Importantly it has no predefined knowledge of which items, publishers, or subscribes exist, and it's only level of trust is provided by the static sealed capabilities that only it can inspect.
+
+### Compartment[1-3] (Subscribers)
+These compartments provide the role of subscribers; Compartment 1 is allowed to receive "config1", Compartment 2 is allowed receive "config2", and Compartment 3 is allowed to receive both "config1" and "config2".
+
+### Validator
+This compartment provides a sandpit in which a compartment can validate a configuration update without exposing its own stack or context; It is prevented from making any heap allocations of its own. This is consistent with the principle that incoming data should be treated as being not only unsafe in content, but potentially even unsafe to parse. It exposes a single cross compartment method to validate the configuration struct used in the example; in practice each config item would need its own validation method. The validation used here is very basic, and implemented in a way to deliberately expose it to bound violations.
+
+## Threads in the example
+A number of thread are used to provide the dynamic behaviour. They are described in the context of the compartments where they start and execute their idle loops, although of course they also perform cross compartment calls.
+
+A thread in the Config Source compartment periodically makes updates to both of the configuration items. A separate thread in Config Source compartment occasionally generates an invalid structure for "config1" which triggers a bounds violation in the validator.
+
+A thread in the Config Broker invokes the callbacks when a configuration item is changed. It uses a _futex_ to sleep until updates are available. Decoupling the arrival of new data from its delivery to subscribers ensures that the thread which is making the updated (which may be part of a network stack) isn't blocked until all of the subscribers have processed it.
+
+A thread in each of the subscribing compartments registers for configuration updates, and then sits in a loop periodically printing the configuration values the compartment has received and validated. The main reason for having this thread is to show that the value remains available after it has been freed by the Config Source. It also provides a convenient way to perform the initial subscription for each compartment.
+
+## Use of Sealed Capabilities
+The CONFIG_CAPABILITY in each compartment holds a list of configuration item names and boolean which defines if the compartment is allowed to be a publisher.
+
+Publishers define their capability with:
+```c++
+DEFINE_CONFIG_SOURCE_CAPABILITY("config1", "config2")
+```
+whereas subscribers define theirs with
+```c++
+DEFINE_CONFIG_CAPABILITY("config1")
+```
+In both cases the macro can take up to 8 names, which are defines in the example to be char[16]. The difference between the macros is value they supply for the is_source element.
+
+Both methods exposed by the Config Broker require the calling compartments capability. The set_config() method also takes name and data values, and the Config Broker checks the name against the list in the unsealed capability along with the is_source value. The on_config() method takes a cheri_callback parameter, which is registers against all of the names in the capability. Although it may seem more obvious to allow a subscriber to register separate callbacks for each item (since they will have different data structures) this approach ensures that a compartment always receives all of the values it is allowed, and the name is passed to the callback to allow simple conditional logic in the callback.
+
+Using the same pattern as the allocator the Config Broker assigns an id to each capability the first time it is presented, which is used to track the association between callback function and capability in the callback lists for each item. If a compartment calls on_config() a second time then the previous callback is replaced.
+
+## Memory Management
+In the example the ConfigSource allocates a new heap object for each updated, and frees it immediately after the call to set_config() - which is prototypical of something working from a network stack and ensured that new values do not overwrite existing ones until they have been validated.
+
+Subscribers can not be allowed to change the configuration data (it may be shared with other compartments) so the Config Broker cderives a Read Only capability to pass to subscribers.
+
+The Config Broker also need to ensure that it can provide the data to any current and future subscribers, so it adds its own claim to the object, which it only releases when it gets a new object for that item. The claim is made against the derived read only capability.
+
+Any subscribers which need to have access the configuration data beyond the scope of the callback can also make their own claim on the object, and release it on the next update.
+
+## Sandpit Compartment
+Although the static sealed capabilities provide protection over who can update and receive configuration items, they can not offer any assurance over the content. To treat the data as initially untrusted we have to assume that not only may it contain invalid values, but that it may be constructed so as to cause harm when it is being parsed. In the example the first action of each callback is to pass the received value to a valuation method in a sandpit container, which has no access to the callers stack or context and cannot allocate any additional heap. An error handler in the validator compartment traps any violations, and if the validator does not return a success value the compartment simply ignores the update and keeps its claim on the previous object.
+
+## Running the example
+The example is built and run with the normal xmake commands, and has no external dependencies.
+
+Thread priorities are uses to ensure a start up sequence that has subscribed run both before and after the initial data is available.
+
+Debug messages from Config Source show when data is updated, and from each compartment when it receives an update plus a timer driven view of the value between updates.
+
+Every 12 seconds a malicious value is sent for "config1" which triggers a BoundsViolation in the validator.
+
+Here are some examples of the output
+
+Compartment 1 registers for updates before any data is available.
+```
+Compartment #1: thread 0x3 Register for config updates
+Config Broker : thread 0x3 on_config called for config1 by id 0x1
+```
+
+Compartment 2 registers for updates and data is already available, so the callback is immediately invoked. All of this happens on the same thread.
+```
+Compartment #2: thread 0x4 Register for config updates
+Config Broker : thread 0x4 on_config called for config2 by id 0x3
+Compartment #2: thread 0x4 Update config2 -- config count: 0x0 token: eggman
+```
+
+Config Sources sets a value for item "config1", and Compartment 1 and Compartment 3's callbacks are called. Note the change in thread as the callback is invoked by the thread in the Config Broker.
+```
+Config Source : thread 0x2 Set config1
+Config Broker : thread 0x1 processing 0x1 updates
+Compartment #1: thread 0x1 Update config1 -- config count: 0x0 token: walrus
+Compartment #3: thread 0x1 Update config1 -- config count: 0x1 token: walrus
+```
+
+Compartment 1 prints it's current value from a timer
+```
+Compartment #1: thread 0x3 Timer config1 -- config count: 0x1 token: walrus
+```
+
+Config Source sets a malicious value for "config 1". Compartment 1 & Compartment 3 call into the validator sandpit which traps the error.
+```
+Config Source : thread 0x6 Sending bad data for config1
+Config Broker : thread 0x1 processing 0x1 updates
+Validator: Detected BoundsViolation(0x1) in validator. Register CA0(0xa) contained invalid value: 0x8000dd58 (v:1 0x8000dd50-0x8000dd58 l:0x8 o:0x0 p: G R----- -- ---)
+Compartment #1: thread 0x1 Validation failed for config1 0x8000dd50 (v:1 0x8000dd50-0x8000dd58 l:0x8 o:0x0 p: G R----- -- ---)
+Validator: Detected BoundsViolation(0x1) in validator. Register CA0(0xa) contained invalid value: 0x8000dd58 (v:1 0x8000dd50-0x8000dd58 l:0x8 o:0x0 p: G R----- -- ---)
+Compartment #3: thread 0x1 Validation failed for config1 0x8000dd50 (v:1 0x8000dd50-0x8000dd58 l:0x8 o:0x0 p: G R----- -- ---)
+```
+
+## To Do
+
+_These are more considerations for an operational system than the example_
+
+Currently we use the same static sealing type for publish and subscribe capabilities, with a bool to define the permission. Although this is defined first in the struct and so should be easy to distinguish in the audit data, maybe separate sealing types would be even easier to audit. | Both are equally easy in the auditing framework. |
cheriot-rtos | github_2023 | cpp | 264 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,78 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+// Contributed by Configured Things Ltd
+
+#include <compartment.h>
+#include <debug.hh>
+#include <fail-simulator-on-error.h>
+#include <thread.h>
+
+// Define a sealed capability that gives this compartment
+// read access to configuration data "config1"
+#include "config_broker.h"
+DEFINE_CONFIG_CAPABILITY("config1")
+
+// Expose debugging features unconditionally for this compartment.
+using Debug = ConditionalDebug<true, "Compartment #1">; | It would be nice to have slightly more descriptive names for these. |
cheriot-rtos | github_2023 | cpp | 264 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,78 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+// Contributed by Configured Things Ltd
+
+#include <compartment.h>
+#include <debug.hh>
+#include <fail-simulator-on-error.h>
+#include <thread.h>
+
+// Define a sealed capability that gives this compartment
+// read access to configuration data "config1"
+#include "config_broker.h"
+DEFINE_CONFIG_CAPABILITY("config1")
+
+// Expose debugging features unconditionally for this compartment.
+using Debug = ConditionalDebug<true, "Compartment #1">;
+
+#include "data.h"
+#include "sleep.h"
+#include "validator.h"
+
+// Local pointer to the most recent config value;
+Data *config = nullptr; | Since we have a claim on this, it is probably better to use `std::unique_ptr`, which will free on assignment automatically. |
cheriot-rtos | github_2023 | cpp | 258 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,211 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+#define TEST_NAME "List"
+#include "tests.hh"
+#include <ds/linked_list.h>
+
+namespace
+{
+ using ObjectRing = ds::linked_list::cell::Pointer;
+
+ /**
+ * Example class we want to link into a doubly linked list.
+ *
+ * The class contains a single integer for the purposes of the test.
+ *
+ * `ds::linked_list` is an intrusive list: we embed the list node into
+ * the class we want to link. There are various implementations of the
+ * list nodes. Here we use the most simple one
+ * (`ds::linked_list::cell::Pointer`) which relies on two pointers
+ * `next` and `prev`. | This bit of the comment might be more naturally associated with the `using ObjectRing` above? That `using` could, I think, move into the `LinkedObject` class were that to be a more natural place for it (the `Sentinel<ObjectRing>` below would have to become `Sentinel<LinkedObject::ObjectRing>`, but otherwise nothing changes, I think). |
cheriot-rtos | github_2023 | cpp | 258 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,211 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+#define TEST_NAME "List"
+#include "tests.hh"
+#include <ds/linked_list.h>
+
+namespace
+{
+ using ObjectRing = ds::linked_list::cell::Pointer;
+
+ /**
+ * Example class we want to link into a doubly linked list.
+ *
+ * The class contains a single integer for the purposes of the test.
+ *
+ * `ds::linked_list` is an intrusive list: we embed the list node into
+ * the class we want to link. There are various implementations of the
+ * list nodes. Here we use the most simple one
+ * (`ds::linked_list::cell::Pointer`) which relies on two pointers
+ * `next` and `prev`.
+ */
+ struct LinkedObject
+ {
+ int data;
+ /**
+ * List node: links objects into the doubly-linked list.
+ */
+ ObjectRing ring __attribute__((__cheri_no_subobject_bounds__)) = {};
+ /**
+ * Container-of for the above field. This is used to retrieve the
+ * corresponding object from a list element.
+ */
+ __always_inline static struct LinkedObject *from_ring(ObjectRing *c)
+ {
+ return reinterpret_cast<struct LinkedObject *>(
+ reinterpret_cast<uintptr_t>(c) -
+ offsetof(struct LinkedObject, ring));
+ }
+ };
+} // namespace
+
+/**
+ * The sentinel is a special class encapsulating a list node. It provides many
+ * handy functions to operate on the list. The sentinel is thus part of the
+ * list, without being one of the objects linked. | This is all true, but it might skip over some steps. Perhaps something like...
`ds::linked_list`-s are circular, doubly-linked collections. While they can stand on their own as rings of objects, it is sometimes convenient to create a designated "sentinel" node that participates in the collection without being part of the collection: it naturally provides pointers to the effective head and tail of the collection (the successor and predecessor of the sentinel, respectively) while not having to special-case "the collection is empty" in as many places as some other representations (that is, collections with sentinels need fewer "null pointer" checks). Towards that end, the `Sentinel` class captures the notion of a designated not-an-element node and provides many handy functions to operate on the list. |
cheriot-rtos | github_2023 | cpp | 258 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,211 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+#define TEST_NAME "List"
+#include "tests.hh"
+#include <ds/linked_list.h>
+
+namespace
+{
+ using ObjectRing = ds::linked_list::cell::Pointer;
+
+ /**
+ * Example class we want to link into a doubly linked list.
+ *
+ * The class contains a single integer for the purposes of the test.
+ *
+ * `ds::linked_list` is an intrusive list: we embed the list node into
+ * the class we want to link. There are various implementations of the
+ * list nodes. Here we use the most simple one
+ * (`ds::linked_list::cell::Pointer`) which relies on two pointers
+ * `next` and `prev`.
+ */
+ struct LinkedObject
+ {
+ int data;
+ /**
+ * List node: links objects into the doubly-linked list.
+ */
+ ObjectRing ring __attribute__((__cheri_no_subobject_bounds__)) = {};
+ /**
+ * Container-of for the above field. This is used to retrieve the
+ * corresponding object from a list element.
+ */
+ __always_inline static struct LinkedObject *from_ring(ObjectRing *c)
+ {
+ return reinterpret_cast<struct LinkedObject *>(
+ reinterpret_cast<uintptr_t>(c) -
+ offsetof(struct LinkedObject, ring));
+ }
+ };
+} // namespace
+
+/**
+ * The sentinel is a special class encapsulating a list node. It provides many
+ * handy functions to operate on the list. The sentinel is thus part of the
+ * list, without being one of the objects linked.
+ *
+ * Note: do not attempt to define the sentinel on the stack, because it would
+ * lead some list nodes holding a pointer to a stack value, i.e., to an invalid
+ * capability. This would lead to a crash while using the list. | This is a really good point and is more general than just the sentinel: don't mix heap and stack allocated objects in a `ds::linked_list` in general! All of our `cell` implementations will crash in one way or another if you try. |
cheriot-rtos | github_2023 | cpp | 258 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,211 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+#define TEST_NAME "List"
+#include "tests.hh"
+#include <ds/linked_list.h>
+
+namespace
+{
+ using ObjectRing = ds::linked_list::cell::Pointer;
+
+ /**
+ * Example class we want to link into a doubly linked list.
+ *
+ * The class contains a single integer for the purposes of the test.
+ *
+ * `ds::linked_list` is an intrusive list: we embed the list node into
+ * the class we want to link. There are various implementations of the
+ * list nodes. Here we use the most simple one
+ * (`ds::linked_list::cell::Pointer`) which relies on two pointers
+ * `next` and `prev`.
+ */
+ struct LinkedObject
+ {
+ int data;
+ /**
+ * List node: links objects into the doubly-linked list.
+ */
+ ObjectRing ring __attribute__((__cheri_no_subobject_bounds__)) = {};
+ /**
+ * Container-of for the above field. This is used to retrieve the
+ * corresponding object from a list element.
+ */
+ __always_inline static struct LinkedObject *from_ring(ObjectRing *c)
+ {
+ return reinterpret_cast<struct LinkedObject *>(
+ reinterpret_cast<uintptr_t>(c) -
+ offsetof(struct LinkedObject, ring));
+ }
+ };
+} // namespace
+
+/**
+ * The sentinel is a special class encapsulating a list node. It provides many
+ * handy functions to operate on the list. The sentinel is thus part of the
+ * list, without being one of the objects linked.
+ *
+ * Note: do not attempt to define the sentinel on the stack, because it would
+ * lead some list nodes holding a pointer to a stack value, i.e., to an invalid
+ * capability. This would lead to a crash while using the list.
+ */
+ds::linked_list::Sentinel<ObjectRing> objects = {};
+
+void test_list()
+{
+ debug_log("Testing the list implementation.");
+
+ // Number of elements we will add to the list in the test. Must be
+ // divisible by two.
+ static constexpr int NumberOfListElements = 30;
+
+ auto heapAtStart = heap_quota_remaining(MALLOC_CAPABILITY);
+
+ TEST(objects.is_empty(), "Newly created list is not empty");
+
+ // Create heap-allocated objects, and link them into the linked list.
+ for (int i = 0; i < NumberOfListElements; i++)
+ {
+ Timeout t{UnlimitedTimeout};
+ LinkedObject *o = (LinkedObject *)heap_allocate(
+ &t, MALLOC_CAPABILITY, sizeof(LinkedObject));
+ TEST(CHERI::Capability{o}.is_valid(), "Cannot allocate linked object");
+
+ // Use the object integer as an index.
+ o->data = i;
+ // The list node has not yet been initialized.
+ o->ring.cell_reset();
+
+ // Test that we can retrieve the object from the link node and
+ // that this results in a valid capability.
+ TEST(o == LinkedObject::from_ring(&(o->ring)), | `==` on pointers in CHERI C/C++ presently defaults to address-only equality. You might use `__builtin_cheri_equal_exact`, or wrap with `Capability` first (since its `operator==` uses that primitive), to be more stringent. |
cheriot-rtos | github_2023 | cpp | 258 | CHERIoT-Platform | rmn30 | @@ -0,0 +1,211 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+#define TEST_NAME "List"
+#include "tests.hh"
+#include <ds/linked_list.h>
+
+namespace
+{
+ using ObjectRing = ds::linked_list::cell::Pointer;
+
+ /**
+ * Example class we want to link into a doubly linked list.
+ *
+ * The class contains a single integer for the purposes of the test.
+ *
+ * `ds::linked_list` is an intrusive list: we embed the list node into
+ * the class we want to link. There are various implementations of the
+ * list nodes. Here we use the most simple one
+ * (`ds::linked_list::cell::Pointer`) which relies on two pointers
+ * `next` and `prev`.
+ */
+ struct LinkedObject
+ {
+ int data;
+ /**
+ * List node: links objects into the doubly-linked list.
+ */
+ ObjectRing ring __attribute__((__cheri_no_subobject_bounds__)) = {};
+ /**
+ * Container-of for the above field. This is used to retrieve the
+ * corresponding object from a list element.
+ */
+ __always_inline static struct LinkedObject *from_ring(ObjectRing *c)
+ {
+ return reinterpret_cast<struct LinkedObject *>(
+ reinterpret_cast<uintptr_t>(c) -
+ offsetof(struct LinkedObject, ring));
+ }
+ };
+} // namespace
+
+/**
+ * The sentinel is a special class encapsulating a list node. It provides many
+ * handy functions to operate on the list. The sentinel is thus part of the
+ * list, without being one of the objects linked.
+ *
+ * Note: do not attempt to define the sentinel on the stack, because it would
+ * lead some list nodes holding a pointer to a stack value, i.e., to an invalid
+ * capability. This would lead to a crash while using the list.
+ */
+ds::linked_list::Sentinel<ObjectRing> objects = {};
+
+void test_list()
+{
+ debug_log("Testing the list implementation.");
+
+ // Number of elements we will add to the list in the test. Must be
+ // divisible by two.
+ static constexpr int NumberOfListElements = 30;
+
+ auto heapAtStart = heap_quota_remaining(MALLOC_CAPABILITY);
+
+ TEST(objects.is_empty(), "Newly created list is not empty");
+
+ // Create heap-allocated objects, and link them into the linked list.
+ for (int i = 0; i < NumberOfListElements; i++)
+ {
+ Timeout t{UnlimitedTimeout};
+ LinkedObject *o = (LinkedObject *)heap_allocate(
+ &t, MALLOC_CAPABILITY, sizeof(LinkedObject));
+ TEST(CHERI::Capability{o}.is_valid(), "Cannot allocate linked object");
+
+ // Use the object integer as an index.
+ o->data = i;
+ // The list node has not yet been initialized.
+ o->ring.cell_reset();
+
+ // Test that we can retrieve the object from the link node and
+ // that this results in a valid capability.
+ TEST(o == LinkedObject::from_ring(&(o->ring)),
+ "The container of method does not return the right object");
+ TEST(CHERI::Capability{LinkedObject::from_ring(&(o->ring))}.is_valid(),
+ "Capability retrieved from `from_ring` is invalid");
+
+ // Add the new object to the list through the sentinel node.
+ objects.append(&(o->ring));
+ }
+
+ TEST(!objects.is_empty(), "The list is not empty."); | ```suggestion
TEST(!objects.is_empty(), "The list is empty after adding objects.");
``` |
cheriot-rtos | github_2023 | cpp | 258 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,211 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+#define TEST_NAME "List"
+#include "tests.hh"
+#include <ds/linked_list.h>
+
+namespace
+{
+ using ObjectRing = ds::linked_list::cell::Pointer;
+
+ /**
+ * Example class we want to link into a doubly linked list.
+ *
+ * The class contains a single integer for the purposes of the test.
+ *
+ * `ds::linked_list` is an intrusive list: we embed the list node into
+ * the class we want to link. There are various implementations of the
+ * list nodes. Here we use the most simple one
+ * (`ds::linked_list::cell::Pointer`) which relies on two pointers
+ * `next` and `prev`.
+ */
+ struct LinkedObject
+ {
+ int data;
+ /**
+ * List node: links objects into the doubly-linked list.
+ */
+ ObjectRing ring __attribute__((__cheri_no_subobject_bounds__)) = {};
+ /**
+ * Container-of for the above field. This is used to retrieve the
+ * corresponding object from a list element.
+ */
+ __always_inline static struct LinkedObject *from_ring(ObjectRing *c)
+ {
+ return reinterpret_cast<struct LinkedObject *>(
+ reinterpret_cast<uintptr_t>(c) -
+ offsetof(struct LinkedObject, ring));
+ }
+ };
+} // namespace
+
+/**
+ * The sentinel is a special class encapsulating a list node. It provides many
+ * handy functions to operate on the list. The sentinel is thus part of the
+ * list, without being one of the objects linked.
+ *
+ * Note: do not attempt to define the sentinel on the stack, because it would
+ * lead some list nodes holding a pointer to a stack value, i.e., to an invalid
+ * capability. This would lead to a crash while using the list.
+ */
+ds::linked_list::Sentinel<ObjectRing> objects = {};
+
+void test_list()
+{
+ debug_log("Testing the list implementation.");
+
+ // Number of elements we will add to the list in the test. Must be
+ // divisible by two.
+ static constexpr int NumberOfListElements = 30;
+
+ auto heapAtStart = heap_quota_remaining(MALLOC_CAPABILITY);
+
+ TEST(objects.is_empty(), "Newly created list is not empty");
+
+ // Create heap-allocated objects, and link them into the linked list.
+ for (int i = 0; i < NumberOfListElements; i++)
+ {
+ Timeout t{UnlimitedTimeout};
+ LinkedObject *o = (LinkedObject *)heap_allocate(
+ &t, MALLOC_CAPABILITY, sizeof(LinkedObject));
+ TEST(CHERI::Capability{o}.is_valid(), "Cannot allocate linked object");
+
+ // Use the object integer as an index.
+ o->data = i;
+ // The list node has not yet been initialized.
+ o->ring.cell_reset();
+
+ // Test that we can retrieve the object from the link node and
+ // that this results in a valid capability.
+ TEST(o == LinkedObject::from_ring(&(o->ring)),
+ "The container of method does not return the right object");
+ TEST(CHERI::Capability{LinkedObject::from_ring(&(o->ring))}.is_valid(),
+ "Capability retrieved from `from_ring` is invalid");
+
+ // Add the new object to the list through the sentinel node.
+ objects.append(&(o->ring));
+ }
+
+ TEST(!objects.is_empty(), "The list is not empty.");
+
+ // Test that the sentinel can be used to retrieve the first and last
+ // elements of the list as expected.
+ TEST(LinkedObject::from_ring(objects.last())->data ==
+ NumberOfListElements - 1,
+ "Last element of the list is incorrect, expected {}, got {}",
+ NumberOfListElements - 1,
+ LinkedObject::from_ring(objects.last())->data);
+ TEST(objects.last()->cell_next() == &objects.sentinel,
+ "Last element in not followed by the sentinel");
+ TEST(objects.last() == objects.sentinel.cell_prev(),
+ "Sentinel is not preceeded by the last element");
+ TEST(LinkedObject::from_ring(objects.first())->data == 0,
+ "First element of the list is incorrect, expected {}, got {}",
+ 0,
+ LinkedObject::from_ring(objects.last())->data);
+ TEST(objects.first()->cell_prev() == &objects.sentinel,
+ "First element in not preceeded by the sentinel");
+ TEST(objects.first() == objects.sentinel.cell_next(),
+ "Sentinel is not followed by the first element");
+
+ // Test that we can go through the list by following `cell_next`
+ // pointers as expected.
+ int counter = 0;
+ // While at it, retrieve a pointer to the middle element which we will
+ // use to cleave the list later.
+ ObjectRing *middle = nullptr;
+ // We reach the sentinel when we have gone through all elements of the
+ // list.
+ for (auto *cell = objects.first(); cell != &objects.sentinel; | More idiomatically, there's `.search()` on the `Sentinel`, though it's probably not bad to demonstrate the raw form as well. |
cheriot-rtos | github_2023 | cpp | 258 | CHERIoT-Platform | rmn30 | @@ -0,0 +1,211 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+#define TEST_NAME "List"
+#include "tests.hh"
+#include <ds/linked_list.h>
+
+namespace
+{
+ using ObjectRing = ds::linked_list::cell::Pointer;
+
+ /**
+ * Example class we want to link into a doubly linked list.
+ *
+ * The class contains a single integer for the purposes of the test.
+ *
+ * `ds::linked_list` is an intrusive list: we embed the list node into
+ * the class we want to link. There are various implementations of the
+ * list nodes. Here we use the most simple one
+ * (`ds::linked_list::cell::Pointer`) which relies on two pointers
+ * `next` and `prev`.
+ */
+ struct LinkedObject
+ {
+ int data;
+ /**
+ * List node: links objects into the doubly-linked list.
+ */
+ ObjectRing ring __attribute__((__cheri_no_subobject_bounds__)) = {};
+ /**
+ * Container-of for the above field. This is used to retrieve the
+ * corresponding object from a list element.
+ */
+ __always_inline static struct LinkedObject *from_ring(ObjectRing *c)
+ {
+ return reinterpret_cast<struct LinkedObject *>(
+ reinterpret_cast<uintptr_t>(c) -
+ offsetof(struct LinkedObject, ring));
+ }
+ };
+} // namespace
+
+/**
+ * The sentinel is a special class encapsulating a list node. It provides many
+ * handy functions to operate on the list. The sentinel is thus part of the
+ * list, without being one of the objects linked.
+ *
+ * Note: do not attempt to define the sentinel on the stack, because it would
+ * lead some list nodes holding a pointer to a stack value, i.e., to an invalid
+ * capability. This would lead to a crash while using the list.
+ */
+ds::linked_list::Sentinel<ObjectRing> objects = {};
+
+void test_list()
+{
+ debug_log("Testing the list implementation.");
+
+ // Number of elements we will add to the list in the test. Must be
+ // divisible by two.
+ static constexpr int NumberOfListElements = 30;
+
+ auto heapAtStart = heap_quota_remaining(MALLOC_CAPABILITY);
+
+ TEST(objects.is_empty(), "Newly created list is not empty");
+
+ // Create heap-allocated objects, and link them into the linked list.
+ for (int i = 0; i < NumberOfListElements; i++)
+ {
+ Timeout t{UnlimitedTimeout};
+ LinkedObject *o = (LinkedObject *)heap_allocate(
+ &t, MALLOC_CAPABILITY, sizeof(LinkedObject));
+ TEST(CHERI::Capability{o}.is_valid(), "Cannot allocate linked object");
+
+ // Use the object integer as an index.
+ o->data = i;
+ // The list node has not yet been initialized.
+ o->ring.cell_reset();
+
+ // Test that we can retrieve the object from the link node and
+ // that this results in a valid capability.
+ TEST(o == LinkedObject::from_ring(&(o->ring)),
+ "The container of method does not return the right object");
+ TEST(CHERI::Capability{LinkedObject::from_ring(&(o->ring))}.is_valid(),
+ "Capability retrieved from `from_ring` is invalid");
+
+ // Add the new object to the list through the sentinel node.
+ objects.append(&(o->ring));
+ }
+
+ TEST(!objects.is_empty(), "The list is not empty.");
+
+ // Test that the sentinel can be used to retrieve the first and last
+ // elements of the list as expected.
+ TEST(LinkedObject::from_ring(objects.last())->data == | Aside: would be nice to have a `TEST_EQUAL` to make this pattern less repetitive. |
cheriot-rtos | github_2023 | cpp | 258 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,211 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+#define TEST_NAME "List"
+#include "tests.hh"
+#include <ds/linked_list.h>
+
+namespace
+{
+ using ObjectRing = ds::linked_list::cell::Pointer;
+
+ /**
+ * Example class we want to link into a doubly linked list.
+ *
+ * The class contains a single integer for the purposes of the test.
+ *
+ * `ds::linked_list` is an intrusive list: we embed the list node into
+ * the class we want to link. There are various implementations of the
+ * list nodes. Here we use the most simple one
+ * (`ds::linked_list::cell::Pointer`) which relies on two pointers
+ * `next` and `prev`.
+ */
+ struct LinkedObject
+ {
+ int data;
+ /**
+ * List node: links objects into the doubly-linked list.
+ */
+ ObjectRing ring __attribute__((__cheri_no_subobject_bounds__)) = {};
+ /**
+ * Container-of for the above field. This is used to retrieve the
+ * corresponding object from a list element.
+ */
+ __always_inline static struct LinkedObject *from_ring(ObjectRing *c)
+ {
+ return reinterpret_cast<struct LinkedObject *>(
+ reinterpret_cast<uintptr_t>(c) -
+ offsetof(struct LinkedObject, ring));
+ }
+ };
+} // namespace
+
+/**
+ * The sentinel is a special class encapsulating a list node. It provides many
+ * handy functions to operate on the list. The sentinel is thus part of the
+ * list, without being one of the objects linked.
+ *
+ * Note: do not attempt to define the sentinel on the stack, because it would
+ * lead some list nodes holding a pointer to a stack value, i.e., to an invalid
+ * capability. This would lead to a crash while using the list.
+ */
+ds::linked_list::Sentinel<ObjectRing> objects = {};
+
+void test_list()
+{
+ debug_log("Testing the list implementation.");
+
+ // Number of elements we will add to the list in the test. Must be
+ // divisible by two.
+ static constexpr int NumberOfListElements = 30;
+
+ auto heapAtStart = heap_quota_remaining(MALLOC_CAPABILITY);
+
+ TEST(objects.is_empty(), "Newly created list is not empty");
+
+ // Create heap-allocated objects, and link them into the linked list.
+ for (int i = 0; i < NumberOfListElements; i++)
+ {
+ Timeout t{UnlimitedTimeout};
+ LinkedObject *o = (LinkedObject *)heap_allocate(
+ &t, MALLOC_CAPABILITY, sizeof(LinkedObject));
+ TEST(CHERI::Capability{o}.is_valid(), "Cannot allocate linked object");
+
+ // Use the object integer as an index.
+ o->data = i;
+ // The list node has not yet been initialized.
+ o->ring.cell_reset();
+
+ // Test that we can retrieve the object from the link node and
+ // that this results in a valid capability.
+ TEST(o == LinkedObject::from_ring(&(o->ring)),
+ "The container of method does not return the right object");
+ TEST(CHERI::Capability{LinkedObject::from_ring(&(o->ring))}.is_valid(),
+ "Capability retrieved from `from_ring` is invalid");
+
+ // Add the new object to the list through the sentinel node.
+ objects.append(&(o->ring));
+ }
+
+ TEST(!objects.is_empty(), "The list is not empty.");
+
+ // Test that the sentinel can be used to retrieve the first and last
+ // elements of the list as expected.
+ TEST(LinkedObject::from_ring(objects.last())->data ==
+ NumberOfListElements - 1,
+ "Last element of the list is incorrect, expected {}, got {}",
+ NumberOfListElements - 1,
+ LinkedObject::from_ring(objects.last())->data);
+ TEST(objects.last()->cell_next() == &objects.sentinel,
+ "Last element in not followed by the sentinel");
+ TEST(objects.last() == objects.sentinel.cell_prev(),
+ "Sentinel is not preceeded by the last element");
+ TEST(LinkedObject::from_ring(objects.first())->data == 0,
+ "First element of the list is incorrect, expected {}, got {}",
+ 0,
+ LinkedObject::from_ring(objects.last())->data);
+ TEST(objects.first()->cell_prev() == &objects.sentinel,
+ "First element in not preceeded by the sentinel");
+ TEST(objects.first() == objects.sentinel.cell_next(),
+ "Sentinel is not followed by the first element");
+
+ // Test that we can go through the list by following `cell_next`
+ // pointers as expected.
+ int counter = 0;
+ // While at it, retrieve a pointer to the middle element which we will
+ // use to cleave the list later.
+ ObjectRing *middle = nullptr;
+ // We reach the sentinel when we have gone through all elements of the
+ // list.
+ for (auto *cell = objects.first(); cell != &objects.sentinel;
+ cell = cell->cell_next())
+ {
+ struct LinkedObject *o = LinkedObject::from_ring(cell);
+ TEST(
+ o->data == counter,
+ "Ordering of elements in the list is incorrect, expected {}, got {}",
+ o->data,
+ counter);
+ if (counter == NumberOfListElements / 2)
+ {
+ middle = cell;
+ }
+ counter++;
+ }
+
+ TEST(middle != nullptr, "Could not find middle element of the list");
+
+ // Cut the list in the middle.
+ ds::linked_list::remove(middle, objects.last()); | Speaking of `Sentinel.search`, `cell::remove` makes the claim that it can be used within if one is careful. It'd be good to both validate that that isn't a stale claim and, if all's good, demonstrate that somewhere in here, too. |
cheriot-rtos | github_2023 | cpp | 258 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,211 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+#define TEST_NAME "List"
+#include "tests.hh"
+#include <ds/linked_list.h>
+
+namespace
+{
+ using ObjectRing = ds::linked_list::cell::Pointer;
+
+ /**
+ * Example class we want to link into a doubly linked list.
+ *
+ * The class contains a single integer for the purposes of the test.
+ *
+ * `ds::linked_list` is an intrusive list: we embed the list node into
+ * the class we want to link. There are various implementations of the
+ * list nodes. Here we use the most simple one
+ * (`ds::linked_list::cell::Pointer`) which relies on two pointers
+ * `next` and `prev`.
+ */
+ struct LinkedObject
+ {
+ int data;
+ /**
+ * List node: links objects into the doubly-linked list.
+ */
+ ObjectRing ring __attribute__((__cheri_no_subobject_bounds__)) = {};
+ /**
+ * Container-of for the above field. This is used to retrieve the
+ * corresponding object from a list element.
+ */
+ __always_inline static struct LinkedObject *from_ring(ObjectRing *c)
+ {
+ return reinterpret_cast<struct LinkedObject *>(
+ reinterpret_cast<uintptr_t>(c) -
+ offsetof(struct LinkedObject, ring));
+ }
+ };
+} // namespace
+
+/**
+ * The sentinel is a special class encapsulating a list node. It provides many
+ * handy functions to operate on the list. The sentinel is thus part of the
+ * list, without being one of the objects linked.
+ *
+ * Note: do not attempt to define the sentinel on the stack, because it would
+ * lead some list nodes holding a pointer to a stack value, i.e., to an invalid
+ * capability. This would lead to a crash while using the list.
+ */
+ds::linked_list::Sentinel<ObjectRing> objects = {};
+
+void test_list()
+{
+ debug_log("Testing the list implementation.");
+
+ // Number of elements we will add to the list in the test. Must be
+ // divisible by two.
+ static constexpr int NumberOfListElements = 30;
+
+ auto heapAtStart = heap_quota_remaining(MALLOC_CAPABILITY);
+
+ TEST(objects.is_empty(), "Newly created list is not empty");
+
+ // Create heap-allocated objects, and link them into the linked list.
+ for (int i = 0; i < NumberOfListElements; i++)
+ {
+ Timeout t{UnlimitedTimeout};
+ LinkedObject *o = (LinkedObject *)heap_allocate(
+ &t, MALLOC_CAPABILITY, sizeof(LinkedObject));
+ TEST(CHERI::Capability{o}.is_valid(), "Cannot allocate linked object");
+
+ // Use the object integer as an index.
+ o->data = i;
+ // The list node has not yet been initialized.
+ o->ring.cell_reset();
+
+ // Test that we can retrieve the object from the link node and
+ // that this results in a valid capability.
+ TEST(o == LinkedObject::from_ring(&(o->ring)),
+ "The container of method does not return the right object");
+ TEST(CHERI::Capability{LinkedObject::from_ring(&(o->ring))}.is_valid(),
+ "Capability retrieved from `from_ring` is invalid");
+
+ // Add the new object to the list through the sentinel node.
+ objects.append(&(o->ring));
+ }
+
+ TEST(!objects.is_empty(), "The list is not empty.");
+
+ // Test that the sentinel can be used to retrieve the first and last
+ // elements of the list as expected.
+ TEST(LinkedObject::from_ring(objects.last())->data ==
+ NumberOfListElements - 1,
+ "Last element of the list is incorrect, expected {}, got {}",
+ NumberOfListElements - 1,
+ LinkedObject::from_ring(objects.last())->data);
+ TEST(objects.last()->cell_next() == &objects.sentinel,
+ "Last element in not followed by the sentinel");
+ TEST(objects.last() == objects.sentinel.cell_prev(),
+ "Sentinel is not preceeded by the last element");
+ TEST(LinkedObject::from_ring(objects.first())->data == 0,
+ "First element of the list is incorrect, expected {}, got {}",
+ 0,
+ LinkedObject::from_ring(objects.last())->data);
+ TEST(objects.first()->cell_prev() == &objects.sentinel,
+ "First element in not preceeded by the sentinel");
+ TEST(objects.first() == objects.sentinel.cell_next(),
+ "Sentinel is not followed by the first element");
+
+ // Test that we can go through the list by following `cell_next`
+ // pointers as expected.
+ int counter = 0;
+ // While at it, retrieve a pointer to the middle element which we will
+ // use to cleave the list later.
+ ObjectRing *middle = nullptr;
+ // We reach the sentinel when we have gone through all elements of the
+ // list.
+ for (auto *cell = objects.first(); cell != &objects.sentinel;
+ cell = cell->cell_next())
+ {
+ struct LinkedObject *o = LinkedObject::from_ring(cell);
+ TEST(
+ o->data == counter,
+ "Ordering of elements in the list is incorrect, expected {}, got {}",
+ o->data,
+ counter);
+ if (counter == NumberOfListElements / 2)
+ {
+ middle = cell;
+ }
+ counter++;
+ }
+
+ TEST(middle != nullptr, "Could not find middle element of the list");
+
+ // Cut the list in the middle. | It might be worth pointing out that `middle` is, after this, still a valid handle to a valid collection of objects that have become detached from the sentinel. |
cheriot-rtos | github_2023 | cpp | 258 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,211 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+#define TEST_NAME "List"
+#include "tests.hh"
+#include <ds/linked_list.h>
+
+namespace
+{
+ using ObjectRing = ds::linked_list::cell::Pointer;
+
+ /**
+ * Example class we want to link into a doubly linked list.
+ *
+ * The class contains a single integer for the purposes of the test.
+ *
+ * `ds::linked_list` is an intrusive list: we embed the list node into
+ * the class we want to link. There are various implementations of the
+ * list nodes. Here we use the most simple one
+ * (`ds::linked_list::cell::Pointer`) which relies on two pointers
+ * `next` and `prev`.
+ */
+ struct LinkedObject
+ {
+ int data;
+ /**
+ * List node: links objects into the doubly-linked list.
+ */
+ ObjectRing ring __attribute__((__cheri_no_subobject_bounds__)) = {};
+ /**
+ * Container-of for the above field. This is used to retrieve the
+ * corresponding object from a list element.
+ */
+ __always_inline static struct LinkedObject *from_ring(ObjectRing *c)
+ {
+ return reinterpret_cast<struct LinkedObject *>(
+ reinterpret_cast<uintptr_t>(c) -
+ offsetof(struct LinkedObject, ring));
+ }
+ };
+} // namespace
+
+/**
+ * The sentinel is a special class encapsulating a list node. It provides many
+ * handy functions to operate on the list. The sentinel is thus part of the
+ * list, without being one of the objects linked.
+ *
+ * Note: do not attempt to define the sentinel on the stack, because it would
+ * lead some list nodes holding a pointer to a stack value, i.e., to an invalid
+ * capability. This would lead to a crash while using the list.
+ */
+ds::linked_list::Sentinel<ObjectRing> objects = {};
+
+void test_list()
+{
+ debug_log("Testing the list implementation.");
+
+ // Number of elements we will add to the list in the test. Must be
+ // divisible by two.
+ static constexpr int NumberOfListElements = 30;
+
+ auto heapAtStart = heap_quota_remaining(MALLOC_CAPABILITY);
+
+ TEST(objects.is_empty(), "Newly created list is not empty");
+
+ // Create heap-allocated objects, and link them into the linked list.
+ for (int i = 0; i < NumberOfListElements; i++)
+ {
+ Timeout t{UnlimitedTimeout};
+ LinkedObject *o = (LinkedObject *)heap_allocate(
+ &t, MALLOC_CAPABILITY, sizeof(LinkedObject));
+ TEST(CHERI::Capability{o}.is_valid(), "Cannot allocate linked object");
+
+ // Use the object integer as an index.
+ o->data = i;
+ // The list node has not yet been initialized.
+ o->ring.cell_reset();
+
+ // Test that we can retrieve the object from the link node and
+ // that this results in a valid capability.
+ TEST(o == LinkedObject::from_ring(&(o->ring)),
+ "The container of method does not return the right object");
+ TEST(CHERI::Capability{LinkedObject::from_ring(&(o->ring))}.is_valid(),
+ "Capability retrieved from `from_ring` is invalid");
+
+ // Add the new object to the list through the sentinel node.
+ objects.append(&(o->ring));
+ }
+
+ TEST(!objects.is_empty(), "The list is not empty.");
+
+ // Test that the sentinel can be used to retrieve the first and last
+ // elements of the list as expected.
+ TEST(LinkedObject::from_ring(objects.last())->data ==
+ NumberOfListElements - 1,
+ "Last element of the list is incorrect, expected {}, got {}",
+ NumberOfListElements - 1,
+ LinkedObject::from_ring(objects.last())->data);
+ TEST(objects.last()->cell_next() == &objects.sentinel,
+ "Last element in not followed by the sentinel");
+ TEST(objects.last() == objects.sentinel.cell_prev(),
+ "Sentinel is not preceeded by the last element");
+ TEST(LinkedObject::from_ring(objects.first())->data == 0,
+ "First element of the list is incorrect, expected {}, got {}",
+ 0,
+ LinkedObject::from_ring(objects.last())->data);
+ TEST(objects.first()->cell_prev() == &objects.sentinel,
+ "First element in not preceeded by the sentinel");
+ TEST(objects.first() == objects.sentinel.cell_next(),
+ "Sentinel is not followed by the first element");
+
+ // Test that we can go through the list by following `cell_next`
+ // pointers as expected.
+ int counter = 0;
+ // While at it, retrieve a pointer to the middle element which we will
+ // use to cleave the list later.
+ ObjectRing *middle = nullptr;
+ // We reach the sentinel when we have gone through all elements of the
+ // list.
+ for (auto *cell = objects.first(); cell != &objects.sentinel;
+ cell = cell->cell_next())
+ {
+ struct LinkedObject *o = LinkedObject::from_ring(cell);
+ TEST(
+ o->data == counter,
+ "Ordering of elements in the list is incorrect, expected {}, got {}",
+ o->data,
+ counter);
+ if (counter == NumberOfListElements / 2)
+ {
+ middle = cell;
+ }
+ counter++;
+ }
+
+ TEST(middle != nullptr, "Could not find middle element of the list");
+
+ // Cut the list in the middle.
+ ds::linked_list::remove(middle, objects.last());
+
+ // This should leave us with a list of size `NumberOfListElements / 2`.
+ counter = 0;
+ for (auto *cell = objects.first(); cell != &objects.sentinel;
+ cell = cell->cell_next())
+ {
+ counter++;
+ }
+ TEST(counter == NumberOfListElements / 2,
+ "Cleaving didn't leave a list with the right number of elements");
+
+ // Now remove (and free) a single element from the list.
+ TEST(LinkedObject::from_ring(objects.first())->data == 0,
+ "First element of the list is incorrect, expected {}, got {}",
+ 0,
+ LinkedObject::from_ring(objects.first())->data);
+ // We must keep a reference to the removed object to free it. | It may be worth expanding on this comment. It's typical that `T *remove(T*)` methods return the thing being removed, but `ds::linked_list::cell::remove` breaks that expectation (for reasons that I think are good reasons, but YMMV), which might be surprising to users. |
cheriot-rtos | github_2023 | cpp | 258 | CHERIoT-Platform | nwf-msr | @@ -0,0 +1,211 @@
+// Copyright Microsoft and CHERIoT Contributors.
+// SPDX-License-Identifier: MIT
+
+#define TEST_NAME "List"
+#include "tests.hh"
+#include <ds/linked_list.h>
+
+namespace
+{
+ using ObjectRing = ds::linked_list::cell::Pointer;
+
+ /**
+ * Example class we want to link into a doubly linked list.
+ *
+ * The class contains a single integer for the purposes of the test.
+ *
+ * `ds::linked_list` is an intrusive list: we embed the list node into
+ * the class we want to link. There are various implementations of the
+ * list nodes. Here we use the most simple one
+ * (`ds::linked_list::cell::Pointer`) which relies on two pointers
+ * `next` and `prev`.
+ */
+ struct LinkedObject
+ {
+ int data;
+ /**
+ * List node: links objects into the doubly-linked list.
+ */
+ ObjectRing ring __attribute__((__cheri_no_subobject_bounds__)) = {};
+ /**
+ * Container-of for the above field. This is used to retrieve the
+ * corresponding object from a list element.
+ */
+ __always_inline static struct LinkedObject *from_ring(ObjectRing *c)
+ {
+ return reinterpret_cast<struct LinkedObject *>(
+ reinterpret_cast<uintptr_t>(c) -
+ offsetof(struct LinkedObject, ring));
+ }
+ };
+} // namespace
+
+/**
+ * The sentinel is a special class encapsulating a list node. It provides many
+ * handy functions to operate on the list. The sentinel is thus part of the
+ * list, without being one of the objects linked.
+ *
+ * Note: do not attempt to define the sentinel on the stack, because it would
+ * lead some list nodes holding a pointer to a stack value, i.e., to an invalid
+ * capability. This would lead to a crash while using the list.
+ */
+ds::linked_list::Sentinel<ObjectRing> objects = {};
+
+void test_list()
+{
+ debug_log("Testing the list implementation.");
+
+ // Number of elements we will add to the list in the test. Must be
+ // divisible by two.
+ static constexpr int NumberOfListElements = 30;
+
+ auto heapAtStart = heap_quota_remaining(MALLOC_CAPABILITY);
+
+ TEST(objects.is_empty(), "Newly created list is not empty");
+
+ // Create heap-allocated objects, and link them into the linked list.
+ for (int i = 0; i < NumberOfListElements; i++)
+ {
+ Timeout t{UnlimitedTimeout};
+ LinkedObject *o = (LinkedObject *)heap_allocate(
+ &t, MALLOC_CAPABILITY, sizeof(LinkedObject));
+ TEST(CHERI::Capability{o}.is_valid(), "Cannot allocate linked object");
+
+ // Use the object integer as an index.
+ o->data = i;
+ // The list node has not yet been initialized.
+ o->ring.cell_reset();
+
+ // Test that we can retrieve the object from the link node and
+ // that this results in a valid capability.
+ TEST(o == LinkedObject::from_ring(&(o->ring)),
+ "The container of method does not return the right object");
+ TEST(CHERI::Capability{LinkedObject::from_ring(&(o->ring))}.is_valid(),
+ "Capability retrieved from `from_ring` is invalid");
+
+ // Add the new object to the list through the sentinel node.
+ objects.append(&(o->ring));
+ }
+
+ TEST(!objects.is_empty(), "The list is not empty.");
+
+ // Test that the sentinel can be used to retrieve the first and last
+ // elements of the list as expected.
+ TEST(LinkedObject::from_ring(objects.last())->data ==
+ NumberOfListElements - 1,
+ "Last element of the list is incorrect, expected {}, got {}",
+ NumberOfListElements - 1,
+ LinkedObject::from_ring(objects.last())->data);
+ TEST(objects.last()->cell_next() == &objects.sentinel,
+ "Last element in not followed by the sentinel");
+ TEST(objects.last() == objects.sentinel.cell_prev(),
+ "Sentinel is not preceeded by the last element");
+ TEST(LinkedObject::from_ring(objects.first())->data == 0,
+ "First element of the list is incorrect, expected {}, got {}",
+ 0,
+ LinkedObject::from_ring(objects.last())->data);
+ TEST(objects.first()->cell_prev() == &objects.sentinel,
+ "First element in not preceeded by the sentinel");
+ TEST(objects.first() == objects.sentinel.cell_next(),
+ "Sentinel is not followed by the first element");
+
+ // Test that we can go through the list by following `cell_next`
+ // pointers as expected.
+ int counter = 0;
+ // While at it, retrieve a pointer to the middle element which we will
+ // use to cleave the list later.
+ ObjectRing *middle = nullptr;
+ // We reach the sentinel when we have gone through all elements of the
+ // list.
+ for (auto *cell = objects.first(); cell != &objects.sentinel;
+ cell = cell->cell_next())
+ {
+ struct LinkedObject *o = LinkedObject::from_ring(cell);
+ TEST(
+ o->data == counter,
+ "Ordering of elements in the list is incorrect, expected {}, got {}",
+ o->data,
+ counter);
+ if (counter == NumberOfListElements / 2)
+ {
+ middle = cell;
+ }
+ counter++;
+ }
+
+ TEST(middle != nullptr, "Could not find middle element of the list");
+
+ // Cut the list in the middle.
+ ds::linked_list::remove(middle, objects.last());
+
+ // This should leave us with a list of size `NumberOfListElements / 2`.
+ counter = 0;
+ for (auto *cell = objects.first(); cell != &objects.sentinel;
+ cell = cell->cell_next())
+ {
+ counter++;
+ }
+ TEST(counter == NumberOfListElements / 2,
+ "Cleaving didn't leave a list with the right number of elements");
+
+ // Now remove (and free) a single element from the list.
+ TEST(LinkedObject::from_ring(objects.first())->data == 0,
+ "First element of the list is incorrect, expected {}, got {}",
+ 0,
+ LinkedObject::from_ring(objects.first())->data);
+ // We must keep a reference to the removed object to free it.
+ ObjectRing *removedCell = objects.first();
+ ds::linked_list::remove(objects.first());
+ heap_free(MALLOC_CAPABILITY, LinkedObject::from_ring(removedCell));
+ TEST(LinkedObject::from_ring(objects.first())->data == 1,
+ "First element of the list is incorrect after removing the first "
+ "element, expected {}, got {}",
+ 1,
+ LinkedObject::from_ring(objects.first())->data);
+
+ // We are done with the list, free it.
+ counter = 0;
+ ObjectRing *cell = objects.first();
+ while (cell != &objects.sentinel)
+ {
+ struct LinkedObject *o = LinkedObject::from_ring(cell);
+ cell = cell->cell_next();
+ heap_free(MALLOC_CAPABILITY, o);
+ counter++;
+ }
+
+ TEST(counter == (NumberOfListElements / 2) - 1,
+ "Incorrect number of elements freed, expected {}, got {}",
+ (NumberOfListElements / 2) - 1,
+ counter);
+
+ // Now that the list is freed, reset the sentinel.
+ objects.reset();
+
+ TEST(objects.is_empty(), "Reset-ed list is not empty");
+
+ // We must also free the span of the list which we removed earlier.
+ cell = middle;
+ do
+ {
+ struct LinkedObject *o = LinkedObject::from_ring(cell);
+ cell = cell->cell_next();
+ heap_free(MALLOC_CAPABILITY, o);
+ counter++;
+ } while (cell != middle); | This might be a good place to demonstrate some of why the interface is as quirky as it is. You could showcase in-place mutation and traversal without a sentinel with something like (not compile tested, but hopefully close):
```
ds::linked_list::search(middle, [](ObjectRing &cell) {
auto l = ds::linked_list::unsafe_remove(cell);
free(LinkedObject::from_ring(cell);
cell = l;
});
free(LinkedObject::from_ring(middle)); |
cheriot-rtos | github_2023 | cpp | 248 | CHERIoT-Platform | davidchisnall | @@ -143,6 +143,30 @@ void __cheri_libcall flaglock_unlock(struct FlagLockState *lock);
void __cheri_libcall
flaglock_upgrade_for_destruction(struct FlagLockState *lock);
+/**
+ * Return the thread ID of the owner of the lock.
+ *
+ * This is only available for priority inherited locks, as this is the only
+ * case where we store the thread ID of the owner.
+ *
+ * The return value is 0 if the lock is not owned or if called on a
+ * non-priority inherited flag lock. The return value is undefined if called on
+ * an uninitialized lock.
+ *
+ * This *will* race with succesful `lock` and `unlock` operations on other
+ * threads, and should thus not be used to check if the lock is owned.
+ *
+ * The main use case for this function is in the error handler to check whether
+ * or not the lock is owned by the thread on which the error handler was
+ * invoked. In this case we can call this function and compare the result with
+ * `thread_id_get` to know if the current thread owns the lock.
+ */
+__always_inline static inline uint16_t
+flaglock_priority_inheriting_get_owner_thread_id(struct FlagLockState *lock)
+{
+ return (lock->lockWord & 0x0000ffff); | ```suggestion
// The lock must be held at this point for the value to be stable so do a non-atomic read.
return ((*(uint32_t*)&(lock->lockWord)) & 0x0000ffff);
``` |
cheriot-rtos | github_2023 | others | 244 | CHERIoT-Platform | nwf-msr | @@ -80,9 +80,14 @@ _Z16token_obj_unsealP10SKeyStructP10SObjStruct:
bne t0, t1, .Lexit_failure
/* Subset bounds to ->data */
+ // Get the top into t1
cgetlen t1, ca0
+ cgetbase t0, ca0
+ add t1, t1, t0
+ // Move the address to the start of the data
cincoffset ca0, ca0, TokenSObj_offset_data
- addi t1, t1, -TokenSObj_offset_data
+ // Subtract the address from the top to give the length | Removing the `addi` seemed odd on first read, but of course the as-integer access to the `incoffset`-ed `ca0` does the right thing. Maybe something like this would have avoided my confusion.
```suggestion
// Subtract the address of the data from the top to give the data length
``` |
cheriot-rtos | github_2023 | cpp | 244 | CHERIoT-Platform | nwf-msr | @@ -1093,13 +1090,20 @@ namespace
Debug::log("Underlying allocation failed for sealed object");
return {nullptr, nullptr};
}
+ obj.address() = obj.top() - (sz + ObjHdrSize);
+ // Round down the base to the heap alignment size.
+ // This ensures that the header is aligned and gives the same alignment
+ // as a normal allocation. We will already be this aligned for most
+ // requested sizes.
+ obj.align_down(MallocAlignment); | This probably deserves more commentary, something like...
we're guaranteed that `obj` is still in-bounds because it is the result of `malloc_internal` for `sz + ObjHdrSize` bytes and so it is at least that big and its base must already be `MallocAlignment`-aligned, so `obj`'s address is at least its base. Moreover, because `ObjHdrSize` is a multiple of `MallocAlignment`, the payload at `pointer_offset(obj, ObjHdrSize)` is still `MallocAlignment`-aligned. |
cheriot-rtos | github_2023 | others | 246 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,83 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * An enum representing each of the Sonata's RGB LEDs.
+ */
+enum class SonataRgbLed
+{
+ Led0,
+ Led1,
+};
+
+/**
+ * A driver for the Sonata's RGB LED Controller
+ */
+struct SonataRgbLedController
+{
+ /**
+ * Registers for setting the 8-bit red, green, and blue values
+ * for the two RGB Leds.
+ */
+ uint32_t rgbLed0;
+ uint32_t rgbLed1; | Should this be `uint32_t ledColours[2]` or similar? You can then use the value of `SonataRgbLed` (0 or 1) to index into them. |
cheriot-rtos | github_2023 | others | 246 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,83 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * An enum representing each of the Sonata's RGB LEDs.
+ */
+enum class SonataRgbLed
+{
+ Led0,
+ Led1,
+};
+
+/**
+ * A driver for the Sonata's RGB LED Controller
+ */
+struct SonataRgbLedController
+{
+ /**
+ * Registers for setting the 8-bit red, green, and blue values
+ * for the two RGB Leds.
+ */
+ uint32_t rgbLed0;
+ uint32_t rgbLed1;
+ /// Control Register | It would be nice to document the bits here. You've done that properly with the enums below, so just a forward ref saying that these are set with the values from the control enum below would be nice. |
cheriot-rtos | github_2023 | others | 246 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,83 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * An enum representing each of the Sonata's RGB LEDs.
+ */
+enum class SonataRgbLed
+{
+ Led0,
+ Led1,
+};
+
+/**
+ * A driver for the Sonata's RGB LED Controller
+ */
+struct SonataRgbLedController
+{
+ /**
+ * Registers for setting the 8-bit red, green, and blue values
+ * for the two RGB Leds.
+ */
+ uint32_t rgbLed0;
+ uint32_t rgbLed1;
+ /// Control Register
+ uint32_t control;
+ /// Status Register
+ uint32_t status;
+
+ /// Control Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Write 1 to set RGB LEDs to specified colours.
+ ControlSet = 1 << 0,
+ /**
+ * Write 1 to turn off RGB LEDs.
+ * Write to ControlSet to turn on again.
+ */
+ ControlOff = 1 << 1,
+ };
+
+ /// Status Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /**
+ * When asserted controller is idle and new colours can be set,
+ * otherwise writes to regLed0, regLed1, and control are ignored.
+ */
+ StatusIdle = 1 << 0,
+ };
+
+ void wait_for_idle() volatile | What does idle mean for an LED? I vaguely remember you or Greg saying that these are surprisingly stateful devices and you're sending them update commands, but a comment to that effect would be nice. |
cheriot-rtos | github_2023 | others | 246 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,83 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * An enum representing each of the Sonata's RGB LEDs.
+ */
+enum class SonataRgbLed
+{
+ Led0,
+ Led1,
+};
+
+/**
+ * A driver for the Sonata's RGB LED Controller
+ */
+struct SonataRgbLedController
+{
+ /**
+ * Registers for setting the 8-bit red, green, and blue values
+ * for the two RGB Leds.
+ */
+ uint32_t rgbLed0;
+ uint32_t rgbLed1;
+ /// Control Register
+ uint32_t control;
+ /// Status Register
+ uint32_t status;
+
+ /// Control Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Write 1 to set RGB LEDs to specified colours.
+ ControlSet = 1 << 0,
+ /**
+ * Write 1 to turn off RGB LEDs.
+ * Write to ControlSet to turn on again.
+ */
+ ControlOff = 1 << 1,
+ };
+
+ /// Status Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /**
+ * When asserted controller is idle and new colours can be set,
+ * otherwise writes to regLed0, regLed1, and control are ignored.
+ */
+ StatusIdle = 1 << 0,
+ };
+
+ void wait_for_idle() volatile
+ {
+ while ((status & StatusIdle) == 0) {}
+ }
+
+ void
+ rgb(uint8_t red, uint8_t green, uint8_t blue, SonataRgbLed led) volatile
+ {
+ uint32_t rgb = (static_cast<uint32_t>(blue) << 16) |
+ (static_cast<uint32_t>(green) << 8) |
+ static_cast<uint32_t>(red);
+ wait_for_idle();
+
+ switch (led)
+ {
+ case SonataRgbLed::Led0:
+ rgbLed0 = rgb;
+ case SonataRgbLed::Led1:
+ rgbLed1 = rgb;
+ }; | ```suggestion
wait_for_idle();
ledColours[led] = static_cast<uint32_t>(blue) << 16) |
(static_cast<uint32_t>(green) << 8) |
static_cast<uint32_t>(red);
``` |
cheriot-rtos | github_2023 | others | 246 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,83 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * An enum representing each of the Sonata's RGB LEDs.
+ */
+enum class SonataRgbLed
+{
+ Led0,
+ Led1,
+};
+
+/**
+ * A driver for the Sonata's RGB LED Controller
+ */
+struct SonataRgbLedController
+{
+ /**
+ * Registers for setting the 8-bit red, green, and blue values
+ * for the two RGB Leds.
+ */
+ uint32_t rgbLed0;
+ uint32_t rgbLed1;
+ /// Control Register
+ uint32_t control;
+ /// Status Register
+ uint32_t status;
+
+ /// Control Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Write 1 to set RGB LEDs to specified colours.
+ ControlSet = 1 << 0,
+ /**
+ * Write 1 to turn off RGB LEDs.
+ * Write to ControlSet to turn on again.
+ */
+ ControlOff = 1 << 1,
+ };
+
+ /// Status Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /**
+ * When asserted controller is idle and new colours can be set,
+ * otherwise writes to regLed0, regLed1, and control are ignored.
+ */
+ StatusIdle = 1 << 0,
+ };
+
+ void wait_for_idle() volatile
+ {
+ while ((status & StatusIdle) == 0) {}
+ }
+
+ void
+ rgb(uint8_t red, uint8_t green, uint8_t blue, SonataRgbLed led) volatile | From the existence of the `update` method, I presume that this does not actually change the colour? A comment to that effect would be nice. |
cheriot-rtos | github_2023 | others | 246 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,83 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * An enum representing each of the Sonata's RGB LEDs.
+ */
+enum class SonataRgbLed
+{
+ Led0,
+ Led1,
+};
+
+/**
+ * A driver for the Sonata's RGB LED Controller
+ */
+struct SonataRgbLedController
+{
+ /**
+ * Registers for setting the 8-bit red, green, and blue values
+ * for the two RGB Leds.
+ */
+ uint32_t rgbLed0;
+ uint32_t rgbLed1;
+ /// Control Register
+ uint32_t control;
+ /// Status Register
+ uint32_t status;
+
+ /// Control Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Write 1 to set RGB LEDs to specified colours.
+ ControlSet = 1 << 0,
+ /**
+ * Write 1 to turn off RGB LEDs.
+ * Write to ControlSet to turn on again.
+ */
+ ControlOff = 1 << 1,
+ };
+
+ /// Status Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /**
+ * When asserted controller is idle and new colours can be set,
+ * otherwise writes to regLed0, regLed1, and control are ignored.
+ */
+ StatusIdle = 1 << 0,
+ };
+
+ void wait_for_idle() volatile
+ {
+ while ((status & StatusIdle) == 0) {}
+ }
+
+ void
+ rgb(uint8_t red, uint8_t green, uint8_t blue, SonataRgbLed led) volatile
+ {
+ uint32_t rgb = (static_cast<uint32_t>(blue) << 16) |
+ (static_cast<uint32_t>(green) << 8) |
+ static_cast<uint32_t>(red);
+ wait_for_idle();
+
+ switch (led)
+ {
+ case SonataRgbLed::Led0:
+ rgbLed0 = rgb;
+ case SonataRgbLed::Led1:
+ rgbLed1 = rgb;
+ };
+ }
+
+ void update() volatile | Does this need to be called after `rgb`? What happens if you call it first (LEDs come on in some undefined colour?) |
cheriot-rtos | github_2023 | others | 246 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,83 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * An enum representing each of the Sonata's RGB LEDs.
+ */
+enum class SonataRgbLed
+{
+ Led0,
+ Led1,
+};
+
+/**
+ * A driver for the Sonata's RGB LED Controller
+ */
+struct SonataRgbLedController
+{
+ /**
+ * Registers for setting the 8-bit red, green, and blue values
+ * for the two RGB Leds.
+ */
+ uint32_t rgbLed0;
+ uint32_t rgbLed1;
+ /// Control Register
+ uint32_t control;
+ /// Status Register
+ uint32_t status;
+
+ /// Control Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Write 1 to set RGB LEDs to specified colours.
+ ControlSet = 1 << 0,
+ /**
+ * Write 1 to turn off RGB LEDs.
+ * Write to ControlSet to turn on again.
+ */
+ ControlOff = 1 << 1,
+ };
+
+ /// Status Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /**
+ * When asserted controller is idle and new colours can be set,
+ * otherwise writes to regLed0, regLed1, and control are ignored.
+ */
+ StatusIdle = 1 << 0,
+ };
+
+ void wait_for_idle() volatile
+ {
+ while ((status & StatusIdle) == 0) {}
+ }
+
+ void
+ rgb(uint8_t red, uint8_t green, uint8_t blue, SonataRgbLed led) volatile
+ {
+ uint32_t rgb = (static_cast<uint32_t>(blue) << 16) |
+ (static_cast<uint32_t>(green) << 8) |
+ static_cast<uint32_t>(red);
+ wait_for_idle();
+
+ switch (led)
+ {
+ case SonataRgbLed::Led0:
+ rgbLed0 = rgb;
+ case SonataRgbLed::Led1:
+ rgbLed1 = rgb;
+ };
+ }
+
+ void update() volatile
+ {
+ wait_for_idle();
+ control = ControlSet;
+ }
+
+ void clear() volatile | Does this turn the LEDs off? Both of them? |
cheriot-rtos | github_2023 | others | 246 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,89 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * An enum representing each of the Sonata's RGB LEDs.
+ */
+enum class SonataRgbLed
+{
+ Led0 = 0,
+ Led1 = 1,
+};
+
+/**
+ * A driver for the Sonata's RGB LED Controller
+ */
+struct SonataRgbLedController
+{
+ /**
+ * Registers for setting the 8-bit red, green, and blue values
+ * for the two RGB Leds.
+ */
+ uint32_t ledColors[2];
+
+ /// Control Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Write 1 to set RGB LEDs to specified colours.
+ ControlSet = 1 << 0,
+ /**
+ * Write 1 to turn off RGB LEDs.
+ * Write to ControlSet to turn on again.
+ */
+ ControlOff = 1 << 1,
+ };
+ /// Control Register (fields documented above) | 'Above' isn't great because the 'above' bit isn't visible in the mouse-over pop-up in IDEs (which is the main thing that we write doc comments for). If you point at another enum by name, people can refer to that. |
cheriot-rtos | github_2023 | cpp | 222 | CHERIoT-Platform | davidchisnall | @@ -247,6 +247,10 @@ namespace
HeapObject(struct SObjStruct *heapCapability, T *allocatedObject)
: pointer(allocatedObject, heapCapability)
{
+ if (__builtin_cheri_tag_get(allocatedObject) == 0) | This built in should return a bool, so comparing it against zero is confusing. |
cheriot-rtos | github_2023 | cpp | 222 | CHERIoT-Platform | davidchisnall | @@ -247,6 +247,10 @@ namespace
HeapObject(struct SObjStruct *heapCapability, T *allocatedObject)
: pointer(allocatedObject, heapCapability)
{
+ if (__builtin_cheri_tag_get(allocatedObject) == false) | Why not just ! __builtin_cheri_tag_get(allocatedObject)? |
cheriot-rtos | github_2023 | cpp | 241 | CHERIoT-Platform | davidchisnall | @@ -85,6 +85,15 @@ DEFINE_ALLOCATOR_CAPABILITY(__default_malloc_capability, MALLOC_QUOTA)
*/
#define MALLOC_CAPABILITY STATIC_SEALED_VALUE(__default_malloc_capability)
+/**
+ * Define how long a call to `malloc` and `calloc` can block to fulfil an
+ * allocation. Regardless of this value, `malloc` and `calloc` will only ever
+ * block to wait for the quarantine to be processed. This means that, even with
+ * a non-zero value of `MALLOC_WAIT_TICKS`, `malloc` would immediately return
+ * if the heap or the quota is exhausted.
+ */
+#define MALLOC_WAIT_TICKS 30 | Maybe wrap this in an `#ifndef` so that users can override it? Since our malloc is always-inline, it's safe to make this a per-compilation-unit thing. |
cheriot-rtos | github_2023 | others | 239 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,385 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+static constexpr uint32_t I2cDevClockHz = CPU_TIMER_HZ; | Is there a reason that this and the things below aren't inside the scope of the device class? |
cheriot-rtos | github_2023 | others | 239 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,385 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+static constexpr uint32_t I2cDevClockHz = CPU_TIMER_HZ;
+
+/**
+ * Performs a 32-bit integer unsigned division, rounding up. The bottom
+ * 16 bits of the result are then returned.
+ *
+ * As usual, a divisor of 0 is still Undefined Behavior.
+ */
+static constexpr uint16_t round_up_divide(const uint32_t A, const uint32_t B)
+{
+ if (A == 0)
+ return 0; | Missing braces. |
cheriot-rtos | github_2023 | others | 239 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,385 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+static constexpr uint32_t I2cDevClockHz = CPU_TIMER_HZ;
+
+/**
+ * Performs a 32-bit integer unsigned division, rounding up. The bottom
+ * 16 bits of the result are then returned.
+ *
+ * As usual, a divisor of 0 is still Undefined Behavior.
+ */
+static constexpr uint16_t round_up_divide(const uint32_t A, const uint32_t B)
+{
+ if (A == 0)
+ return 0;
+ return static_cast<uint16_t>(((A - 1) / B) + 1);
+}
+
+/**
+ * The interrupts of the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/interfaces.md
+ */
+enum class OpenTitanI2cInterrupt
+{
+ // host mode interrupt: asserted whilst the Format FIFO level is below the | Please make these proper sentences and doc comments. |
cheriot-rtos | github_2023 | others | 239 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,385 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+static constexpr uint32_t I2cDevClockHz = CPU_TIMER_HZ;
+
+/**
+ * Performs a 32-bit integer unsigned division, rounding up. The bottom
+ * 16 bits of the result are then returned.
+ *
+ * As usual, a divisor of 0 is still Undefined Behavior.
+ */
+static constexpr uint16_t round_up_divide(const uint32_t A, const uint32_t B)
+{
+ if (A == 0)
+ return 0;
+ return static_cast<uint16_t>(((A - 1) / B) + 1);
+}
+
+/**
+ * The interrupts of the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/interfaces.md
+ */
+enum class OpenTitanI2cInterrupt
+{
+ // host mode interrupt: asserted whilst the Format FIFO level is below the
+ // low threshold. This is a level status interrupt.
+ FormatThreshold,
+ // host mode interrupt: asserted whilst the Receive FIFO level is above the
+ // high threshold. This is a level status interrupt.
+ ReceiveThreshold,
+ // target mode interrupt: asserted whilst the Aquired FIFO level is above
+ // the high threshold. This is a level status interrupt.
+ AcquiredThreshold,
+ // host mode interrupt: raised if the Receive FIFO has overflowed.
+ ReceiveOverflow,
+ // host mode interrupt: raised if there is no ACK in response to an address
+ // or data
+ Nak,
+ // host mode interrupt: raised if the SCL line drops early (not supported
+ // without clock synchronization).
+ SclInterference,
+ // host mode interrupt: raised if the SDA line goes low when host is trying
+ // to assert high
+ SdaInterference,
+ // host mode interrupt: raised if target stretches the clock beyond the
+ // allowed timeout period
+ StretchTimeout,
+ // host mode interrupt: raised if the target does not assert a constant
+ // value of SDA during transmission.
+ SdaUnstable,
+ // host and target mode interrupt. In host mode, raised if the host issues a
+ // repeated START or terminates the transaction by issuing STOP. In target
+ // mode, raised if the external host issues a STOP or repeated START.
+ CommandComplete,
+ // target mode interrupt: raised if the target is stretching clocks for a
+ // read command. This is a level status interrupt.
+ TransmitStretch,
+ // target mode interrupt: asserted whilst the Transmit FIFO level is below
+ // the low threshold. This is a level status interrupt.
+ TransmitThreshold,
+ // target mode interrupt: raised if the target is stretching clocks due to
+ // full Aquired FIFO or zero count in targetAckControl.NBYTES (if enabled).
+ // This is a level status interrupt.
+ AcquiredFull,
+ // target mode interrupt: raised if STOP is received without a preceding
+ // NACK during an external host read.
+ UnexpectedStop,
+ // target mode interrupt: raised if the host stops sending the clock during
+ // an ongoing transaction.
+ HostTimeout,
+};
+
+static constexpr uint32_t interrupt_bit(const OpenTitanI2cInterrupt Interrupt)
+{
+ return 1 << static_cast<uint32_t>(Interrupt);
+};
+
+/**
+ * Driver for the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/tree/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c
+ */
+struct OpenTitanI2c
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Alert Test Register (Unused in Sonata)
+ uint32_t alertTest;
+ /// I2C Control Register
+ uint32_t control;
+ /// I2C Live Status Register for Host and Target modes
+ uint32_t status;
+ /// I2C Read Data
+ uint32_t readData;
+ /// I2C Host Format Data
+ uint32_t formatData;
+ /// I2C FIFO control register
+ uint32_t fifoCtrl;
+ /// Host mode FIFO configuration
+ uint32_t hostFifoConfiguration;
+ /// Target mode FIFO configuration
+ uint32_t targetFifoConfiguration;
+ /// Host mode FIFO status register
+ uint32_t hostFifoStatus;
+ /// Target mode FIFO status register
+ uint32_t targetFifoStatus;
+ /// I2C Override Control Register
+ uint32_t override;
+ /// Oversampled Receive values
+ uint32_t values;
+ /**
+ * Detailed I2C Timings (directly corresponding to table 10 in the I2C
+ * Specification).
+ */
+ uint32_t timing0;
+ uint32_t timing1;
+ uint32_t timing2;
+ uint32_t timing3;
+ uint32_t timing4;
+ /// I2C clock stretching timeout control.
+ uint32_t timeoutControl;
+ /// I2C target address and mask pairs
+ uint32_t targetId;
+ /// I2C target acquired data
+ uint32_t acquiredData;
+ /// I2C target transmit data
+ uint32_t transmitData;
+ /**
+ * I2C host clock generation timeout value (in units of input clock
+ * frequency).
+ */
+ uint32_t hostTimeoutControl;
+ /// I2C target internal stretching timeout control.
+ uint32_t targetTimeoutControl;
+ /**
+ * Number of times the I2C target has NACK'ed a new transaction since the
+ * last read of this register.
+ */
+ uint32_t targetNackCount;
+ /**
+ * Timeout in Host-Mode for an unhandled NACK before hardware automatically
+ * ends the transaction.
+ */
+ uint32_t targetAckControl;
+
+ /// Control Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Enable Host I2C functionality
+ ControlEnableHost = 1 << 0,
+ /// Enable Target I2C functionality
+ ControlEnableTarget = 1 << 1,
+ /// Enable I2C line loopback test If line loopback is enabled, the
+ /// internal design sees ACQ and RX data as "1"
+ ControlLineLoopback = 1 << 2,
+ };
+
+ /// Status Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Host mode Format FIFO is full
+ StatusFormatFull = 1 << 0,
+ /// Host mode Receive FIFO is full
+ StatusReceiveFull = 1 << 1,
+ /// Host mode Format FIFO is empty
+ StatusFormatEmpty = 1 << 2,
+ /// Host functionality is idle. No Host transaction is in progress
+ StatusHostIdle = 1 << 3,
+ /// Target functionality is idle. No Target transaction is in progress
+ StatusTargetIdle = 1 << 4,
+ /// Host mode Receive FIFO is empty
+ SmatusReceiveEmpty = 1 << 5,
+ /// Target mode Transmit FIFO is full
+ StatusTransmitFull = 1 << 6,
+ /// Target mode Receive FIFO is full
+ StatusAcquiredFull = 1 << 7,
+ /// Target mode Transmit FIFO is empty
+ StatusTransmitEmpty = 1 << 8,
+ /// Target mode Aquired FIFO is empty
+ StatusAcquiredEmpty = 1 << 9,
+ /**
+ * A Host-Mode active transaction has been ended by the
+ * HostNackHandlerTimeout mechanism. This bit is cleared when
+ * Control.EnableHost is set by software to start a new transaction.
+ */
+ StatusHostDisabledNackTimeout = 1 << 10,
+ };
+
+ /// FormatData Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Issue a START condition before transmitting BYTE.
+ FormatDataStart = 1 << 8,
+ /// Issue a STOP condition after this operation
+ FormatDataStop = 1 << 9,
+ /// Read BYTE bytes from I2C. (256 if BYTE==0)
+ FormatDataReadBytes = 1 << 10,
+ /**
+ * Do not NACK the last byte read, let the read
+ * operation continue
+ */
+ FormatDataReadCount = 1 << 11,
+ /// Do not signal an exception if the current byte is not ACK’d
+ FormatDataNakOk = 1 << 12,
+ };
+
+ /// FifoControl Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Receive fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlReceiveReset = 1 << 0,
+ /// Format fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlFormatReset = 1 << 1,
+ /// Aquired FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlAcquiredReset = 1 << 7,
+ /// Transmit FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlTransmitReset = 1 << 8,
+ };
+
+ /**
+ * Specification times (Table 10) in nanoseconds for each bus mode.
+ */
+ static constexpr uint16_t SpcThigh[] = {4000u, 600u, 260u}; | What is a Spc Thigh?
This kind of naming is why we avoid abbreviations in names. |
cheriot-rtos | github_2023 | others | 239 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,385 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+static constexpr uint32_t I2cDevClockHz = CPU_TIMER_HZ;
+
+/**
+ * Performs a 32-bit integer unsigned division, rounding up. The bottom
+ * 16 bits of the result are then returned.
+ *
+ * As usual, a divisor of 0 is still Undefined Behavior.
+ */
+static constexpr uint16_t round_up_divide(const uint32_t A, const uint32_t B)
+{
+ if (A == 0)
+ return 0;
+ return static_cast<uint16_t>(((A - 1) / B) + 1);
+}
+
+/**
+ * The interrupts of the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/interfaces.md
+ */
+enum class OpenTitanI2cInterrupt
+{
+ // host mode interrupt: asserted whilst the Format FIFO level is below the
+ // low threshold. This is a level status interrupt.
+ FormatThreshold,
+ // host mode interrupt: asserted whilst the Receive FIFO level is above the
+ // high threshold. This is a level status interrupt.
+ ReceiveThreshold,
+ // target mode interrupt: asserted whilst the Aquired FIFO level is above
+ // the high threshold. This is a level status interrupt.
+ AcquiredThreshold,
+ // host mode interrupt: raised if the Receive FIFO has overflowed.
+ ReceiveOverflow,
+ // host mode interrupt: raised if there is no ACK in response to an address
+ // or data
+ Nak,
+ // host mode interrupt: raised if the SCL line drops early (not supported
+ // without clock synchronization).
+ SclInterference,
+ // host mode interrupt: raised if the SDA line goes low when host is trying
+ // to assert high
+ SdaInterference,
+ // host mode interrupt: raised if target stretches the clock beyond the
+ // allowed timeout period
+ StretchTimeout,
+ // host mode interrupt: raised if the target does not assert a constant
+ // value of SDA during transmission.
+ SdaUnstable,
+ // host and target mode interrupt. In host mode, raised if the host issues a
+ // repeated START or terminates the transaction by issuing STOP. In target
+ // mode, raised if the external host issues a STOP or repeated START.
+ CommandComplete,
+ // target mode interrupt: raised if the target is stretching clocks for a
+ // read command. This is a level status interrupt.
+ TransmitStretch,
+ // target mode interrupt: asserted whilst the Transmit FIFO level is below
+ // the low threshold. This is a level status interrupt.
+ TransmitThreshold,
+ // target mode interrupt: raised if the target is stretching clocks due to
+ // full Aquired FIFO or zero count in targetAckControl.NBYTES (if enabled).
+ // This is a level status interrupt.
+ AcquiredFull,
+ // target mode interrupt: raised if STOP is received without a preceding
+ // NACK during an external host read.
+ UnexpectedStop,
+ // target mode interrupt: raised if the host stops sending the clock during
+ // an ongoing transaction.
+ HostTimeout,
+};
+
+static constexpr uint32_t interrupt_bit(const OpenTitanI2cInterrupt Interrupt)
+{
+ return 1 << static_cast<uint32_t>(Interrupt);
+};
+
+/**
+ * Driver for the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/tree/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c
+ */
+struct OpenTitanI2c
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Alert Test Register (Unused in Sonata)
+ uint32_t alertTest;
+ /// I2C Control Register
+ uint32_t control;
+ /// I2C Live Status Register for Host and Target modes
+ uint32_t status;
+ /// I2C Read Data
+ uint32_t readData;
+ /// I2C Host Format Data
+ uint32_t formatData;
+ /// I2C FIFO control register
+ uint32_t fifoCtrl;
+ /// Host mode FIFO configuration
+ uint32_t hostFifoConfiguration;
+ /// Target mode FIFO configuration
+ uint32_t targetFifoConfiguration;
+ /// Host mode FIFO status register
+ uint32_t hostFifoStatus;
+ /// Target mode FIFO status register
+ uint32_t targetFifoStatus;
+ /// I2C Override Control Register
+ uint32_t override;
+ /// Oversampled Receive values
+ uint32_t values;
+ /**
+ * Detailed I2C Timings (directly corresponding to table 10 in the I2C
+ * Specification).
+ */
+ uint32_t timing0;
+ uint32_t timing1;
+ uint32_t timing2;
+ uint32_t timing3;
+ uint32_t timing4;
+ /// I2C clock stretching timeout control.
+ uint32_t timeoutControl;
+ /// I2C target address and mask pairs
+ uint32_t targetId;
+ /// I2C target acquired data
+ uint32_t acquiredData;
+ /// I2C target transmit data
+ uint32_t transmitData;
+ /**
+ * I2C host clock generation timeout value (in units of input clock
+ * frequency).
+ */
+ uint32_t hostTimeoutControl;
+ /// I2C target internal stretching timeout control.
+ uint32_t targetTimeoutControl;
+ /**
+ * Number of times the I2C target has NACK'ed a new transaction since the
+ * last read of this register.
+ */
+ uint32_t targetNackCount;
+ /**
+ * Timeout in Host-Mode for an unhandled NACK before hardware automatically
+ * ends the transaction.
+ */
+ uint32_t targetAckControl;
+
+ /// Control Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Enable Host I2C functionality
+ ControlEnableHost = 1 << 0,
+ /// Enable Target I2C functionality
+ ControlEnableTarget = 1 << 1,
+ /// Enable I2C line loopback test If line loopback is enabled, the
+ /// internal design sees ACQ and RX data as "1"
+ ControlLineLoopback = 1 << 2,
+ };
+
+ /// Status Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Host mode Format FIFO is full
+ StatusFormatFull = 1 << 0,
+ /// Host mode Receive FIFO is full
+ StatusReceiveFull = 1 << 1,
+ /// Host mode Format FIFO is empty
+ StatusFormatEmpty = 1 << 2,
+ /// Host functionality is idle. No Host transaction is in progress
+ StatusHostIdle = 1 << 3,
+ /// Target functionality is idle. No Target transaction is in progress
+ StatusTargetIdle = 1 << 4,
+ /// Host mode Receive FIFO is empty
+ SmatusReceiveEmpty = 1 << 5,
+ /// Target mode Transmit FIFO is full
+ StatusTransmitFull = 1 << 6,
+ /// Target mode Receive FIFO is full
+ StatusAcquiredFull = 1 << 7,
+ /// Target mode Transmit FIFO is empty
+ StatusTransmitEmpty = 1 << 8,
+ /// Target mode Aquired FIFO is empty
+ StatusAcquiredEmpty = 1 << 9,
+ /**
+ * A Host-Mode active transaction has been ended by the
+ * HostNackHandlerTimeout mechanism. This bit is cleared when
+ * Control.EnableHost is set by software to start a new transaction.
+ */
+ StatusHostDisabledNackTimeout = 1 << 10,
+ };
+
+ /// FormatData Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Issue a START condition before transmitting BYTE.
+ FormatDataStart = 1 << 8,
+ /// Issue a STOP condition after this operation
+ FormatDataStop = 1 << 9,
+ /// Read BYTE bytes from I2C. (256 if BYTE==0)
+ FormatDataReadBytes = 1 << 10,
+ /**
+ * Do not NACK the last byte read, let the read
+ * operation continue
+ */
+ FormatDataReadCount = 1 << 11,
+ /// Do not signal an exception if the current byte is not ACK’d
+ FormatDataNakOk = 1 << 12,
+ };
+
+ /// FifoControl Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Receive fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlReceiveReset = 1 << 0,
+ /// Format fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlFormatReset = 1 << 1,
+ /// Aquired FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlAcquiredReset = 1 << 7,
+ /// Transmit FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlTransmitReset = 1 << 8,
+ };
+
+ /**
+ * Specification times (Table 10) in nanoseconds for each bus mode.
+ */
+ static constexpr uint16_t SpcThigh[] = {4000u, 600u, 260u};
+ static constexpr uint16_t SpcTlow[] = {4700u, 1300u, 150u};
+ static constexpr uint16_t SpcThdSta[] = {4000u, 600u, 260u};
+ static constexpr uint16_t SpcTsuSta[] = {4700u, 600u, 260u};
+ static constexpr uint16_t SpcThdDat[] = {4000u, 1u, 1u};
+ static constexpr uint16_t SpcTsuDat[] = {500u, 100u, 50u};
+ static constexpr uint16_t SpcTBuf[] = {4700u, 1300u, 500u};
+ static constexpr uint16_t SpcTsuSto[] = {4000u, 600u, 260u};
+
+ /// Reset all of the fifos
+ void reset_fifos() volatile
+ {
+ fifoCtrl = (FifoControlReceiveReset | FifoControlFormatReset |
+ FifoControlAcquiredReset | FifoControlTransmitReset);
+ }
+
+ /// Configure the I2C block to be in host mode
+ void set_host_mode() volatile | We normally name things noun-verb, so that similar things are sorted together when autocompleting or reading generated docs. Ideally avoid starting things with `set` because it ends up with a load of unrelated `set_` things in autocomplete.
My preferred style here (which we haven't done uniformly) is to have two overloads with the name of the thing, one of which takes an argument and updates it, the other that takes no arguments and does not update it. |
cheriot-rtos | github_2023 | others | 239 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,385 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+static constexpr uint32_t I2cDevClockHz = CPU_TIMER_HZ;
+
+/**
+ * Performs a 32-bit integer unsigned division, rounding up. The bottom
+ * 16 bits of the result are then returned.
+ *
+ * As usual, a divisor of 0 is still Undefined Behavior.
+ */
+static constexpr uint16_t round_up_divide(const uint32_t A, const uint32_t B)
+{
+ if (A == 0)
+ return 0;
+ return static_cast<uint16_t>(((A - 1) / B) + 1);
+}
+
+/**
+ * The interrupts of the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/interfaces.md
+ */
+enum class OpenTitanI2cInterrupt
+{
+ // host mode interrupt: asserted whilst the Format FIFO level is below the
+ // low threshold. This is a level status interrupt.
+ FormatThreshold,
+ // host mode interrupt: asserted whilst the Receive FIFO level is above the
+ // high threshold. This is a level status interrupt.
+ ReceiveThreshold,
+ // target mode interrupt: asserted whilst the Aquired FIFO level is above
+ // the high threshold. This is a level status interrupt.
+ AcquiredThreshold,
+ // host mode interrupt: raised if the Receive FIFO has overflowed.
+ ReceiveOverflow,
+ // host mode interrupt: raised if there is no ACK in response to an address
+ // or data
+ Nak,
+ // host mode interrupt: raised if the SCL line drops early (not supported
+ // without clock synchronization).
+ SclInterference,
+ // host mode interrupt: raised if the SDA line goes low when host is trying
+ // to assert high
+ SdaInterference,
+ // host mode interrupt: raised if target stretches the clock beyond the
+ // allowed timeout period
+ StretchTimeout,
+ // host mode interrupt: raised if the target does not assert a constant
+ // value of SDA during transmission.
+ SdaUnstable,
+ // host and target mode interrupt. In host mode, raised if the host issues a
+ // repeated START or terminates the transaction by issuing STOP. In target
+ // mode, raised if the external host issues a STOP or repeated START.
+ CommandComplete,
+ // target mode interrupt: raised if the target is stretching clocks for a
+ // read command. This is a level status interrupt.
+ TransmitStretch,
+ // target mode interrupt: asserted whilst the Transmit FIFO level is below
+ // the low threshold. This is a level status interrupt.
+ TransmitThreshold,
+ // target mode interrupt: raised if the target is stretching clocks due to
+ // full Aquired FIFO or zero count in targetAckControl.NBYTES (if enabled).
+ // This is a level status interrupt.
+ AcquiredFull,
+ // target mode interrupt: raised if STOP is received without a preceding
+ // NACK during an external host read.
+ UnexpectedStop,
+ // target mode interrupt: raised if the host stops sending the clock during
+ // an ongoing transaction.
+ HostTimeout,
+};
+
+static constexpr uint32_t interrupt_bit(const OpenTitanI2cInterrupt Interrupt)
+{
+ return 1 << static_cast<uint32_t>(Interrupt);
+};
+
+/**
+ * Driver for the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/tree/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c
+ */
+struct OpenTitanI2c
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Alert Test Register (Unused in Sonata)
+ uint32_t alertTest;
+ /// I2C Control Register
+ uint32_t control;
+ /// I2C Live Status Register for Host and Target modes
+ uint32_t status;
+ /// I2C Read Data
+ uint32_t readData;
+ /// I2C Host Format Data
+ uint32_t formatData;
+ /// I2C FIFO control register
+ uint32_t fifoCtrl;
+ /// Host mode FIFO configuration
+ uint32_t hostFifoConfiguration;
+ /// Target mode FIFO configuration
+ uint32_t targetFifoConfiguration;
+ /// Host mode FIFO status register
+ uint32_t hostFifoStatus;
+ /// Target mode FIFO status register
+ uint32_t targetFifoStatus;
+ /// I2C Override Control Register
+ uint32_t override;
+ /// Oversampled Receive values
+ uint32_t values;
+ /**
+ * Detailed I2C Timings (directly corresponding to table 10 in the I2C
+ * Specification).
+ */
+ uint32_t timing0;
+ uint32_t timing1;
+ uint32_t timing2;
+ uint32_t timing3;
+ uint32_t timing4;
+ /// I2C clock stretching timeout control.
+ uint32_t timeoutControl;
+ /// I2C target address and mask pairs
+ uint32_t targetId;
+ /// I2C target acquired data
+ uint32_t acquiredData;
+ /// I2C target transmit data
+ uint32_t transmitData;
+ /**
+ * I2C host clock generation timeout value (in units of input clock
+ * frequency).
+ */
+ uint32_t hostTimeoutControl;
+ /// I2C target internal stretching timeout control.
+ uint32_t targetTimeoutControl;
+ /**
+ * Number of times the I2C target has NACK'ed a new transaction since the
+ * last read of this register.
+ */
+ uint32_t targetNackCount;
+ /**
+ * Timeout in Host-Mode for an unhandled NACK before hardware automatically
+ * ends the transaction.
+ */
+ uint32_t targetAckControl;
+
+ /// Control Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Enable Host I2C functionality
+ ControlEnableHost = 1 << 0,
+ /// Enable Target I2C functionality
+ ControlEnableTarget = 1 << 1,
+ /// Enable I2C line loopback test If line loopback is enabled, the
+ /// internal design sees ACQ and RX data as "1"
+ ControlLineLoopback = 1 << 2,
+ };
+
+ /// Status Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Host mode Format FIFO is full
+ StatusFormatFull = 1 << 0,
+ /// Host mode Receive FIFO is full
+ StatusReceiveFull = 1 << 1,
+ /// Host mode Format FIFO is empty
+ StatusFormatEmpty = 1 << 2,
+ /// Host functionality is idle. No Host transaction is in progress
+ StatusHostIdle = 1 << 3,
+ /// Target functionality is idle. No Target transaction is in progress
+ StatusTargetIdle = 1 << 4,
+ /// Host mode Receive FIFO is empty
+ SmatusReceiveEmpty = 1 << 5,
+ /// Target mode Transmit FIFO is full
+ StatusTransmitFull = 1 << 6,
+ /// Target mode Receive FIFO is full
+ StatusAcquiredFull = 1 << 7,
+ /// Target mode Transmit FIFO is empty
+ StatusTransmitEmpty = 1 << 8,
+ /// Target mode Aquired FIFO is empty
+ StatusAcquiredEmpty = 1 << 9,
+ /**
+ * A Host-Mode active transaction has been ended by the
+ * HostNackHandlerTimeout mechanism. This bit is cleared when
+ * Control.EnableHost is set by software to start a new transaction.
+ */
+ StatusHostDisabledNackTimeout = 1 << 10,
+ };
+
+ /// FormatData Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Issue a START condition before transmitting BYTE.
+ FormatDataStart = 1 << 8,
+ /// Issue a STOP condition after this operation
+ FormatDataStop = 1 << 9,
+ /// Read BYTE bytes from I2C. (256 if BYTE==0)
+ FormatDataReadBytes = 1 << 10,
+ /**
+ * Do not NACK the last byte read, let the read
+ * operation continue
+ */
+ FormatDataReadCount = 1 << 11,
+ /// Do not signal an exception if the current byte is not ACK’d
+ FormatDataNakOk = 1 << 12,
+ };
+
+ /// FifoControl Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Receive fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlReceiveReset = 1 << 0,
+ /// Format fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlFormatReset = 1 << 1,
+ /// Aquired FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlAcquiredReset = 1 << 7,
+ /// Transmit FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlTransmitReset = 1 << 8,
+ };
+
+ /**
+ * Specification times (Table 10) in nanoseconds for each bus mode.
+ */
+ static constexpr uint16_t SpcThigh[] = {4000u, 600u, 260u};
+ static constexpr uint16_t SpcTlow[] = {4700u, 1300u, 150u};
+ static constexpr uint16_t SpcThdSta[] = {4000u, 600u, 260u};
+ static constexpr uint16_t SpcTsuSta[] = {4700u, 600u, 260u};
+ static constexpr uint16_t SpcThdDat[] = {4000u, 1u, 1u};
+ static constexpr uint16_t SpcTsuDat[] = {500u, 100u, 50u};
+ static constexpr uint16_t SpcTBuf[] = {4700u, 1300u, 500u};
+ static constexpr uint16_t SpcTsuSto[] = {4000u, 600u, 260u};
+
+ /// Reset all of the fifos
+ void reset_fifos() volatile
+ {
+ fifoCtrl = (FifoControlReceiveReset | FifoControlFormatReset |
+ FifoControlAcquiredReset | FifoControlTransmitReset);
+ }
+
+ /// Configure the I2C block to be in host mode
+ void set_host_mode() volatile
+ {
+ control = ControlEnableHost;
+ }
+
+ /**
+ * Set the I2C timing parameters appropriately for the given bit rate.
+ * Distilled from:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/programmers_guide.md
+ */
+ void set_speed(const uint32_t SpeedKhz) volatile
+ {
+ // We must round up the system clock frequency to lengthen intervals.
+ constexpr uint32_t SysclkKhz = (I2cDevClockHz + 999) / 1000; | Is this doing the same round up thing as your helper? |
cheriot-rtos | github_2023 | others | 239 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,385 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+static constexpr uint32_t I2cDevClockHz = CPU_TIMER_HZ;
+
+/**
+ * Performs a 32-bit integer unsigned division, rounding up. The bottom
+ * 16 bits of the result are then returned.
+ *
+ * As usual, a divisor of 0 is still Undefined Behavior.
+ */
+static constexpr uint16_t round_up_divide(const uint32_t A, const uint32_t B)
+{
+ if (A == 0)
+ return 0;
+ return static_cast<uint16_t>(((A - 1) / B) + 1);
+}
+
+/**
+ * The interrupts of the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/interfaces.md
+ */
+enum class OpenTitanI2cInterrupt
+{
+ // host mode interrupt: asserted whilst the Format FIFO level is below the
+ // low threshold. This is a level status interrupt.
+ FormatThreshold,
+ // host mode interrupt: asserted whilst the Receive FIFO level is above the
+ // high threshold. This is a level status interrupt.
+ ReceiveThreshold,
+ // target mode interrupt: asserted whilst the Aquired FIFO level is above
+ // the high threshold. This is a level status interrupt.
+ AcquiredThreshold,
+ // host mode interrupt: raised if the Receive FIFO has overflowed.
+ ReceiveOverflow,
+ // host mode interrupt: raised if there is no ACK in response to an address
+ // or data
+ Nak,
+ // host mode interrupt: raised if the SCL line drops early (not supported
+ // without clock synchronization).
+ SclInterference,
+ // host mode interrupt: raised if the SDA line goes low when host is trying
+ // to assert high
+ SdaInterference,
+ // host mode interrupt: raised if target stretches the clock beyond the
+ // allowed timeout period
+ StretchTimeout,
+ // host mode interrupt: raised if the target does not assert a constant
+ // value of SDA during transmission.
+ SdaUnstable,
+ // host and target mode interrupt. In host mode, raised if the host issues a
+ // repeated START or terminates the transaction by issuing STOP. In target
+ // mode, raised if the external host issues a STOP or repeated START.
+ CommandComplete,
+ // target mode interrupt: raised if the target is stretching clocks for a
+ // read command. This is a level status interrupt.
+ TransmitStretch,
+ // target mode interrupt: asserted whilst the Transmit FIFO level is below
+ // the low threshold. This is a level status interrupt.
+ TransmitThreshold,
+ // target mode interrupt: raised if the target is stretching clocks due to
+ // full Aquired FIFO or zero count in targetAckControl.NBYTES (if enabled).
+ // This is a level status interrupt.
+ AcquiredFull,
+ // target mode interrupt: raised if STOP is received without a preceding
+ // NACK during an external host read.
+ UnexpectedStop,
+ // target mode interrupt: raised if the host stops sending the clock during
+ // an ongoing transaction.
+ HostTimeout,
+};
+
+static constexpr uint32_t interrupt_bit(const OpenTitanI2cInterrupt Interrupt)
+{
+ return 1 << static_cast<uint32_t>(Interrupt);
+};
+
+/**
+ * Driver for the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/tree/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c
+ */
+struct OpenTitanI2c
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Alert Test Register (Unused in Sonata)
+ uint32_t alertTest;
+ /// I2C Control Register
+ uint32_t control;
+ /// I2C Live Status Register for Host and Target modes
+ uint32_t status;
+ /// I2C Read Data
+ uint32_t readData;
+ /// I2C Host Format Data
+ uint32_t formatData;
+ /// I2C FIFO control register
+ uint32_t fifoCtrl;
+ /// Host mode FIFO configuration
+ uint32_t hostFifoConfiguration;
+ /// Target mode FIFO configuration
+ uint32_t targetFifoConfiguration;
+ /// Host mode FIFO status register
+ uint32_t hostFifoStatus;
+ /// Target mode FIFO status register
+ uint32_t targetFifoStatus;
+ /// I2C Override Control Register
+ uint32_t override;
+ /// Oversampled Receive values
+ uint32_t values;
+ /**
+ * Detailed I2C Timings (directly corresponding to table 10 in the I2C
+ * Specification).
+ */
+ uint32_t timing0;
+ uint32_t timing1;
+ uint32_t timing2;
+ uint32_t timing3;
+ uint32_t timing4;
+ /// I2C clock stretching timeout control.
+ uint32_t timeoutControl;
+ /// I2C target address and mask pairs
+ uint32_t targetId;
+ /// I2C target acquired data
+ uint32_t acquiredData;
+ /// I2C target transmit data
+ uint32_t transmitData;
+ /**
+ * I2C host clock generation timeout value (in units of input clock
+ * frequency).
+ */
+ uint32_t hostTimeoutControl;
+ /// I2C target internal stretching timeout control.
+ uint32_t targetTimeoutControl;
+ /**
+ * Number of times the I2C target has NACK'ed a new transaction since the
+ * last read of this register.
+ */
+ uint32_t targetNackCount;
+ /**
+ * Timeout in Host-Mode for an unhandled NACK before hardware automatically
+ * ends the transaction.
+ */
+ uint32_t targetAckControl;
+
+ /// Control Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Enable Host I2C functionality
+ ControlEnableHost = 1 << 0,
+ /// Enable Target I2C functionality
+ ControlEnableTarget = 1 << 1,
+ /// Enable I2C line loopback test If line loopback is enabled, the
+ /// internal design sees ACQ and RX data as "1"
+ ControlLineLoopback = 1 << 2,
+ };
+
+ /// Status Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Host mode Format FIFO is full
+ StatusFormatFull = 1 << 0,
+ /// Host mode Receive FIFO is full
+ StatusReceiveFull = 1 << 1,
+ /// Host mode Format FIFO is empty
+ StatusFormatEmpty = 1 << 2,
+ /// Host functionality is idle. No Host transaction is in progress
+ StatusHostIdle = 1 << 3,
+ /// Target functionality is idle. No Target transaction is in progress
+ StatusTargetIdle = 1 << 4,
+ /// Host mode Receive FIFO is empty
+ SmatusReceiveEmpty = 1 << 5,
+ /// Target mode Transmit FIFO is full
+ StatusTransmitFull = 1 << 6,
+ /// Target mode Receive FIFO is full
+ StatusAcquiredFull = 1 << 7,
+ /// Target mode Transmit FIFO is empty
+ StatusTransmitEmpty = 1 << 8,
+ /// Target mode Aquired FIFO is empty
+ StatusAcquiredEmpty = 1 << 9,
+ /**
+ * A Host-Mode active transaction has been ended by the
+ * HostNackHandlerTimeout mechanism. This bit is cleared when
+ * Control.EnableHost is set by software to start a new transaction.
+ */
+ StatusHostDisabledNackTimeout = 1 << 10,
+ };
+
+ /// FormatData Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Issue a START condition before transmitting BYTE.
+ FormatDataStart = 1 << 8,
+ /// Issue a STOP condition after this operation
+ FormatDataStop = 1 << 9,
+ /// Read BYTE bytes from I2C. (256 if BYTE==0)
+ FormatDataReadBytes = 1 << 10,
+ /**
+ * Do not NACK the last byte read, let the read
+ * operation continue
+ */
+ FormatDataReadCount = 1 << 11,
+ /// Do not signal an exception if the current byte is not ACK’d
+ FormatDataNakOk = 1 << 12,
+ };
+
+ /// FifoControl Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Receive fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlReceiveReset = 1 << 0,
+ /// Format fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlFormatReset = 1 << 1,
+ /// Aquired FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlAcquiredReset = 1 << 7,
+ /// Transmit FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlTransmitReset = 1 << 8,
+ };
+
+ /**
+ * Specification times (Table 10) in nanoseconds for each bus mode.
+ */
+ static constexpr uint16_t SpcThigh[] = {4000u, 600u, 260u};
+ static constexpr uint16_t SpcTlow[] = {4700u, 1300u, 150u};
+ static constexpr uint16_t SpcThdSta[] = {4000u, 600u, 260u};
+ static constexpr uint16_t SpcTsuSta[] = {4700u, 600u, 260u};
+ static constexpr uint16_t SpcThdDat[] = {4000u, 1u, 1u};
+ static constexpr uint16_t SpcTsuDat[] = {500u, 100u, 50u};
+ static constexpr uint16_t SpcTBuf[] = {4700u, 1300u, 500u};
+ static constexpr uint16_t SpcTsuSto[] = {4000u, 600u, 260u};
+
+ /// Reset all of the fifos
+ void reset_fifos() volatile
+ {
+ fifoCtrl = (FifoControlReceiveReset | FifoControlFormatReset |
+ FifoControlAcquiredReset | FifoControlTransmitReset);
+ }
+
+ /// Configure the I2C block to be in host mode
+ void set_host_mode() volatile
+ {
+ control = ControlEnableHost;
+ }
+
+ /**
+ * Set the I2C timing parameters appropriately for the given bit rate.
+ * Distilled from:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/programmers_guide.md
+ */
+ void set_speed(const uint32_t SpeedKhz) volatile
+ {
+ // We must round up the system clock frequency to lengthen intervals.
+ constexpr uint32_t SysclkKhz = (I2cDevClockHz + 999) / 1000;
+ // We want to underestimate the clock period, to lengthen the timings.
+ uint32_t clkPeriod = (1000 * 1000) / SysclkKhz;
+
+ // Decide which bus mode this represents
+ uint32_t mode = (SpeedKhz > 100u) + (SpeedKhz > 400u);
+
+ // Calculation of timing parameters
+ uint16_t tHigh =
+ round_up_divide(SpcThigh[mode], clkPeriod); // Spec. min.
+ uint16_t tLow = round_up_divide(SpcTlow[mode], clkPeriod); // Spec. min.
+ uint16_t tFall =
+ round_up_divide(20 * 3 / 5, clkPeriod); // Spec. min. 3.3V
+ uint16_t tRise = round_up_divide(120, clkPeriod);
+ // Setup and Hold times for Start | I can't quite parse this comment. |
cheriot-rtos | github_2023 | others | 239 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,385 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+static constexpr uint32_t I2cDevClockHz = CPU_TIMER_HZ;
+
+/**
+ * Performs a 32-bit integer unsigned division, rounding up. The bottom
+ * 16 bits of the result are then returned.
+ *
+ * As usual, a divisor of 0 is still Undefined Behavior.
+ */
+static constexpr uint16_t round_up_divide(const uint32_t A, const uint32_t B)
+{
+ if (A == 0)
+ return 0;
+ return static_cast<uint16_t>(((A - 1) / B) + 1);
+}
+
+/**
+ * The interrupts of the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/interfaces.md
+ */
+enum class OpenTitanI2cInterrupt
+{
+ // host mode interrupt: asserted whilst the Format FIFO level is below the
+ // low threshold. This is a level status interrupt.
+ FormatThreshold,
+ // host mode interrupt: asserted whilst the Receive FIFO level is above the
+ // high threshold. This is a level status interrupt.
+ ReceiveThreshold,
+ // target mode interrupt: asserted whilst the Aquired FIFO level is above
+ // the high threshold. This is a level status interrupt.
+ AcquiredThreshold,
+ // host mode interrupt: raised if the Receive FIFO has overflowed.
+ ReceiveOverflow,
+ // host mode interrupt: raised if there is no ACK in response to an address
+ // or data
+ Nak,
+ // host mode interrupt: raised if the SCL line drops early (not supported
+ // without clock synchronization).
+ SclInterference,
+ // host mode interrupt: raised if the SDA line goes low when host is trying
+ // to assert high
+ SdaInterference,
+ // host mode interrupt: raised if target stretches the clock beyond the
+ // allowed timeout period
+ StretchTimeout,
+ // host mode interrupt: raised if the target does not assert a constant
+ // value of SDA during transmission.
+ SdaUnstable,
+ // host and target mode interrupt. In host mode, raised if the host issues a
+ // repeated START or terminates the transaction by issuing STOP. In target
+ // mode, raised if the external host issues a STOP or repeated START.
+ CommandComplete,
+ // target mode interrupt: raised if the target is stretching clocks for a
+ // read command. This is a level status interrupt.
+ TransmitStretch,
+ // target mode interrupt: asserted whilst the Transmit FIFO level is below
+ // the low threshold. This is a level status interrupt.
+ TransmitThreshold,
+ // target mode interrupt: raised if the target is stretching clocks due to
+ // full Aquired FIFO or zero count in targetAckControl.NBYTES (if enabled).
+ // This is a level status interrupt.
+ AcquiredFull,
+ // target mode interrupt: raised if STOP is received without a preceding
+ // NACK during an external host read.
+ UnexpectedStop,
+ // target mode interrupt: raised if the host stops sending the clock during
+ // an ongoing transaction.
+ HostTimeout,
+};
+
+static constexpr uint32_t interrupt_bit(const OpenTitanI2cInterrupt Interrupt)
+{
+ return 1 << static_cast<uint32_t>(Interrupt);
+};
+
+/**
+ * Driver for the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/tree/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c
+ */
+struct OpenTitanI2c
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Alert Test Register (Unused in Sonata)
+ uint32_t alertTest;
+ /// I2C Control Register
+ uint32_t control;
+ /// I2C Live Status Register for Host and Target modes
+ uint32_t status;
+ /// I2C Read Data
+ uint32_t readData;
+ /// I2C Host Format Data
+ uint32_t formatData;
+ /// I2C FIFO control register
+ uint32_t fifoCtrl;
+ /// Host mode FIFO configuration
+ uint32_t hostFifoConfiguration;
+ /// Target mode FIFO configuration
+ uint32_t targetFifoConfiguration;
+ /// Host mode FIFO status register
+ uint32_t hostFifoStatus;
+ /// Target mode FIFO status register
+ uint32_t targetFifoStatus;
+ /// I2C Override Control Register
+ uint32_t override;
+ /// Oversampled Receive values
+ uint32_t values;
+ /**
+ * Detailed I2C Timings (directly corresponding to table 10 in the I2C
+ * Specification).
+ */
+ uint32_t timing0;
+ uint32_t timing1;
+ uint32_t timing2;
+ uint32_t timing3;
+ uint32_t timing4;
+ /// I2C clock stretching timeout control.
+ uint32_t timeoutControl;
+ /// I2C target address and mask pairs
+ uint32_t targetId;
+ /// I2C target acquired data
+ uint32_t acquiredData;
+ /// I2C target transmit data
+ uint32_t transmitData;
+ /**
+ * I2C host clock generation timeout value (in units of input clock
+ * frequency).
+ */
+ uint32_t hostTimeoutControl;
+ /// I2C target internal stretching timeout control.
+ uint32_t targetTimeoutControl;
+ /**
+ * Number of times the I2C target has NACK'ed a new transaction since the
+ * last read of this register.
+ */
+ uint32_t targetNackCount;
+ /**
+ * Timeout in Host-Mode for an unhandled NACK before hardware automatically
+ * ends the transaction.
+ */
+ uint32_t targetAckControl;
+
+ /// Control Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Enable Host I2C functionality
+ ControlEnableHost = 1 << 0,
+ /// Enable Target I2C functionality
+ ControlEnableTarget = 1 << 1,
+ /// Enable I2C line loopback test If line loopback is enabled, the
+ /// internal design sees ACQ and RX data as "1"
+ ControlLineLoopback = 1 << 2,
+ };
+
+ /// Status Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Host mode Format FIFO is full
+ StatusFormatFull = 1 << 0,
+ /// Host mode Receive FIFO is full
+ StatusReceiveFull = 1 << 1,
+ /// Host mode Format FIFO is empty
+ StatusFormatEmpty = 1 << 2,
+ /// Host functionality is idle. No Host transaction is in progress
+ StatusHostIdle = 1 << 3,
+ /// Target functionality is idle. No Target transaction is in progress
+ StatusTargetIdle = 1 << 4,
+ /// Host mode Receive FIFO is empty
+ SmatusReceiveEmpty = 1 << 5,
+ /// Target mode Transmit FIFO is full
+ StatusTransmitFull = 1 << 6,
+ /// Target mode Receive FIFO is full
+ StatusAcquiredFull = 1 << 7,
+ /// Target mode Transmit FIFO is empty
+ StatusTransmitEmpty = 1 << 8,
+ /// Target mode Aquired FIFO is empty
+ StatusAcquiredEmpty = 1 << 9,
+ /**
+ * A Host-Mode active transaction has been ended by the
+ * HostNackHandlerTimeout mechanism. This bit is cleared when
+ * Control.EnableHost is set by software to start a new transaction.
+ */
+ StatusHostDisabledNackTimeout = 1 << 10,
+ };
+
+ /// FormatData Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Issue a START condition before transmitting BYTE.
+ FormatDataStart = 1 << 8,
+ /// Issue a STOP condition after this operation
+ FormatDataStop = 1 << 9,
+ /// Read BYTE bytes from I2C. (256 if BYTE==0)
+ FormatDataReadBytes = 1 << 10,
+ /**
+ * Do not NACK the last byte read, let the read
+ * operation continue
+ */
+ FormatDataReadCount = 1 << 11,
+ /// Do not signal an exception if the current byte is not ACK’d
+ FormatDataNakOk = 1 << 12,
+ };
+
+ /// FifoControl Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Receive fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlReceiveReset = 1 << 0,
+ /// Format fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlFormatReset = 1 << 1,
+ /// Aquired FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlAcquiredReset = 1 << 7,
+ /// Transmit FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlTransmitReset = 1 << 8,
+ };
+
+ /**
+ * Specification times (Table 10) in nanoseconds for each bus mode.
+ */
+ static constexpr uint16_t SpcThigh[] = {4000u, 600u, 260u};
+ static constexpr uint16_t SpcTlow[] = {4700u, 1300u, 150u};
+ static constexpr uint16_t SpcThdSta[] = {4000u, 600u, 260u};
+ static constexpr uint16_t SpcTsuSta[] = {4700u, 600u, 260u};
+ static constexpr uint16_t SpcThdDat[] = {4000u, 1u, 1u};
+ static constexpr uint16_t SpcTsuDat[] = {500u, 100u, 50u};
+ static constexpr uint16_t SpcTBuf[] = {4700u, 1300u, 500u};
+ static constexpr uint16_t SpcTsuSto[] = {4000u, 600u, 260u};
+
+ /// Reset all of the fifos
+ void reset_fifos() volatile
+ {
+ fifoCtrl = (FifoControlReceiveReset | FifoControlFormatReset |
+ FifoControlAcquiredReset | FifoControlTransmitReset);
+ }
+
+ /// Configure the I2C block to be in host mode
+ void set_host_mode() volatile
+ {
+ control = ControlEnableHost;
+ }
+
+ /**
+ * Set the I2C timing parameters appropriately for the given bit rate.
+ * Distilled from:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/programmers_guide.md
+ */
+ void set_speed(const uint32_t SpeedKhz) volatile
+ {
+ // We must round up the system clock frequency to lengthen intervals.
+ constexpr uint32_t SysclkKhz = (I2cDevClockHz + 999) / 1000;
+ // We want to underestimate the clock period, to lengthen the timings.
+ uint32_t clkPeriod = (1000 * 1000) / SysclkKhz;
+
+ // Decide which bus mode this represents
+ uint32_t mode = (SpeedKhz > 100u) + (SpeedKhz > 400u);
+
+ // Calculation of timing parameters
+ uint16_t tHigh =
+ round_up_divide(SpcThigh[mode], clkPeriod); // Spec. min.
+ uint16_t tLow = round_up_divide(SpcTlow[mode], clkPeriod); // Spec. min.
+ uint16_t tFall =
+ round_up_divide(20 * 3 / 5, clkPeriod); // Spec. min. 3.3V
+ uint16_t tRise = round_up_divide(120, clkPeriod);
+ // Setup and Hold times for Start
+ uint16_t thdSta = round_up_divide(SpcThdSta[mode], clkPeriod);
+ uint16_t tsuSta = round_up_divide(SpcTsuSta[mode], clkPeriod);
+ // Setup and Hold times for Data
+ uint16_t thdDat = round_up_divide(SpcThdDat[mode], clkPeriod);
+ uint16_t tsuDat = round_up_divide(SpcTsuDat[mode], clkPeriod);
+ uint16_t tBuf = round_up_divide(SpcTBuf[mode], clkPeriod);
+ uint16_t tsuSto = round_up_divide(SpcTsuSto[mode], clkPeriod); | There's a lot of code duplication here. Would it be cleaner if you created an array of these and iterated over them? Similarly, if `timing0` to `timing4` were exposed as an array, you'd be able to set them all in the same loop.
|
cheriot-rtos | github_2023 | others | 239 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,385 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+static constexpr uint32_t I2cDevClockHz = CPU_TIMER_HZ;
+
+/**
+ * Performs a 32-bit integer unsigned division, rounding up. The bottom
+ * 16 bits of the result are then returned.
+ *
+ * As usual, a divisor of 0 is still Undefined Behavior.
+ */
+static constexpr uint16_t round_up_divide(const uint32_t A, const uint32_t B)
+{
+ if (A == 0)
+ return 0;
+ return static_cast<uint16_t>(((A - 1) / B) + 1);
+}
+
+/**
+ * The interrupts of the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/interfaces.md
+ */
+enum class OpenTitanI2cInterrupt
+{
+ // host mode interrupt: asserted whilst the Format FIFO level is below the
+ // low threshold. This is a level status interrupt.
+ FormatThreshold,
+ // host mode interrupt: asserted whilst the Receive FIFO level is above the
+ // high threshold. This is a level status interrupt.
+ ReceiveThreshold,
+ // target mode interrupt: asserted whilst the Aquired FIFO level is above
+ // the high threshold. This is a level status interrupt.
+ AcquiredThreshold,
+ // host mode interrupt: raised if the Receive FIFO has overflowed.
+ ReceiveOverflow,
+ // host mode interrupt: raised if there is no ACK in response to an address
+ // or data
+ Nak,
+ // host mode interrupt: raised if the SCL line drops early (not supported
+ // without clock synchronization).
+ SclInterference,
+ // host mode interrupt: raised if the SDA line goes low when host is trying
+ // to assert high
+ SdaInterference,
+ // host mode interrupt: raised if target stretches the clock beyond the
+ // allowed timeout period
+ StretchTimeout,
+ // host mode interrupt: raised if the target does not assert a constant
+ // value of SDA during transmission.
+ SdaUnstable,
+ // host and target mode interrupt. In host mode, raised if the host issues a
+ // repeated START or terminates the transaction by issuing STOP. In target
+ // mode, raised if the external host issues a STOP or repeated START.
+ CommandComplete,
+ // target mode interrupt: raised if the target is stretching clocks for a
+ // read command. This is a level status interrupt.
+ TransmitStretch,
+ // target mode interrupt: asserted whilst the Transmit FIFO level is below
+ // the low threshold. This is a level status interrupt.
+ TransmitThreshold,
+ // target mode interrupt: raised if the target is stretching clocks due to
+ // full Aquired FIFO or zero count in targetAckControl.NBYTES (if enabled).
+ // This is a level status interrupt.
+ AcquiredFull,
+ // target mode interrupt: raised if STOP is received without a preceding
+ // NACK during an external host read.
+ UnexpectedStop,
+ // target mode interrupt: raised if the host stops sending the clock during
+ // an ongoing transaction.
+ HostTimeout,
+};
+
+static constexpr uint32_t interrupt_bit(const OpenTitanI2cInterrupt Interrupt)
+{
+ return 1 << static_cast<uint32_t>(Interrupt);
+};
+
+/**
+ * Driver for the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/tree/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c
+ */
+struct OpenTitanI2c
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Alert Test Register (Unused in Sonata)
+ uint32_t alertTest;
+ /// I2C Control Register
+ uint32_t control;
+ /// I2C Live Status Register for Host and Target modes
+ uint32_t status;
+ /// I2C Read Data
+ uint32_t readData;
+ /// I2C Host Format Data
+ uint32_t formatData;
+ /// I2C FIFO control register
+ uint32_t fifoCtrl;
+ /// Host mode FIFO configuration
+ uint32_t hostFifoConfiguration;
+ /// Target mode FIFO configuration
+ uint32_t targetFifoConfiguration;
+ /// Host mode FIFO status register
+ uint32_t hostFifoStatus;
+ /// Target mode FIFO status register
+ uint32_t targetFifoStatus;
+ /// I2C Override Control Register
+ uint32_t override;
+ /// Oversampled Receive values
+ uint32_t values;
+ /**
+ * Detailed I2C Timings (directly corresponding to table 10 in the I2C
+ * Specification).
+ */
+ uint32_t timing0;
+ uint32_t timing1;
+ uint32_t timing2;
+ uint32_t timing3;
+ uint32_t timing4;
+ /// I2C clock stretching timeout control.
+ uint32_t timeoutControl;
+ /// I2C target address and mask pairs
+ uint32_t targetId;
+ /// I2C target acquired data
+ uint32_t acquiredData;
+ /// I2C target transmit data
+ uint32_t transmitData;
+ /**
+ * I2C host clock generation timeout value (in units of input clock
+ * frequency).
+ */
+ uint32_t hostTimeoutControl;
+ /// I2C target internal stretching timeout control.
+ uint32_t targetTimeoutControl;
+ /**
+ * Number of times the I2C target has NACK'ed a new transaction since the
+ * last read of this register.
+ */
+ uint32_t targetNackCount;
+ /**
+ * Timeout in Host-Mode for an unhandled NACK before hardware automatically
+ * ends the transaction.
+ */
+ uint32_t targetAckControl;
+
+ /// Control Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Enable Host I2C functionality
+ ControlEnableHost = 1 << 0,
+ /// Enable Target I2C functionality
+ ControlEnableTarget = 1 << 1,
+ /// Enable I2C line loopback test If line loopback is enabled, the
+ /// internal design sees ACQ and RX data as "1"
+ ControlLineLoopback = 1 << 2,
+ };
+
+ /// Status Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Host mode Format FIFO is full
+ StatusFormatFull = 1 << 0,
+ /// Host mode Receive FIFO is full
+ StatusReceiveFull = 1 << 1,
+ /// Host mode Format FIFO is empty
+ StatusFormatEmpty = 1 << 2,
+ /// Host functionality is idle. No Host transaction is in progress
+ StatusHostIdle = 1 << 3,
+ /// Target functionality is idle. No Target transaction is in progress
+ StatusTargetIdle = 1 << 4,
+ /// Host mode Receive FIFO is empty
+ SmatusReceiveEmpty = 1 << 5,
+ /// Target mode Transmit FIFO is full
+ StatusTransmitFull = 1 << 6,
+ /// Target mode Receive FIFO is full
+ StatusAcquiredFull = 1 << 7,
+ /// Target mode Transmit FIFO is empty
+ StatusTransmitEmpty = 1 << 8,
+ /// Target mode Aquired FIFO is empty
+ StatusAcquiredEmpty = 1 << 9,
+ /**
+ * A Host-Mode active transaction has been ended by the
+ * HostNackHandlerTimeout mechanism. This bit is cleared when
+ * Control.EnableHost is set by software to start a new transaction.
+ */
+ StatusHostDisabledNackTimeout = 1 << 10,
+ };
+
+ /// FormatData Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Issue a START condition before transmitting BYTE.
+ FormatDataStart = 1 << 8,
+ /// Issue a STOP condition after this operation
+ FormatDataStop = 1 << 9,
+ /// Read BYTE bytes from I2C. (256 if BYTE==0)
+ FormatDataReadBytes = 1 << 10,
+ /**
+ * Do not NACK the last byte read, let the read
+ * operation continue
+ */
+ FormatDataReadCount = 1 << 11,
+ /// Do not signal an exception if the current byte is not ACK’d
+ FormatDataNakOk = 1 << 12,
+ };
+
+ /// FifoControl Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Receive fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlReceiveReset = 1 << 0,
+ /// Format fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlFormatReset = 1 << 1,
+ /// Aquired FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlAcquiredReset = 1 << 7,
+ /// Transmit FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlTransmitReset = 1 << 8,
+ };
+
+ /**
+ * Specification times (Table 10) in nanoseconds for each bus mode.
+ */
+ static constexpr uint16_t SpcThigh[] = {4000u, 600u, 260u};
+ static constexpr uint16_t SpcTlow[] = {4700u, 1300u, 150u};
+ static constexpr uint16_t SpcThdSta[] = {4000u, 600u, 260u};
+ static constexpr uint16_t SpcTsuSta[] = {4700u, 600u, 260u};
+ static constexpr uint16_t SpcThdDat[] = {4000u, 1u, 1u};
+ static constexpr uint16_t SpcTsuDat[] = {500u, 100u, 50u};
+ static constexpr uint16_t SpcTBuf[] = {4700u, 1300u, 500u};
+ static constexpr uint16_t SpcTsuSto[] = {4000u, 600u, 260u};
+
+ /// Reset all of the fifos
+ void reset_fifos() volatile
+ {
+ fifoCtrl = (FifoControlReceiveReset | FifoControlFormatReset |
+ FifoControlAcquiredReset | FifoControlTransmitReset);
+ }
+
+ /// Configure the I2C block to be in host mode
+ void set_host_mode() volatile
+ {
+ control = ControlEnableHost;
+ }
+
+ /**
+ * Set the I2C timing parameters appropriately for the given bit rate.
+ * Distilled from:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/programmers_guide.md
+ */
+ void set_speed(const uint32_t SpeedKhz) volatile
+ {
+ // We must round up the system clock frequency to lengthen intervals.
+ constexpr uint32_t SysclkKhz = (I2cDevClockHz + 999) / 1000;
+ // We want to underestimate the clock period, to lengthen the timings.
+ uint32_t clkPeriod = (1000 * 1000) / SysclkKhz;
+
+ // Decide which bus mode this represents
+ uint32_t mode = (SpeedKhz > 100u) + (SpeedKhz > 400u);
+
+ // Calculation of timing parameters
+ uint16_t tHigh =
+ round_up_divide(SpcThigh[mode], clkPeriod); // Spec. min.
+ uint16_t tLow = round_up_divide(SpcTlow[mode], clkPeriod); // Spec. min.
+ uint16_t tFall =
+ round_up_divide(20 * 3 / 5, clkPeriod); // Spec. min. 3.3V
+ uint16_t tRise = round_up_divide(120, clkPeriod);
+ // Setup and Hold times for Start
+ uint16_t thdSta = round_up_divide(SpcThdSta[mode], clkPeriod);
+ uint16_t tsuSta = round_up_divide(SpcTsuSta[mode], clkPeriod);
+ // Setup and Hold times for Data
+ uint16_t thdDat = round_up_divide(SpcThdDat[mode], clkPeriod);
+ uint16_t tsuDat = round_up_divide(SpcTsuDat[mode], clkPeriod);
+ uint16_t tBuf = round_up_divide(SpcTBuf[mode], clkPeriod);
+ uint16_t tsuSto = round_up_divide(SpcTsuSto[mode], clkPeriod);
+
+ // Prevent counters underflowing
+ if (tLow < thdDat + 1u)
+ tLow = thdDat + 1u;
+ if (tBuf < tsuSta + 1u)
+ tBuf = tsuSta + 1u;
+
+ timing0 = (tLow << 16) | tHigh;
+ timing1 = (tFall << 16) | tRise;
+ timing2 = (thdSta << 16) | tsuSta;
+ timing3 = (thdDat << 16) | tsuDat;
+ timing4 = (tBuf << 16) | tsuSto;
+ }
+
+ void blocking_write_byte(const uint32_t Fmt) volatile
+ {
+ while (0 != (StatusFormatFull & status)) {}
+ formatData = Fmt;
+ }
+
+ /// Returns true when the format fifo is empty
+ [[nodiscard]] bool format_empty() volatile | Predicates should normally include `is` or `are` in their names. This one is particularly bad. We have an explicit style rule to avoid words that are both verbs and nouns and, in this case, format and empty are *both* verbs and nouns and I don't know if this is a thing that formats an empty thing, empties a format, or some combination of the two. |
cheriot-rtos | github_2023 | others | 239 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,385 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+static constexpr uint32_t I2cDevClockHz = CPU_TIMER_HZ;
+
+/**
+ * Performs a 32-bit integer unsigned division, rounding up. The bottom
+ * 16 bits of the result are then returned.
+ *
+ * As usual, a divisor of 0 is still Undefined Behavior.
+ */
+static constexpr uint16_t round_up_divide(const uint32_t A, const uint32_t B)
+{
+ if (A == 0)
+ return 0;
+ return static_cast<uint16_t>(((A - 1) / B) + 1);
+}
+
+/**
+ * The interrupts of the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/interfaces.md
+ */
+enum class OpenTitanI2cInterrupt
+{
+ // host mode interrupt: asserted whilst the Format FIFO level is below the
+ // low threshold. This is a level status interrupt.
+ FormatThreshold,
+ // host mode interrupt: asserted whilst the Receive FIFO level is above the
+ // high threshold. This is a level status interrupt.
+ ReceiveThreshold,
+ // target mode interrupt: asserted whilst the Aquired FIFO level is above
+ // the high threshold. This is a level status interrupt.
+ AcquiredThreshold,
+ // host mode interrupt: raised if the Receive FIFO has overflowed.
+ ReceiveOverflow,
+ // host mode interrupt: raised if there is no ACK in response to an address
+ // or data
+ Nak,
+ // host mode interrupt: raised if the SCL line drops early (not supported
+ // without clock synchronization).
+ SclInterference,
+ // host mode interrupt: raised if the SDA line goes low when host is trying
+ // to assert high
+ SdaInterference,
+ // host mode interrupt: raised if target stretches the clock beyond the
+ // allowed timeout period
+ StretchTimeout,
+ // host mode interrupt: raised if the target does not assert a constant
+ // value of SDA during transmission.
+ SdaUnstable,
+ // host and target mode interrupt. In host mode, raised if the host issues a
+ // repeated START or terminates the transaction by issuing STOP. In target
+ // mode, raised if the external host issues a STOP or repeated START.
+ CommandComplete,
+ // target mode interrupt: raised if the target is stretching clocks for a
+ // read command. This is a level status interrupt.
+ TransmitStretch,
+ // target mode interrupt: asserted whilst the Transmit FIFO level is below
+ // the low threshold. This is a level status interrupt.
+ TransmitThreshold,
+ // target mode interrupt: raised if the target is stretching clocks due to
+ // full Aquired FIFO or zero count in targetAckControl.NBYTES (if enabled).
+ // This is a level status interrupt.
+ AcquiredFull,
+ // target mode interrupt: raised if STOP is received without a preceding
+ // NACK during an external host read.
+ UnexpectedStop,
+ // target mode interrupt: raised if the host stops sending the clock during
+ // an ongoing transaction.
+ HostTimeout,
+};
+
+static constexpr uint32_t interrupt_bit(const OpenTitanI2cInterrupt Interrupt)
+{
+ return 1 << static_cast<uint32_t>(Interrupt);
+};
+
+/**
+ * Driver for the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/tree/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c
+ */
+struct OpenTitanI2c
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Alert Test Register (Unused in Sonata)
+ uint32_t alertTest;
+ /// I2C Control Register
+ uint32_t control;
+ /// I2C Live Status Register for Host and Target modes
+ uint32_t status;
+ /// I2C Read Data
+ uint32_t readData;
+ /// I2C Host Format Data
+ uint32_t formatData;
+ /// I2C FIFO control register
+ uint32_t fifoCtrl;
+ /// Host mode FIFO configuration
+ uint32_t hostFifoConfiguration;
+ /// Target mode FIFO configuration
+ uint32_t targetFifoConfiguration;
+ /// Host mode FIFO status register
+ uint32_t hostFifoStatus;
+ /// Target mode FIFO status register
+ uint32_t targetFifoStatus;
+ /// I2C Override Control Register
+ uint32_t override;
+ /// Oversampled Receive values
+ uint32_t values;
+ /**
+ * Detailed I2C Timings (directly corresponding to table 10 in the I2C
+ * Specification).
+ */
+ uint32_t timing0;
+ uint32_t timing1;
+ uint32_t timing2;
+ uint32_t timing3;
+ uint32_t timing4;
+ /// I2C clock stretching timeout control.
+ uint32_t timeoutControl;
+ /// I2C target address and mask pairs
+ uint32_t targetId;
+ /// I2C target acquired data
+ uint32_t acquiredData;
+ /// I2C target transmit data
+ uint32_t transmitData;
+ /**
+ * I2C host clock generation timeout value (in units of input clock
+ * frequency).
+ */
+ uint32_t hostTimeoutControl;
+ /// I2C target internal stretching timeout control.
+ uint32_t targetTimeoutControl;
+ /**
+ * Number of times the I2C target has NACK'ed a new transaction since the
+ * last read of this register.
+ */
+ uint32_t targetNackCount;
+ /**
+ * Timeout in Host-Mode for an unhandled NACK before hardware automatically
+ * ends the transaction.
+ */
+ uint32_t targetAckControl;
+
+ /// Control Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Enable Host I2C functionality
+ ControlEnableHost = 1 << 0,
+ /// Enable Target I2C functionality
+ ControlEnableTarget = 1 << 1,
+ /// Enable I2C line loopback test If line loopback is enabled, the
+ /// internal design sees ACQ and RX data as "1"
+ ControlLineLoopback = 1 << 2,
+ };
+
+ /// Status Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Host mode Format FIFO is full
+ StatusFormatFull = 1 << 0,
+ /// Host mode Receive FIFO is full
+ StatusReceiveFull = 1 << 1,
+ /// Host mode Format FIFO is empty
+ StatusFormatEmpty = 1 << 2,
+ /// Host functionality is idle. No Host transaction is in progress
+ StatusHostIdle = 1 << 3,
+ /// Target functionality is idle. No Target transaction is in progress
+ StatusTargetIdle = 1 << 4,
+ /// Host mode Receive FIFO is empty
+ SmatusReceiveEmpty = 1 << 5,
+ /// Target mode Transmit FIFO is full
+ StatusTransmitFull = 1 << 6,
+ /// Target mode Receive FIFO is full
+ StatusAcquiredFull = 1 << 7,
+ /// Target mode Transmit FIFO is empty
+ StatusTransmitEmpty = 1 << 8,
+ /// Target mode Aquired FIFO is empty
+ StatusAcquiredEmpty = 1 << 9,
+ /**
+ * A Host-Mode active transaction has been ended by the
+ * HostNackHandlerTimeout mechanism. This bit is cleared when
+ * Control.EnableHost is set by software to start a new transaction.
+ */
+ StatusHostDisabledNackTimeout = 1 << 10,
+ };
+
+ /// FormatData Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Issue a START condition before transmitting BYTE.
+ FormatDataStart = 1 << 8,
+ /// Issue a STOP condition after this operation
+ FormatDataStop = 1 << 9,
+ /// Read BYTE bytes from I2C. (256 if BYTE==0)
+ FormatDataReadBytes = 1 << 10,
+ /**
+ * Do not NACK the last byte read, let the read
+ * operation continue
+ */
+ FormatDataReadCount = 1 << 11,
+ /// Do not signal an exception if the current byte is not ACK’d
+ FormatDataNakOk = 1 << 12,
+ };
+
+ /// FifoControl Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Receive fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlReceiveReset = 1 << 0,
+ /// Format fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlFormatReset = 1 << 1,
+ /// Aquired FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlAcquiredReset = 1 << 7,
+ /// Transmit FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlTransmitReset = 1 << 8,
+ };
+
+ /**
+ * Specification times (Table 10) in nanoseconds for each bus mode.
+ */
+ static constexpr uint16_t SpcThigh[] = {4000u, 600u, 260u};
+ static constexpr uint16_t SpcTlow[] = {4700u, 1300u, 150u};
+ static constexpr uint16_t SpcThdSta[] = {4000u, 600u, 260u};
+ static constexpr uint16_t SpcTsuSta[] = {4700u, 600u, 260u};
+ static constexpr uint16_t SpcThdDat[] = {4000u, 1u, 1u};
+ static constexpr uint16_t SpcTsuDat[] = {500u, 100u, 50u};
+ static constexpr uint16_t SpcTBuf[] = {4700u, 1300u, 500u};
+ static constexpr uint16_t SpcTsuSto[] = {4000u, 600u, 260u};
+
+ /// Reset all of the fifos
+ void reset_fifos() volatile
+ {
+ fifoCtrl = (FifoControlReceiveReset | FifoControlFormatReset |
+ FifoControlAcquiredReset | FifoControlTransmitReset);
+ }
+
+ /// Configure the I2C block to be in host mode
+ void set_host_mode() volatile
+ {
+ control = ControlEnableHost;
+ }
+
+ /**
+ * Set the I2C timing parameters appropriately for the given bit rate.
+ * Distilled from:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/programmers_guide.md
+ */
+ void set_speed(const uint32_t SpeedKhz) volatile
+ {
+ // We must round up the system clock frequency to lengthen intervals.
+ constexpr uint32_t SysclkKhz = (I2cDevClockHz + 999) / 1000;
+ // We want to underestimate the clock period, to lengthen the timings.
+ uint32_t clkPeriod = (1000 * 1000) / SysclkKhz;
+
+ // Decide which bus mode this represents
+ uint32_t mode = (SpeedKhz > 100u) + (SpeedKhz > 400u);
+
+ // Calculation of timing parameters
+ uint16_t tHigh =
+ round_up_divide(SpcThigh[mode], clkPeriod); // Spec. min.
+ uint16_t tLow = round_up_divide(SpcTlow[mode], clkPeriod); // Spec. min.
+ uint16_t tFall =
+ round_up_divide(20 * 3 / 5, clkPeriod); // Spec. min. 3.3V
+ uint16_t tRise = round_up_divide(120, clkPeriod);
+ // Setup and Hold times for Start
+ uint16_t thdSta = round_up_divide(SpcThdSta[mode], clkPeriod);
+ uint16_t tsuSta = round_up_divide(SpcTsuSta[mode], clkPeriod);
+ // Setup and Hold times for Data
+ uint16_t thdDat = round_up_divide(SpcThdDat[mode], clkPeriod);
+ uint16_t tsuDat = round_up_divide(SpcTsuDat[mode], clkPeriod);
+ uint16_t tBuf = round_up_divide(SpcTBuf[mode], clkPeriod);
+ uint16_t tsuSto = round_up_divide(SpcTsuSto[mode], clkPeriod);
+
+ // Prevent counters underflowing
+ if (tLow < thdDat + 1u)
+ tLow = thdDat + 1u;
+ if (tBuf < tsuSta + 1u)
+ tBuf = tsuSta + 1u;
+
+ timing0 = (tLow << 16) | tHigh;
+ timing1 = (tFall << 16) | tRise;
+ timing2 = (thdSta << 16) | tsuSta;
+ timing3 = (thdDat << 16) | tsuDat;
+ timing4 = (tBuf << 16) | tsuSto;
+ }
+
+ void blocking_write_byte(const uint32_t Fmt) volatile
+ {
+ while (0 != (StatusFormatFull & status)) {}
+ formatData = Fmt;
+ }
+
+ /// Returns true when the format fifo is empty
+ [[nodiscard]] bool format_empty() volatile
+ {
+ return 0 != (StatusFormatEmpty & status);
+ }
+
+ void blocking_write(const uint8_t Addr7,
+ const uint8_t data[],
+ const uint32_t NumBytes,
+ const bool SkipStop) volatile
+ {
+ if (NumBytes == 0)
+ return; | Missing braces. |
cheriot-rtos | github_2023 | others | 239 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,385 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+static constexpr uint32_t I2cDevClockHz = CPU_TIMER_HZ;
+
+/**
+ * Performs a 32-bit integer unsigned division, rounding up. The bottom
+ * 16 bits of the result are then returned.
+ *
+ * As usual, a divisor of 0 is still Undefined Behavior.
+ */
+static constexpr uint16_t round_up_divide(const uint32_t A, const uint32_t B)
+{
+ if (A == 0)
+ return 0;
+ return static_cast<uint16_t>(((A - 1) / B) + 1);
+}
+
+/**
+ * The interrupts of the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/interfaces.md
+ */
+enum class OpenTitanI2cInterrupt
+{
+ // host mode interrupt: asserted whilst the Format FIFO level is below the
+ // low threshold. This is a level status interrupt.
+ FormatThreshold,
+ // host mode interrupt: asserted whilst the Receive FIFO level is above the
+ // high threshold. This is a level status interrupt.
+ ReceiveThreshold,
+ // target mode interrupt: asserted whilst the Aquired FIFO level is above
+ // the high threshold. This is a level status interrupt.
+ AcquiredThreshold,
+ // host mode interrupt: raised if the Receive FIFO has overflowed.
+ ReceiveOverflow,
+ // host mode interrupt: raised if there is no ACK in response to an address
+ // or data
+ Nak,
+ // host mode interrupt: raised if the SCL line drops early (not supported
+ // without clock synchronization).
+ SclInterference,
+ // host mode interrupt: raised if the SDA line goes low when host is trying
+ // to assert high
+ SdaInterference,
+ // host mode interrupt: raised if target stretches the clock beyond the
+ // allowed timeout period
+ StretchTimeout,
+ // host mode interrupt: raised if the target does not assert a constant
+ // value of SDA during transmission.
+ SdaUnstable,
+ // host and target mode interrupt. In host mode, raised if the host issues a
+ // repeated START or terminates the transaction by issuing STOP. In target
+ // mode, raised if the external host issues a STOP or repeated START.
+ CommandComplete,
+ // target mode interrupt: raised if the target is stretching clocks for a
+ // read command. This is a level status interrupt.
+ TransmitStretch,
+ // target mode interrupt: asserted whilst the Transmit FIFO level is below
+ // the low threshold. This is a level status interrupt.
+ TransmitThreshold,
+ // target mode interrupt: raised if the target is stretching clocks due to
+ // full Aquired FIFO or zero count in targetAckControl.NBYTES (if enabled).
+ // This is a level status interrupt.
+ AcquiredFull,
+ // target mode interrupt: raised if STOP is received without a preceding
+ // NACK during an external host read.
+ UnexpectedStop,
+ // target mode interrupt: raised if the host stops sending the clock during
+ // an ongoing transaction.
+ HostTimeout,
+};
+
+static constexpr uint32_t interrupt_bit(const OpenTitanI2cInterrupt Interrupt)
+{
+ return 1 << static_cast<uint32_t>(Interrupt);
+};
+
+/**
+ * Driver for the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/tree/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c
+ */
+struct OpenTitanI2c
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Alert Test Register (Unused in Sonata)
+ uint32_t alertTest;
+ /// I2C Control Register
+ uint32_t control;
+ /// I2C Live Status Register for Host and Target modes
+ uint32_t status;
+ /// I2C Read Data
+ uint32_t readData;
+ /// I2C Host Format Data
+ uint32_t formatData;
+ /// I2C FIFO control register
+ uint32_t fifoCtrl;
+ /// Host mode FIFO configuration
+ uint32_t hostFifoConfiguration;
+ /// Target mode FIFO configuration
+ uint32_t targetFifoConfiguration;
+ /// Host mode FIFO status register
+ uint32_t hostFifoStatus;
+ /// Target mode FIFO status register
+ uint32_t targetFifoStatus;
+ /// I2C Override Control Register
+ uint32_t override;
+ /// Oversampled Receive values
+ uint32_t values;
+ /**
+ * Detailed I2C Timings (directly corresponding to table 10 in the I2C
+ * Specification).
+ */
+ uint32_t timing0;
+ uint32_t timing1;
+ uint32_t timing2;
+ uint32_t timing3;
+ uint32_t timing4;
+ /// I2C clock stretching timeout control.
+ uint32_t timeoutControl;
+ /// I2C target address and mask pairs
+ uint32_t targetId;
+ /// I2C target acquired data
+ uint32_t acquiredData;
+ /// I2C target transmit data
+ uint32_t transmitData;
+ /**
+ * I2C host clock generation timeout value (in units of input clock
+ * frequency).
+ */
+ uint32_t hostTimeoutControl;
+ /// I2C target internal stretching timeout control.
+ uint32_t targetTimeoutControl;
+ /**
+ * Number of times the I2C target has NACK'ed a new transaction since the
+ * last read of this register.
+ */
+ uint32_t targetNackCount;
+ /**
+ * Timeout in Host-Mode for an unhandled NACK before hardware automatically
+ * ends the transaction.
+ */
+ uint32_t targetAckControl;
+
+ /// Control Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Enable Host I2C functionality
+ ControlEnableHost = 1 << 0,
+ /// Enable Target I2C functionality
+ ControlEnableTarget = 1 << 1,
+ /// Enable I2C line loopback test If line loopback is enabled, the
+ /// internal design sees ACQ and RX data as "1"
+ ControlLineLoopback = 1 << 2,
+ };
+
+ /// Status Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Host mode Format FIFO is full
+ StatusFormatFull = 1 << 0,
+ /// Host mode Receive FIFO is full
+ StatusReceiveFull = 1 << 1,
+ /// Host mode Format FIFO is empty
+ StatusFormatEmpty = 1 << 2,
+ /// Host functionality is idle. No Host transaction is in progress
+ StatusHostIdle = 1 << 3,
+ /// Target functionality is idle. No Target transaction is in progress
+ StatusTargetIdle = 1 << 4,
+ /// Host mode Receive FIFO is empty
+ SmatusReceiveEmpty = 1 << 5,
+ /// Target mode Transmit FIFO is full
+ StatusTransmitFull = 1 << 6,
+ /// Target mode Receive FIFO is full
+ StatusAcquiredFull = 1 << 7,
+ /// Target mode Transmit FIFO is empty
+ StatusTransmitEmpty = 1 << 8,
+ /// Target mode Aquired FIFO is empty
+ StatusAcquiredEmpty = 1 << 9,
+ /**
+ * A Host-Mode active transaction has been ended by the
+ * HostNackHandlerTimeout mechanism. This bit is cleared when
+ * Control.EnableHost is set by software to start a new transaction.
+ */
+ StatusHostDisabledNackTimeout = 1 << 10,
+ };
+
+ /// FormatData Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Issue a START condition before transmitting BYTE.
+ FormatDataStart = 1 << 8,
+ /// Issue a STOP condition after this operation
+ FormatDataStop = 1 << 9,
+ /// Read BYTE bytes from I2C. (256 if BYTE==0)
+ FormatDataReadBytes = 1 << 10,
+ /**
+ * Do not NACK the last byte read, let the read
+ * operation continue
+ */
+ FormatDataReadCount = 1 << 11,
+ /// Do not signal an exception if the current byte is not ACK’d
+ FormatDataNakOk = 1 << 12,
+ };
+
+ /// FifoControl Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Receive fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlReceiveReset = 1 << 0,
+ /// Format fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlFormatReset = 1 << 1,
+ /// Aquired FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlAcquiredReset = 1 << 7,
+ /// Transmit FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlTransmitReset = 1 << 8,
+ };
+
+ /**
+ * Specification times (Table 10) in nanoseconds for each bus mode.
+ */
+ static constexpr uint16_t SpcThigh[] = {4000u, 600u, 260u};
+ static constexpr uint16_t SpcTlow[] = {4700u, 1300u, 150u};
+ static constexpr uint16_t SpcThdSta[] = {4000u, 600u, 260u};
+ static constexpr uint16_t SpcTsuSta[] = {4700u, 600u, 260u};
+ static constexpr uint16_t SpcThdDat[] = {4000u, 1u, 1u};
+ static constexpr uint16_t SpcTsuDat[] = {500u, 100u, 50u};
+ static constexpr uint16_t SpcTBuf[] = {4700u, 1300u, 500u};
+ static constexpr uint16_t SpcTsuSto[] = {4000u, 600u, 260u};
+
+ /// Reset all of the fifos
+ void reset_fifos() volatile
+ {
+ fifoCtrl = (FifoControlReceiveReset | FifoControlFormatReset |
+ FifoControlAcquiredReset | FifoControlTransmitReset);
+ }
+
+ /// Configure the I2C block to be in host mode
+ void set_host_mode() volatile
+ {
+ control = ControlEnableHost;
+ }
+
+ /**
+ * Set the I2C timing parameters appropriately for the given bit rate.
+ * Distilled from:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/programmers_guide.md
+ */
+ void set_speed(const uint32_t SpeedKhz) volatile
+ {
+ // We must round up the system clock frequency to lengthen intervals.
+ constexpr uint32_t SysclkKhz = (I2cDevClockHz + 999) / 1000;
+ // We want to underestimate the clock period, to lengthen the timings.
+ uint32_t clkPeriod = (1000 * 1000) / SysclkKhz;
+
+ // Decide which bus mode this represents
+ uint32_t mode = (SpeedKhz > 100u) + (SpeedKhz > 400u);
+
+ // Calculation of timing parameters
+ uint16_t tHigh =
+ round_up_divide(SpcThigh[mode], clkPeriod); // Spec. min.
+ uint16_t tLow = round_up_divide(SpcTlow[mode], clkPeriod); // Spec. min.
+ uint16_t tFall =
+ round_up_divide(20 * 3 / 5, clkPeriod); // Spec. min. 3.3V
+ uint16_t tRise = round_up_divide(120, clkPeriod);
+ // Setup and Hold times for Start
+ uint16_t thdSta = round_up_divide(SpcThdSta[mode], clkPeriod);
+ uint16_t tsuSta = round_up_divide(SpcTsuSta[mode], clkPeriod);
+ // Setup and Hold times for Data
+ uint16_t thdDat = round_up_divide(SpcThdDat[mode], clkPeriod);
+ uint16_t tsuDat = round_up_divide(SpcTsuDat[mode], clkPeriod);
+ uint16_t tBuf = round_up_divide(SpcTBuf[mode], clkPeriod);
+ uint16_t tsuSto = round_up_divide(SpcTsuSto[mode], clkPeriod);
+
+ // Prevent counters underflowing
+ if (tLow < thdDat + 1u)
+ tLow = thdDat + 1u;
+ if (tBuf < tsuSta + 1u)
+ tBuf = tsuSta + 1u;
+
+ timing0 = (tLow << 16) | tHigh;
+ timing1 = (tFall << 16) | tRise;
+ timing2 = (thdSta << 16) | tsuSta;
+ timing3 = (thdDat << 16) | tsuDat;
+ timing4 = (tBuf << 16) | tsuSto;
+ }
+
+ void blocking_write_byte(const uint32_t Fmt) volatile
+ {
+ while (0 != (StatusFormatFull & status)) {}
+ formatData = Fmt;
+ }
+
+ /// Returns true when the format fifo is empty
+ [[nodiscard]] bool format_empty() volatile
+ {
+ return 0 != (StatusFormatEmpty & status);
+ }
+
+ void blocking_write(const uint8_t Addr7,
+ const uint8_t data[],
+ const uint32_t NumBytes,
+ const bool SkipStop) volatile
+ {
+ if (NumBytes == 0)
+ return;
+ blocking_write_byte(FormatDataStart | (Addr7 << 1) | 0u);
+ for (uint32_t i = 0; i < NumBytes - 1; ++i)
+ {
+ blocking_write_byte(data[i]);
+ }
+ blocking_write_byte((SkipStop ? 0u : FormatDataStop) |
+ data[NumBytes - 1]);
+ }
+
+ [[nodiscard]] bool blocking_read(const uint8_t Addr7,
+ uint8_t buf[],
+ const uint32_t NumBytes) volatile
+ {
+ for (uint32_t idx = 0; idx < NumBytes; idx += UINT8_MAX)
+ {
+ blocking_write_byte(FormatDataStart | (Addr7 << 1) | 1u);
+ while (!format_empty()) {}
+ if (interrupt_asserted(OpenTitanI2cInterrupt::Nak))
+ {
+ clear_interrupt(OpenTitanI2cInterrupt::Nak);
+ return false;
+ }
+ uint32_t bytesRemaining = NumBytes - idx;
+ bool lastChunk = UINT8_MAX >= bytesRemaining;
+ uint8_t chunkSize =
+ lastChunk ? static_cast<uint8_t>(bytesRemaining) : UINT8_MAX;
+
+ blocking_write_byte((lastChunk ? FormatDataStop : 0) |
+ FormatDataReadBytes | chunkSize);
+ while (!format_empty()) {}
+
+ for (uint32_t chunkIdx = 0; chunkIdx < chunkSize; ++chunkIdx)
+ {
+ buf[idx + chunkIdx] = readData;
+ }
+ }
+ return true;
+ }
+
+ /// Returns true if the given interrupt is asserted.
+ [[nodiscard]] bool
+ interrupt_asserted(const OpenTitanI2cInterrupt Interrupt) volatile | Consider `interrupt_is_asserted`.
Avoid `const` for value parameters.
This could also do with some explanation of how these relate to interrupts in the interrupt controller. |
cheriot-rtos | github_2023 | others | 239 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,385 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+static constexpr uint32_t I2cDevClockHz = CPU_TIMER_HZ;
+
+/**
+ * Performs a 32-bit integer unsigned division, rounding up. The bottom
+ * 16 bits of the result are then returned.
+ *
+ * As usual, a divisor of 0 is still Undefined Behavior.
+ */
+static constexpr uint16_t round_up_divide(const uint32_t A, const uint32_t B)
+{
+ if (A == 0)
+ return 0;
+ return static_cast<uint16_t>(((A - 1) / B) + 1);
+}
+
+/**
+ * The interrupts of the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/interfaces.md
+ */
+enum class OpenTitanI2cInterrupt
+{
+ // host mode interrupt: asserted whilst the Format FIFO level is below the
+ // low threshold. This is a level status interrupt.
+ FormatThreshold,
+ // host mode interrupt: asserted whilst the Receive FIFO level is above the
+ // high threshold. This is a level status interrupt.
+ ReceiveThreshold,
+ // target mode interrupt: asserted whilst the Aquired FIFO level is above
+ // the high threshold. This is a level status interrupt.
+ AcquiredThreshold,
+ // host mode interrupt: raised if the Receive FIFO has overflowed.
+ ReceiveOverflow,
+ // host mode interrupt: raised if there is no ACK in response to an address
+ // or data
+ Nak,
+ // host mode interrupt: raised if the SCL line drops early (not supported
+ // without clock synchronization).
+ SclInterference,
+ // host mode interrupt: raised if the SDA line goes low when host is trying
+ // to assert high
+ SdaInterference,
+ // host mode interrupt: raised if target stretches the clock beyond the
+ // allowed timeout period
+ StretchTimeout,
+ // host mode interrupt: raised if the target does not assert a constant
+ // value of SDA during transmission.
+ SdaUnstable,
+ // host and target mode interrupt. In host mode, raised if the host issues a
+ // repeated START or terminates the transaction by issuing STOP. In target
+ // mode, raised if the external host issues a STOP or repeated START.
+ CommandComplete,
+ // target mode interrupt: raised if the target is stretching clocks for a
+ // read command. This is a level status interrupt.
+ TransmitStretch,
+ // target mode interrupt: asserted whilst the Transmit FIFO level is below
+ // the low threshold. This is a level status interrupt.
+ TransmitThreshold,
+ // target mode interrupt: raised if the target is stretching clocks due to
+ // full Aquired FIFO or zero count in targetAckControl.NBYTES (if enabled).
+ // This is a level status interrupt.
+ AcquiredFull,
+ // target mode interrupt: raised if STOP is received without a preceding
+ // NACK during an external host read.
+ UnexpectedStop,
+ // target mode interrupt: raised if the host stops sending the clock during
+ // an ongoing transaction.
+ HostTimeout,
+};
+
+static constexpr uint32_t interrupt_bit(const OpenTitanI2cInterrupt Interrupt)
+{
+ return 1 << static_cast<uint32_t>(Interrupt);
+};
+
+/**
+ * Driver for the OpenTitan's I2C block.
+ *
+ * Documentation source can be found at:
+ * https://github.com/lowRISC/opentitan/tree/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c
+ */
+struct OpenTitanI2c
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Alert Test Register (Unused in Sonata)
+ uint32_t alertTest;
+ /// I2C Control Register
+ uint32_t control;
+ /// I2C Live Status Register for Host and Target modes
+ uint32_t status;
+ /// I2C Read Data
+ uint32_t readData;
+ /// I2C Host Format Data
+ uint32_t formatData;
+ /// I2C FIFO control register
+ uint32_t fifoCtrl;
+ /// Host mode FIFO configuration
+ uint32_t hostFifoConfiguration;
+ /// Target mode FIFO configuration
+ uint32_t targetFifoConfiguration;
+ /// Host mode FIFO status register
+ uint32_t hostFifoStatus;
+ /// Target mode FIFO status register
+ uint32_t targetFifoStatus;
+ /// I2C Override Control Register
+ uint32_t override;
+ /// Oversampled Receive values
+ uint32_t values;
+ /**
+ * Detailed I2C Timings (directly corresponding to table 10 in the I2C
+ * Specification).
+ */
+ uint32_t timing0;
+ uint32_t timing1;
+ uint32_t timing2;
+ uint32_t timing3;
+ uint32_t timing4;
+ /// I2C clock stretching timeout control.
+ uint32_t timeoutControl;
+ /// I2C target address and mask pairs
+ uint32_t targetId;
+ /// I2C target acquired data
+ uint32_t acquiredData;
+ /// I2C target transmit data
+ uint32_t transmitData;
+ /**
+ * I2C host clock generation timeout value (in units of input clock
+ * frequency).
+ */
+ uint32_t hostTimeoutControl;
+ /// I2C target internal stretching timeout control.
+ uint32_t targetTimeoutControl;
+ /**
+ * Number of times the I2C target has NACK'ed a new transaction since the
+ * last read of this register.
+ */
+ uint32_t targetNackCount;
+ /**
+ * Timeout in Host-Mode for an unhandled NACK before hardware automatically
+ * ends the transaction.
+ */
+ uint32_t targetAckControl;
+
+ /// Control Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Enable Host I2C functionality
+ ControlEnableHost = 1 << 0,
+ /// Enable Target I2C functionality
+ ControlEnableTarget = 1 << 1,
+ /// Enable I2C line loopback test If line loopback is enabled, the
+ /// internal design sees ACQ and RX data as "1"
+ ControlLineLoopback = 1 << 2,
+ };
+
+ /// Status Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Host mode Format FIFO is full
+ StatusFormatFull = 1 << 0,
+ /// Host mode Receive FIFO is full
+ StatusReceiveFull = 1 << 1,
+ /// Host mode Format FIFO is empty
+ StatusFormatEmpty = 1 << 2,
+ /// Host functionality is idle. No Host transaction is in progress
+ StatusHostIdle = 1 << 3,
+ /// Target functionality is idle. No Target transaction is in progress
+ StatusTargetIdle = 1 << 4,
+ /// Host mode Receive FIFO is empty
+ SmatusReceiveEmpty = 1 << 5,
+ /// Target mode Transmit FIFO is full
+ StatusTransmitFull = 1 << 6,
+ /// Target mode Receive FIFO is full
+ StatusAcquiredFull = 1 << 7,
+ /// Target mode Transmit FIFO is empty
+ StatusTransmitEmpty = 1 << 8,
+ /// Target mode Aquired FIFO is empty
+ StatusAcquiredEmpty = 1 << 9,
+ /**
+ * A Host-Mode active transaction has been ended by the
+ * HostNackHandlerTimeout mechanism. This bit is cleared when
+ * Control.EnableHost is set by software to start a new transaction.
+ */
+ StatusHostDisabledNackTimeout = 1 << 10,
+ };
+
+ /// FormatData Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Issue a START condition before transmitting BYTE.
+ FormatDataStart = 1 << 8,
+ /// Issue a STOP condition after this operation
+ FormatDataStop = 1 << 9,
+ /// Read BYTE bytes from I2C. (256 if BYTE==0)
+ FormatDataReadBytes = 1 << 10,
+ /**
+ * Do not NACK the last byte read, let the read
+ * operation continue
+ */
+ FormatDataReadCount = 1 << 11,
+ /// Do not signal an exception if the current byte is not ACK’d
+ FormatDataNakOk = 1 << 12,
+ };
+
+ /// FifoControl Register Fields
+ enum [[clang::flag_enum]] : uint32_t{
+ /// Receive fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlReceiveReset = 1 << 0,
+ /// Format fifo reset. Write 1 to the register resets it. Read returns 0
+ FifoControlFormatReset = 1 << 1,
+ /// Aquired FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlAcquiredReset = 1 << 7,
+ /// Transmit FIFO reset. Write 1 to the register resets it. Read returns 0
+ FifoControlTransmitReset = 1 << 8,
+ };
+
+ /**
+ * Specification times (Table 10) in nanoseconds for each bus mode.
+ */
+ static constexpr uint16_t SpcThigh[] = {4000u, 600u, 260u};
+ static constexpr uint16_t SpcTlow[] = {4700u, 1300u, 150u};
+ static constexpr uint16_t SpcThdSta[] = {4000u, 600u, 260u};
+ static constexpr uint16_t SpcTsuSta[] = {4700u, 600u, 260u};
+ static constexpr uint16_t SpcThdDat[] = {4000u, 1u, 1u};
+ static constexpr uint16_t SpcTsuDat[] = {500u, 100u, 50u};
+ static constexpr uint16_t SpcTBuf[] = {4700u, 1300u, 500u};
+ static constexpr uint16_t SpcTsuSto[] = {4000u, 600u, 260u};
+
+ /// Reset all of the fifos
+ void reset_fifos() volatile
+ {
+ fifoCtrl = (FifoControlReceiveReset | FifoControlFormatReset |
+ FifoControlAcquiredReset | FifoControlTransmitReset);
+ }
+
+ /// Configure the I2C block to be in host mode
+ void set_host_mode() volatile
+ {
+ control = ControlEnableHost;
+ }
+
+ /**
+ * Set the I2C timing parameters appropriately for the given bit rate.
+ * Distilled from:
+ * https://github.com/lowRISC/opentitan/blob/9ddf276c64e2974ed8e528e8b2feb00b977861de/hw/ip/i2c/doc/programmers_guide.md
+ */
+ void set_speed(const uint32_t SpeedKhz) volatile
+ {
+ // We must round up the system clock frequency to lengthen intervals.
+ constexpr uint32_t SysclkKhz = (I2cDevClockHz + 999) / 1000;
+ // We want to underestimate the clock period, to lengthen the timings.
+ uint32_t clkPeriod = (1000 * 1000) / SysclkKhz;
+
+ // Decide which bus mode this represents
+ uint32_t mode = (SpeedKhz > 100u) + (SpeedKhz > 400u);
+
+ // Calculation of timing parameters
+ uint16_t tHigh =
+ round_up_divide(SpcThigh[mode], clkPeriod); // Spec. min.
+ uint16_t tLow = round_up_divide(SpcTlow[mode], clkPeriod); // Spec. min.
+ uint16_t tFall =
+ round_up_divide(20 * 3 / 5, clkPeriod); // Spec. min. 3.3V
+ uint16_t tRise = round_up_divide(120, clkPeriod);
+ // Setup and Hold times for Start
+ uint16_t thdSta = round_up_divide(SpcThdSta[mode], clkPeriod);
+ uint16_t tsuSta = round_up_divide(SpcTsuSta[mode], clkPeriod);
+ // Setup and Hold times for Data
+ uint16_t thdDat = round_up_divide(SpcThdDat[mode], clkPeriod);
+ uint16_t tsuDat = round_up_divide(SpcTsuDat[mode], clkPeriod);
+ uint16_t tBuf = round_up_divide(SpcTBuf[mode], clkPeriod);
+ uint16_t tsuSto = round_up_divide(SpcTsuSto[mode], clkPeriod);
+
+ // Prevent counters underflowing
+ if (tLow < thdDat + 1u)
+ tLow = thdDat + 1u;
+ if (tBuf < tsuSta + 1u)
+ tBuf = tsuSta + 1u;
+
+ timing0 = (tLow << 16) | tHigh;
+ timing1 = (tFall << 16) | tRise;
+ timing2 = (thdSta << 16) | tsuSta;
+ timing3 = (thdDat << 16) | tsuDat;
+ timing4 = (tBuf << 16) | tsuSto;
+ }
+
+ void blocking_write_byte(const uint32_t Fmt) volatile
+ {
+ while (0 != (StatusFormatFull & status)) {}
+ formatData = Fmt;
+ }
+
+ /// Returns true when the format fifo is empty
+ [[nodiscard]] bool format_empty() volatile
+ {
+ return 0 != (StatusFormatEmpty & status);
+ }
+
+ void blocking_write(const uint8_t Addr7,
+ const uint8_t data[],
+ const uint32_t NumBytes,
+ const bool SkipStop) volatile
+ {
+ if (NumBytes == 0)
+ return;
+ blocking_write_byte(FormatDataStart | (Addr7 << 1) | 0u);
+ for (uint32_t i = 0; i < NumBytes - 1; ++i)
+ {
+ blocking_write_byte(data[i]);
+ }
+ blocking_write_byte((SkipStop ? 0u : FormatDataStop) |
+ data[NumBytes - 1]);
+ }
+
+ [[nodiscard]] bool blocking_read(const uint8_t Addr7,
+ uint8_t buf[],
+ const uint32_t NumBytes) volatile
+ {
+ for (uint32_t idx = 0; idx < NumBytes; idx += UINT8_MAX)
+ {
+ blocking_write_byte(FormatDataStart | (Addr7 << 1) | 1u);
+ while (!format_empty()) {}
+ if (interrupt_asserted(OpenTitanI2cInterrupt::Nak))
+ {
+ clear_interrupt(OpenTitanI2cInterrupt::Nak);
+ return false;
+ }
+ uint32_t bytesRemaining = NumBytes - idx;
+ bool lastChunk = UINT8_MAX >= bytesRemaining;
+ uint8_t chunkSize =
+ lastChunk ? static_cast<uint8_t>(bytesRemaining) : UINT8_MAX;
+
+ blocking_write_byte((lastChunk ? FormatDataStop : 0) |
+ FormatDataReadBytes | chunkSize);
+ while (!format_empty()) {}
+
+ for (uint32_t chunkIdx = 0; chunkIdx < chunkSize; ++chunkIdx)
+ {
+ buf[idx + chunkIdx] = readData;
+ }
+ }
+ return true;
+ }
+
+ /// Returns true if the given interrupt is asserted.
+ [[nodiscard]] bool
+ interrupt_asserted(const OpenTitanI2cInterrupt Interrupt) volatile
+ {
+ return 0 != (interruptState & interrupt_bit(Interrupt));
+ }
+
+ /// Clears the given interrupt.
+ void clear_interrupt(const OpenTitanI2cInterrupt Interrupt) volatile | Verb-noun again. |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,92 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's GPIO.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ // Interrupt State Register
+ uint32_t intrState; | Please use full words for variable and function names. Our coding guidelines to avoid abbreviations. You know what intr means but the next person looking at this file or seeing it pop up in autocomplete may not.
Same for most of the other fields and methods here. |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,92 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's GPIO.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ // Interrupt State Register | Please make these doc comments (three slashes). |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,92 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's GPIO.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ // Interrupt State Register
+ uint32_t intrState;
+ // Interrupt Enable Register
+ uint32_t intrEnable;
+ // Interrupt Test Register
+ uint32_t intrTest;
+ // Configuration register. Controls how the SPI block transmits
+ uint32_t cfg;
+ // Controls the operation of the SPI block. This register can
+ uint32_t control;
+ // Status information about the SPI block
+ uint32_t status;
+ // When written begins an SPI operation. Writes are ignored when the
+ uint32_t start;
+ // Data from the receive FIFO. When read the data is popped from the
+ uint32_t rxFifo;
+ // Bytes written here are pushed to the transmit FIFO. If the FIFO
+ uint32_t txFifo;
+
+
+ // Initialises the SPI block
+ void
+ init(bool cpol, bool cpha, bool msbFirst, uint16_t halfClkPeriod) volatile
+ {
+ cfg = (cpol ? 1 << 31 : 0) | (cpha ? 1 << 30 : 0) | | What are all of these magic numbers? |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,92 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's GPIO.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ // Interrupt State Register
+ uint32_t intrState;
+ // Interrupt Enable Register
+ uint32_t intrEnable;
+ // Interrupt Test Register
+ uint32_t intrTest;
+ // Configuration register. Controls how the SPI block transmits
+ uint32_t cfg;
+ // Controls the operation of the SPI block. This register can
+ uint32_t control;
+ // Status information about the SPI block
+ uint32_t status;
+ // When written begins an SPI operation. Writes are ignored when the
+ uint32_t start;
+ // Data from the receive FIFO. When read the data is popped from the
+ uint32_t rxFifo;
+ // Bytes written here are pushed to the transmit FIFO. If the FIFO
+ uint32_t txFifo;
+
+
+ // Initialises the SPI block
+ void
+ init(bool cpol, bool cpha, bool msbFirst, uint16_t halfClkPeriod) volatile
+ {
+ cfg = (cpol ? 1 << 31 : 0) | (cpha ? 1 << 30 : 0) |
+ (msbFirst ? 1 << 29 : 0) | halfClkPeriod;
+ }
+
+ // Waits for the SPI device to become idle
+ void wait_idle() volatile
+ {
+ // Wait whilst IDLE field in STATUS is low
+ while ((status & 0x40000) == 0) {}
+ }
+
+ // Sends `len` bytes from the given `data` buffer.
+ void tx(const uint8_t data[], uint32_t len) volatile | That’s fine (though please name these ‘transmit’ and ‘receive’ or similar). We probably should also have a concept covering this interface. |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,92 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's GPIO.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ // Interrupt State Register
+ uint32_t intrState;
+ // Interrupt Enable Register
+ uint32_t intrEnable;
+ // Interrupt Test Register
+ uint32_t intrTest;
+ // Configuration register. Controls how the SPI block transmits
+ uint32_t cfg;
+ // Controls the operation of the SPI block. This register can
+ uint32_t control;
+ // Status information about the SPI block
+ uint32_t status;
+ // When written begins an SPI operation. Writes are ignored when the
+ uint32_t start;
+ // Data from the receive FIFO. When read the data is popped from the
+ uint32_t rxFifo;
+ // Bytes written here are pushed to the transmit FIFO. If the FIFO
+ uint32_t txFifo;
+
+
+ // Initialises the SPI block
+ void
+ init(bool cpol, bool cpha, bool msbFirst, uint16_t halfClkPeriod) volatile
+ {
+ cfg = (cpol ? 1 << 31 : 0) | (cpha ? 1 << 30 : 0) |
+ (msbFirst ? 1 << 29 : 0) | halfClkPeriod;
+ }
+
+ // Waits for the SPI device to become idle
+ void wait_idle() volatile
+ {
+ // Wait whilst IDLE field in STATUS is low
+ while ((status & 0x40000) == 0) {}
+ }
+
+ // Sends `len` bytes from the given `data` buffer.
+ void tx(const uint8_t data[], uint32_t len) volatile
+ {
+ wait_idle();
+ // Set TX_ENABLE
+ control = 0x4;
+ start = len;
+
+ uint32_t txAvail = 0;
+ for (int i = 0; i < len; ++i)
+ {
+ if (txAvail == 0)
+ {
+ while (txAvail < 64)
+ {
+ // Read number of bytes in TX FIFO to calculate space
+ // available for more bytes
+ txAvail = 64 - (status & 0xff);
+ }
+ }
+
+ txFifo = data[i];
+ txAvail--;
+ }
+ }
+
+ // Receives `len` bytes and puts them in the `data` buffer.
+ void rx(uint8_t data[], uint32_t len) volatile | What is the behaviour of this if there are not the required number of bytes? |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,92 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's GPIO.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ // Interrupt State Register
+ uint32_t intrState;
+ // Interrupt Enable Register
+ uint32_t intrEnable;
+ // Interrupt Test Register
+ uint32_t intrTest;
+ // Configuration register. Controls how the SPI block transmits
+ uint32_t cfg;
+ // Controls the operation of the SPI block. This register can
+ uint32_t control;
+ // Status information about the SPI block
+ uint32_t status;
+ // When written begins an SPI operation. Writes are ignored when the
+ uint32_t start;
+ // Data from the receive FIFO. When read the data is popped from the
+ uint32_t rxFifo;
+ // Bytes written here are pushed to the transmit FIFO. If the FIFO
+ uint32_t txFifo;
+
+
+ // Initialises the SPI block
+ void
+ init(bool cpol, bool cpha, bool msbFirst, uint16_t halfClkPeriod) volatile
+ {
+ cfg = (cpol ? 1 << 31 : 0) | (cpha ? 1 << 30 : 0) |
+ (msbFirst ? 1 << 29 : 0) | halfClkPeriod;
+ }
+
+ // Waits for the SPI device to become idle
+ void wait_idle() volatile
+ {
+ // Wait whilst IDLE field in STATUS is low
+ while ((status & 0x40000) == 0) {}
+ }
+
+ // Sends `len` bytes from the given `data` buffer.
+ void tx(const uint8_t data[], uint32_t len) volatile
+ {
+ wait_idle();
+ // Set TX_ENABLE
+ control = 0x4;
+ start = len;
+
+ uint32_t txAvail = 0;
+ for (int i = 0; i < len; ++i)
+ {
+ if (txAvail == 0)
+ {
+ while (txAvail < 64)
+ {
+ // Read number of bytes in TX FIFO to calculate space
+ // available for more bytes
+ txAvail = 64 - (status & 0xff);
+ }
+ }
+
+ txFifo = data[i];
+ txAvail--;
+ }
+ }
+
+ // Receives `len` bytes and puts them in the `data` buffer.
+ void rx(uint8_t data[], uint32_t len) volatile
+ {
+ wait_idle();
+ // Set RX_ENABLE
+ control = 0x8;
+ start = len;
+
+ for (int i = 0; i < len; ++i)
+ {
+ // Wait for at least one byte to be available in the RX FIFO
+ while (((status >> 8) & 0xff) == 0) {} | I don’t really like this spinning without providing an opportunity to yield. Is there not an interrupt that this can block on? |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | nwf | @@ -0,0 +1,92 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's GPIO. | Copy-paste-o
```suggestion
* A Simple Driver for the Sonata's SPI.
``` |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,171 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's SPI.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Configuration register. Controls how the SPI block transmits and receives
+ /// data. This register can only be modified whilst the SPI block is idle.
+ uint32_t configuration;
+ /// Controls the operation of the SPI block. This register can
+ /// only be modified whilst the SPI block is idle.
+ uint32_t control;
+ /// Status information about the SPI block
+ uint32_t status;
+ /// When written begins 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;
+
+ /// 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. At the
+ /// standard Sonata 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.
+ ConfigurationHalfClkPeriodMask = 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 CPHA 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 CPHA is 1 data is sampled on
+ /// the trailing edge and change on the leading edge.
+ ConfigurationCPHA = 1u << 30,
+ /// The polarity of the spi_clk signal. When CPOL is 0 clock is low when
+ /// idle and the leading edge is positive. When CPOL is 1 clock is high
+ /// when idle and the leading edge is negative
+ ConfigurationCPOL = 1u << 31,
+ };
+
+ /// Control Register Fields
+ enum : uint32_t
+ {
+ /// Write 1 to clear the transmit FIFO.
+ ControlTxClear = 1 << 0,
+ /// Write 1 to clear the receive FIFO.
+ ControlRxClear = 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.
+ ControlTxEnable = 1 << 2,
+ /// When set incoming bits are written to the receive FIFO. When clear
+ /// incoming bits are ignored.
+ ControlRxEnable = 1 << 3,
+ /// The watermark level for the transmit FIFO, depending on the value
+ /// the interrupt will trigger at different points
+ ControlTxWatermarkMask = 0xf << 4,
+ /// The watermark level for the receive FIFO, depending on the value the
+ /// interrupt will trigger at different points
+ ControlRxWatermarkMask = 0xf << 8,
+ };
+
+ /// 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,
+ };
+
+
+ /// Initialises the SPI block | If the code below can use the symbolic constants then that's fine.
I would like the doc comment t explain what the arguments mean. |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,175 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's SPI.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Configuration register. Controls how the SPI block transmits and
+ /// receives data. This register can only be modified whilst the SPI block
+ /// is idle.
+ uint32_t configuration;
+ /// Controls the operation of the SPI block. This register can
+ /// only be modified whilst the SPI block is idle.
+ uint32_t control;
+ /// Status information about the SPI block
+ uint32_t status;
+ /// When written begins 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;
+
+ /// 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. At the
+ /// standard Sonata 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.
+ ConfigurationHalfClkPeriodMask = 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 CPHA 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 CPHA is 1 data is sampled on
+ /// the trailing edge and change on the leading edge.
+ ConfigurationCPHA = 1u << 30,
+ /// The polarity of the spi_clk signal. When CPOL is 0 clock is low when
+ /// idle and the leading edge is positive. When CPOL is 1 clock is high
+ /// when idle and the leading edge is negative
+ ConfigurationCPOL = 1u << 31,
+ };
+
+ /// Control Register Fields
+ enum : uint32_t
+ {
+ /// Write 1 to clear the transmit FIFO.
+ ControlTxClear = 1 << 0,
+ /// Write 1 to clear the receive FIFO.
+ ControlRxClear = 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.
+ ControlTxEnable = 1 << 2,
+ /// When set incoming bits are written to the receive FIFO. When clear
+ /// incoming bits are ignored.
+ ControlRxEnable = 1 << 3,
+ /// The watermark level for the transmit FIFO, depending on the value
+ /// the interrupt will trigger at different points
+ ControlTxWatermarkMask = 0xf << 4,
+ /// The watermark level for the receive FIFO, depending on the value the
+ /// interrupt will trigger at different points
+ ControlRxWatermarkMask = 0xf << 8,
+ };
+
+ /// 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,
+ };
+
+ /// Initialises the SPI block
+ void init(const bool ClkPolarity,
+ const bool ClkPhase,
+ const bool MsbFirst,
+ const uint16_t HalfClkPeriod) volatile
+ {
+ configuration = (ClkPolarity ? 1 << 31 : 0) | (ClkPhase ? 1 << 30 : 0) |
+ (MsbFirst ? 1 << 29 : 0) | HalfClkPeriod;
+ }
+
+ /// Waits for the SPI device to become idle
+ void wait_idle() volatile
+ {
+ // Wait whilst IDLE field in STATUS is low
+ while ((status & StatusIdle) == 0) {}
+ }
+
+ /// Sends `Len` bytes from the given `data` buffer,
+ /// where `Len` is at most `0x7ff`.
+ void transmit(const uint8_t data[], const uint16_t Len) volatile
+ {
+ const uint32_t LenTruncated = Len & StartByteCountMask; | Maybe a `Debug::Assert` that `Len <= 0x7ff`? |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,175 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's SPI.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Configuration register. Controls how the SPI block transmits and | Minor nit, but we normally use `/** */` blocks for multi-line doc comments. |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,175 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's SPI.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Configuration register. Controls how the SPI block transmits and
+ /// receives data. This register can only be modified whilst the SPI block
+ /// is idle.
+ uint32_t configuration;
+ /// Controls the operation of the SPI block. This register can
+ /// only be modified whilst the SPI block is idle. | ```suggestion
/// be modified only whilst the SPI block is idle.
``` |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,175 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's SPI.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Configuration register. Controls how the SPI block transmits and
+ /// receives data. This register can only be modified whilst the SPI block
+ /// is idle.
+ uint32_t configuration;
+ /// Controls the operation of the SPI block. This register can
+ /// only be modified whilst the SPI block is idle.
+ uint32_t control;
+ /// Status information about the SPI block
+ uint32_t status;
+ /// When written begins an SPI operation. | This took a few attempts for me to parse. Maybe 'Writes to this begin an SPI operation'? |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,175 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's SPI.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Configuration register. Controls how the SPI block transmits and
+ /// receives data. This register can only be modified whilst the SPI block
+ /// is idle.
+ uint32_t configuration;
+ /// Controls the operation of the SPI block. This register can
+ /// only be modified whilst the SPI block is idle.
+ uint32_t control;
+ /// Status information about the SPI block
+ uint32_t status;
+ /// When written begins 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;
+
+ /// 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. At the
+ /// standard Sonata 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.
+ ConfigurationHalfClkPeriodMask = 0xffu << 0, | ```suggestion
ConfigurationHalfClockPeriodMask = 0xffu << 0,
``` |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,175 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's SPI.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Configuration register. Controls how the SPI block transmits and
+ /// receives data. This register can only be modified whilst the SPI block
+ /// is idle.
+ uint32_t configuration;
+ /// Controls the operation of the SPI block. This register can
+ /// only be modified whilst the SPI block is idle.
+ uint32_t control;
+ /// Status information about the SPI block
+ uint32_t status;
+ /// When written begins 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;
+
+ /// 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. At the
+ /// standard Sonata 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.
+ ConfigurationHalfClkPeriodMask = 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 CPHA is 0 data is sampled on | What is CPHA? |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,175 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's SPI.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Configuration register. Controls how the SPI block transmits and
+ /// receives data. This register can only be modified whilst the SPI block
+ /// is idle.
+ uint32_t configuration;
+ /// Controls the operation of the SPI block. This register can
+ /// only be modified whilst the SPI block is idle.
+ uint32_t control;
+ /// Status information about the SPI block
+ uint32_t status;
+ /// When written begins 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;
+
+ /// 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. At the
+ /// standard Sonata 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.
+ ConfigurationHalfClkPeriodMask = 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 CPHA 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 CPHA is 1 data is sampled on
+ /// the trailing edge and change on the leading edge.
+ ConfigurationCPHA = 1u << 30,
+ /// The polarity of the spi_clk signal. When CPOL is 0 clock is low when | What is CPOL? |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,175 @@
+#pragma once
+#include <cdefs.h>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's SPI.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /// Configuration register. Controls how the SPI block transmits and
+ /// receives data. This register can only be modified whilst the SPI block
+ /// is idle.
+ uint32_t configuration;
+ /// Controls the operation of the SPI block. This register can
+ /// only be modified whilst the SPI block is idle.
+ uint32_t control;
+ /// Status information about the SPI block
+ uint32_t status;
+ /// When written begins 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;
+
+ /// 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. At the
+ /// standard Sonata 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.
+ ConfigurationHalfClkPeriodMask = 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 CPHA 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 CPHA is 1 data is sampled on
+ /// the trailing edge and change on the leading edge.
+ ConfigurationCPHA = 1u << 30,
+ /// The polarity of the spi_clk signal. When CPOL is 0 clock is low when
+ /// idle and the leading edge is positive. When CPOL is 1 clock is high
+ /// when idle and the leading edge is negative
+ ConfigurationCPOL = 1u << 31,
+ };
+
+ /// Control Register Fields
+ enum : uint32_t
+ {
+ /// Write 1 to clear the transmit FIFO.
+ ControlTxClear = 1 << 0, | ```suggestion
ControlTransmitClear = 1 << 0,
```
The abbreviations tx and rx are ubiquitous in communication literature, but not everyone reading this code will have that background.
Same comment for the next ones down. |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,227 @@
+#pragma once
+#include <cdefs.h>
+#include <debug.hh>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's SPI.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable; | It looks as if we're missing the interrupt definitions in the board JSON? |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,227 @@
+#pragma once
+#include <cdefs.h>
+#include <debug.hh>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's SPI.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /**
+ * Configuration register. Controls how the SPI block transmits and
+ * receives data. This register can only be modified whilst the SPI block | ```suggestion
* receives data. This register can be modified only whilst the SPI block
``` |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,227 @@
+#pragma once
+#include <cdefs.h>
+#include <debug.hh>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's SPI.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /**
+ * Configuration register. Controls how the SPI block transmits and
+ * receives data. This register can only be modified 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;
+
+ /// Configuration Register Fields
+ enum : uint32_t | It would be nice to add a `clang::flag_enum` attribute here. |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,227 @@
+#pragma once
+#include <cdefs.h>
+#include <debug.hh>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's SPI.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /**
+ * Configuration register. Controls how the SPI block transmits and
+ * receives data. This register can only be modified 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;
+
+ /// 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. At the
+ * standard Sonata 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 | Same here (`clang::flag_enum`) |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,227 @@
+#pragma once
+#include <cdefs.h>
+#include <debug.hh>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's SPI.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /**
+ * Configuration register. Controls how the SPI block transmits and
+ * receives data. This register can only be modified 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;
+
+ /// 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. At the
+ * standard Sonata 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,
+ };
+
+ /// 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,
+ };
+
+ /**
+ * Flag set when we're debugging this driver.
+ */
+ static constexpr bool DebugSonataSpi = false;
+
+ /**
+ * Helper for conditional debug logs and assertions.
+ */
+ using Debug = ConditionalDebug<DebugSonataSpi, "Sonata SPI">;
+
+ /**
+ * Initialises the SPI block
+ */
+ void init(const bool ClockPolarity,
+ const bool ClockPhase,
+ const bool MsbFirst,
+ const uint16_t HalfClkPeriod) volatile | ```suggestion
const uint16_t HalfClockPeriod) volatile
```
Can the doc comment explain the parameters too? This is the thing that pops up when you type this in an IDE, so it's nice if it can be self-contained. |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,227 @@
+#pragma once
+#include <cdefs.h>
+#include <debug.hh>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's SPI.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /**
+ * Configuration register. Controls how the SPI block transmits and
+ * receives data. This register can only be modified 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;
+
+ /// 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. At the
+ * standard Sonata 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,
+ };
+
+ /// 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,
+ };
+
+ /**
+ * Flag set when we're debugging this driver.
+ */
+ static constexpr bool DebugSonataSpi = false;
+
+ /**
+ * Helper for conditional debug logs and assertions.
+ */
+ using Debug = ConditionalDebug<DebugSonataSpi, "Sonata SPI">;
+
+ /**
+ * Initialises the SPI block
+ */
+ void init(const bool ClockPolarity,
+ const bool ClockPhase,
+ const bool MsbFirst,
+ const uint16_t HalfClkPeriod) volatile
+ {
+ configuration = (ClockPolarity ? ConfigurationClockPolarity : 0) |
+ (ClockPhase ? ConfigurationClockPhase : 0) |
+ (MsbFirst ? ConfigurationMSBFirst : 0) |
+ (HalfClkPeriod & ConfigurationHalfClockPeriodMask);
+ }
+
+ /// Waits for the SPI device to become idle
+ void wait_idle() volatile
+ {
+ // Wait whilst IDLE field in STATUS is low
+ while ((status & StatusIdle) == 0) {}
+ }
+
+ /**
+ * Sends `Len` bytes from the given `data` buffer,
+ * where `Len` is at most `0x7ff`.
+ */
+ void transmit(const uint8_t data[], const uint16_t Len) volatile | I'm not really a fan of `const` parameters that are value types. `const` on a parameter is a contract not to mutate the object, but when mutation is not observable in the caller then it's not helpful, and making this `const` means that we then have a new `LenTruncated` rather than just having a `length` parameter that we mask. |
cheriot-rtos | github_2023 | others | 234 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,227 @@
+#pragma once
+#include <cdefs.h>
+#include <debug.hh>
+#include <stdint.h>
+
+/**
+ * A Simple Driver for the Sonata's SPI.
+ *
+ * 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
+ */
+struct SonataSpi
+{
+ /// Interrupt State Register
+ uint32_t interruptState;
+ /// Interrupt Enable Register
+ uint32_t interruptEnable;
+ /// Interrupt Test Register
+ uint32_t interruptTest;
+ /**
+ * Configuration register. Controls how the SPI block transmits and
+ * receives data. This register can only be modified 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;
+
+ /// 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. At the
+ * standard Sonata 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,
+ };
+
+ /// 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,
+ };
+
+ /**
+ * Flag set when we're debugging this driver.
+ */
+ static constexpr bool DebugSonataSpi = false;
+
+ /**
+ * Helper for conditional debug logs and assertions.
+ */
+ using Debug = ConditionalDebug<DebugSonataSpi, "Sonata SPI">;
+
+ /**
+ * Initialises the SPI block
+ */
+ void init(const bool ClockPolarity,
+ const bool ClockPhase,
+ const bool MsbFirst,
+ const uint16_t HalfClkPeriod) volatile
+ {
+ configuration = (ClockPolarity ? ConfigurationClockPolarity : 0) |
+ (ClockPhase ? ConfigurationClockPhase : 0) |
+ (MsbFirst ? ConfigurationMSBFirst : 0) |
+ (HalfClkPeriod & ConfigurationHalfClockPeriodMask);
+ }
+
+ /// Waits for the SPI device to become idle
+ void wait_idle() volatile
+ {
+ // Wait whilst IDLE field in STATUS is low
+ while ((status & StatusIdle) == 0) {}
+ }
+
+ /**
+ * Sends `Len` bytes from the given `data` buffer,
+ * where `Len` is at most `0x7ff`.
+ */
+ void transmit(const uint8_t data[], const uint16_t Len) volatile
+ {
+ Debug::Assert(Len <= 0x7ff,
+ "You can't transfer more than 0x7ff bytes at a time.");
+ const uint32_t LenTruncated = Len & StartByteCountMask;
+
+ wait_idle();
+ control = ControlTransmitEnable;
+ start = LenTruncated;
+
+ uint32_t transmitAvailable = 0;
+ for (uint32_t i = 0; i < LenTruncated; ++i)
+ {
+ if (transmitAvailable == 0)
+ {
+ while (transmitAvailable < 64)
+ {
+ // Read number of bytes in TX FIFO to calculate space
+ // available for more bytes
+ transmitAvailable = 64 - (status & StatusTxFifoLevel);
+ }
+ }
+ transmitFifo = data[i];
+ transmitAvailable--;
+ }
+ }
+
+ /*
+ * Receives `Len` bytes and puts them in the `data` buffer,
+ * where `Len` is at most `0x7ff`.
+ *
+ * This method will block until the requested number of bytes
+ * has been seen. There is currently no timeout.
+ */
+ void receive(uint8_t data[], const uint16_t Len) volatile | Same comment here. |
cheriot-rtos | github_2023 | others | 220 | CHERIoT-Platform | davidchisnall | @@ -2,6 +2,15 @@
#include <cdefs.h>
#include <stdint.h>
+enum class SonataJoystick : uint8_t | It would be nice to have a doc comment for this, especially to tell me if more than one direction can be returned at once (are diagonals represented as two directions? Can it be pressed and moved in a direction)? |
cheriot-rtos | github_2023 | others | 220 | CHERIoT-Platform | davidchisnall | @@ -58,4 +67,37 @@ struct SonataGPIO
{
output = output ^ led_bit(index);
}
+
+ /**
+ * The bit index of the first GPIO pin connected to a user switch.
+ */
+ static constexpr uint32_t FirstSwitch = 5;
+ /**
+ * The bit index of the last GPIO pin connected to a user switch.
+ */
+ static constexpr uint32_t LastSwitch = 13;
+ /**
+ * The number of user switches.
+ */
+ static constexpr uint32_t SwitchCount = LastSwitch - FirstSwitch + 1;
+ /**
+ * The mask covering the GPIO pins used for user switches.
+ */
+ static constexpr uint32_t SwitchMask = ((1 << SwitchCount) - 1)
+ << FirstSwitch;
+
+ constexpr static uint32_t switch_bit(uint32_t index) | Please can you add doc comments on these too? |
cheriot-rtos | github_2023 | others | 224 | CHERIoT-Platform | rmn30 | @@ -302,6 +314,16 @@ after_zero:
// ca1, used for second return value
zeroAllRegistersExcept ra, sp, gp, s0, s1, a0, a1
cret
+
+ // If the stack is too small, we don't do the call, but to avoid leaking
+ // any other state we still go through the same return path as normal. We
+ // set the return registers to -ENOTENOUGHSTACK and 0, so users can see
+ // that this is the failure reason.
+.Lstack_too_small:
+ // Return register is -ENOTENOUGHSTACK
+ li a0, -140 | Why can't we use the macro here?
|
cheriot-rtos | github_2023 | cpp | 224 | CHERIoT-Platform | rmn30 | @@ -104,6 +107,7 @@ void __cheri_compartment("test_runner") run_tests()
debug_log("Trying to print string: {}", std::string_view{testString, 13});
run_timed("All tests", []() {
+ run_timed("Stacks exhaustion in the switcher", test_stack); | I guess this was left in from testing as it also appears below?
```suggestion
``` |
cheriot-rtos | github_2023 | cpp | 224 | CHERIoT-Platform | rmn30 | @@ -72,8 +72,42 @@ namespace
debug_log("Expected to invoke the handler? {}", handlerExpected);
set_expected_behaviour(&threadStackTestFailed, handlerExpected);
}
+
+ __attribute__((used)) extern "C" int test_small_stack()
+ {
+ return test_stack_requirement();
+ }
} // namespace
+__attribute__((used)) extern "C" int test_with_small_stack(size_t stackSize);
+
+asm(".section .text\n"
+ ".global test_with_small_stack\n"
+ "test_with_small_stack:\n"
+ // Preserve the old stack
+ " cmove ct0, csp\n"
+ // Add space to the requested size for the spill slots and the size of the
+ // stack that `test_small_stack` will use, plus the four capabilities that
+ // the switcher will spill for us.
+ " add a0, a0, 64\n" | I guess this is 2 x spills here, 2 x spills in test_small_stack and 4 x switcher spills? Would be good to be explicit. Are the spills in `test_small_stack` dependent on anything like debug level? Concerned the magic number may be a bit brittle. |
cheriot-rtos | github_2023 | others | 191 | CHERIoT-Platform | davidchisnall | @@ -13,6 +13,10 @@
.p2align 2
.type start,@function
start:
+ .rept 32
+ .word 0x0000006f
+ .endr
+ | CHERIoT doesn't use the vectored interrupts (CHERIoT Ibex doesn't support the vectored mode). Interrupts are configured by the scheduler. If Sunburst is doing something different for the interrupt controller (not the CLINT + PLIC combination that we normally use with CHERIoT Ibex) then you'll need a custom driver. |
cheriot-rtos | github_2023 | others | 191 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,32 @@
+{
+ "devices": {
+ "clint": {
+ "start": 0x2000000,
+ "length": 0x10000
+ },
+ "uart": {
+ "start": 0x81000000,
+ "length": 0x1000 | This doesn't seem to match the size of the UART device that you've added (should be 52 bytes?) |
cheriot-rtos | github_2023 | others | 191 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,70 @@
+#pragma once
+#pragma push_macro("CHERIOT_PLATFORM_CUSTOM_UART")
+#define CHERIOT_PLATFORM_CUSTOM_UART
+#include_next <platform-uart.hh>
+#pragma pop_macro("CHERIOT_PLATFORM_CUSTOM_UART")
+
+/**
+ * OpenTitan UART
+ */
+template<unsigned DefaultBaudRate = 115'200>
+class OpenTitanUart
+{
+ public:
+ uint32_t intrState;
+ uint32_t intrEnable;
+ uint32_t intrTest;
+ uint32_t alertTest;
+ uint32_t ctrl;
+ uint32_t status;
+ uint32_t rData;
+ uint32_t wData;
+ uint32_t fifoCtrl;
+ uint32_t fifoStatus;
+ uint32_t ovrd;
+ uint32_t val;
+ uint32_t timeoutCtrl; | These should all have doc comments explaining what they do (which are for reading, which for writing, which bits are valid in each and what they mean, and so on). |
cheriot-rtos | github_2023 | others | 191 | CHERIoT-Platform | davidchisnall | @@ -0,0 +1,70 @@
+#pragma once
+#pragma push_macro("CHERIOT_PLATFORM_CUSTOM_UART")
+#define CHERIOT_PLATFORM_CUSTOM_UART
+#include_next <platform-uart.hh>
+#pragma pop_macro("CHERIOT_PLATFORM_CUSTOM_UART")
+
+/**
+ * OpenTitan UART
+ */
+template<unsigned DefaultBaudRate = 115'200>
+class OpenTitanUart
+{
+ public:
+ uint32_t intrState;
+ uint32_t intrEnable;
+ uint32_t intrTest;
+ uint32_t alertTest;
+ uint32_t ctrl;
+ uint32_t status;
+ uint32_t rData;
+ uint32_t wData;
+ uint32_t fifoCtrl;
+ uint32_t fifoStatus;
+ uint32_t ovrd;
+ uint32_t val;
+ uint32_t timeoutCtrl;
+
+ void init(unsigned baudRate = DefaultBaudRate) volatile
+ {
+ // NCO = 2^20 * baud rate / cpu frequency
+ const uint32_t NCO =
+ ((static_cast<uint64_t>(baudRate) << 20) / CPU_TIMER_HZ);
+ // Set the baud rate and enable transmit & receive
+ ctrl = (NCO << 16) | 0b11;
+ };
+
+ bool can_write() volatile
+ {
+ return (fifoStatus & 0xff) < 32;
+ };
+
+ bool can_read() volatile
+ {
+ // Not efficient, but explanatory | I don't understand this comment. |
cheriot-rtos | github_2023 | cpp | 206 | CHERIoT-Platform | davidchisnall | @@ -211,6 +262,7 @@ namespace
*/
void test_ticket_lock_ordering()
{
+ counter = 0; | What is this? |
cheriot-rtos | github_2023 | cpp | 212 | CHERIoT-Platform | davidchisnall | @@ -108,3 +108,12 @@ int __cheri_libcall eventgroup_get(struct EventGroup *group, uint32_t *outBits);
*/
int __cheri_libcall eventgroup_destroy(struct SObjStruct *heapCapability,
struct EventGroup *group);
+
+/**
+ * Destroy an event group without tacking the lock.
+ *
+ * This API is inherently racy. Its main purpose is to cleanup the event group | Cleanup is a noun, you mean clean up. |
cheriot-rtos | github_2023 | others | 195 | CHERIoT-Platform | davidchisnall | @@ -741,6 +741,17 @@ class KunyanEthernet
while (transmitControl & 1) {}
// Write the frame to the transmit buffer.
auto transmitBuffer = transmit_buffer_pointer();
+ // We must check the frame pointer and its length. Although it
+ // is supplied by the firewall which is trusted, the firewall
+ // does not check the pointer which is coming from external
+ // untrusted components.
+ Timeout t{10};
+ if (heap_claim_fast(&t, buffer) < 0 || | Please can you add brackets around the < expression? |
cheriot-rtos | github_2023 | others | 199 | CHERIoT-Platform | davidchisnall | @@ -9,6 +9,7 @@ DECLARE_AND_DEFINE_INTERRUPT_CAPABILITY(RevokerInterruptEntropy,
InterruptName::EthernetReceiveInterrupt,
true,
false)
+#define REVOKER_INTERRUPT_ENTROPY STATIC_SEALED_VALUE(RevokerInterruptEntropy) | Why a define for a thing that is used only once? |
cheriot-rtos | github_2023 | others | 170 | CHERIoT-Platform | davidchisnall | @@ -224,3 +224,119 @@ For Ubuntu, you can do:
# apt install xmake
```
+Running on the Arty A7
+----------------------
+
+We previously run the test suite in the simulator. | ```suggestion
We previously ran the test suite in the simulator.
``` |
cheriot-rtos | github_2023 | others | 170 | CHERIoT-Platform | davidchisnall | @@ -224,3 +224,119 @@ For Ubuntu, you can do:
# apt install xmake
```
+Running on the Arty A7
+----------------------
+
+We previously run the test suite in the simulator.
+Let us now run it on the Arty A7 FPGA development board.
+
+We will first build the CHERIoT [small and fast FPGA emulator](https://github.com/microsoft/cheriot-safe) (SAFE) configuration and load it onto the FPGA.
+Then, we will build, install, and run the CHERIoT RTOS firmware on the board.
+
+### Building and Installing the SAFE FPGA Configuration
+
+We will add documentation for this part later.
+In the meantime, our [blog post](https://cheriot.org/fpga/try/2023/11/16/cheriot-on-the-arty-a7.html) provides pointers on how to do this.
+
+### Building, Copying, and Running the Firmware
+
+We have now configured the FPGA.
+The LD4 LED on the FPGA board should be blinking green.
+We are ready to build, copy, and run the firmware.
+
+#### Building the Firmware
+
+We first need to reconfigure the build, and rebuild: | ```suggestion
We first need to reconfigure the build, and rebuild.
For this example, we'll show rebuilding the test suite, but the same set of steps should work for any CHERIoT RTOS project (try the examples!):
``` |
cheriot-rtos | github_2023 | others | 170 | CHERIoT-Platform | davidchisnall | @@ -224,3 +224,119 @@ For Ubuntu, you can do:
# apt install xmake
```
+Running on the Arty A7
+----------------------
+
+We previously run the test suite in the simulator.
+Let us now run it on the Arty A7 FPGA development board.
+
+We will first build the CHERIoT [small and fast FPGA emulator](https://github.com/microsoft/cheriot-safe) (SAFE) configuration and load it onto the FPGA.
+Then, we will build, install, and run the CHERIoT RTOS firmware on the board.
+
+### Building and Installing the SAFE FPGA Configuration
+
+We will add documentation for this part later.
+In the meantime, our [blog post](https://cheriot.org/fpga/try/2023/11/16/cheriot-on-the-arty-a7.html) provides pointers on how to do this.
+
+### Building, Copying, and Running the Firmware
+
+We have now configured the FPGA.
+The LD4 LED on the FPGA board should be blinking green.
+We are ready to build, copy, and run the firmware.
+
+#### Building the Firmware
+
+We first need to reconfigure the build, and rebuild:
+
+```sh
+$ cd tests
+$ xmake config --sdk=/cheriot-tools/ --board=ibex-arty-a7-100
+$ xmake
+```
+
+Note that `/cheriot-tools` is the location in the dev container.
+This value may vary if you did not use the dev container. | ```suggestion
This value may vary if you did not use the dev container and must be the directory containing a `bin` directory with your LLVM build in it.
``` |
cheriot-rtos | github_2023 | others | 170 | CHERIoT-Platform | davidchisnall | @@ -224,3 +224,119 @@ For Ubuntu, you can do:
# apt install xmake
```
+Running on the Arty A7
+----------------------
+
+We previously run the test suite in the simulator.
+Let us now run it on the Arty A7 FPGA development board.
+
+We will first build the CHERIoT [small and fast FPGA emulator](https://github.com/microsoft/cheriot-safe) (SAFE) configuration and load it onto the FPGA.
+Then, we will build, install, and run the CHERIoT RTOS firmware on the board.
+
+### Building and Installing the SAFE FPGA Configuration
+
+We will add documentation for this part later.
+In the meantime, our [blog post](https://cheriot.org/fpga/try/2023/11/16/cheriot-on-the-arty-a7.html) provides pointers on how to do this.
+
+### Building, Copying, and Running the Firmware
+
+We have now configured the FPGA.
+The LD4 LED on the FPGA board should be blinking green.
+We are ready to build, copy, and run the firmware.
+
+#### Building the Firmware
+
+We first need to reconfigure the build, and rebuild:
+
+```sh
+$ cd tests
+$ xmake config --sdk=/cheriot-tools/ --board=ibex-arty-a7-100
+$ xmake
+```
+
+Note that `/cheriot-tools` is the location in the dev container.
+This value may vary if you did not use the dev container.
+
+Then, we need to build the firmware.
+This repository comes with a script to do this:
+
+```sh
+$ ../scripts/ibex-build-firmware.sh build/cheriot/cheriot/release/test-suite
+```
+
+The `./firmware` directory should now contain a firmware file `cpu0_iram.vhx`.
+This is the firmware we want copy onto the FPGA development board.
+
+#### Installing and Running the Firmware
+
+To copy the firmware onto the FPGA board, we will use minicom, which you can obtain through your your distribution's packaging system.
+For example on Ubuntu Linux distributions you would need to run (as root):
+
+```sh
+# apt install minicom
+```
+
+Now, plug the FPGA development board to your computer.
+We need to identify which serial device we will be using.
+On Linux, we do this by looking at the dmesg output:
+
+```sh
+$ sudo dmesg | grep tty
+(...)
+[19966.674679] usb 1-4: FTDI USB Serial Device converter now attached to ttyUSB1
+```
+
+The most recent lines of this command appear when plugging and unplugging your FPGA board, and indicate which serial device corresponds to the board.
+Here, it is `ttyUSB1`.
+
+Now we can open minicom (replace `ttyUSB1` with the serial device you just determined):
+
+```sh
+$ sudo minicom -c on -D ttyUSB1
+Welcome to minicom 2.8
+
+OPTIONS: I18n
+Port /dev/ttyUSB1, 13:51:28
+
+Press CTRL-A Z for help on special keys
+
+Ready to load firmware, hold BTN0 to ignore UART input.
+```
+
+Hitting the RESET button on the FPGA should produce the "Ready to load firmware..." line, which is the output from the loader on the FPGA.
+
+The "Press CTRL-A Z for help on special keys" message tells you which meta key is configured on your system. Here, the meta key is `CTRL-A`. Since the meta key varies across systems and configurations, we refer to it as `<META>`.
+
+We must now configure a few things:
+- Hit `<META>` + `U` to turn carriage return `ON`
+- Hit `<META>` + `W` to turn linewrap `ON`
+- Hit `<META>` + `O`, then select `Serial Port Setup`, to ensure that `Bps/Par/Bits` (E) is set to `115200 8N1`, F to L on `No`, and M and N on `0`.
+ | ```suggestion
Make sure that hardware and software flow control are *off*.
On macOS, the kernel silently ignores these if they are not supported but on Linux the kernel will refuse to send data unless the flow control is in the correct state.
Unfortunately, the hardware flow control lines in the Arty A7's UART are not physically connected to the USB controller.
``` |
cheriot-rtos | github_2023 | others | 170 | CHERIoT-Platform | davidchisnall | @@ -224,3 +224,119 @@ For Ubuntu, you can do:
# apt install xmake
```
+Running on the Arty A7
+----------------------
+
+We previously run the test suite in the simulator.
+Let us now run it on the Arty A7 FPGA development board.
+
+We will first build the CHERIoT [small and fast FPGA emulator](https://github.com/microsoft/cheriot-safe) (SAFE) configuration and load it onto the FPGA.
+Then, we will build, install, and run the CHERIoT RTOS firmware on the board.
+
+### Building and Installing the SAFE FPGA Configuration
+
+We will add documentation for this part later.
+In the meantime, our [blog post](https://cheriot.org/fpga/try/2023/11/16/cheriot-on-the-arty-a7.html) provides pointers on how to do this.
+
+### Building, Copying, and Running the Firmware
+
+We have now configured the FPGA.
+The LD4 LED on the FPGA board should be blinking green.
+We are ready to build, copy, and run the firmware.
+
+#### Building the Firmware
+
+We first need to reconfigure the build, and rebuild:
+
+```sh
+$ cd tests
+$ xmake config --sdk=/cheriot-tools/ --board=ibex-arty-a7-100
+$ xmake
+```
+
+Note that `/cheriot-tools` is the location in the dev container.
+This value may vary if you did not use the dev container.
+
+Then, we need to build the firmware.
+This repository comes with a script to do this:
+
+```sh
+$ ../scripts/ibex-build-firmware.sh build/cheriot/cheriot/release/test-suite
+```
+
+The `./firmware` directory should now contain a firmware file `cpu0_iram.vhx`.
+This is the firmware we want copy onto the FPGA development board.
+
+#### Installing and Running the Firmware
+
+To copy the firmware onto the FPGA board, we will use minicom, which you can obtain through your your distribution's packaging system.
+For example on Ubuntu Linux distributions you would need to run (as root):
+
+```sh
+# apt install minicom
+```
+
+Now, plug the FPGA development board to your computer.
+We need to identify which serial device we will be using.
+On Linux, we do this by looking at the dmesg output:
+
+```sh
+$ sudo dmesg | grep tty
+(...)
+[19966.674679] usb 1-4: FTDI USB Serial Device converter now attached to ttyUSB1
+```
+
+The most recent lines of this command appear when plugging and unplugging your FPGA board, and indicate which serial device corresponds to the board.
+Here, it is `ttyUSB1`.
+
+Now we can open minicom (replace `ttyUSB1` with the serial device you just determined):
+
+```sh
+$ sudo minicom -c on -D ttyUSB1
+Welcome to minicom 2.8
+
+OPTIONS: I18n
+Port /dev/ttyUSB1, 13:51:28
+
+Press CTRL-A Z for help on special keys
+
+Ready to load firmware, hold BTN0 to ignore UART input.
+```
+
+Hitting the RESET button on the FPGA should produce the "Ready to load firmware..." line, which is the output from the loader on the FPGA.
+
+The "Press CTRL-A Z for help on special keys" message tells you which meta key is configured on your system. Here, the meta key is `CTRL-A`. Since the meta key varies across systems and configurations, we refer to it as `<META>`. | ```suggestion
The "Press CTRL-A Z for help on special keys" message tells you which meta key is configured on your system.
Here, the meta key is `CTRL-A`.
The meta key varies across systems (the default on macOS is `<ESC>`) and configurations and so we refer to it as `<META>`.
``` |
cheriot-rtos | github_2023 | others | 170 | CHERIoT-Platform | davidchisnall | @@ -224,3 +224,119 @@ For Ubuntu, you can do:
# apt install xmake
```
+Running on the Arty A7
+----------------------
+
+We previously run the test suite in the simulator.
+Let us now run it on the Arty A7 FPGA development board.
+
+We will first build the CHERIoT [small and fast FPGA emulator](https://github.com/microsoft/cheriot-safe) (SAFE) configuration and load it onto the FPGA.
+Then, we will build, install, and run the CHERIoT RTOS firmware on the board.
+
+### Building and Installing the SAFE FPGA Configuration
+
+We will add documentation for this part later.
+In the meantime, our [blog post](https://cheriot.org/fpga/try/2023/11/16/cheriot-on-the-arty-a7.html) provides pointers on how to do this.
+
+### Building, Copying, and Running the Firmware
+
+We have now configured the FPGA.
+The LD4 LED on the FPGA board should be blinking green.
+We are ready to build, copy, and run the firmware.
+
+#### Building the Firmware
+
+We first need to reconfigure the build, and rebuild:
+
+```sh
+$ cd tests
+$ xmake config --sdk=/cheriot-tools/ --board=ibex-arty-a7-100
+$ xmake
+```
+
+Note that `/cheriot-tools` is the location in the dev container.
+This value may vary if you did not use the dev container.
+
+Then, we need to build the firmware.
+This repository comes with a script to do this:
+
+```sh
+$ ../scripts/ibex-build-firmware.sh build/cheriot/cheriot/release/test-suite
+```
+
+The `./firmware` directory should now contain a firmware file `cpu0_iram.vhx`.
+This is the firmware we want copy onto the FPGA development board.
+
+#### Installing and Running the Firmware
+
+To copy the firmware onto the FPGA board, we will use minicom, which you can obtain through your your distribution's packaging system.
+For example on Ubuntu Linux distributions you would need to run (as root):
+
+```sh
+# apt install minicom
+```
+
+Now, plug the FPGA development board to your computer.
+We need to identify which serial device we will be using.
+On Linux, we do this by looking at the dmesg output:
+
+```sh
+$ sudo dmesg | grep tty
+(...)
+[19966.674679] usb 1-4: FTDI USB Serial Device converter now attached to ttyUSB1
+```
+
+The most recent lines of this command appear when plugging and unplugging your FPGA board, and indicate which serial device corresponds to the board.
+Here, it is `ttyUSB1`.
+
+Now we can open minicom (replace `ttyUSB1` with the serial device you just determined):
+
+```sh
+$ sudo minicom -c on -D ttyUSB1
+Welcome to minicom 2.8
+
+OPTIONS: I18n
+Port /dev/ttyUSB1, 13:51:28
+
+Press CTRL-A Z for help on special keys
+
+Ready to load firmware, hold BTN0 to ignore UART input.
+```
+
+Hitting the RESET button on the FPGA should produce the "Ready to load firmware..." line, which is the output from the loader on the FPGA.
+
+The "Press CTRL-A Z for help on special keys" message tells you which meta key is configured on your system. Here, the meta key is `CTRL-A`. Since the meta key varies across systems and configurations, we refer to it as `<META>`.
+
+We must now configure a few things:
+- Hit `<META>` + `U` to turn carriage return `ON`
+- Hit `<META>` + `W` to turn linewrap `ON`
+- Hit `<META>` + `O`, then select `Serial Port Setup`, to ensure that `Bps/Par/Bits` (E) is set to `115200 8N1`, F to L on `No`, and M and N on `0`.
+
+We can now send our firmware to the FPGA.
+Hit `<META>` + `Y`, and select the `cpu0_iram.vhx` file we produced earlier.
+Minicom should now start outputing:
+
+```
+Ready to load firmware, hold BTN0 to ignore UART input.
+Starting loading. First word was: 40812A15
+..
+```
+
+Here, minicom blocks after printing a few dots, and you must hit enter to unblock it. | ```suggestion
Minicom may block after printing a one or a small number of dots.
If it does, then it will resume if you press any key that would be sent over the serial link.
Each dot represents 1 KiB of transmitted data.
``` |
cheriot-rtos | github_2023 | cpp | 169 | CHERIoT-Platform | davidchisnall | @@ -57,6 +46,13 @@ namespace
{
while (true)
{
+ // Do not attempt to lock if the destruct mode
+ // flag is set
+ if ((lockWord & Flag::LockedInDestructMode) != 0) | Possibly move this down. The common case should be that the lock is not held, so we want the fast path to be the CAS. If the lock is in destruction mode then we're happy to be in a slow path. |
cheriot-rtos | github_2023 | cpp | 169 | CHERIoT-Platform | davidchisnall | @@ -136,14 +132,33 @@ namespace
lockWord.notify_all();
}
}
+
+ /**
+ * Set the destruction bit in the flag lock word and wake
+ * waiters. Assumes that the lock is hold by the caller. | ```suggestion
* waiters. Assumes that the lock is held by the caller.``` |
cheriot-rtos | github_2023 | cpp | 169 | CHERIoT-Platform | davidchisnall | @@ -65,6 +65,81 @@ namespace
}
}
+ /**
+ * Test that destructing a lock automatically wakes up all waiters,
+ * failing them to acquire the lock.
+ */
+ template<typename Lock>
+ void test_destruct_lock_wake_up(Lock &lock)
+ {
+ modified = false;
+
+ Timeout t{1};
+ lock.try_lock(&t);
+
+ // Create an async that tries to grab the lock | ```suggestion
// Try to acquire the lock in a background thread
``` |
cheriot-rtos | github_2023 | cpp | 169 | CHERIoT-Platform | davidchisnall | @@ -65,6 +65,81 @@ namespace
}
}
+ /**
+ * Test that destructing a lock automatically wakes up all waiters,
+ * failing them to acquire the lock.
+ */
+ template<typename Lock>
+ void test_destruct_lock_wake_up(Lock &lock)
+ {
+ modified = false;
+
+ Timeout t{1};
+ lock.try_lock(&t);
+
+ // Create an async that tries to grab the lock
+ async([&]() {
+ lock.lock();
+
+ // We will only reach this if lock() fails because of | ```suggestion
// When the lock is upgraded in destruction mode, `lock` will return failure.
``` |
cheriot-rtos | github_2023 | cpp | 169 | CHERIoT-Platform | davidchisnall | @@ -65,6 +65,81 @@ namespace
}
}
+ /**
+ * Test that destructing a lock automatically wakes up all waiters,
+ * failing them to acquire the lock.
+ */
+ template<typename Lock>
+ void test_destruct_lock_wake_up(Lock &lock)
+ {
+ modified = false;
+
+ Timeout t{1};
+ lock.try_lock(&t);
+
+ // Create an async that tries to grab the lock
+ async([&]() {
+ lock.lock(); | ```suggestion
// Make sure that we don't prevent the thread pool making progress if this test fails.
Timeout t{100};
TEST(lock.lock() == false, "Lock acquisition should not succeed!");
``` |
cheriot-rtos | github_2023 | cpp | 169 | CHERIoT-Platform | davidchisnall | @@ -65,6 +65,81 @@ namespace
}
}
+ /**
+ * Test that destructing a lock automatically wakes up all waiters,
+ * failing them to acquire the lock.
+ */
+ template<typename Lock>
+ void test_destruct_lock_wake_up(Lock &lock)
+ {
+ modified = false;
+
+ Timeout t{1};
+ lock.try_lock(&t);
+
+ // Create an async that tries to grab the lock
+ async([&]() {
+ lock.lock();
+
+ // We will only reach this if lock() fails because of
+ // the destruction mode
+ modified = true;
+ });
+
+ // Give the thread a chance to run
+ sleep(1);
+
+ // Upgrade the lock to destruction mode
+ lock.upgrade_for_destruction();
+
+ // Give the waiter a chance to wake up
+ sleep(1);
+
+ // Check that the destruction mode woke up the waiters
+ TEST(modified == true,
+ "Destruction mode did not wake up waiters!");
+
+ // Reset the lock in case other tests use it.
+ // Note: in practice, lock.upgrade_for_destruction() would be
+ // followed by a free() operation, not by unlock(). However
+ // unlock() comes handy here to remove the destruction flag to
+ // let other tests run properly with the same lock object
+ lock.unlock(); | We should have an assert that's triggered here if this is reached, because this is always API misuse. |
cheriot-rtos | github_2023 | cpp | 169 | CHERIoT-Platform | davidchisnall | @@ -63,6 +52,17 @@ namespace
{
return 0;
}
+
+ // Do not attempt to lock if the destruct mode
+ // flag is set. Note that the lock is in
+ // destruction mode iff it is already locked, | I don't think that's the reason: we are not setting the locked-for-destruction bit in our expected value, so the CAS will always fail if the lock-for-destruction bit is set. Being locked for destruction is unusual (it should happen exactly once for any lock) and so we don't bother to check for it unless we've failed to acquire the lock. |
cheriot-rtos | github_2023 | cpp | 169 | CHERIoT-Platform | davidchisnall | @@ -136,14 +136,33 @@ namespace
lockWord.notify_all();
}
}
+
+ /**
+ * Set the destruction bit in the flag lock word and wake
+ * waiters. Assumes that the lock is held by the caller.
+ *
+ * Note: This does not check that the lock is owned by the | It might be nice to have an assert that does check. There's a `Debug::Assert` variant that takes a lambda as the argument and so will not compile the check unless we've turned on lock debugging. |
cheriot-rtos | github_2023 | cpp | 169 | CHERIoT-Platform | davidchisnall | @@ -90,8 +90,8 @@ int __cheri_libcall flaglock_trylock(Timeout *timeout,
* that thread either releases the lock with `flaglock_unlock` or the timeout
* expires.
*
- * Returns 0 on success, -ETIMEDOUT if the timeout expired, or -EINVAL if the
- * arguments are invalid.
+ * Returns 0 on success, -ETIMEDOUT if the timeout expired, -EINVAL if the
+ * arguments are invalid, or -ENOENT if the lock is set in destruction mode. | ```suggestion
* arguments are invalid, or -ENOENT if the lock is set in destruction mode.
* Note: if the object is deallocated while trying to acquire the lock, then this will fault. In many cases, this is called at a compartment boundary and so this is fine. If it is not acceptable, use `heap_claim_fast` to ensure that the object remains live until after the call.
``` |
cheriot-rtos | github_2023 | cpp | 169 | CHERIoT-Platform | davidchisnall | @@ -123,6 +123,11 @@ flaglock_priority_inheriting_lock(struct FlagLockState *lock)
*/
void __cheri_libcall flaglock_unlock(struct FlagLockState *lock);
+/**
+ * Set a flag lock in destruction mode. | ```suggestion
* Set a flag lock in destruction mode.
* Locks in destruction mode cannot be acquired by other threads. Any threads currently attempting to acquire the lock will wake and fail to acquire the lock. This should be called before deallocating an object that contains a lock.
``` |
cheriot-rtos | github_2023 | others | 169 | CHERIoT-Platform | davidchisnall | @@ -21,10 +21,9 @@ __clang_ignored_warning_push("-Watomic-alignment");
/**
* A simple flag log, wrapping an atomic word used with the `futex` calls.
- * Threads blocked on this will be woken in priority order but this does not
- * propagate priority and so can lead to priority inversion if a low-priority
- * thread is attempting to acquire a flag lock to perform an operation on
- * behalf of a high priority thread.
+ * Threads blocked on this will be woken in priority order. If
+ * IsPriorityInherited is set, priority is inherited by waiters to avoid | ```suggestion
* `IsPriorityInherited` is set, priority is inherited by waiters to avoid
``` |
cheriot-rtos | github_2023 | others | 169 | CHERIoT-Platform | davidchisnall | @@ -85,6 +84,14 @@ class FlagLockGeneric
{
flaglock_unlock(&state);
}
+
+ /**
+ * Set the lock in destruction mode. | ```suggestion
* Set the lock in destruction mode. See the documentation of `flaglock_upgrade_for_destruction` for more information.
``` |
cheriot-rtos | github_2023 | cpp | 169 | CHERIoT-Platform | davidchisnall | @@ -63,6 +52,19 @@ namespace
{
return 0;
}
+
+ // We are not setting the LockedInDestructMode
+ // bit in our expected value (`old`), so the
+ // CAS will always fail if the bit is set.
+ // Being locked for destruction is unusual (it
+ // should happen at most once for any lock) and
+ // so we don't bother to check for it unless
+ // we've failed to acquire the lock.
+ if ((lockWord & Flag::LockedInDestructMode) != 0) | ```suggestion
if ((old & Flag::LockedInDestructMode) != 0)
```
We don't need to do another atomic load, the CAS has just told us the value that was there. If it has the destruction bit set, we can abort. |
cheriot-rtos | github_2023 | cpp | 169 | CHERIoT-Platform | davidchisnall | @@ -136,14 +138,33 @@ namespace
lockWord.notify_all();
}
}
+
+ /**
+ * Set the destruction bit in the flag lock word and wake
+ * waiters. Assumes that the lock is held by the caller.
+ *
+ * Note: This does not check that the lock is owned by the
+ * calling thread.
+ */
+ void upgrade_for_destruction()
+ {
+ Debug::log("Setting {} for destruction", &lockWord);
+
+ // set the destruction bit
+ lockWord |= Flag::LockedInDestructMode;
+
+ // wake up waiters | I think this is correct, but it might be worth a comment that explains the ordering. Importantly:
- The `lock` path always adds the waiters bit with a CAS and retries from the top in case of failure.
- We always do an atomic or to set the destruct mode bit.
- We load to check the waiters bit *after* setting it.
If someone manages to CAS in the waiters bit just after we do the update and then either their futex_wait, their wait will fail because we've added the other bit, or it will succeed but we'll trigger a wake. I *think* the code is correct, but a comment walking through the options would make it easier for the next person who reads it to be sure. |
cheriot-rtos | github_2023 | cpp | 169 | CHERIoT-Platform | davidchisnall | @@ -65,6 +65,85 @@ namespace
}
}
+ /**
+ * Test that destructing a lock automatically wakes up all waiters,
+ * failing them to acquire the lock.
+ */
+ template<typename Lock>
+ void test_destruct_lock_wake_up(Lock &lock)
+ {
+ modified = false;
+
+ Timeout t{1};
+ lock.try_lock(&t); | Doing `try_lock` and not checking the return is confusing. You probably want this to be `TEST(lock.try_lock(&t), "Failed to acquire uncontended lock");` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.