From: Baineng Shou <shoubaineng@gmail.com>
To: Vinod Koul <vkoul@kernel.org>
Cc: Baineng Shou <shoubaineng@gmail.com>,
Frank Li <Frank.Li@kernel.org>,
dmaengine@vger.kernel.org, Jonathan Corbet <corbet@lwn.net>,
Shuah Khan <skhan@linuxfoundation.org>,
Randy Dunlap <rdunlap@infradead.org>,
linux-doc@vger.kernel.org
Subject: [PATCH] dmaengine: dmatest: Add optional per-stage latency profiling
Date: Tue, 1 Dec 2026 10:58:13 +0800 [thread overview]
Message-ID: <20261201025813.2994236-1-shoubaineng@gmail.com> (raw)
The aggregate dmatest throughput does not show whether time is spent in
DMA mapping, descriptor preparation, execution or completion delivery.
This makes it difficult to investigate a low copy rate without adding
ad-hoc instrumentation to a test client or a controller driver.
Add a profile parameter to accumulate six consecutive latency intervals
per test thread: map, prep, submit, issue-to-callback, callback-to-wait-
return, and status-check/unmap. Report the average latency, elapsed time
and percentage for each interval after the existing summary, together
with the minimum, average and maximum map-to-unmap latency. Derive the
effective and execution rates from aggregate bytes and aggregate time.
Publish the callback timestamp before the completion flag using release
and acquire ordering. Include issue_pending() in the issue-to-callback
interval so that a callback running before the issue call returns does
not create overlapping intervals. Stop accumulating samples after the
first transfer error, verification failure or invalid timestamp sequence
to avoid attributing late callbacks to subsequent samples. Leave the
existing test flow and error handling in place.
Keep profiling disabled by default and print only per-thread totals at
test completion. Preserve the existing summary and verbose output, and
report profiling as unavailable in polled mode. Document the boundaries,
the accounting rules and the added measurement overhead. In particular,
execution latency includes queueing, interrupt and driver completion
processing; neither rate represents hardware-only or whole-run bandwidth.
---
Validation:
- x86-64, GCC 12: minimal vmlinux and modules build, DMATEST=m, W=1.
- i386, GCC 12: dmatest.o build, DMATEST=y, W=1.
- arm64, Clang 19: dmatest.o cross-build, DMATEST=y, W=1.
- Host tests exercise the accounting helpers extracted from this source,
with UBSan, including invalid timestamps and early-callback ordering.
These tests do not exercise kernel callback concurrency.
- Complete dmatest.rst parsed by Docutils; no full Sphinx build.
- checkpatch --strict --no-signoff and git diff --check.
A downstream port ran on ASR8861 with 1, 2, 4, 8 and 10 channels and
1 MiB copies. It completed 60 verified transfers and 30,000 transfers
with verification disabled without reported failures. That port has
different error handling and is not a runtime test of this exact patch.
This mainline version has not been run on DMA hardware; controlled
profile-on/off overhead and late-callback fault injection remain untested.
AI assistance: OpenAI Codex assisted with the implementation,
documentation, commit message and validation. The request was to retain
the existing summary and DMA controller drivers, add optional per-stage
latency accounting in dmatest, and report per-thread totals only when
testing finishes. The human submitter must review and certify the DCO.
.../driver-api/dmaengine/dmatest.rst | 82 +++++++++
drivers/dma/dmatest.c | 167 +++++++++++++++++-
2 files changed, 247 insertions(+), 2 deletions(-)
diff --git a/Documentation/driver-api/dmaengine/dmatest.rst b/Documentation/driver-api/dmaengine/dmatest.rst
index e2a63cefd783..677101bf74b1 100644
--- a/Documentation/driver-api/dmaengine/dmatest.rst
+++ b/Documentation/driver-api/dmaengine/dmatest.rst
@@ -230,3 +230,85 @@ Example::
Channels allocated by previous test runs are automatically freed when a new
channel is requested after completing a successful test run.
+
+Part 6 - Optional latency profiling
+=====================================
+
+Set ``profile=1`` before selecting channels to collect per-thread latency
+statistics. Profiling is disabled by default and does not require changes to
+the DMA controller driver. For example::
+
+ % modprobe dmatest
+ % echo 1 > /sys/module/dmatest/parameters/profile
+ % echo 100 > /sys/module/dmatest/parameters/iterations
+ % echo 0 > /sys/module/dmatest/parameters/verbose
+ % echo dma0chan0 > /sys/module/dmatest/parameters/channel
+ % echo 1 > /sys/module/dmatest/parameters/run
+ % cat /sys/module/dmatest/parameters/wait
+
+Choose an available channel on the system under test. The existing summary,
+verification, error handling and verbose output are unchanged. Profiling adds
+an aggregate report when each thread finishes; it does not log individual
+samples. Leave verbose logging and dynamic debug disabled when measuring
+latency. Polled tests run normally but report profiling as unavailable, since
+they do not use a completion callback.
+
+Seven monotonic timestamps delimit six consecutive stages:
+
+.. list-table:: Profiling boundaries
+ :header-rows: 1
+ :widths: 15 85
+
+ * - Stage
+ - Interval
+ * - Map
+ - Before allocating unmap metadata through completion of source and
+ destination DMA mappings.
+ * - Prep
+ - After mapping through descriptor preparation and callback setup, ending
+ immediately before submitting the descriptor.
+ * - Submit
+ - Before submission through the cookie check, ending immediately before
+ calling ``dma_async_issue_pending()``.
+ * - Execute
+ - Before ``dma_async_issue_pending()`` through timestamp capture in the
+ completion callback.
+ * - Wakeup
+ - Callback timestamp capture through return from the completion wait.
+ * - Unmap
+ - Return from the wait through completion-status checking and DMA unmap.
+
+Execute includes the issue call, possible queueing, hardware execution,
+interrupt latency and driver completion processing. It is not a measurement
+of hardware-only transfer time. A callback can run before the issue call
+returns; in that case Wakeup also includes the remainder of the issue call
+and must not be interpreted as scheduler latency alone.
+
+Each stage reports its average in microseconds, its percentage of the summed
+stage times and its total in nanoseconds. The sum covers the contiguous
+map-to-unmap interval, including bookkeeping between its boundaries. It
+excludes buffer filling, verification, random parameter generation, initial
+resource allocation and final cleanup. Minimum, average and maximum latency
+refer to this interval. Displayed percentages may not sum to exactly 100 due
+to rounding.
+
+Only successful transfers with ordered timestamps are included. With
+``noverify=0``, a sample must also pass data verification. After the first
+transfer error, verification failure or invalid timestamp sequence, the
+thread stops collecting samples and marks its report ``aborted=1``. This
+prevents a late callback following a timeout from being attributed to a later
+sample. The original test and its error handling continue unchanged.
+
+The report includes the number of samples and their actual transferred byte
+count. For an error-free run with valid samples, Effective BW divides that
+byte count by the summed map-to-unmap time; Execution BW divides it by the
+summed Execute time. Both use MiB/s and count each transfer's data length
+once, without multiplying by the number of source buffers or counting the
+read and write traffic separately. They are ratios of sums, rather than
+averages of individual transfer rates.
+
+These rates have different timing windows from the original summary. Rates
+from different threads must not be added to infer system-wide throughput:
+their measurement windows can overlap and differ in duration. Timestamp
+capture and accumulation add overhead when profiling is enabled, so compare
+with profiling disabled, particularly for small transfers.
diff --git a/drivers/dma/dmatest.c b/drivers/dma/dmatest.c
index 2ae3469397f3..e692b41759d6 100644
--- a/drivers/dma/dmatest.c
+++ b/drivers/dma/dmatest.c
@@ -16,6 +16,8 @@
#include <linux/kthread.h>
#include <linux/sched/task.h>
#include <linux/module.h>
+#include <linux/math64.h>
+#include <linux/timekeeping.h>
#include <linux/moduleparam.h>
#include <linux/random.h>
#include <linux/slab.h>
@@ -88,6 +90,10 @@ static unsigned int transfer_size;
module_param(transfer_size, uint, 0644);
MODULE_PARM_DESC(transfer_size, "Optional custom transfer size in bytes (default: not used (0))");
+static bool profile;
+module_param(profile, bool, 0644);
+MODULE_PARM_DESC(profile, "Report per-stage latency statistics at test completion (default: off)");
+
static bool polled;
module_param(polled, bool, 0644);
MODULE_PARM_DESC(polled, "Use polling for completion instead of interrupts");
@@ -108,6 +114,7 @@ MODULE_PARM_DESC(polled, "Use polling for completion instead of interrupts");
* @norandom: disable random offset setup
* @alignment: custom data address alignment taken as 2^alignment
* @transfer_size: custom transfer size in bytes
+ * @profile: collect per-stage latency statistics
* @polled: use polling for completion instead of interrupts
*/
struct dmatest_params {
@@ -126,6 +133,7 @@ struct dmatest_params {
int alignment;
unsigned int transfer_size;
bool polled;
+ bool profile;
};
/**
@@ -217,6 +225,8 @@ MODULE_PARM_DESC(test_list, "Print current test list");
/* poor man's completion - we want to use wait_event_freezable() on it */
struct dmatest_done {
bool done;
+ bool profile;
+ u64 callback_ns;
wait_queue_head_t *wait;
};
@@ -439,7 +449,10 @@ static void dmatest_callback(void *arg)
struct dmatest_thread *thread =
container_of(done, struct dmatest_thread, test_done);
if (!thread->done) {
- done->done = true;
+ if (done->profile)
+ done->callback_ns = ktime_get_ns();
+ /* Publish callback_ns before the waiting thread observes done. */
+ smp_store_release(&done->done, true);
wake_up_all(done->wait);
} else {
/*
@@ -512,6 +525,110 @@ static unsigned long long dmatest_KBs(s64 runtime, unsigned long long len)
return FIXPT_TO_INT(dmatest_persec(runtime, len >> 10));
}
+/* Consecutive boundaries: map, prep, submit, issue, callback, wake, unmap. */
+enum dmatest_profile_stage {
+ PROFILE_MAP, PROFILE_PREP, PROFILE_SUBMIT, PROFILE_EXECUTE,
+ PROFILE_WAKEUP, PROFILE_UNMAP, PROFILE_STAGES,
+};
+
+struct dmatest_profile_sample {
+ u64 ts[PROFILE_STAGES + 1];
+};
+
+struct dmatest_profile_stats {
+ u64 ns[PROFILE_STAGES];
+ u64 total_ns;
+ u64 min_ns;
+ u64 max_ns;
+ u64 bytes;
+ u64 samples;
+ u64 invalid;
+ bool aborted;
+};
+
+static bool dmatest_profile_add(struct dmatest_profile_stats *stats,
+ const struct dmatest_profile_sample *sample,
+ unsigned int len)
+{
+ const u64 *ts = sample->ts;
+ u64 ns;
+ int i;
+
+ for (i = 0; i < PROFILE_STAGES; i++) {
+ if (ts[i + 1] < ts[i])
+ goto invalid;
+ }
+ ns = ts[PROFILE_STAGES] - ts[0];
+ if (!ns || ts[PROFILE_WAKEUP] == ts[PROFILE_EXECUTE])
+ goto invalid;
+ for (i = 0; i < PROFILE_STAGES; i++)
+ stats->ns[i] += ts[i + 1] - ts[i];
+ stats->total_ns += ns;
+ if (!stats->samples || ns < stats->min_ns)
+ stats->min_ns = ns;
+ stats->max_ns = max(stats->max_ns, ns);
+ stats->bytes += len;
+ stats->samples++;
+ return true;
+invalid:
+ stats->invalid++;
+ stats->aborted = true;
+ return false;
+}
+
+static void dmatest_profile_rate(const char *name, u64 bytes, u64 ns)
+{
+ u64 bytes_per_sec, rate;
+ u32 fraction;
+
+ if (!ns)
+ return;
+ /* Aggregate bytes / aggregate time, not the mean of per-copy rates. */
+ bytes_per_sec = mul_u64_u64_div_u64(bytes, NSEC_PER_SEC, ns);
+ rate = mul_u64_u64_div_u64(bytes_per_sec, 1000, 1ULL << 20);
+ rate = div_u64_rem(rate, 1000, &fraction);
+ pr_info("%s: profiling %s BW: %llu.%03u MiB/s\n",
+ current->comm, name, rate, fraction);
+}
+
+static void dmatest_profile_report(const struct dmatest_profile_stats *stats,
+ unsigned int attempted, unsigned int failures,
+ int error, bool verified)
+{
+ static const char * const names[] = {
+ "Map", "Prep", "Submit", "Execute", "Wakeup", "Unmap",
+ };
+ u64 avg, percent;
+ u32 avg_fraction, percent_fraction;
+ int i;
+
+ pr_info("%s: profiling samples=%llu attempted=%u failures=%u invalid=%llu bytes=%llu verified=%u aborted=%u error=%d\n",
+ current->comm, stats->samples, attempted, failures, stats->invalid,
+ stats->bytes, verified, stats->aborted, error);
+ pr_info("%s: profiling Stage Avg(us) Percent Total(ns)\n",
+ current->comm);
+ for (i = 0; i < PROFILE_STAGES; i++) {
+ /* Fixed point: 0.01 us and 0.01 percent. */
+ avg = stats->samples ? div_u64(div64_u64(stats->ns[i], stats->samples), 10) : 0;
+ percent = stats->total_ns ?
+ mul_u64_u64_div_u64(stats->ns[i], 10000, stats->total_ns) : 0;
+ avg = div_u64_rem(avg, 100, &avg_fraction);
+ percent = div_u64_rem(percent, 100, &percent_fraction);
+ pr_info("%s: profiling %-8s %8llu.%02u %6llu.%02u%% %15llu\n",
+ current->comm, names[i], avg, avg_fraction,
+ percent, percent_fraction, stats->ns[i]);
+ }
+ avg = stats->samples ? div64_u64(stats->total_ns, stats->samples) : 0;
+ pr_info("%s: profiling total_ns=%llu min_ns=%llu avg_ns=%llu max_ns=%llu\n",
+ current->comm, stats->total_ns, stats->min_ns, avg, stats->max_ns);
+ if (!error && !failures && !stats->aborted && stats->samples) {
+ dmatest_profile_rate("Effective", stats->bytes, stats->total_ns);
+ dmatest_profile_rate("Execution", stats->bytes, stats->ns[PROFILE_EXECUTE]);
+ }
+ pr_info("%s: profiling Execute=issue-to-callback (includes IRQ/tasklet); Total excludes fill/verify/initialization\n",
+ current->comm);
+}
+
static void __dmatest_free_test_data(struct dmatest_data *d, unsigned int cnt)
{
unsigned int i;
@@ -604,6 +721,8 @@ static int dmatest_func(void *data)
bool is_memset = false;
dma_addr_t *srcs;
dma_addr_t *dma_pq;
+ struct dmatest_profile_stats profile_stats = {};
+ bool profile_requested, profile_polled, do_profile;
set_freezable();
@@ -613,6 +732,10 @@ static int dmatest_func(void *data)
thread->pending = false;
info = thread->info;
params = &info->params;
+ profile_requested = params->profile;
+ profile_polled = params->polled;
+ do_profile = profile_requested && !profile_polled;
+ done->profile = do_profile;
chan = thread->chan;
dev = chan->device;
dma_dev = dmaengine_get_dma_device(chan);
@@ -702,8 +825,13 @@ static int dmatest_func(void *data)
struct dmaengine_unmap_data *um;
dma_addr_t *dsts;
unsigned int len;
+ struct dmatest_profile_sample ps;
total_tests++;
+ if (do_profile) {
+ memset(&ps, 0, sizeof(ps));
+ done->callback_ns = 0;
+ }
if (params->transfer_size) {
if (params->transfer_size >= buf_size) {
@@ -748,9 +876,13 @@ static int dmatest_func(void *data)
filltime = ktime_add(filltime, diff);
}
+ if (do_profile)
+ ps.ts[PROFILE_MAP] = ktime_get_ns();
um = dmaengine_get_unmap_data(dma_dev, src->cnt + dst->cnt,
GFP_KERNEL);
if (!um) {
+ profile_stats.aborted = true;
+ do_profile = false;
failed_tests++;
result("unmap data NULL", total_tests,
src->off, dst->off, len, ret);
@@ -792,6 +924,8 @@ static int dmatest_func(void *data)
um->bidi_cnt++;
}
+ if (do_profile)
+ ps.ts[PROFILE_PREP] = ktime_get_ns();
if (thread->type == DMA_MEMCPY)
tx = dev->device_prep_dma_memcpy(chan,
dsts[0] + dst->off,
@@ -826,6 +960,8 @@ static int dmatest_func(void *data)
tx->callback = dmatest_callback;
tx->callback_param = done;
}
+ if (do_profile)
+ ps.ts[PROFILE_SUBMIT] = ktime_get_ns();
cookie = tx->tx_submit(tx);
if (dma_submit_error(cookie)) {
@@ -841,12 +977,17 @@ static int dmatest_func(void *data)
if (status == DMA_COMPLETE)
done->done = true;
} else {
+ if (do_profile)
+ ps.ts[PROFILE_EXECUTE] = ktime_get_ns();
dma_async_issue_pending(chan);
wait_event_freezable_timeout(thread->done_wait,
- done->done,
+ /* Pairs with callback's store-release. */
+ smp_load_acquire(&done->done),
msecs_to_jiffies(params->timeout));
+ if (do_profile)
+ ps.ts[PROFILE_UNMAP] = ktime_get_ns();
status = dma_async_is_tx_complete(chan, cookie, NULL,
NULL);
}
@@ -867,8 +1008,14 @@ static int dmatest_func(void *data)
}
dmaengine_unmap_put(um);
+ if (do_profile) {
+ ps.ts[PROFILE_STAGES] = ktime_get_ns();
+ ps.ts[PROFILE_WAKEUP] = done->callback_ns;
+ }
if (params->noverify) {
+ if (do_profile)
+ do_profile = dmatest_profile_add(&profile_stats, &ps, len);
verbose_result("test passed", total_tests, src->off,
dst->off, len, 0);
continue;
@@ -901,10 +1048,14 @@ static int dmatest_func(void *data)
comparetime = ktime_add(comparetime, diff);
if (error_count) {
+ profile_stats.aborted = true;
+ do_profile = false;
result("data error", total_tests, src->off, dst->off,
len, error_count);
failed_tests++;
} else {
+ if (do_profile)
+ do_profile = dmatest_profile_add(&profile_stats, &ps, len);
verbose_result("test passed", total_tests, src->off,
dst->off, len, 0);
}
@@ -912,6 +1063,9 @@ static int dmatest_func(void *data)
continue;
error_unmap_continue:
+ /* A late callback must not be attributed to a later sample. */
+ profile_stats.aborted = true;
+ do_profile = false;
dmaengine_unmap_put(um);
failed_tests++;
}
@@ -937,6 +1091,14 @@ static int dmatest_func(void *data)
FIXPT_TO_INT(iops), FIXPT_GET_FRAC(iops),
dmatest_KBs(runtime, total_len), ret);
+ if (profile_requested) {
+ if (profile_polled)
+ pr_info("%s: profiling unavailable in polled mode\n", current->comm);
+ else
+ dmatest_profile_report(&profile_stats, total_tests, failed_tests,
+ ret, !params->noverify);
+ }
+
/* terminate all transfers on specified channels */
if (ret || failed_tests)
dmaengine_terminate_sync(chan);
@@ -1124,6 +1286,7 @@ static void add_threaded_test(struct dmatest_info *info)
params->alignment = alignment;
params->transfer_size = transfer_size;
params->polled = polled;
+ params->profile = profile;
request_channels(info, DMA_MEMCPY);
request_channels(info, DMA_MEMSET);
base-commit: 9437ee8b6cf607e883b36e44bd755968daaebd48
--
2.34.1
next reply other threads:[~2026-12-01 2:58 UTC|newest]
Thread overview: 2+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-12-01 2:58 Baineng Shou [this message]
2026-12-01 3:08 ` [PATCH] dmaengine: dmatest: Add optional per-stage latency profiling sashiko-bot
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20261201025813.2994236-1-shoubaineng@gmail.com \
--to=shoubaineng@gmail.com \
--cc=Frank.Li@kernel.org \
--cc=corbet@lwn.net \
--cc=dmaengine@vger.kernel.org \
--cc=linux-doc@vger.kernel.org \
--cc=rdunlap@infradead.org \
--cc=skhan@linuxfoundation.org \
--cc=vkoul@kernel.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox