pw_{sync,chrono}_freertos: Add initial FreeRTOS support

Adds initial FreeRTOS support through a set of backends for
pw_sync through pw_sync_freertos and pw_chrono through
pw_chrono_freertos.

Change-Id: I2c57482fbdac6993f2ccf756870fe6e2f138a62a
Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/24422
Reviewed-by: Ewout van Bekkum <ewout@google.com>
Reviewed-by: Wyatt Hepler <hepler@google.com>
Commit-Queue: Ewout van Bekkum <ewout@google.com>
diff --git a/modules.gni b/modules.gni
index 4385513..a08c554 100644
--- a/modules.gni
+++ b/modules.gni
@@ -30,6 +30,7 @@
   dir_pw_bytes = get_path_info("pw_bytes", "abspath")
   dir_pw_checksum = get_path_info("pw_checksum", "abspath")
   dir_pw_chrono = get_path_info("pw_chrono", "abspath")
+  dir_pw_chrono_freertos = get_path_info("pw_chrono_freertos", "abspath")
   dir_pw_chrono_stl = get_path_info("pw_chrono_stl", "abspath")
   dir_pw_chrono_threadx = get_path_info("pw_chrono_threadx", "abspath")
   dir_pw_cli = get_path_info("pw_cli", "abspath")
@@ -73,6 +74,7 @@
   dir_pw_stream = get_path_info("pw_stream", "abspath")
   dir_pw_string = get_path_info("pw_string", "abspath")
   dir_pw_sync = get_path_info("pw_sync", "abspath")
+  dir_pw_sync_freertos = get_path_info("pw_sync_freertos", "abspath")
   dir_pw_sync_stl = get_path_info("pw_sync_stl", "abspath")
   dir_pw_sync_threadx = get_path_info("pw_sync_threadx", "abspath")
   dir_pw_sys_io = get_path_info("pw_sys_io", "abspath")
