[FFmpeg-devel] [PATCH] lavu/riscv: cycle counter for AV_READ_TIME

remi at remlab.net remi at remlab.net
Mon Sep 5 20:05:59 EEST 2022


From: Rémi Denis-Courmont <remi at remlab.net>

This uses the architected RISC-V 64-bit cycle counter from the
RISC-V unprivileged instruction set.

In 64-bit and 128-bit, this is a straightforward CSR read.
In 32-bit mode, the 64-bit value is exposed as two CSRs, which
cannot be read atomically, so a loop is necessary to detect and fix up
the race condition where the bottom half wraps exactly between the two
reads.

---
Tested on VisionFive SBC courtesy of Shanghai StarFive Technology.
---
 libavutil/riscv/timer.h | 54 +++++++++++++++++++++++++++++++++++++++++
 libavutil/timer.h       |  2 ++
 2 files changed, 56 insertions(+)
 create mode 100644 libavutil/riscv/timer.h

diff --git a/libavutil/riscv/timer.h b/libavutil/riscv/timer.h
new file mode 100644
index 0000000000..02a4b3962e
--- /dev/null
+++ b/libavutil/riscv/timer.h
@@ -0,0 +1,54 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_RISCV_TIMER_H
+#define AVUTIL_RISCV_TIMER_H
+
+#include "config.h"
+
+#if HAVE_INLINE_ASM
+#include <stdint.h>
+
+static inline uint64_t rdcycle64(void)
+{
+#if (__riscv_xlen >= 64)
+    uintptr_t cycles;
+
+    __asm__ volatile ("rdcycle %0" : "=r"(cycles));
+
+#else
+    uint64_t cycles;
+    uint32_t hi, lo, check;
+
+    do {
+        __asm__ volatile (
+            "rdcycleh %0\n"
+            "rdcycle  %1\n"
+            "rdcycleh %2\n" : "=r" (hi), "=r" (lo), "=r" (check));
+    } while (hi != check);
+
+    cycles = (((uint64_t)hi) << 32) | lo;
+
+#endif
+    return cycles;
+}
+
+#define AV_READ_TIME rdcycle64
+
+#endif
+#endif /* AVUTIL_RISCV_TIMER_H */
diff --git a/libavutil/timer.h b/libavutil/timer.h
index 48e576739f..0b3460c682 100644
--- a/libavutil/timer.h
+++ b/libavutil/timer.h
@@ -55,6 +55,8 @@
 #   include "aarch64/timer.h"
 #elif ARCH_ARM
 #   include "arm/timer.h"
+#elif ARCH_RISCV
+#   include "riscv/timer.h"
 #elif ARCH_PPC
 #   include "ppc/timer.h"
 #elif ARCH_X86
-- 
2.37.2



More information about the ffmpeg-devel mailing list