diff --git a/pw_chrono_freertos/BUILD b/pw_chrono_freertos/BUILD
new file mode 100644
index 0000000..6c65913
--- /dev/null
+++ b/pw_chrono_freertos/BUILD
@@ -0,0 +1,52 @@
+# Copyright 2020 The Pigweed Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may not
+# use this file except in compliance with the License. You may obtain a copy of
+# the License at
+#
+#     https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations under
+# the License.
+
+load(
+    "//pw_build:pigweed.bzl",
+    "pw_cc_library",
+)
+
+package(default_visibility = ["//visibility:public"])
+
+licenses(["notice"])  # Apache License 2.0
+
+pw_cc_library(
+    name = "system_clock_headers",
+    hdrs = [
+        "public/pw_chrono_freertos/config.h",
+        "public/pw_chrono_freertos/system_clock_config.h",
+        "public/pw_chrono_freertos/system_clock_constants.h",
+        "public_overrides/pw_chrono_backend/system_clock_config.h",
+    ],
+    includes = [
+        "public",
+        "public_overrides",
+    ],
+    deps = [
+        "//pw_chrono:epoch",
+    ],
+)
+
+pw_cc_library(
+    name = "system_clock",
+    srcs = [
+        "system_clock.cc",
+    ],
+    deps = [
+        ":system_clock_headers",
+        "//pw_chrono:system_clock_facade",
+        # TODO: This should depend on FreeRTOS but our third parties currently
+        # do not have Bazel support.
+    ],
+)
diff --git a/pw_chrono_freertos/BUILD.gn b/pw_chrono_freertos/BUILD.gn
new file mode 100644
index 0000000..b204749
--- /dev/null
+++ b/pw_chrono_freertos/BUILD.gn
@@ -0,0 +1,74 @@
+# Copyright 2020 The Pigweed Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may not
+# use this file except in compliance with the License. You may obtain a copy of
+# the License at
+#
+#     https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations under
+# the License.
+
+import("//build_overrides/pigweed.gni")
+
+import("$dir_pw_build/module_config.gni")
+import("$dir_pw_build/target_types.gni")
+import("$dir_pw_docgen/docs.gni")
+
+declare_args() {
+  # The build target that overrides the default configuration options for this
+  # module. This should point to a source set that provides defines through a
+  # public config (which may -include a file or add defines directly).
+  pw_chrono_freertos_CONFIG = pw_build_DEFAULT_MODULE_CONFIG
+}
+
+config("public_include_path") {
+  include_dirs = [ "public" ]
+  visibility = [ ":*" ]
+}
+
+config("backend_config") {
+  include_dirs = [ "public_overrides" ]
+  visibility = [ ":*" ]
+}
+
+pw_source_set("config") {
+  public = [ "public/pw_chrono_freertos/config.h" ]
+  public_configs = [ ":public_include_path" ]
+  public_deps = [
+    "$dir_pw_third_party/freertos",
+    pw_chrono_freertos_CONFIG,
+  ]
+}
+
+# This target provides the backend for pw::chrono::SystemClock.
+pw_source_set("system_clock") {
+  public_configs = [
+    ":public_include_path",
+    ":backend_config",
+  ]
+  public = [
+    "public/pw_chrono_freertos/system_clock_config.h",
+    "public/pw_chrono_freertos/system_clock_constants.h",
+    "public_overrides/pw_chrono_backend/system_clock_config.h",
+  ]
+  public_deps = [
+    ":config",
+    "$dir_pw_chrono:epoch",
+    "$dir_pw_chrono:system_clock.facade",
+    "$dir_pw_third_party/freertos",
+  ]
+  sources = [ "system_clock.cc" ]
+  deps = [
+    "$dir_pw_chrono:system_clock.facade",
+    "$dir_pw_interrupt:context",
+    "$dir_pw_sync:spin_lock",
+  ]
+}
+
+pw_doc_group("docs") {
+  sources = [ "docs.rst" ]
+}
diff --git a/pw_chrono_freertos/docs.rst b/pw_chrono_freertos/docs.rst
new file mode 100644
index 0000000..d09bebf
--- /dev/null
+++ b/pw_chrono_freertos/docs.rst
@@ -0,0 +1,32 @@
+.. _module-pw_chrono_freertos:
+
+------------------
+pw_chrono_freertos
+------------------
+``pw_chrono_freertos`` is a collection of ``pw_chrono`` backends that are
+implemented using FreeRTOS.
+
+.. warning::
+  This module is under construction, not ready for use, and the documentation
+  is incomplete.
+
+SystemClock backend
+-------------------
+The FreeRTOS based ``system_clock`` backend implements the
+``pw_chrono:system_clock`` facade by using ``xTaskGetTickCountFromISR()`` and
+``xTaskGetTickCount()`` based on the current context. Before the global
+singleton SystemClock's SpinLock is constructed the raw result is returned,
+after the overflows are managed in a thread and IRQ safe manner to produce a
+signed 64 bit timestamp.
+
+The ``SystemClock::now()`` must be used more than once per overflow of the
+native FreeRTOS ``xTaskGetTickCount*()`` overflow. Note that this duration may
+vary if ``portSUPPRESS_TICKS_AND_SLEEP()``, ``vTaskStepTick()``, and/or
+``xTaskCatchUpTicks()`` are used.
+
+Build targets
+-------------
+The GN build for ``pw_chrono_freertos`` has one target: ``system_clock``.
+The ``system_clock`` target provides the
+``pw_chrono_backend/system_clock_config.h`` and ``pw_chrono_freertos/config.h``
+headers and the backend for the ``pw_chrono:system_clock``.
diff --git a/pw_chrono_freertos/public/pw_chrono_freertos/config.h b/pw_chrono_freertos/public/pw_chrono_freertos/config.h
new file mode 100644
index 0000000..d51c3e1
--- /dev/null
+++ b/pw_chrono_freertos/public/pw_chrono_freertos/config.h
@@ -0,0 +1,31 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+// Configuration macros for the tokenizer module.
+#pragma once
+
+#include <assert.h>
+
+#include "FreeRTOS.h"
+
+// Because the SystemClock::now() implementation requires the user to invoke it
+// more than once per overflow period, the max timeout is set to ensure that
+// blocking indefinitely on a single primitive will meet this constraint with
+// margin (i.e. more than twice per overflow).
+#ifndef PW_CHRONO_FREERTOS_CFG_MAX_TIMEOUT
+#define PW_CHRONO_FREERTOS_CFG_MAX_TIMEOUT (portMAX_DELAY / 3)
+#endif  // PW_CHRONO_FREERTOS_CFG_MAX_TIMEOUT
+
+static_assert((PW_CHRONO_FREERTOS_CFG_MAX_TIMEOUT > 0) &&
+                  (PW_CHRONO_FREERTOS_CFG_MAX_TIMEOUT <= portMAX_DELAY),
+              "Invalid MAX timeout configuration");
diff --git a/pw_chrono_freertos/public/pw_chrono_freertos/system_clock_config.h b/pw_chrono_freertos/public/pw_chrono_freertos/system_clock_config.h
new file mode 100644
index 0000000..348392e
--- /dev/null
+++ b/pw_chrono_freertos/public/pw_chrono_freertos/system_clock_config.h
@@ -0,0 +1,36 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include <ratio>
+
+#include "FreeRTOS.h"
+#include "pw_chrono/epoch.h"
+
+namespace pw::chrono::backend {
+
+// Use the FreeRTOS config's tick rate.
+using SystemClockPeriodSecondsRatio = std::ratio<1, configTICK_RATE_HZ>;
+
+// The FreeRTOS clock starts at zero during initialization, approximately the
+// time since boot.
+constexpr inline Epoch kSystemClockEpoch = pw::chrono::Epoch::kTimeSinceBoot;
+
+// The current backend implementation is not NMI safe.
+constexpr inline bool kSystemClockNmiSafe = false;
+
+// The FreeRTOS clock halts when the systick interrupt is masked.
+constexpr inline bool kSystemClockFreeRunning = false;
+
+}  // namespace pw::chrono::backend
diff --git a/pw_chrono_freertos/public/pw_chrono_freertos/system_clock_constants.h b/pw_chrono_freertos/public/pw_chrono_freertos/system_clock_constants.h
new file mode 100644
index 0000000..3035ed0
--- /dev/null
+++ b/pw_chrono_freertos/public/pw_chrono_freertos/system_clock_constants.h
@@ -0,0 +1,26 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include "pw_chrono/system_clock.h"
+#include "pw_chrono_freertos/config.h"
+
+namespace pw::chrono::freertos {
+
+// Max timeout to be used by users of the FreeRTOS's pw::chrono::SystemClock
+// backend provided by this module.
+inline constexpr SystemClock::duration kMaxTimeout =
+    SystemClock::duration(PW_CHRONO_FREERTOS_CFG_MAX_TIMEOUT);
+
+}  // namespace pw::chrono::freertos
diff --git a/pw_chrono_freertos/public_overrides/pw_chrono_backend/system_clock_config.h b/pw_chrono_freertos/public_overrides/pw_chrono_backend/system_clock_config.h
new file mode 100644
index 0000000..804d76c
--- /dev/null
+++ b/pw_chrono_freertos/public_overrides/pw_chrono_backend/system_clock_config.h
@@ -0,0 +1,19 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+
+// This override header includes the main tokenized logging header and defines
+// the PW_LOG macro as the tokenized logging macro.
+#pragma once
+
+#include "pw_chrono_freertos/system_clock_config.h"
diff --git a/pw_chrono_freertos/system_clock.cc b/pw_chrono_freertos/system_clock.cc
new file mode 100644
index 0000000..17c42b3
--- /dev/null
+++ b/pw_chrono_freertos/system_clock.cc
@@ -0,0 +1,81 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+
+#include "pw_chrono/system_clock.h"
+
+#include <atomic>
+#include <chrono>
+#include <limits>
+#include <mutex>
+
+#include "FreeRTOS.h"
+#include "pw_interrupt/context.h"
+#include "pw_sync/spin_lock.h"
+#include "task.h"
+
+namespace pw::chrono::backend {
+namespace {
+
+// Extension wrapping pw::SpinLock to allow an atomic to be used to determine
+// whether it has been constructed and is ready to be used.
+class ConstructionSignalingSpinLock : public sync::SpinLock {
+ public:
+  ConstructionSignalingSpinLock(std::atomic<bool>& constructed_signal)
+      : sync::SpinLock() {
+    // Note that the memory order is relaxed because C++ global static
+    // construction is a single threaded environment.
+    constructed_signal.store(true, std::memory_order_relaxed);
+  };
+};
+
+// This is POD, meaning this atomic is available before static C++ global
+// constructors are run.
+std::atomic<bool> system_clock_spin_lock_constructed = {false};
+
+ConstructionSignalingSpinLock system_clock_spin_lock(
+    system_clock_spin_lock_constructed);
+
+int64_t overflow_tick_count = 0;
+TickType_t native_tick_count = 0;
+static_assert(!SystemClock::is_nmi_safe,
+              "global state is not atomic nor double buferred");
+
+// The tick count resets to 0, ergo the overflow count is the max count + 1.
+constexpr int64_t kNativeOverflowTickCount =
+    static_cast<int64_t>(std::numeric_limits<TickType_t>::max()) + 1;
+
+}  // namespace
+
+int64_t GetSystemClockTickCount() {
+  // Note that the memory order is relaxed because C++ global static
+  // construction is a single threaded environment.
+  if (!system_clock_spin_lock_constructed.load(std::memory_order_relaxed)) {
+    return interrupt::InInterruptContext() ? xTaskGetTickCountFromISR()
+                                           : xTaskGetTickCount();
+  }
+
+  std::lock_guard lock(system_clock_spin_lock);
+  const TickType_t new_native_tick_count = interrupt::InInterruptContext()
+                                               ? xTaskGetTickCountFromISR()
+                                               : xTaskGetTickCount();
+  // WARNING: This must be called more than once per overflow period!
+  if (new_native_tick_count < native_tick_count) {
+    // Native tick count overflow detected!
+    overflow_tick_count += kNativeOverflowTickCount;
+  }
+  native_tick_count = new_native_tick_count;
+  return overflow_tick_count + native_tick_count;
+}
+
+}  // namespace pw::chrono::backend
diff --git a/pw_sync_freertos/BUILD b/pw_sync_freertos/BUILD
new file mode 100644
index 0000000..5837d8f
--- /dev/null
+++ b/pw_sync_freertos/BUILD
@@ -0,0 +1,146 @@
+# Copyright 2020 The Pigweed Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may not
+# use this file except in compliance with the License. You may obtain a copy of
+# the License at
+#
+#     https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations under
+# the License.
+
+load(
+    "//pw_build:pigweed.bzl",
+    "pw_cc_library",
+)
+
+package(default_visibility = ["//visibility:public"])
+
+licenses(["notice"])  # Apache License 2.0
+
+pw_cc_library(
+    name = "binary_semaphore_headers",
+    hdrs = [
+        "public/pw_sync_freertos/binary_semaphore_inline.h",
+        "public/pw_sync_freertos/binary_semaphore_native.h",
+        "public_overrides/pw_sync_backend/binary_semaphore_inline.h",
+        "public_overrides/pw_sync_backend/binary_semaphore_native.h",
+    ],
+    includes = [
+        "public",
+        "public_overrides",
+    ],
+    deps = [
+        # TODO: This should depend on FreeRTOS but our third parties currently
+        # do not have Bazel support.
+        "//pw_chrono:system_clock",
+        "//pw_chrono_freertos:system_clock_headers",
+    ],
+)
+
+pw_cc_library(
+    name = "binary_semaphore",
+    srcs = [
+        "binary_semaphore.cc",
+    ],
+    deps = [
+        ":binary_semaphore_headers",
+        "//pw_interrupt:context",
+        "//pw_sync:binary_semaphore_facade",
+    ],
+)
+
+pw_cc_library(
+    name = "counting_semaphore_headers",
+    hdrs = [
+        "public/pw_sync_freertos/counting_semaphore_inline.h",
+        "public/pw_sync_freertos/counting_semaphore_native.h",
+        "public_overrides/pw_sync_backend/counting_semaphore_inline.h",
+        "public_overrides/pw_sync_backend/counting_semaphore_native.h",
+    ],
+    includes = [
+        "public",
+        "public_overrides",
+    ],
+    deps = [
+        # TODO: This should depend on FreeRTOS but our third parties currently
+        # do not have Bazel support.
+        "//pw_chrono:system_clock",
+        "//pw_chrono_freertos:system_clock_headers",
+    ],
+)
+
+pw_cc_library(
+    name = "counting_semaphore",
+    srcs = [
+        "counting_semaphore.cc",
+    ],
+    deps = [
+        ":counting_semaphore_headers",
+        "//pw_interrupt:context",
+        "//pw_sync:counting_semaphore_facade",
+    ],
+)
+
+pw_cc_library(
+    name = "mutex_headers",
+    hdrs = [
+        "public/pw_sync_freertos/mutex_inline.h",
+        "public/pw_sync_freertos/mutex_native.h",
+        "public_overrides/pw_sync_backend/mutex_inline.h",
+        "public_overrides/pw_sync_backend/mutex_native.h",
+    ],
+    includes = [
+        "public",
+        "public_overrides",
+    ],
+    deps = [
+        # TODO: This should depend on FreeRTOS but our third parties currently
+        # do not have Bazel support.
+        "//pw_chrono:system_clock",
+        "//pw_chrono_freertos:system_clock_headers",
+    ],
+)
+
+pw_cc_library(
+    name = "mutex",
+    srcs = [
+        "mutex.cc",
+    ],
+    deps = [
+        ":mutex_headers",
+        "//pw_interrupt:context",
+        "//pw_sync:mutex_facade",
+    ],
+)
+
+pw_cc_library(
+    name = "spin_lock_headers",
+    hdrs = [
+        "public/pw_sync_freertos/spin_lock_inline.h",
+        "public/pw_sync_freertos/spin_lock_native.h",
+        "public_overrides/pw_sync_backend/spin_lock_inline.h",
+        "public_overrides/pw_sync_backend/spin_lock_native.h",
+    ],
+    includes = [
+        "public",
+        "public_overrides",
+    ],
+    # TODO: This should depend on FreeRTOS but our third parties currently
+    # do not have Bazel support.
+)
+
+pw_cc_library(
+    name = "spin_lock",
+    srcs = [
+        "spin_lock.cc",
+    ],
+    deps = [
+        ":spin_lock_headers",
+        "//pw_interrupt:context",
+        "//pw_sync:spin_lock_facade",
+    ],
+)
diff --git a/pw_sync_freertos/BUILD.gn b/pw_sync_freertos/BUILD.gn
new file mode 100644
index 0000000..8869db5
--- /dev/null
+++ b/pw_sync_freertos/BUILD.gn
@@ -0,0 +1,139 @@
+# Copyright 2020 The Pigweed Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may not
+# use this file except in compliance with the License. You may obtain a copy of
+# the License at
+#
+#     https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations under
+# the License.
+
+import("//build_overrides/pigweed.gni")
+
+import("$dir_pw_build/target_types.gni")
+import("$dir_pw_chrono/backend.gni")
+import("$dir_pw_docgen/docs.gni")
+
+config("public_include_path") {
+  include_dirs = [ "public" ]
+  visibility = [ ":*" ]
+}
+
+config("backend_config") {
+  include_dirs = [ "public_overrides" ]
+  visibility = [ ":*" ]
+}
+
+# This target provides the backend for pw::sync::BinarySemaphore.
+pw_source_set("binary_semaphore") {
+  public_configs = [
+    ":public_include_path",
+    ":backend_config",
+  ]
+  public = [
+    "public/pw_sync_freertos/binary_semaphore_inline.h",
+    "public/pw_sync_freertos/binary_semaphore_native.h",
+    "public_overrides/pw_sync_backend/binary_semaphore_inline.h",
+    "public_overrides/pw_sync_backend/binary_semaphore_native.h",
+  ]
+  public_deps = [
+    "$dir_pw_assert",
+    "$dir_pw_chrono:system_clock",
+    "$dir_pw_chrono_freertos:system_clock",
+    "$dir_pw_interrupt:context",
+    "$dir_pw_third_party/freertos",
+  ]
+  sources = [ "binary_semaphore.cc" ]
+  deps = [ "$dir_pw_sync:binary_semaphore.facade" ]
+  assert(pw_chrono_SYSTEM_CLOCK_BACKEND == "" ||
+             pw_chrono_SYSTEM_CLOCK_BACKEND ==
+                 "$dir_pw_chrono_freertos:system_clock",
+         "The FreeRTOS pw::sync::BinarySemaphore backend only works with the " +
+             "FreeRTOS pw::chrono::SystemClock backend.")
+}
+
+# This target provides the backend for pw::sync::CountingSemaphore.
+pw_source_set("counting_semaphore") {
+  public_configs = [
+    ":public_include_path",
+    ":backend_config",
+  ]
+  public = [
+    "public/pw_sync_freertos/counting_semaphore_inline.h",
+    "public/pw_sync_freertos/counting_semaphore_native.h",
+    "public_overrides/pw_sync_backend/counting_semaphore_inline.h",
+    "public_overrides/pw_sync_backend/counting_semaphore_native.h",
+  ]
+  public_deps = [
+    "$dir_pw_assert",
+    "$dir_pw_chrono:system_clock",
+    "$dir_pw_chrono_freertos:system_clock",
+    "$dir_pw_interrupt:context",
+    "$dir_pw_third_party/freertos",
+  ]
+  sources = [ "counting_semaphore.cc" ]
+  deps = [ "$dir_pw_sync:counting_semaphore.facade" ]
+  assert(pw_chrono_SYSTEM_CLOCK_BACKEND == "" ||
+             pw_chrono_SYSTEM_CLOCK_BACKEND ==
+                 "$dir_pw_chrono_freertos:system_clock",
+         "The FreeRTOS pw::sync::CountingSemaphore backend only works with " +
+             "the FreeRTOS pw::chrono::SystemClock backend.")
+}
+
+# This target provides the backend for pw::sync::Mutex.
+pw_source_set("mutex") {
+  public_configs = [
+    ":public_include_path",
+    ":backend_config",
+  ]
+  public = [
+    "public/pw_sync_freertos/mutex_inline.h",
+    "public/pw_sync_freertos/mutex_native.h",
+    "public_overrides/pw_sync_backend/mutex_inline.h",
+    "public_overrides/pw_sync_backend/mutex_native.h",
+  ]
+  public_deps = [
+    "$dir_pw_assert",
+    "$dir_pw_chrono:system_clock",
+    "$dir_pw_chrono_freertos:system_clock",
+    "$dir_pw_interrupt:context",
+    "$dir_pw_third_party/freertos",
+  ]
+  sources = [ "mutex.cc" ]
+  deps = [ "$dir_pw_sync:mutex.facade" ]
+  assert(pw_chrono_SYSTEM_CLOCK_BACKEND == "" ||
+             pw_chrono_SYSTEM_CLOCK_BACKEND ==
+                 "$dir_pw_chrono_freertos:system_clock",
+         "The FreeRTOS pw::sync::Mutex backend only works with the FreeRTOS " +
+             "pw::chrono::SystemClock backend.")
+}
+
+# This target provides the backend for pw::sync::SpinLock.
+pw_source_set("spin_lock") {
+  public_configs = [
+    ":public_include_path",
+    ":backend_config",
+  ]
+  public = [
+    "public/pw_sync_freertos/spin_lock_inline.h",
+    "public/pw_sync_freertos/spin_lock_native.h",
+    "public_overrides/pw_sync_backend/spin_lock_inline.h",
+    "public_overrides/pw_sync_backend/spin_lock_native.h",
+  ]
+  public_deps = [ "$dir_pw_third_party/freertos" ]
+  sources = [ "spin_lock.cc" ]
+  deps = [
+    "$dir_pw_assert",
+    "$dir_pw_interrupt:context",
+    "$dir_pw_sync:spin_lock.facade",
+    "$dir_pw_third_party/freertos",
+  ]
+}
+
+pw_doc_group("docs") {
+  sources = [ "docs.rst" ]
+}
diff --git a/pw_sync_freertos/binary_semaphore.cc b/pw_sync_freertos/binary_semaphore.cc
new file mode 100644
index 0000000..0d59a25
--- /dev/null
+++ b/pw_sync_freertos/binary_semaphore.cc
@@ -0,0 +1,51 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+
+#include "pw_sync/binary_semaphore.h"
+
+#include <algorithm>
+
+#include "FreeRTOS.h"
+#include "pw_assert/assert.h"
+#include "pw_chrono/system_clock.h"
+#include "pw_chrono_freertos/system_clock_constants.h"
+#include "pw_interrupt/context.h"
+#include "semphr.h"
+
+using pw::chrono::SystemClock;
+using pw::chrono::freertos::kMaxTimeout;
+
+namespace pw::sync {
+namespace {
+
+static_assert(configSUPPORT_STATIC_ALLOCATION != 0);
+
+}  // namespace
+
+bool BinarySemaphore::try_acquire_for(SystemClock::duration for_at_least) {
+  PW_DCHECK(!interrupt::InInterruptContext());
+
+  // Clamp negative durations to be 0 which maps to non-blocking.
+  for_at_least = std::max(for_at_least, SystemClock::duration::zero());
+
+  while (for_at_least > kMaxTimeout) {
+    if (xSemaphoreTake(native_type_.handle, kMaxTimeout.count()) == pdTRUE) {
+      return true;
+    }
+    for_at_least -= kMaxTimeout;
+  }
+  return xSemaphoreTake(native_type_.handle, for_at_least.count()) == pdTRUE;
+}
+
+}  // namespace pw::sync
diff --git a/pw_sync_freertos/counting_semaphore.cc b/pw_sync_freertos/counting_semaphore.cc
new file mode 100644
index 0000000..33b2705
--- /dev/null
+++ b/pw_sync_freertos/counting_semaphore.cc
@@ -0,0 +1,69 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+
+#include "pw_sync/counting_semaphore.h"
+
+#include <algorithm>
+
+#include "FreeRTOS.h"
+#include "pw_assert/assert.h"
+#include "pw_chrono/system_clock.h"
+#include "pw_chrono_freertos/system_clock_constants.h"
+#include "pw_interrupt/context.h"
+#include "semphr.h"
+
+using pw::chrono::SystemClock;
+using pw::chrono::freertos::kMaxTimeout;
+
+namespace pw::sync {
+namespace {
+
+static_assert(configUSE_COUNTING_SEMAPHORES != 0,
+              "FreeRTOS counting semaphores aren't enabled.");
+
+static_assert(configSUPPORT_STATIC_ALLOCATION != 0);
+
+}  // namespace
+
+void CountingSemaphore::release(ptrdiff_t update) {
+  if (interrupt::InInterruptContext()) {
+    for (; update > 0; --update) {
+      BaseType_t woke_higher_task = pdFALSE;
+      const BaseType_t result =
+          xSemaphoreGiveFromISR(native_type_.handle, &woke_higher_task);
+      PW_DCHECK_UINT_EQ(result, pdTRUE, "Overflowed counting semaphore.");
+      portYIELD_FROM_ISR(woke_higher_task);
+    }
+  } else {  // Task context
+    for (; update > 0; --update) {
+      const BaseType_t result = xSemaphoreGive(native_type_.handle);
+      PW_DCHECK_UINT_EQ(result, pdTRUE, "Overflowed counting semaphore.");
+    }
+  }
+}
+
+bool CountingSemaphore::try_acquire_for(SystemClock::duration for_at_least) {
+  PW_DCHECK(!interrupt::InInterruptContext());
+  while (for_at_least > kMaxTimeout) {
+    if (xSemaphoreTake(native_type_.handle, kMaxTimeout.count()) == pdTRUE) {
+      return true;
+    }
+    for_at_least -= kMaxTimeout;
+  }
+  // Clamp negative durations to be 0 which maps to non-blocking.
+  for_at_least = std::max(for_at_least, SystemClock::duration::zero());
+  return xSemaphoreTake(native_type_.handle, for_at_least.count()) == pdTRUE;
+}
+
+}  // namespace pw::sync
diff --git a/pw_sync_freertos/docs.rst b/pw_sync_freertos/docs.rst
new file mode 100644
index 0000000..0053f02
--- /dev/null
+++ b/pw_sync_freertos/docs.rst
@@ -0,0 +1,8 @@
+.. _module-pw_sync_freertos:
+
+----------------
+pw_sync_freertos
+----------------
+This is a set of backends for pw_sync based on FreeRTOS. It is not ready for
+use, and is under construction.
+
diff --git a/pw_sync_freertos/mutex.cc b/pw_sync_freertos/mutex.cc
new file mode 100644
index 0000000..52333a1
--- /dev/null
+++ b/pw_sync_freertos/mutex.cc
@@ -0,0 +1,53 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+
+#include "pw_sync/mutex.h"
+
+#include <algorithm>
+
+#include "FreeRTOS.h"
+#include "pw_assert/assert.h"
+#include "pw_chrono/system_clock.h"
+#include "pw_chrono_freertos/system_clock_constants.h"
+#include "pw_interrupt/context.h"
+#include "semphr.h"
+
+using pw::chrono::SystemClock;
+using pw::chrono::freertos::kMaxTimeout;
+
+namespace pw::sync {
+namespace {
+
+static_assert(configUSE_MUTEXES != 0, "FreeRTOS mutexes aren't enabled.");
+
+static_assert(configSUPPORT_STATIC_ALLOCATION != 0);
+
+}  // namespace
+
+bool Mutex::try_lock_for(SystemClock::duration for_at_least) {
+  PW_DCHECK(!interrupt::InInterruptContext());
+
+  // Clamp negative durations to be 0 which maps to non-blocking.
+  for_at_least = std::max(for_at_least, SystemClock::duration::zero());
+
+  while (for_at_least > kMaxTimeout) {
+    if (xSemaphoreTake(native_type_.handle, kMaxTimeout.count()) == pdTRUE) {
+      return true;
+    }
+    for_at_least -= kMaxTimeout;
+  }
+  return xSemaphoreTake(native_type_.handle, for_at_least.count()) == pdTRUE;
+}
+
+}  // namespace pw::sync
diff --git a/pw_sync_freertos/public/pw_sync_freertos/binary_semaphore_inline.h b/pw_sync_freertos/public/pw_sync_freertos/binary_semaphore_inline.h
new file mode 100644
index 0000000..eab8d02
--- /dev/null
+++ b/pw_sync_freertos/public/pw_sync_freertos/binary_semaphore_inline.h
@@ -0,0 +1,84 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include "FreeRTOS.h"
+#include "pw_assert/light.h"
+#include "pw_chrono/system_clock.h"
+#include "pw_chrono_freertos/system_clock_constants.h"
+#include "pw_interrupt/context.h"
+#include "pw_sync/binary_semaphore.h"
+#include "semphr.h"
+
+namespace pw::sync {
+
+inline BinarySemaphore::BinarySemaphore() : native_type_() {
+  native_type_.handle = xSemaphoreCreateBinaryStatic(&native_type_.buffer);
+  // This should never fail since the pointer provided was not null.
+  PW_DASSERT(native_type_.handle != nullptr);
+}
+
+inline BinarySemaphore::~BinarySemaphore() { vSemaphoreDelete(&native_type_); }
+
+inline void BinarySemaphore::release() {
+  if (interrupt::InInterruptContext()) {
+    BaseType_t woke_higher_task = pdFALSE;
+    // It's perfectly fine if the semaphore already has a count of 1.
+    [[maybe_unused]] BaseType_t already_full =
+        xSemaphoreGiveFromISR(native_type_.handle, &woke_higher_task);
+    portYIELD_FROM_ISR(woke_higher_task);
+  } else {  // Task context
+    // It's perfectly fine if the semaphore already has a count of 1.
+    [[maybe_unused]] BaseType_t already_full =
+        xSemaphoreGive(native_type_.handle);
+  }
+}
+
+inline void BinarySemaphore::acquire() {
+  PW_ASSERT(!interrupt::InInterruptContext());
+#if INCLUDE_vTaskSuspend == 1  // This means portMAX_DELAY is indefinite.
+  const BaseType_t result = xSemaphoreTake(native_type_.handle, portMAX_DELAY);
+  PW_DASSERT(result == pdTRUE);
+#else
+  // In case we need to block for longer than the FreeRTOS delay can represent
+  // repeatedly hit take until success.
+  while (xSemaphoreTake(native_type_.handle,
+                        chrono::freertos::kMaxTimeout.count()) == pdFALSE) {
+  }
+#endif  // INCLUDE_vTaskSuspend
+}
+
+inline bool BinarySemaphore::try_acquire() {
+  if (interrupt::InInterruptContext()) {
+    BaseType_t woke_higher_task = pdFALSE;
+    const bool success =
+        xSemaphoreTakeFromISR(native_type_.handle, &woke_higher_task) == pdTRUE;
+    portYIELD_FROM_ISR(woke_higher_task);
+    return success;
+  }
+
+  // Task Context
+  return xSemaphoreTake(native_type_.handle, 0) == pdTRUE;
+}
+
+inline bool BinarySemaphore::try_acquire_until(
+    chrono::SystemClock::time_point until_at_least) {
+  return try_acquire_for(until_at_least - chrono::SystemClock::now());
+}
+
+inline BinarySemaphore::native_handle_type BinarySemaphore::native_handle() {
+  return native_type_;
+}
+
+}  // namespace pw::sync
diff --git a/pw_sync_freertos/public/pw_sync_freertos/binary_semaphore_native.h b/pw_sync_freertos/public/pw_sync_freertos/binary_semaphore_native.h
new file mode 100644
index 0000000..065fbe7
--- /dev/null
+++ b/pw_sync_freertos/public/pw_sync_freertos/binary_semaphore_native.h
@@ -0,0 +1,35 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include <limits>
+
+#include "FreeRTOS.h"
+#include "semphr.h"
+
+namespace pw::sync::backend {
+
+struct NativeBinarySemaphore {
+  StaticSemaphore_t buffer;
+  SemaphoreHandle_t handle;
+};
+using NativeBinarySemaphoreHandle = NativeBinarySemaphore&;
+
+inline constexpr ptrdiff_t kBinarySemaphoreMaxValue =
+    std::numeric_limits<ptrdiff_t>::max() <
+            std::numeric_limits<UBaseType_t>::max()
+        ? std::numeric_limits<ptrdiff_t>::max()
+        : std::numeric_limits<UBaseType_t>::max();
+
+}  // namespace pw::sync::backend
diff --git a/pw_sync_freertos/public/pw_sync_freertos/counting_semaphore_inline.h b/pw_sync_freertos/public/pw_sync_freertos/counting_semaphore_inline.h
new file mode 100644
index 0000000..8a293d2
--- /dev/null
+++ b/pw_sync_freertos/public/pw_sync_freertos/counting_semaphore_inline.h
@@ -0,0 +1,74 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include "FreeRTOS.h"
+#include "pw_assert/light.h"
+#include "pw_chrono/system_clock.h"
+#include "pw_chrono_freertos/system_clock_constants.h"
+#include "pw_interrupt/context.h"
+#include "pw_sync/counting_semaphore.h"
+#include "semphr.h"
+
+namespace pw::sync {
+
+inline CountingSemaphore::CountingSemaphore() : native_type_() {
+  native_type_.handle =
+      xSemaphoreCreateCountingStatic(max(), 0, &native_type_.buffer);
+  // This should never fail since the pointer provided was not null.
+  PW_DASSERT(native_type_.handle != nullptr);
+}
+
+inline CountingSemaphore::~CountingSemaphore() {
+  vSemaphoreDelete(&native_type_);
+}
+
+inline void CountingSemaphore::acquire() {
+  PW_ASSERT(!interrupt::InInterruptContext());
+#if INCLUDE_vTaskSuspend == 1  // This means portMAX_DELAY is indefinite.
+  const BaseType_t result = xSemaphoreTake(native_type_.handle, portMAX_DELAY);
+  PW_DASSERT(result == pdTRUE);
+#else
+  // In case we need to block for longer than the FreeRTOS delay can represent
+  // repeatedly hit take until success.
+  while (xSemaphoreTake(native_type_.handle,
+                        chrono::freertos::kMaxTimeout.count()) == pdFALSE) {
+  }
+#endif  // INCLUDE_vTaskSuspend
+}
+
+inline bool CountingSemaphore::try_acquire() {
+  if (interrupt::InInterruptContext()) {
+    BaseType_t woke_higher_task = pdFALSE;
+    const bool success =
+        xSemaphoreTakeFromISR(native_type_.handle, &woke_higher_task) == pdTRUE;
+    portYIELD_FROM_ISR(woke_higher_task);
+    return success;
+  }
+
+  // Task Context
+  return xSemaphoreTake(native_type_.handle, 0) == pdTRUE;
+}
+
+inline bool CountingSemaphore::try_acquire_until(
+    chrono::SystemClock::time_point until_at_least) {
+  return try_acquire_for(until_at_least - chrono::SystemClock::now());
+}
+
+inline CountingSemaphore::native_handle_type
+CountingSemaphore::native_handle() {
+  return native_type_;
+}
+
+}  // namespace pw::sync
diff --git a/pw_sync_freertos/public/pw_sync_freertos/counting_semaphore_native.h b/pw_sync_freertos/public/pw_sync_freertos/counting_semaphore_native.h
new file mode 100644
index 0000000..4e1f06f
--- /dev/null
+++ b/pw_sync_freertos/public/pw_sync_freertos/counting_semaphore_native.h
@@ -0,0 +1,35 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include <limits>
+
+#include "FreeRTOS.h"
+#include "semphr.h"
+
+namespace pw::sync::backend {
+
+struct NativeCountingSemaphore {
+  StaticSemaphore_t buffer;
+  SemaphoreHandle_t handle;
+};
+using NativeCountingSemaphoreHandle = NativeCountingSemaphore&;
+
+inline constexpr ptrdiff_t kBinarySemaphoreMaxValue =
+    std::numeric_limits<ptrdiff_t>::max() <
+            std::numeric_limits<UBaseType_t>::max()
+        ? std::numeric_limits<ptrdiff_t>::max()
+        : std::numeric_limits<UBaseType_t>::max();
+
+}  // namespace pw::sync::backend
diff --git a/pw_sync_freertos/public/pw_sync_freertos/mutex_inline.h b/pw_sync_freertos/public/pw_sync_freertos/mutex_inline.h
new file mode 100644
index 0000000..9ae4b7a
--- /dev/null
+++ b/pw_sync_freertos/public/pw_sync_freertos/mutex_inline.h
@@ -0,0 +1,66 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include "FreeRTOS.h"
+#include "pw_assert/light.h"
+#include "pw_chrono/system_clock.h"
+#include "pw_chrono_freertos/system_clock_constants.h"
+#include "pw_interrupt/context.h"
+#include "pw_sync/mutex.h"
+#include "semphr.h"
+
+namespace pw::sync {
+
+inline Mutex::Mutex() : native_type_() {
+  native_type_.handle = xSemaphoreCreateMutexStatic(&native_type_.buffer);
+  // This should never fail since the pointer provided was not null.
+  PW_DASSERT(native_type_.handle != nullptr);
+}
+
+inline Mutex::~Mutex() { vSemaphoreDelete(&native_type_); }
+
+inline void Mutex::lock() {
+  PW_ASSERT(!interrupt::InInterruptContext());
+#if INCLUDE_vTaskSuspend == 1  // This means portMAX_DELAY is indefinite.
+  const BaseType_t result = xSemaphoreTake(native_type_.handle, portMAX_DELAY);
+  PW_DASSERT(result == pdTRUE);
+#else
+  // In case we need to block for longer than the FreeRTOS delay can represent
+  // repeatedly hit take until success.
+  while (xSemaphoreTake(native_type_.handle,
+                        chrono::freertos::kMaxTimeout.count()) == pdFALSE) {
+  }
+#endif  // INCLUDE_vTaskSuspend
+}
+
+inline bool Mutex::try_lock() {
+  PW_ASSERT(!interrupt::InInterruptContext());
+  return xSemaphoreTake(native_type_.handle, 0) == pdTRUE;
+}
+
+inline bool Mutex::try_lock_until(
+    chrono::SystemClock::time_point until_at_least) {
+  return try_lock_for(until_at_least - chrono::SystemClock::now());
+}
+
+inline void Mutex::unlock() {
+  PW_ASSERT(!interrupt::InInterruptContext());
+  // Unlocking only fails if it was not locked first.
+  PW_ASSERT(xSemaphoreGive(native_type_.handle) == pdTRUE);
+}
+
+inline Mutex::native_handle_type Mutex::native_handle() { return native_type_; }
+
+}  // namespace pw::sync
diff --git a/pw_sync_freertos/public/pw_sync_freertos/mutex_native.h b/pw_sync_freertos/public/pw_sync_freertos/mutex_native.h
new file mode 100644
index 0000000..17613b9
--- /dev/null
+++ b/pw_sync_freertos/public/pw_sync_freertos/mutex_native.h
@@ -0,0 +1,27 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include "FreeRTOS.h"
+#include "semphr.h"
+
+namespace pw::sync::backend {
+
+struct NativeMutex {
+  StaticSemaphore_t buffer;
+  SemaphoreHandle_t handle;
+};
+using NativeMutexHandle = NativeMutex&;
+
+}  // namespace pw::sync::backend
diff --git a/pw_sync_freertos/public/pw_sync_freertos/spin_lock_inline.h b/pw_sync_freertos/public/pw_sync_freertos/spin_lock_inline.h
new file mode 100644
index 0000000..af81d78
--- /dev/null
+++ b/pw_sync_freertos/public/pw_sync_freertos/spin_lock_inline.h
@@ -0,0 +1,27 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include "pw_sync/spin_lock.h"
+
+namespace pw::sync {
+
+inline SpinLock::SpinLock()
+    : native_type_{.locked = false, .saved_interrupt_mask = 0} {}
+
+inline SpinLock::native_handle_type SpinLock::native_handle() {
+  return native_type_;
+}
+
+}  // namespace pw::sync
diff --git a/pw_sync_freertos/public/pw_sync_freertos/spin_lock_native.h b/pw_sync_freertos/public/pw_sync_freertos/spin_lock_native.h
new file mode 100644
index 0000000..c291e4a
--- /dev/null
+++ b/pw_sync_freertos/public/pw_sync_freertos/spin_lock_native.h
@@ -0,0 +1,28 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include <atomic>
+
+#include "FreeRTOS.h"
+
+namespace pw::sync::backend {
+
+struct NativeSpinLock {
+  std::atomic<bool> locked;  // Used to detect recursion.
+  UBaseType_t saved_interrupt_mask;
+};
+using NativeSpinLockHandle = NativeSpinLock&;
+
+}  // namespace pw::sync::backend
diff --git a/pw_sync_freertos/public_overrides/pw_sync_backend/binary_semaphore_inline.h b/pw_sync_freertos/public_overrides/pw_sync_backend/binary_semaphore_inline.h
new file mode 100644
index 0000000..9a41fdf
--- /dev/null
+++ b/pw_sync_freertos/public_overrides/pw_sync_backend/binary_semaphore_inline.h
@@ -0,0 +1,16 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include "pw_sync_freertos/binary_semaphore_inline.h"
diff --git a/pw_sync_freertos/public_overrides/pw_sync_backend/binary_semaphore_native.h b/pw_sync_freertos/public_overrides/pw_sync_backend/binary_semaphore_native.h
new file mode 100644
index 0000000..7b95373
--- /dev/null
+++ b/pw_sync_freertos/public_overrides/pw_sync_backend/binary_semaphore_native.h
@@ -0,0 +1,16 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include "pw_sync_freertos/binary_semaphore_native.h"
diff --git a/pw_sync_freertos/public_overrides/pw_sync_backend/counting_semaphore_inline.h b/pw_sync_freertos/public_overrides/pw_sync_backend/counting_semaphore_inline.h
new file mode 100644
index 0000000..7a03fdb
--- /dev/null
+++ b/pw_sync_freertos/public_overrides/pw_sync_backend/counting_semaphore_inline.h
@@ -0,0 +1,16 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include "pw_sync_freertos/counting_semaphore_inline.h"
diff --git a/pw_sync_freertos/public_overrides/pw_sync_backend/counting_semaphore_native.h b/pw_sync_freertos/public_overrides/pw_sync_backend/counting_semaphore_native.h
new file mode 100644
index 0000000..b3a9d1d
--- /dev/null
+++ b/pw_sync_freertos/public_overrides/pw_sync_backend/counting_semaphore_native.h
@@ -0,0 +1,16 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include "pw_sync_freertos/counting_semaphore_native.h"
diff --git a/pw_sync_freertos/public_overrides/pw_sync_backend/mutex_inline.h b/pw_sync_freertos/public_overrides/pw_sync_backend/mutex_inline.h
new file mode 100644
index 0000000..2c55565
--- /dev/null
+++ b/pw_sync_freertos/public_overrides/pw_sync_backend/mutex_inline.h
@@ -0,0 +1,16 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include "pw_sync_freertos/mutex_inline.h"
diff --git a/pw_sync_freertos/public_overrides/pw_sync_backend/mutex_native.h b/pw_sync_freertos/public_overrides/pw_sync_backend/mutex_native.h
new file mode 100644
index 0000000..36647a9
--- /dev/null
+++ b/pw_sync_freertos/public_overrides/pw_sync_backend/mutex_native.h
@@ -0,0 +1,16 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include "pw_sync_freertos/mutex_native.h"
diff --git a/pw_sync_freertos/public_overrides/pw_sync_backend/spin_lock_inline.h b/pw_sync_freertos/public_overrides/pw_sync_backend/spin_lock_inline.h
new file mode 100644
index 0000000..94e44eb
--- /dev/null
+++ b/pw_sync_freertos/public_overrides/pw_sync_backend/spin_lock_inline.h
@@ -0,0 +1,16 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include "pw_sync_freertos/spin_lock_inline.h"
diff --git a/pw_sync_freertos/public_overrides/pw_sync_backend/spin_lock_native.h b/pw_sync_freertos/public_overrides/pw_sync_backend/spin_lock_native.h
new file mode 100644
index 0000000..103292e
--- /dev/null
+++ b/pw_sync_freertos/public_overrides/pw_sync_backend/spin_lock_native.h
@@ -0,0 +1,16 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+#pragma once
+
+#include "pw_sync_freertos/spin_lock_native.h"
diff --git a/pw_sync_freertos/spin_lock.cc b/pw_sync_freertos/spin_lock.cc
new file mode 100644
index 0000000..b7898f8
--- /dev/null
+++ b/pw_sync_freertos/spin_lock.cc
@@ -0,0 +1,65 @@
+// Copyright 2020 The Pigweed Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License"); you may not
+// use this file except in compliance with the License. You may obtain a copy of
+// the License at
+//
+//     https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations under
+// the License.
+
+#include "pw_sync/spin_lock.h"
+
+#include "pw_assert/assert.h"
+#include "pw_interrupt/context.h"
+#include "task.h"
+
+namespace pw::sync {
+
+void SpinLock::lock() {
+  if (interrupt::InInterruptContext()) {
+    native_type_.saved_interrupt_mask = taskENTER_CRITICAL_FROM_ISR();
+  } else {  // Task context
+    taskENTER_CRITICAL();
+  }
+  // We can't deadlock here so crash instead.
+  PW_CHECK(!native_type_.locked.load(std::memory_order_relaxed),
+           "Recursive SpinLock::lock() detected");
+  native_type_.locked.store(true, std::memory_order_relaxed);
+}
+
+bool SpinLock::try_lock() {
+  if (interrupt::InInterruptContext()) {
+    UBaseType_t saved_interrupt_mask = taskENTER_CRITICAL_FROM_ISR();
+    if (native_type_.locked.load(std::memory_order_relaxed)) {
+      // Already locked, restore interrupts and bail out.
+      taskEXIT_CRITICAL_FROM_ISR(saved_interrupt_mask);
+      return false;
+    }
+    native_type_.saved_interrupt_mask = saved_interrupt_mask;
+  } else {  // Task context
+    taskENTER_CRITICAL();
+    if (native_type_.locked.load(std::memory_order_relaxed)) {
+      // ALready locked, restore interrupts and bail out.
+      taskEXIT_CRITICAL();
+      return false;
+    }
+  }
+  native_type_.locked.store(true, std::memory_order_relaxed);
+  return true;
+}
+
+void SpinLock::unlock() {
+  native_type_.locked.store(false, std::memory_order_relaxed);
+  if (interrupt::InInterruptContext()) {
+    taskEXIT_CRITICAL_FROM_ISR(native_type_.saved_interrupt_mask);
+  } else {  // Task context
+    taskEXIT_CRITICAL();
+  }
+}
+
+}  // namespace pw::sync
diff --git a/third_party/freertos/BUILD.gn b/third_party/freertos/BUILD.gn
new file mode 100644
index 0000000..416f7e6
--- /dev/null
+++ b/third_party/freertos/BUILD.gn
@@ -0,0 +1,78 @@
+# Copyright 2020 The Pigweed Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may not
+# use this file except in compliance with the License. You may obtain a copy of
+# the License at
+#
+#     https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations under
+# the License.
+
+import("//build_overrides/pigweed.gni")
+
+import("$dir_pw_build/target_types.gni")
+import("freertos.gni")
+
+# This file defines a GN source_set for an external installation of freertos.
+# To use, checkout the freertos source into a directory, then set the build arg
+# dir_pw_third_party_freertos to point to that directory. The freertos library
+# will be available in GN at "$dir_pw_third_party/freertos".
+if (dir_pw_third_party_freertos != "") {
+  config("disable_warnings") {
+    cflags = [ "-Wno-error=unused-parameter" ]
+    visibility = [ ":*" ]
+  }
+
+  config("public_includes") {
+    include_dirs = [ "Source/include" ]
+    visibility = [ ":*" ]
+  }
+
+  pw_source_set("freertos") {
+    public_configs = [ ":public_includes" ]
+    allow_circular_includes_from = [ pw_third_party_freertos_PORT ]
+    public_deps = [
+      pw_third_party_freertos_CONFIG,
+      pw_third_party_freertos_PORT,
+    ]
+    public = [
+      "$dir_pw_third_party_freertos/Source/include/FreeRTOS.h",
+      "$dir_pw_third_party_freertos/Source/include/StackMacros.h",
+      "$dir_pw_third_party_freertos/Source/include/croutine.h",
+      "$dir_pw_third_party_freertos/Source/include/deprecated_definitions.h",
+      "$dir_pw_third_party_freertos/Source/include/event_groups.h",
+      "$dir_pw_third_party_freertos/Source/include/list.h",
+      "$dir_pw_third_party_freertos/Source/include/message_buffer.h",
+      "$dir_pw_third_party_freertos/Source/include/mpu_prototypes.h",
+      "$dir_pw_third_party_freertos/Source/include/mpu_wrappers.h",
+      "$dir_pw_third_party_freertos/Source/include/portable.h",
+      "$dir_pw_third_party_freertos/Source/include/projdefs.h",
+      "$dir_pw_third_party_freertos/Source/include/queue.h",
+      "$dir_pw_third_party_freertos/Source/include/semphr.h",
+      "$dir_pw_third_party_freertos/Source/include/stack_macros.h",
+      "$dir_pw_third_party_freertos/Source/include/stream_buffer.h",
+      "$dir_pw_third_party_freertos/Source/include/task.h",
+      "$dir_pw_third_party_freertos/Source/include/timers.h",
+    ]
+    configs = [ ":disable_warnings" ]
+    sources = [
+      "$dir_pw_third_party_freertos/Source/croutine.c",
+      "$dir_pw_third_party_freertos/Source/event_groups.c",
+
+      # Put here to ensure it cannot be included.
+      "$dir_pw_third_party_freertos/Source/include/FreeRTOSConfig_template.h",
+      "$dir_pw_third_party_freertos/Source/list.c",
+      "$dir_pw_third_party_freertos/Source/queue.c",
+      "$dir_pw_third_party_freertos/Source/stream_buffer.c",
+      "$dir_pw_third_party_freertos/Source/tasks.c",
+      "$dir_pw_third_party_freertos/Source/timers.c",
+    ]
+  }
+} else {
+  group("freertos") {
+  }
+}
diff --git a/third_party/freertos/freertos.gni b/third_party/freertos/freertos.gni
new file mode 100644
index 0000000..c3f5147
--- /dev/null
+++ b/third_party/freertos/freertos.gni
@@ -0,0 +1,26 @@
+# Copyright 2020 The Pigweed Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may not
+# use this file except in compliance with the License. You may obtain a copy of
+# the License at
+#
+#     https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations under
+# the License.
+
+declare_args() {
+  # If compiling backends with freertos, this variable is set to the path to the
+  # freertos installation. When set, a pw_source_set for the freertos library is
+  # created at "$dir_pw_third_party/freertos".
+  dir_pw_third_party_freertos = ""
+
+  # The pw_source_set which provides the FreeRTOS config header.
+  pw_third_party_freertos_CONFIG = ""
+
+  # The pw_source_set which provides the port specific includes and sources.
+  pw_third_party_freertos_PORT = ""
+}