From bc2883e58173c884d04b62ba5d768947f1ff3cf1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:16:15 +1100 Subject: [PATCH 01/13] media: apple: ave: do not round huge shared-memory requests to zero ave_smalloc_get() rounds the size the firmware asks for on the SHAREDMALLOC ring up to whole granules with DIV_ROUND_UP() in 32 bits. A request of 0xfffff001..0xffffffff bytes wraps to 0 units, passes the "units > total" check and is answered with the first free block and a length of about 4 GiB, while nothing is reserved: the bound on the pool is defeated and the same block is lent again to the next request. Round in 64 bits so such a request needs more units than the pool has and is refused. Fixes: 01d0284e3837 ("media: apple: ave: serve the 6070 firmware channels") Signed-off-by: Ryan Murray --- drivers/media/platform/apple/ave/ave-ipc.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/media/platform/apple/ave/ave-ipc.c b/drivers/media/platform/apple/ave/ave-ipc.c index 518604147cc17..60a5b006a7875 100644 --- a/drivers/media/platform/apple/ave/ave-ipc.c +++ b/drivers/media/platform/apple/ave/ave-ipc.c @@ -389,7 +389,8 @@ static int ave_smalloc_get(struct ave_dev *ave, u32 bytes, u64 *addr) const struct ave_fw_transport *t = ave->layout->abi->transport; u32 total = min_t(u32, t->smalloc_bytes / AVE_SMALLOC_GRANULE, AVE_SMALLOC_UNITS); - u32 units = DIV_ROUND_UP(bytes, AVE_SMALLOC_GRANULE); + /* In 64 bits: a request near 4 GiB must not round up to 0 units */ + u32 units = DIV_ROUND_UP_ULL(bytes, AVE_SMALLOC_GRANULE); unsigned long first; unsigned int i; From 7a7a7d408b51970bfb0a42389e8450945c4ed0ce Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:16:15 +1100 Subject: [PATCH 02/13] drm: apple: parser: ignore channel counts the layout mask cannot hold parse_nchans_mask() sets "1 << nchans" for every channel count in an AudioChannelLayoutElements array. The count comes from the firmware's dictionary as a 64-bit integer and is truncated to int on the way, so a count of 32 or more, or a negative one, is an undefined shift, and a count above U32_MAX aliases a small one (2^32 + 2 becomes 2). Pass counts outside the u32 range on as U32_MAX, which matches no channel sieve, and only set a mask bit for a count the mask has a bit for. Every count from 0 to 31 is handled as before. Fixes: 2c7e3cad911d ("drm: apple: Add sound mode parsing") Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/parser.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/apple/parser.c b/drivers/gpu/drm/apple/parser.c index 28c429e48ecc7..0acc268c6813e 100644 --- a/drivers/gpu/drm/apple/parser.c +++ b/drivers/gpu/drm/apple/parser.c @@ -2189,8 +2189,9 @@ static int parse_chan_layout_element(struct dcp_parse_ctx *handle, return ret; } + /* A count no u32 holds is no channel count: U32_MAX matches nothing */ if (nchans_out) - *nchans_out = nchans; + *nchans_out = nchans >= 0 && nchans <= U32_MAX ? nchans : U32_MAX; return 0; } @@ -2207,12 +2208,14 @@ static int parse_nchans_mask(struct dcp_parse_ctx *handle, unsigned int *mask) return ret; for (; it.idx < it.len; ++it.idx) { - int nchans; + unsigned int nchans; ret = parse_chan_layout_element(it.handle, &nchans, NULL); if (ret) return ret; - *mask |= 1 << nchans; + /* The firmware's count: one the mask has no bit for matches no sieve */ + if (nchans < BITS_PER_TYPE(*mask)) + *mask |= BIT(nchans); } return 0; @@ -2275,7 +2278,7 @@ static int parse_mode_in_avep_element(struct dcp_parse_ctx *handle, for (; it.idx < it.len; ++it.idx) { if (consume_string(it.handle, "AudioChannelLayoutElements")) { struct iterator inner_it; - int nchans; + unsigned int nchans; ret = iterator_begin(it.handle, &inner_it, false); if (ret) From 0ccf128c06ce984c4bca0123dfc4fbb11aa1d51b Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:04 +1100 Subject: [PATCH 03/13] soc: apple: rtkit: add KUnit tests The RTKit IPC library and its crashlog parser have no tests. Add two suites, included from the drivers so they reach the static handlers: apple-rtkit (27 cases) feeds apple_rtkit_rx_dispatch() the messages a co-processor sends: HELLO version negotiation (accepted, capped, refused, client versions), the endpoint map (multipart, base offsets, EARLY_CRASHLOG and CoreAnalytics flags, retained state), IOP/AP power ACKs, idle notification, buffer requests, syslog, ioreport, kdebug, CoreAnalytics and crash reports, and checks the replies. A static stub on apple_rtkit_send_message() records them, after the crashed and running checks, so no mailbox is touched. apple-rtkit-crashlog (11 cases) checks that the parser follows the containers to the right log and never reads past a truncated or malformed crashlog: each log is placed flush against the end of a vzalloc'd area, so a read past it faults the case. Mutations caught: endpoint map base, crashlog size against the space left, the footer margin and the syslog index bound. Signed-off-by: Ryan Murray --- drivers/soc/apple/Kconfig | 15 + drivers/soc/apple/rtkit-crashlog-test.c | 454 ++++++++++ drivers/soc/apple/rtkit-crashlog.c | 4 + drivers/soc/apple/rtkit-test.c | 1035 +++++++++++++++++++++++ drivers/soc/apple/rtkit.c | 12 + drivers/soc/apple/rtkit.kunitconfig | 7 + 6 files changed, 1527 insertions(+) create mode 100644 drivers/soc/apple/rtkit-crashlog-test.c create mode 100644 drivers/soc/apple/rtkit-test.c create mode 100644 drivers/soc/apple/rtkit.kunitconfig diff --git a/drivers/soc/apple/Kconfig b/drivers/soc/apple/Kconfig index a9cf80938dc4e..45bd3f05d7068 100644 --- a/drivers/soc/apple/Kconfig +++ b/drivers/soc/apple/Kconfig @@ -140,6 +140,21 @@ config APPLE_RTKIT Say 'y' here if you have an Apple SoC. +config APPLE_RTKIT_KUNIT_TEST + bool "KUnit tests for the Apple RTKit IPC library" if !KUNIT_ALL_TESTS + depends on APPLE_RTKIT=y && KUNIT=y + default KUNIT_ALL_TESTS + help + Feed the RTKit receive handlers the messages a co-processor sends + (HELLO version negotiation, the endpoint map, power state ACKs, + buffer requests, syslog, ioreport, kdebug, CoreAnalytics and crash + reports) and check the replies, with the mailbox send replaced by a + static stub. Check that the crashlog parser follows containers to + the right log and never reads past a truncated or malformed + crashlog. The tests touch no hardware. + + If unsure, say N. + config APPLE_RTKIT_HELPER tristate "Apple Generic RTKit helper co-processor" depends on APPLE_RTKIT diff --git a/drivers/soc/apple/rtkit-crashlog-test.c b/drivers/soc/apple/rtkit-crashlog-test.c new file mode 100644 index 0000000000000..930f9b07d8b93 --- /dev/null +++ b/drivers/soc/apple/rtkit-crashlog-test.c @@ -0,0 +1,454 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the RTKit crashlog parser. Included by rtkit-crashlog.c. + * + * apple_rtkit_crashlog_locate() is checked for the offsets it returns. The + * dump tests place each log flush against the end of a vmalloc() area, so a + * read past the log runs into the guard page and fails the case. + */ +#include +#include +#include + +#define CL_TEST_AREA PAGE_SIZE +#define CL_TEST_ID_OUTER FOURCC('A', 'O', 'P', ' ') +#define CL_TEST_ID_INNER FOURCC('t', 's', 'k', '1') +#define CL_TEST_SECTION 16 + +struct cl_test_ctx { + struct apple_rtkit *rtk; + u8 *area; +}; + +static int cl_test_init(struct kunit *test) +{ + struct cl_test_ctx *ctx; + struct device *dev; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + ctx->rtk = kunit_kzalloc(test, sizeof(*ctx->rtk), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx->rtk); + dev = kunit_device_register(test, "apple-rtkit-crashlog-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + ctx->rtk->dev = dev; + ctx->area = vzalloc(CL_TEST_AREA); + KUNIT_ASSERT_NOT_NULL(test, ctx->area); + test->priv = ctx; + return 0; +} + +static void cl_test_exit(struct kunit *test) +{ + struct cl_test_ctx *ctx = test->priv; + + vfree(ctx->area); +} + +/* A buffer of @size bytes that ends where the vmalloc guard page begins. */ +static u8 *cl_test_tail(struct kunit *test, size_t size) +{ + struct cl_test_ctx *ctx = test->priv; + + KUNIT_ASSERT_LE(test, size, CL_TEST_AREA); + memset(ctx->area, 0, CL_TEST_AREA); + return ctx->area + CL_TEST_AREA - size; +} + +static void cl_test_put32(u8 *p, u32 v) +{ + memcpy(p, &v, sizeof(v)); +} + +static void cl_test_put64(u8 *p, u64 v) +{ + memcpy(p, &v, sizeof(v)); +} + +static void cl_test_log(u8 *p, u32 size, u32 flags) +{ + struct apple_rtkit_crashlog_header h = { + .fourcc = APPLE_RTKIT_CRASHLOG_HEADER_FOURCC, + .size = size, + .flags = flags, + }; + + memcpy(p, &h, sizeof(h)); +} + +static void cl_test_container(u8 *p, u32 size, u32 current_id, u32 count) +{ + struct apple_rtkit_crashlog_container c = { + .fourcc = APPLE_RTKIT_CRASHLOG_CONTAINER_FOURCC, + .version = APPLE_RTKIT_CRASHLOG_CONTAINER_VERSION << 8, + .size = size, + .current_id = current_id, + .count = count, + }; + + memcpy(p, &c, sizeof(c)); +} + +static void cl_test_record(u8 *container, u32 i, u64 id, u32 offset) +{ + struct apple_rtkit_crashlog_record r = { + .id = id, + .offset = offset, + }; + + memcpy(container + sizeof(struct apple_rtkit_crashlog_container) + i * sizeof(r), + &r, sizeof(r)); +} + +/* A section header: its fourcc and its size, which counts the header. */ +static u8 *cl_test_section(u8 *p, u32 fourcc, u32 size) +{ + cl_test_put32(p, fourcc); + cl_test_put32(p + 12, size); + return p + size; +} + +static int cl_test_locate(const u8 *bfr, size_t size, size_t *offset, u32 *id, + unsigned int *depth) +{ + *offset = ~0; + *id = ~0; + *depth = ~0; + return apple_rtkit_crashlog_locate(bfr, size, offset, id, depth); +} + +static void cl_test_locate_bare(struct kunit *test) +{ + u8 *bfr = cl_test_tail(test, 0x100); + unsigned int depth; + size_t offset; + u32 id; + + cl_test_log(bfr, 0x100, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), 0); + KUNIT_EXPECT_EQ(test, offset, 0); + KUNIT_EXPECT_EQ(test, id, 0); + KUNIT_EXPECT_EQ(test, depth, 0); + + /* A bare log is taken as it is, even marked as still being written. */ + cl_test_log(bfr, 0x40, APPLE_RTKIT_CRASHLOG_INCOMPLETE); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), 0); +} + +static void cl_test_locate_bare_invalid(struct kunit *test) +{ + u8 *bfr = cl_test_tail(test, 0x100); + unsigned int depth; + size_t offset; + u32 id; + + cl_test_log(bfr, 0x101, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_log(bfr, sizeof(struct apple_rtkit_crashlog_header) - 1, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_put32(bfr, FOURCC('C', 'L', 'H', 'F')); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + + /* Shorter than a header: nothing is read past the end. */ + bfr = cl_test_tail(test, sizeof(struct apple_rtkit_crashlog_header) - 1); + cl_test_put32(bfr, APPLE_RTKIT_CRASHLOG_HEADER_FOURCC); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x1f, &offset, &id, &depth), -EINVAL); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0, &offset, &id, &depth), -EINVAL); +} + +static void cl_test_locate_container(struct kunit *test) +{ + u8 *bfr = cl_test_tail(test, 0x200); + unsigned int depth; + size_t offset; + u32 id; + + cl_test_container(bfr, 0x200, CL_TEST_ID_OUTER, 2); + cl_test_record(bfr, 0, FOURCC('o', 't', 'h', 'r'), 0x80); + cl_test_record(bfr, 1, CL_TEST_ID_OUTER, 0x100); + cl_test_log(bfr + 0x80, 0x40, 0); + cl_test_log(bfr + 0x100, 0x100, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x200, &offset, &id, &depth), 0); + KUNIT_EXPECT_EQ(test, offset, 0x100); + KUNIT_EXPECT_EQ(test, id, CL_TEST_ID_OUTER); + KUNIT_EXPECT_EQ(test, depth, 1); + + /* The selected log may fill the rest of the buffer, but no more. */ + cl_test_log(bfr + 0x100, 0x101, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x200, &offset, &id, &depth), -EINVAL); + + /* A log still being written is retried later. */ + cl_test_log(bfr + 0x100, 0x100, APPLE_RTKIT_CRASHLOG_INCOMPLETE); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x200, &offset, &id, &depth), -EAGAIN); +} + +static void cl_test_locate_nested(struct kunit *test) +{ + u8 *bfr = cl_test_tail(test, 0x400); + unsigned int depth; + size_t offset; + u32 id; + + /* Per-coprocessor, then per-task: offsets are from each container. */ + cl_test_container(bfr, 0x400, CL_TEST_ID_OUTER, 1); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x100); + cl_test_container(bfr + 0x100, 0x300, CL_TEST_ID_INNER, 2); + cl_test_record(bfr + 0x100, 0, FOURCC('t', 's', 'k', '0'), 0x80); + cl_test_record(bfr + 0x100, 1, CL_TEST_ID_INNER, 0x200); + cl_test_log(bfr + 0x300, 0x100, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x400, &offset, &id, &depth), 0); + KUNIT_EXPECT_EQ(test, offset, 0x300); + KUNIT_EXPECT_EQ(test, id, CL_TEST_ID_INNER); + KUNIT_EXPECT_EQ(test, depth, 2); + + /* + * The inner log's size is checked against what follows it, not against + * the whole buffer: 0x180 fits the buffer but not the space left. + */ + cl_test_log(bfr + 0x300, 0x180, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x400, &offset, &id, &depth), -EINVAL); + + /* The same for an inner container claiming more than is left. */ + cl_test_log(bfr + 0x300, 0x100, 0); + cl_test_container(bfr + 0x100, 0x301, CL_TEST_ID_INNER, 2); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x400, &offset, &id, &depth), -EINVAL); +} + +static void cl_test_locate_bad_container(struct kunit *test) +{ + u8 *bfr = cl_test_tail(test, 0x100); + unsigned int depth; + size_t offset; + u32 id; + +#define CL_TEST_RESET() do { \ + cl_test_container(bfr, 0x100, CL_TEST_ID_OUTER, 1); \ + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x80); \ + cl_test_log(bfr + 0x80, 0x80, 0); \ + } while (0) + + CL_TEST_RESET(); + KUNIT_ASSERT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), 0); + + /* Another container version. */ + cl_test_put32(bfr + 4, 3 << 8); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + CL_TEST_RESET(); + /* Larger than the buffer. */ + cl_test_container(bfr, 0x101, CL_TEST_ID_OUTER, 1); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + /* No records, or more than the buffer can hold. */ + cl_test_container(bfr, 0x100, CL_TEST_ID_OUTER, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_container(bfr, 0x100, CL_TEST_ID_OUTER, (0x100 - 0x14) / 0x18 + 1); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + /* No record has the current ID. */ + cl_test_container(bfr, 0x100, CL_TEST_ID_INNER, 1); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + /* A record pointing back into its container, at its end, or past it. */ + CL_TEST_RESET(); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x13); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x100); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0xffffffff); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); + /* A record leading to too little for a header. */ + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0xf0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, 0x100, &offset, &id, &depth), -EINVAL); +#undef CL_TEST_RESET +} + +static void cl_test_locate_depth(struct kunit *test) +{ + unsigned int max = APPLE_RTKIT_CRASHLOG_CONTAINER_MAX_DEPTH, depth, i; + size_t len = 0x40 * (max + 2), offset; + u8 *bfr = cl_test_tail(test, len); + u32 id; + + /* @max containers, each leading 0x40 bytes on, then a log. */ + for (i = 0; i < max; i++) { + cl_test_container(bfr + 0x40 * i, len - 0x40 * i, i + 1, 1); + cl_test_record(bfr + 0x40 * i, 0, i + 1, 0x40); + } + cl_test_log(bfr + 0x40 * max, 0x40, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, len, &offset, &id, &depth), 0); + KUNIT_EXPECT_EQ(test, depth, max); + KUNIT_EXPECT_EQ(test, offset, 0x40 * max); + KUNIT_EXPECT_EQ(test, id, max); + + /* One container more is too deep. */ + cl_test_container(bfr + 0x40 * max, len - 0x40 * max, max + 1, 1); + cl_test_record(bfr + 0x40 * max, 0, max + 1, 0x40); + cl_test_log(bfr + 0x40 * (max + 1), 0x40, 0); + KUNIT_EXPECT_EQ(test, cl_test_locate(bfr, len, &offset, &id, &depth), -EINVAL); +} + +/* Every decoder, ending with a footer. The dump must reach it in bounds. */ +static void cl_test_dump_full(struct kunit *test) +{ + struct cl_test_ctx *ctx = test->priv; + size_t len = 0x20 + 0x30 + 0x30 + 0x18 + (28 + 2 * 24) + (16 + 0x350) + + APPLE_RTKIT_CRASHLOG_CL4_SECTION_SIZE + 0x30 + 0x10 + CL_TEST_SECTION; + u8 *bfr = cl_test_tail(test, len), *p; + + cl_test_log(bfr, len, 0); + p = bfr + 0x20; + memcpy(p + 20, "panic: test\nsecond line", 23); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_STR, 0x30); + memset(p + 16, 'v', 0x30 - 16); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_VERSION, 0x30); + cl_test_put64(p + 16, 1234); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_TIME, 0x18); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_MBOX, 28 + 2 * 24); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_REGS, 16 + 0x350); + cl_test_put32(p + APPLE_RTKIT_CRASHLOG_CL4_SIZE, APPLE_RTKIT_CRASHLOG_CL4_NOMINAL_SIZE); + p = cl_test_section(p, APPLE_RTKIT_CRASHLOG_REGS_CL4, + APPLE_RTKIT_CRASHLOG_CL4_SECTION_SIZE); + p = cl_test_section(p, FOURCC('C', 'c', 's', 't'), 0x30); + /* An empty unknown section: a header only. */ + p = cl_test_section(p, FOURCC('C', 'x', 'y', 'z'), 0x10); + cl_test_section(p, APPLE_RTKIT_CRASHLOG_HEADER_FOURCC, CL_TEST_SECTION); + KUNIT_ASSERT_PTR_EQ(test, p + CL_TEST_SECTION, bfr + len); + + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + KUNIT_SUCCEED(test); +} + +/* + * The last section of a log without a footer: its decoder could read 16 + * bytes past the log, so it is not decoded. + */ +static void cl_test_dump_no_footer(struct kunit *test) +{ + static const u32 fourccs[] = { + APPLE_RTKIT_CRASHLOG_STR, APPLE_RTKIT_CRASHLOG_VERSION, + APPLE_RTKIT_CRASHLOG_MBOX, APPLE_RTKIT_CRASHLOG_TIME, + FOURCC('C', 'c', 's', 't'), + }; + struct cl_test_ctx *ctx = test->priv; + size_t len = 0x20 + 0x40; + u8 *bfr; + int i; + + for (i = 0; i < ARRAY_SIZE(fourccs); i++) { + bfr = cl_test_tail(test, len); + cl_test_log(bfr, len, 0); + /* No newline and no terminator: Cstr must stop at the section. */ + memset(bfr + 0x20 + 16, 'x', 0x40 - 16); + cl_test_section(bfr + 0x20, fourccs[i], 0x40); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + } + KUNIT_SUCCEED(test); +} + +static void cl_test_dump_bad_sizes(struct kunit *test) +{ + struct cl_test_ctx *ctx = test->priv; + size_t len = 0x80; + u8 *bfr = cl_test_tail(test, len); + + /* A log claiming more than the buffer. */ + cl_test_log(bfr, len + 0x1000, 0); + cl_test_section(bfr + 0x20, APPLE_RTKIT_CRASHLOG_VERSION, len - 0x20 + 0x800); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + + /* A section larger than what is left of the log. */ + cl_test_log(bfr, len, 0); + cl_test_section(bfr + 0x20, APPLE_RTKIT_CRASHLOG_VERSION, len - 0x20 + 1); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + + /* Sizes that would never advance or underflow a decoder. */ + cl_test_section(bfr + 0x20, APPLE_RTKIT_CRASHLOG_VERSION, 0); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + cl_test_section(bfr + 0x20, APPLE_RTKIT_CRASHLOG_VERSION, 15); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + + /* A section header cut off by the end of the log. */ + bfr = cl_test_tail(test, 0x28); + cl_test_log(bfr, 0x28, 0); + cl_test_put32(bfr + 0x20, APPLE_RTKIT_CRASHLOG_VERSION); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, 0x28); + + /* Too small for a header. */ + apple_rtkit_crashlog_dump(ctx->rtk, cl_test_tail(test, 0x1f), 0x1f); + KUNIT_SUCCEED(test); +} + +/* Sections too small for their decoders are skipped, not decoded. */ +static void cl_test_dump_small_sections(struct kunit *test) +{ + static const u32 fourccs[] = { + APPLE_RTKIT_CRASHLOG_MBOX, APPLE_RTKIT_CRASHLOG_REGS, + APPLE_RTKIT_CRASHLOG_REGS_CL4, APPLE_RTKIT_CRASHLOG_TIME, + }; + struct cl_test_ctx *ctx = test->priv; + size_t len = 0x20 + 0x10 + CL_TEST_SECTION; + u8 *bfr; + int i; + + for (i = 0; i < ARRAY_SIZE(fourccs); i++) { + bfr = cl_test_tail(test, len); + cl_test_log(bfr, len, 0); + cl_test_section(bfr + 0x20, fourccs[i], 0x10); + cl_test_section(bfr + 0x30, APPLE_RTKIT_CRASHLOG_HEADER_FOURCC, + CL_TEST_SECTION); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + } + + /* A Crl4 frame of another size is not decoded either. */ + len = 0x20 + APPLE_RTKIT_CRASHLOG_CL4_SECTION_SIZE + CL_TEST_SECTION; + bfr = cl_test_tail(test, len); + cl_test_log(bfr, len, 0); + cl_test_put32(bfr + 0x20 + APPLE_RTKIT_CRASHLOG_CL4_SIZE, 0xd0); + cl_test_section(bfr + 0x20, APPLE_RTKIT_CRASHLOG_REGS_CL4, + APPLE_RTKIT_CRASHLOG_CL4_SECTION_SIZE); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + KUNIT_SUCCEED(test); +} + +static void cl_test_dump_container(struct kunit *test) +{ + struct cl_test_ctx *ctx = test->priv; + size_t len = 0x100; + u8 *bfr = cl_test_tail(test, len); + + /* The selected log ends the buffer; its last section has no footer. */ + cl_test_container(bfr, len, CL_TEST_ID_OUTER, 1); + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x80); + cl_test_log(bfr + 0x80, 0x80, 0); + memset(bfr + 0xa0 + 16, 'x', 0x60 - 16); + cl_test_section(bfr + 0xa0, APPLE_RTKIT_CRASHLOG_VERSION, 0x60); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + + /* A container whose record leads past the end is not followed. */ + cl_test_record(bfr, 0, CL_TEST_ID_OUTER, 0x1000); + apple_rtkit_crashlog_dump(ctx->rtk, bfr, len); + KUNIT_SUCCEED(test); +} + +static struct kunit_case apple_rtkit_crashlog_test_cases[] = { + KUNIT_CASE(cl_test_locate_bare), + KUNIT_CASE(cl_test_locate_bare_invalid), + KUNIT_CASE(cl_test_locate_container), + KUNIT_CASE(cl_test_locate_nested), + KUNIT_CASE(cl_test_locate_bad_container), + KUNIT_CASE(cl_test_locate_depth), + KUNIT_CASE(cl_test_dump_full), + KUNIT_CASE(cl_test_dump_no_footer), + KUNIT_CASE(cl_test_dump_bad_sizes), + KUNIT_CASE(cl_test_dump_small_sections), + KUNIT_CASE(cl_test_dump_container), + {} +}; + +static struct kunit_suite apple_rtkit_crashlog_test_suite = { + .name = "apple-rtkit-crashlog", + .init = cl_test_init, + .exit = cl_test_exit, + .test_cases = apple_rtkit_crashlog_test_cases, +}; + +kunit_test_suite(apple_rtkit_crashlog_test_suite); diff --git a/drivers/soc/apple/rtkit-crashlog.c b/drivers/soc/apple/rtkit-crashlog.c index 81c5af4e29fc0..47335bf11c493 100644 --- a/drivers/soc/apple/rtkit-crashlog.c +++ b/drivers/soc/apple/rtkit-crashlog.c @@ -492,3 +492,7 @@ void apple_rtkit_crashlog_dump(struct apple_rtkit *rtk, u8 *bfr, size_t size) dev_warn(rtk->dev, "RTKit: End of crashlog reached but no footer present"); } + +#if IS_ENABLED(CONFIG_APPLE_RTKIT_KUNIT_TEST) +#include "rtkit-crashlog-test.c" +#endif diff --git a/drivers/soc/apple/rtkit-test.c b/drivers/soc/apple/rtkit-test.c new file mode 100644 index 0000000000000..aba873abbe37c --- /dev/null +++ b/drivers/soc/apple/rtkit-test.c @@ -0,0 +1,1035 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple RTKit IPC library. Included by rtkit.c. + * + * The tests drive the receive handlers with messages a co-processor would + * send and check the replies. apple_rtkit_send_message() is redirected to a + * static stub just before the mailbox write, so its crashed and running + * checks still run; shared buffers come from a fake shmem_setup_ep. No + * mailbox, IOMMU or MMIO is touched. + */ +#include +#include +#include + +#define RTK_TEST_MAX_SENT 32 +#define RTK_TEST_IOVA_BASE 0x10000000 + +struct rtk_test_msg { + u8 ep; + u64 msg; +}; + +struct rtk_test_ctx { + struct kunit *test; + struct apple_rtkit *rtk; + struct apple_rtkit_ops ops; + + struct rtk_test_msg sent[RTK_TEST_MAX_SENT]; + unsigned int n_sent; + + unsigned int n_setup; + u8 setup_ep; + struct apple_rtkit_shmem setup_req; + int setup_ret; + dma_addr_t next_iova; + /* Written to each new buffer, as a log the firmware already wrote. */ + const void *prefill; + size_t prefill_len; + + unsigned int n_crashed; + size_t crashed_size; + u32 crashed_fourcc; + + unsigned int n_syslog; + char syslog_ctx[24]; + char syslog_msg[64]; + + unsigned int n_recv; + u8 recv_ep; + u64 recv_msg; +}; + +static int rtk_test_send(struct apple_rtkit *rtk, u8 ep, u64 message, + struct completion *completion, bool atomic) +{ + struct rtk_test_ctx *ctx = rtk->cookie; + + if (ctx->n_sent < RTK_TEST_MAX_SENT) { + ctx->sent[ctx->n_sent].ep = ep; + ctx->sent[ctx->n_sent].msg = message; + } + ctx->n_sent++; + return 0; +} + +static int rtk_test_shmem_setup(void *cookie, u8 ep, struct apple_rtkit_shmem *bfr) +{ + struct rtk_test_ctx *ctx = cookie; + + ctx->n_setup++; + ctx->setup_ep = ep; + ctx->setup_req = *bfr; + if (ctx->setup_ret) + return ctx->setup_ret; + + bfr->buffer = kunit_kzalloc(ctx->test, bfr->size, GFP_KERNEL); + if (!bfr->buffer) + return -ENOMEM; + if (ctx->prefill) + memcpy(bfr->buffer, ctx->prefill, min(ctx->prefill_len, bfr->size)); + if (bfr->iova) { + /* A buffer the co-processor placed at its own address. */ + bfr->is_mapped = true; + } else { + bfr->iova = ctx->next_iova; + ctx->next_iova += SZ_1M; + } + return 0; +} + +static void rtk_test_shmem_destroy(void *cookie, struct apple_rtkit_shmem *bfr) +{ +} + +static void rtk_test_crashed(void *cookie, const void *crashlog, size_t size) +{ + struct rtk_test_ctx *ctx = cookie; + + ctx->n_crashed++; + ctx->crashed_size = size; + ctx->crashed_fourcc = 0; + if (crashlog && size >= sizeof(u32)) + memcpy(&ctx->crashed_fourcc, crashlog, sizeof(u32)); +} + +static bool rtk_test_syslog_is_debug(void *cookie, const char *context, + const char *message) +{ + struct rtk_test_ctx *ctx = cookie; + + ctx->n_syslog++; + strscpy(ctx->syslog_ctx, context, sizeof(ctx->syslog_ctx)); + strscpy(ctx->syslog_msg, message, sizeof(ctx->syslog_msg)); + return true; +} + +static void rtk_test_recv(void *cookie, u8 endpoint, u64 message) +{ + struct rtk_test_ctx *ctx = cookie; + + ctx->n_recv++; + ctx->recv_ep = endpoint; + ctx->recv_msg = message; +} + +static int rtk_test_init(struct kunit *test) +{ + struct rtk_test_ctx *ctx; + struct apple_rtkit *rtk; + struct device *dev; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + rtk = kunit_kzalloc(test, sizeof(*rtk), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, rtk); + dev = kunit_device_register(test, "apple-rtkit-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + + ctx->test = test; + ctx->rtk = rtk; + ctx->next_iova = RTK_TEST_IOVA_BASE; + ctx->ops.crashed = rtk_test_crashed; + ctx->ops.recv_message = rtk_test_recv; + ctx->ops.shmem_setup_ep = rtk_test_shmem_setup; + ctx->ops.shmem_destroy = rtk_test_shmem_destroy; + ctx->ops.syslog_is_debug = rtk_test_syslog_is_debug; + + rtk->dev = dev; + rtk->cookie = ctx; + rtk->ops = &ctx->ops; + rtk->handshake_timeout_ms = APPLE_RTKIT_HANDSHAKE_TIMEOUT_MS; + init_completion(&rtk->epmap_completion); + init_completion(&rtk->coreanalytics_completion); + init_completion(&rtk->iop_pwr_ack_completion); + init_completion(&rtk->ap_pwr_ack_completion); + init_completion(&rtk->strict_idle_done); + INIT_KFIFO(rtk->sync_ack_fifo); + INIT_KFIFO(rtk->m5_saved.deferred); + INIT_DELAYED_WORK(&rtk->crashlog_late_work, apple_rtkit_crashlog_late); + rtk->wq = alloc_ordered_workqueue("apple-rtkit-test", 0); + KUNIT_ASSERT_NOT_NULL(test, rtk->wq); + + kunit_activate_static_stub(test, apple_rtkit_send_message, rtk_test_send); + test->priv = ctx; + return 0; +} + +static void rtk_test_exit(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + cancel_delayed_work_sync(&rtk->crashlog_late_work); + destroy_workqueue(rtk->wq); + kfree(rtk->syslog_msg_buffer); +} + +static u64 rtk_test_mgmt(u8 type, u64 payload) +{ + return FIELD_PREP(APPLE_RTKIT_MGMT_TYPE, type) | payload; +} + +static u64 rtk_test_hello(unsigned int min_ver, unsigned int max_ver) +{ + return rtk_test_mgmt(APPLE_RTKIT_MGMT_HELLO, + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MINVER, min_ver) | + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MAXVER, max_ver)); +} + +static u64 rtk_test_epmap(u32 base, u32 bitmap, bool last) +{ + return rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP, + FIELD_PREP(APPLE_RTKIT_MGMT_EPMAP_BASE, base) | + FIELD_PREP(APPLE_RTKIT_MGMT_EPMAP_BITMAP, bitmap) | + (last ? APPLE_RTKIT_MGMT_EPMAP_LAST : 0)); +} + +static u64 rtk_test_startep(u8 ep) +{ + return rtk_test_mgmt(APPLE_RTKIT_MGMT_STARTEP, + FIELD_PREP(APPLE_RTKIT_MGMT_STARTEP_EP, ep) | + APPLE_RTKIT_MGMT_STARTEP_FLAG); +} + +static u64 rtk_test_buffer_request(u8 type, size_t size, u64 iova) +{ + return FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, type) | + FIELD_PREP(APPLE_RTKIT_BUFFER_REQUEST_SIZE, size >> 12) | + FIELD_PREP(APPLE_RTKIT_BUFFER_REQUEST_IOVA, iova); +} + +static void rtk_test_expect_sent(struct kunit *test, unsigned int i, u8 ep, u64 msg) +{ + struct rtk_test_ctx *ctx = test->priv; + + KUNIT_ASSERT_LT(test, i, ctx->n_sent); + KUNIT_ASSERT_LT(test, i, RTK_TEST_MAX_SENT); + KUNIT_EXPECT_EQ(test, ctx->sent[i].ep, ep); + KUNIT_EXPECT_EQ(test, ctx->sent[i].msg, msg); +} + +static void rtk_test_hello_accepts_supported(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 reply12 = rtk_test_mgmt(APPLE_RTKIT_MGMT_HELLO_REPLY, + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MINVER, 12) | + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MAXVER, 12)); + + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(11, 12), false, 0); + KUNIT_EXPECT_EQ(test, rtk->version, 12); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, reply12); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->epmap_completion)); + + /* A newer remote maximum settles on the highest version supported here. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(11, 14), false, 0); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_MGMT, reply12); + + /* Both ends of the supported range are accepted alone. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(12, 12), false, 0); + rtk_test_expect_sent(test, 2, APPLE_RTKIT_EP_MGMT, reply12); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(1, 11), false, 0); + KUNIT_EXPECT_EQ(test, rtk->version, 11); + rtk_test_expect_sent(test, 3, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_HELLO_REPLY, + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MINVER, 11) | + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MAXVER, 11))); + KUNIT_EXPECT_EQ(test, rtk->boot_result, 0); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->epmap_completion)); +} + +static void rtk_test_hello_rejects_unsupported(struct kunit *test) +{ + static const struct { unsigned int min, max; } bad[] = { + { 13, 14 }, /* minimum too new */ + { 9, 10 }, /* maximum too old */ + }; + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + int i; + + for (i = 0; i < ARRAY_SIZE(bad); i++) { + reinit_completion(&rtk->epmap_completion); + rtk->boot_result = 0; + rtk->version = 0; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_hello(bad[i].min, bad[i].max), false, 0); + KUNIT_EXPECT_EQ_MSG(test, rtk->boot_result, -EINVAL, "range %u..%u", + bad[i].min, bad[i].max); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); + KUNIT_EXPECT_EQ(test, rtk->version, 0); + } + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_hello_client_version(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + ctx->ops.protocol_version = 11; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(11, 12), false, 0); + KUNIT_EXPECT_EQ(test, rtk->version, 11); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_HELLO_REPLY, + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MINVER, 11) | + FIELD_PREP(APPLE_RTKIT_MGMT_HELLO_MAXVER, 11))); + + /* The client's exact version outside the remote range aborts the boot. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_hello(12, 12), false, 0); + KUNIT_EXPECT_EQ(test, rtk->boot_result, -EINVAL); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); +} + +static void rtk_test_epmap_starts_system_endpoints(struct kunit *test) +{ + static const u8 started[] = { 1, 2, 3, 4, 8, 0xa }; + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + /* mgmt, crashlog, syslog, debug, ioreport, 5 (unknown), 7, oslog, tracekit */ + u32 bitmap = BIT(0) | BIT(1) | BIT(2) | BIT(3) | BIT(4) | BIT(5) | + BIT(7) | BIT(8) | BIT(0xa); + int i; + + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_epmap(0, bitmap, true), + false, 0); + + for (i = 0; i < 32; i++) + KUNIT_EXPECT_EQ_MSG(test, apple_rtkit_has_endpoint(rtk, i), + !!(bitmap & BIT(i)), "endpoint %d", i); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1 + ARRAY_SIZE(started)); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP_REPLY, + APPLE_RTKIT_MGMT_EPMAP_LAST)); + for (i = 0; i < ARRAY_SIZE(started); i++) { + rtk_test_expect_sent(test, 1 + i, APPLE_RTKIT_EP_MGMT, + rtk_test_startep(started[i])); + KUNIT_EXPECT_TRUE(test, apple_rtkit_endpoint_started(rtk, started[i])); + } + /* Neither management, an unknown system endpoint nor CoreAnalytics. */ + KUNIT_EXPECT_FALSE(test, apple_rtkit_endpoint_started(rtk, 0)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_endpoint_started(rtk, 5)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_endpoint_started(rtk, 7)); + KUNIT_EXPECT_EQ(test, rtk->boot_result, 0); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); +} + +static void rtk_test_epmap_multipart(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_epmap(0, BIT(0) | BIT(2), false), false, 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP_REPLY, + APPLE_RTKIT_MGMT_EPMAP_REPLY_MORE)); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->epmap_completion)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_endpoint_started(rtk, 2)); + + /* The second part: endpoints 0x20 and 0x37 are application endpoints. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_epmap(1, BIT(0) | BIT(0x17), true), false, 0); + KUNIT_EXPECT_TRUE(test, apple_rtkit_has_endpoint(rtk, 0x20)); + KUNIT_EXPECT_TRUE(test, apple_rtkit_has_endpoint(rtk, 0x37)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_has_endpoint(rtk, 1)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_has_endpoint(rtk, 0x17)); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 3); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP_REPLY, + FIELD_PREP(APPLE_RTKIT_MGMT_EPMAP_BASE, 1) | + APPLE_RTKIT_MGMT_EPMAP_LAST)); + /* Only system endpoints are started by RTKit itself. */ + rtk_test_expect_sent(test, 2, APPLE_RTKIT_EP_MGMT, rtk_test_startep(2)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_endpoint_started(rtk, 0x20)); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); +} + +static void rtk_test_epmap_flags(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + ctx->ops.flags = APPLE_RTKIT_NEEDS_COREANALYTICS | APPLE_RTKIT_EARLY_CRASHLOG; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_epmap(0, BIT(0) | BIT(1) | BIT(7), true), false, 0); + + /* The crash log is started before the map is acknowledged, and only once. */ + KUNIT_ASSERT_EQ(test, ctx->n_sent, 3); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, rtk_test_startep(1)); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP_REPLY, + APPLE_RTKIT_MGMT_EPMAP_LAST)); + rtk_test_expect_sent(test, 2, APPLE_RTKIT_EP_MGMT, rtk_test_startep(7)); + KUNIT_EXPECT_TRUE(test, apple_rtkit_endpoint_started(rtk, 7)); +} + +static void rtk_test_epmap_retained(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + rtk->retained_wake = true; + set_bit(1, rtk->started); + set_bit(2, rtk->started); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_epmap(0, BIT(0) | BIT(1) | BIT(2) | BIT(4), true), + false, 0); + /* The started endpoints are echoed and nothing is started again. */ + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_EPMAP_REPLY, + BIT(1) | BIT(2) | APPLE_RTKIT_MGMT_EPMAP_LAST)); + KUNIT_EXPECT_EQ(test, rtk->boot_result, 0); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); + + /* A started endpoint missing from the map fails the wake. */ + reinit_completion(&rtk->epmap_completion); + set_bit(4 + 32, rtk->started); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_epmap(1, BIT(0), true), false, 0); + KUNIT_EXPECT_EQ(test, rtk->boot_result, -EPROTO); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); +} + +static void rtk_test_power_acks(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + KUNIT_EXPECT_FALSE(test, apple_rtkit_is_running(rtk)); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE_ACK, + APPLE_RTKIT_PWR_STATE_ON), false, 0); + KUNIT_EXPECT_EQ(test, rtk->iop_power_state, APPLE_RTKIT_PWR_STATE_ON); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->iop_pwr_ack_completion)); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->ap_pwr_ack_completion)); + KUNIT_EXPECT_FALSE(test, apple_rtkit_is_running(rtk)); + + /* Bits above the 16-bit state field are not part of the state. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_SET_AP_PWR_STATE_ACK, + BIT_ULL(40) | APPLE_RTKIT_PWR_STATE_ON), + false, 0); + KUNIT_EXPECT_EQ(test, rtk->ap_power_state, APPLE_RTKIT_PWR_STATE_ON); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->ap_pwr_ack_completion)); + KUNIT_EXPECT_TRUE(test, apple_rtkit_is_running(rtk)); + + rtk->crashed = true; + KUNIT_EXPECT_FALSE(test, apple_rtkit_is_running(rtk)); + KUNIT_EXPECT_TRUE(test, apple_rtkit_is_crashed(rtk)); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_retained_quiesced(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 quiesced = rtk_test_mgmt(APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE_ACK, + APPLE_RTKIT_PWR_STATE_QUIESCED); + + rtk->retained_wake = true; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, quiesced, false, 0); + /* One ON request, and still waiting for ON. */ + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_SET_IOP_PWR_STATE, + APPLE_RTKIT_PWR_STATE_ON)); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->iop_pwr_ack_completion)); + + /* A second QUIESCED is not asked again: it fails the wake. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, quiesced, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); + KUNIT_EXPECT_EQ(test, rtk->boot_result, -EPROTO); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->iop_pwr_ack_completion)); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->epmap_completion)); +} + +static void rtk_test_idle_notify(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + rtk->strict_idle_waiting = true; + rtk->iop_power_state = APPLE_RTKIT_PWR_STATE_IDLE; + rtk->ap_power_state = APPLE_RTKIT_PWR_STATE_IDLE; + /* A nonzero argument is not the idle notification. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_IDLE_NOTIFY, 1), false, 0); + KUNIT_EXPECT_FALSE(test, completion_done(&rtk->strict_idle_done)); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, + rtk_test_mgmt(APPLE_RTKIT_MGMT_IDLE_NOTIFY, 0), false, 0); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->strict_idle_done)); + + /* Unknown management messages are dropped without a reply. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_MGMT, rtk_test_mgmt(0x3f, 0), false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_send_checks(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + set_bit(0x20, rtk->endpoints); + /* Application endpoints need a running co-processor. */ + KUNIT_EXPECT_EQ(test, apple_rtkit_send_message(rtk, 0x20, 0x1234, NULL, false), + -EINVAL); + KUNIT_EXPECT_EQ(test, apple_rtkit_start_ep(rtk, 0x20), -EINVAL); + /* An undiscovered endpoint cannot be started. */ + KUNIT_EXPECT_EQ(test, apple_rtkit_start_ep(rtk, 2), -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); + + rtk->iop_power_state = APPLE_RTKIT_PWR_STATE_ON; + rtk->ap_power_state = APPLE_RTKIT_PWR_STATE_ON; + KUNIT_EXPECT_EQ(test, apple_rtkit_send_message(rtk, 0x20, 0x1234, NULL, false), 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_start_ep(rtk, 0x20), 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 2); + rtk_test_expect_sent(test, 0, 0x20, 0x1234); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_MGMT, rtk_test_startep(0x20)); + KUNIT_EXPECT_TRUE(test, apple_rtkit_endpoint_started(rtk, 0x20)); + + /* Nothing is sent to a crashed co-processor, not even management. */ + rtk->crashed = true; + KUNIT_EXPECT_EQ(test, apple_rtkit_send_message(rtk, 0, 0, NULL, false), -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 2); +} + +static void rtk_test_app_endpoint_dispatch(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + apple_rtkit_rx_dispatch(rtk, 0x37, 0xdeadbeefcafeull, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_recv, 1); + KUNIT_EXPECT_EQ(test, ctx->recv_ep, 0x37); + KUNIT_EXPECT_EQ(test, ctx->recv_msg, 0xdeadbeefcafeull); + + /* Nothing is delivered once teardown has started. */ + rtk->shutting_down = true; + apple_rtkit_rx_dispatch(rtk, 0x37, 1, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_recv, 1); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_buffer_reply(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req = rtk_test_buffer_request(APPLE_RTKIT_BUFFER_REQUEST, SZ_8K, 0); + + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, req, false, 0); + KUNIT_ASSERT_EQ(test, ctx->n_setup, 1); + KUNIT_EXPECT_EQ(test, ctx->setup_ep, APPLE_RTKIT_EP_IOREPORT); + KUNIT_EXPECT_EQ(test, ctx->setup_req.size, SZ_8K); + KUNIT_EXPECT_EQ(test, ctx->setup_req.iova, 0); + KUNIT_EXPECT_EQ(test, rtk->ioreport_buffer.size, SZ_8K); + KUNIT_EXPECT_EQ(test, rtk->ioreport_buffer.iova, RTK_TEST_IOVA_BASE); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_IOREPORT, + rtk_test_buffer_request(APPLE_RTKIT_BUFFER_REQUEST, SZ_8K, + RTK_TEST_IOVA_BASE)); + + /* An identical request is answered again without a new buffer. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 1); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 2); + KUNIT_EXPECT_EQ(test, ctx->sent[1].msg, ctx->sent[0].msg); + + /* A changed geometry is refused while the buffer is live. */ + req = rtk_test_buffer_request(1, SZ_16K, 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_common_rx_get_buffer(rtk, &rtk->ioreport_buffer, + APPLE_RTKIT_EP_IOREPORT, req), + -EBUSY); + KUNIT_EXPECT_EQ(test, rtk->ioreport_buffer.size, SZ_8K); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 1); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 2); + + /* ioreport's two unknown notifications are echoed, others dropped. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 0x8) | 0x55, false, 0); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 0xc), false, 0); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 0x9), false, 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 4); + rtk_test_expect_sent(test, 2, APPLE_RTKIT_EP_IOREPORT, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 0x8) | 0x55); + rtk_test_expect_sent(test, 3, APPLE_RTKIT_EP_IOREPORT, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 0xc)); +} + +static void rtk_test_buffer_request_invalid(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req; + + /* A zero size is never set up. */ + req = rtk_test_buffer_request(1, 0, 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_common_rx_get_buffer(rtk, &rtk->ioreport_buffer, + APPLE_RTKIT_EP_IOREPORT, req), + -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 0); + + /* A failed setup leaves no buffer behind and sends no reply. */ + ctx->setup_ret = -ENOMEM; + req = rtk_test_buffer_request(1, SZ_4K, 0); + KUNIT_EXPECT_EQ(test, apple_rtkit_common_rx_get_buffer(rtk, &rtk->syslog_buffer, + APPLE_RTKIT_EP_SYSLOG, req), + -ENOMEM); + KUNIT_EXPECT_EQ(test, rtk->syslog_buffer.size, 0); + ctx->setup_ret = 0; + + /* Without a setup callback, a placed buffer cannot be mapped. */ + ctx->ops.shmem_setup_ep = NULL; + req = rtk_test_buffer_request(1, SZ_4K, 0x8000); + KUNIT_EXPECT_EQ(test, apple_rtkit_common_rx_get_buffer(rtk, &rtk->ioreport_buffer, + APPLE_RTKIT_EP_IOREPORT, req), + -EINVAL); + KUNIT_EXPECT_EQ(test, rtk->ioreport_buffer.size, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_placed_buffers(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req = rtk_test_buffer_request(1, SZ_16K, 0xabc000); + + /* A placed buffer is acknowledged with its request, unchanged. */ + ctx->ops.flags = APPLE_RTKIT_COPROC_PLACES_BUFFERS; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_IOREPORT, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->setup_req.iova, 0xabc000); + KUNIT_EXPECT_EQ(test, ctx->setup_req.size, SZ_16K); + KUNIT_EXPECT_TRUE(test, rtk->ioreport_buffer.is_mapped); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_IOREPORT, req); + + /* A firmware-owned log buffer is taken as it is, unmapped and unanswered. */ + ctx->ops.flags = APPLE_RTKIT_FIRMWARE_OWNED_LOGS; + req = rtk_test_buffer_request(1, SZ_8K, 0xdef000); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 1); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); + KUNIT_EXPECT_TRUE(test, rtk->syslog_buffer.is_mapped); + KUNIT_EXPECT_NULL(test, rtk->syslog_buffer.buffer); + KUNIT_EXPECT_EQ(test, rtk->syslog_buffer.iova, 0xdef000); + KUNIT_EXPECT_EQ(test, rtk->syslog_buffer.size, SZ_8K); + + /* Its records are still acknowledged, without being read. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG), + false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 2); + KUNIT_EXPECT_EQ(test, ctx->n_syslog, 0); +} + +static void rtk_test_oslog_buffer_request(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req = FIELD_PREP(APPLE_RTKIT_OSLOG_TYPE, APPLE_RTKIT_OSLOG_BUFFER_REQUEST) | + FIELD_PREP(APPLE_RTKIT_OSLOG_SIZE, SZ_16K); + + /* oslog carries its size unshifted and its IOVA in 4 KiB pages. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_OSLOG, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->setup_ep, APPLE_RTKIT_EP_OSLOG); + KUNIT_EXPECT_EQ(test, ctx->setup_req.size, SZ_16K); + KUNIT_EXPECT_EQ(test, ctx->setup_req.iova, 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_OSLOG, + FIELD_PREP(APPLE_RTKIT_OSLOG_TYPE, APPLE_RTKIT_OSLOG_BUFFER_REQUEST) | + FIELD_PREP(APPLE_RTKIT_OSLOG_SIZE, SZ_16K) | + FIELD_PREP(APPLE_RTKIT_OSLOG_IOVA, RTK_TEST_IOVA_BASE >> 12)); + + apple_rtkit_free_buffer(rtk, &rtk->oslog_buffer); + req = FIELD_PREP(APPLE_RTKIT_OSLOG_TYPE, APPLE_RTKIT_OSLOG_BUFFER_REQUEST) | + FIELD_PREP(APPLE_RTKIT_OSLOG_SIZE, SZ_8K) | + FIELD_PREP(APPLE_RTKIT_OSLOG_IOVA, 0x12345); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_OSLOG, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->setup_req.size, SZ_8K); + KUNIT_EXPECT_EQ(test, ctx->setup_req.iova, 0x12345000); + KUNIT_EXPECT_EQ(test, rtk->oslog_buffer.iova, 0x12345000); +} + +/* Builds a syslog ring of four entries with a 0x40-byte message each. */ +static void rtk_test_syslog_setup(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + size_t entry_size = 0x20 + 0x40; + u8 *entry; + + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, + rtk_test_buffer_request(1, SZ_8K, 0), false, 0); + KUNIT_ASSERT_NOT_NULL(test, rtk->syslog_buffer.buffer); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_INIT) | + FIELD_PREP(APPLE_RTKIT_SYSLOG_N_ENTRIES, 4) | + FIELD_PREP(APPLE_RTKIT_SYSLOG_MSG_SIZE, 0x40), false, 0); + KUNIT_ASSERT_NOT_NULL(test, rtk->syslog_msg_buffer); + KUNIT_ASSERT_EQ(test, rtk->syslog_n_entries, 4); + KUNIT_ASSERT_EQ(test, rtk->syslog_msg_size, 0x40); + + entry = rtk->syslog_buffer.buffer + 1 * entry_size; + strscpy(entry + 8, "ctx", 24); + strscpy(entry + 8 + 24, "hello rtkit \r\n", 0x40); + /* Entry 4 is past the ring the firmware described, but inside the buffer. */ + entry = rtk->syslog_buffer.buffer + 4 * entry_size; + strscpy(entry + 8, "stale", 24); + strscpy(entry + 8 + 24, "not a record", 0x40); + ctx->n_sent = 0; +} + +static void rtk_test_syslog_log(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 log1 = FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG) | 1; + + rtk_test_syslog_setup(test); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, log1, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_syslog, 1); + KUNIT_EXPECT_STREQ(test, ctx->syslog_ctx, "ctx"); + /* Trailing whitespace is cropped. */ + KUNIT_EXPECT_STREQ(test, ctx->syslog_msg, "hello rtkit"); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_SYSLOG, log1); +} + +static void rtk_test_syslog_index_range(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 log4 = FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG) | 4; + u64 log_ff = FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG) | 0xff; + + rtk_test_syslog_setup(test); + /* Records past the ring are not read, but still acknowledged. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, log4, false, 0); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, log_ff, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_syslog, 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 2); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_SYSLOG, log4); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_SYSLOG, log_ff); +} + +static void rtk_test_syslog_no_geometry(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 log0 = FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_LOG); + + rtk_test_syslog_setup(test); + /* A zero-sized INIT drops the message buffer rather than kzalloc(0). */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, APPLE_RTKIT_SYSLOG_INIT) | + FIELD_PREP(APPLE_RTKIT_SYSLOG_N_ENTRIES, 4), false, 0); + KUNIT_EXPECT_NULL(test, rtk->syslog_msg_buffer); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, log0, false, 0); + + /* An inherited session cannot read the ring either. */ + rtk->syslog_inherited = true; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_SYSLOG, log0, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_syslog, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 2); +} + +static void rtk_test_kdebug(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 get = FIELD_PREP(APPLE_RTKIT_KDEBUG_TYPE, APPLE_RTKIT_KDEBUG_GET_BUFFER); + + rtk->sync_syslog_ack = true; + /* No entries, and more than the cap, are refused before any setup. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_DEBUG, get, false, 0); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_DEBUG, + get | FIELD_PREP(APPLE_RTKIT_KDEBUG_DATA, + APPLE_RTKIT_KDEBUG_BUF0_MAX / + APPLE_RTKIT_KDEBUG_ENTRY_SIZE + 1), false, 0); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_DEBUG, + get | APPLE_RTKIT_KDEBUG_DATA, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); + + /* 16 entries round up to one aligned buffer, plus the fixed second one. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_DEBUG, + get | FIELD_PREP(APPLE_RTKIT_KDEBUG_DATA, 16), false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 2); + KUNIT_EXPECT_EQ(test, rtk->kdebug_buffer0.size, APPLE_RTKIT_KDEBUG_BUF_ALIGN); + KUNIT_EXPECT_EQ(test, rtk->kdebug_buffer1.size, APPLE_RTKIT_KDEBUG_BUF1_SIZE); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 2); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_DEBUG, + FIELD_PREP(APPLE_RTKIT_KDEBUG_TYPE, APPLE_RTKIT_KDEBUG_SET_BUFFER0) | + RTK_TEST_IOVA_BASE); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_DEBUG, + FIELD_PREP(APPLE_RTKIT_KDEBUG_TYPE, APPLE_RTKIT_KDEBUG_SET_BUFFER1) | + (RTK_TEST_IOVA_BASE + SZ_1M)); + + /* A repeated request of the same size reuses both buffers. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_DEBUG, + get | FIELD_PREP(APPLE_RTKIT_KDEBUG_DATA, 16), false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 2); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 4); +} + +static void rtk_test_coreanalytics_encoding(struct kunit *test) +{ + u64 reply; + + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_size(APPLE_RTKIT_CA_UNIT_4K | + FIELD_PREP(APPLE_RTKIT_CA_COUNT, 3)), + 0x3000); + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_size(APPLE_RTKIT_CA_UNIT_1M | + FIELD_PREP(APPLE_RTKIT_CA_COUNT, 2)), + 0x200000); + /* Without a unit there is no size. */ + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_size(FIELD_PREP(APPLE_RTKIT_CA_COUNT, 2)), + 0); + + KUNIT_ASSERT_EQ(test, apple_rtkit_coreanalytics_reply(0x3000, 0x40000, &reply), 0); + KUNIT_EXPECT_EQ(test, reply, + FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_BUFFER_REPLY) | + FIELD_PREP(APPLE_RTKIT_CA_COUNT, 3) | APPLE_RTKIT_CA_UNIT_4K | 0x40000); + /* A partial unit rounds up; a megabyte or more counts in megabytes. */ + KUNIT_ASSERT_EQ(test, apple_rtkit_coreanalytics_reply(0x2001, 0, &reply), 0); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_RTKIT_CA_COUNT, reply), 3); + KUNIT_ASSERT_EQ(test, apple_rtkit_coreanalytics_reply(0x180000, 0, &reply), 0); + KUNIT_EXPECT_EQ(test, FIELD_GET(APPLE_RTKIT_CA_COUNT, reply), 2); + KUNIT_EXPECT_TRUE(test, reply & APPLE_RTKIT_CA_UNIT_1M); + KUNIT_EXPECT_FALSE(test, reply & APPLE_RTKIT_CA_UNIT_4K); + + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_reply(0, 0, &reply), -EINVAL); + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_reply(0x1000, BIT_ULL(44), &reply), + -EINVAL); + /* 256 MiB needs a count of 256, which the 8-bit field cannot hold. */ + KUNIT_EXPECT_EQ(test, apple_rtkit_coreanalytics_reply(SZ_256M, 0, &reply), -EINVAL); +} + +static void rtk_test_coreanalytics_rx(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req = FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_BUFFER_REQUEST) | + APPLE_RTKIT_CA_UNIT_4K | FIELD_PREP(APPLE_RTKIT_CA_COUNT, 4); + u64 event = FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_EVENT) | + FIELD_PREP(APPLE_RTKIT_CA_EVENT_ID, 0x1234) | 0xff; + + /* A client that asks for CoreAnalytics, as the PMP does. */ + ctx->ops.flags = APPLE_RTKIT_NEEDS_COREANALYTICS; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_COREANALYTICS, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->setup_ep, APPLE_RTKIT_EP_COREANALYTICS); + KUNIT_EXPECT_EQ(test, rtk->coreanalytics_buffer.size, 0x4000); + KUNIT_EXPECT_TRUE(test, completion_done(&rtk->coreanalytics_completion)); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_COREANALYTICS, + FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_BUFFER_REPLY) | + APPLE_RTKIT_CA_UNIT_4K | FIELD_PREP(APPLE_RTKIT_CA_COUNT, 4) | + RTK_TEST_IOVA_BASE); + + /* A duplicate request never replaces the live buffer. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_COREANALYTICS, req, false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_setup, 1); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); + + /* An event is acknowledged with its ID only. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_COREANALYTICS, event, false, 0); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 2); + rtk_test_expect_sent(test, 1, APPLE_RTKIT_EP_COREANALYTICS, + FIELD_PREP(APPLE_RTKIT_CA_TYPE, APPLE_RTKIT_CA_EVENT_ACK) | + FIELD_PREP(APPLE_RTKIT_CA_EVENT_ID, 0x1234)); +} + +static void rtk_test_crashlog_handshake_then_crash(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + u64 req = rtk_test_buffer_request(APPLE_RTKIT_CRASHLOG_CRASH, SZ_4K, 0); + struct apple_rtkit_crashlog_header *hdr; + + set_bit(APPLE_RTKIT_EP_CRASHLOG, rtk->endpoints); + /* In a handshaked session the first message is the buffer request. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, req, false, 0); + KUNIT_EXPECT_FALSE(test, rtk->crashed); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 0); + KUNIT_EXPECT_EQ(test, rtk->crashlog_buffer.size, SZ_4K); + KUNIT_ASSERT_EQ(test, ctx->n_sent, 1); + rtk_test_expect_sent(test, 0, APPLE_RTKIT_EP_CRASHLOG, + rtk_test_buffer_request(APPLE_RTKIT_BUFFER_REQUEST, SZ_4K, + RTK_TEST_IOVA_BASE)); + + /* The firmware writes a log, then reports the crash. */ + hdr = rtk->crashlog_buffer.buffer; + hdr->fourcc = APPLE_RTKIT_CRASHLOG_HEADER_FOURCC; + hdr->size = sizeof(*hdr); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, req, false, 0); + KUNIT_EXPECT_TRUE(test, rtk->crashed); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 1); + KUNIT_EXPECT_EQ(test, ctx->crashed_size, SZ_4K); + KUNIT_EXPECT_EQ(test, ctx->crashed_fourcc, APPLE_RTKIT_CRASHLOG_HEADER_FOURCC); + + /* Unknown crashlog messages are ignored; a crashed IOP gets no messages. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, + FIELD_PREP(APPLE_RTKIT_SYSLOG_TYPE, 2), false, 0); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 1); + KUNIT_EXPECT_EQ(test, apple_rtkit_send_message(rtk, APPLE_RTKIT_EP_MGMT, 0, NULL, false), + -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 1); +} + +static void rtk_test_crashlog_report_only(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + struct apple_rtkit_crashlog_header log = { + .fourcc = APPLE_RTKIT_CRASHLOG_HEADER_FOURCC, + .size = sizeof(log), + }; + + /* + * An undiscovered crashlog endpoint only reports crashes; the client's + * setup maps the buffer, which already holds the log. + */ + ctx->prefill = &log; + ctx->prefill_len = sizeof(log); + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, + rtk_test_buffer_request(1, SZ_4K, 0x7000), false, 0); + KUNIT_EXPECT_TRUE(test, rtk->crashed); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 1); + KUNIT_EXPECT_EQ(test, ctx->crashed_size, SZ_4K); + KUNIT_EXPECT_EQ(test, ctx->crashed_fourcc, APPLE_RTKIT_CRASHLOG_HEADER_FOURCC); +} + +static void rtk_test_crashlog_unreadable(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + /* A buffer holding no log yet: the crash is reported without one. */ + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, + rtk_test_buffer_request(1, SZ_4K, 0x7000), false, 0); + KUNIT_EXPECT_TRUE(test, rtk->crashed); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 1); + KUNIT_EXPECT_EQ(test, ctx->crashed_size, 0); + /* ...and the log is looked for again later. */ + KUNIT_EXPECT_TRUE(test, delayed_work_pending(&rtk->crashlog_late_work)); + cancel_delayed_work_sync(&rtk->crashlog_late_work); +} + +static void rtk_test_crashlog_no_mapping(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + + /* No setup callback and no IOMMU domain: the crash is still reported. */ + ctx->ops.shmem_setup_ep = NULL; + apple_rtkit_rx_dispatch(rtk, APPLE_RTKIT_EP_CRASHLOG, + rtk_test_buffer_request(1, SZ_4K, 0x7000), false, 0); + KUNIT_EXPECT_TRUE(test, rtk->crashed); + KUNIT_EXPECT_EQ(test, ctx->n_crashed, 1); + KUNIT_EXPECT_EQ(test, ctx->crashed_size, 0); + KUNIT_EXPECT_EQ(test, rtk->crashlog_buffer.size, 0); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static void rtk_test_crashlog_header_valid(struct kunit *test) +{ + struct rtk_test_ctx *ctx = test->priv; + struct apple_rtkit *rtk = ctx->rtk; + struct apple_rtkit_crashlog_header *hdr; + u32 *words; + + rtk->crashlog_buffer.size = 0x100; + rtk->crashlog_buffer.buffer = kunit_kzalloc(test, 0x100, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, rtk->crashlog_buffer.buffer); + hdr = rtk->crashlog_buffer.buffer; + + KUNIT_EXPECT_FALSE(test, apple_rtkit_crashlog_header_valid(rtk)); + hdr->fourcc = APPLE_RTKIT_CRASHLOG_HEADER_FOURCC; + hdr->size = 0x100; + KUNIT_EXPECT_TRUE(test, apple_rtkit_crashlog_header_valid(rtk)); + hdr->size = 0x101; + KUNIT_EXPECT_FALSE(test, apple_rtkit_crashlog_header_valid(rtk)); + hdr->size = sizeof(*hdr) - 1; + KUNIT_EXPECT_FALSE(test, apple_rtkit_crashlog_header_valid(rtk)); + + /* A container is valid when its current record leads to a log. */ + words = rtk->crashlog_buffer.buffer; + memset(words, 0, 0x100); + words[0] = APPLE_RTKIT_CRASHLOG_CONTAINER_FOURCC; + words[1] = 0x200; /* version 2 */ + words[2] = 0x100; /* size */ + words[3] = 0x41; /* current id */ + words[4] = 1; /* one record */ + /* record 0 at 0x14: id (u64), unknown (u64), offset (u32) */ + words[5] = 0x41; + words[9] = 0x80; + hdr = rtk->crashlog_buffer.buffer + 0x80; + hdr->fourcc = APPLE_RTKIT_CRASHLOG_HEADER_FOURCC; + hdr->size = 0x80; + KUNIT_EXPECT_TRUE(test, apple_rtkit_crashlog_header_valid(rtk)); + words[3] = 0x42; + KUNIT_EXPECT_FALSE(test, apple_rtkit_crashlog_header_valid(rtk)); + + /* Too small for a header at all. */ + rtk->crashlog_buffer.size = sizeof(*hdr) - 1; + KUNIT_EXPECT_FALSE(test, apple_rtkit_crashlog_header_valid(rtk)); + KUNIT_EXPECT_EQ(test, ctx->n_sent, 0); +} + +static struct kunit_case apple_rtkit_test_cases[] = { + KUNIT_CASE(rtk_test_hello_accepts_supported), + KUNIT_CASE(rtk_test_hello_rejects_unsupported), + KUNIT_CASE(rtk_test_hello_client_version), + KUNIT_CASE(rtk_test_epmap_starts_system_endpoints), + KUNIT_CASE(rtk_test_epmap_multipart), + KUNIT_CASE(rtk_test_epmap_flags), + KUNIT_CASE(rtk_test_epmap_retained), + KUNIT_CASE(rtk_test_power_acks), + KUNIT_CASE(rtk_test_retained_quiesced), + KUNIT_CASE(rtk_test_idle_notify), + KUNIT_CASE(rtk_test_send_checks), + KUNIT_CASE(rtk_test_app_endpoint_dispatch), + KUNIT_CASE(rtk_test_buffer_reply), + KUNIT_CASE(rtk_test_buffer_request_invalid), + KUNIT_CASE(rtk_test_placed_buffers), + KUNIT_CASE(rtk_test_oslog_buffer_request), + KUNIT_CASE(rtk_test_syslog_log), + KUNIT_CASE(rtk_test_syslog_index_range), + KUNIT_CASE(rtk_test_syslog_no_geometry), + KUNIT_CASE(rtk_test_kdebug), + KUNIT_CASE(rtk_test_coreanalytics_encoding), + KUNIT_CASE(rtk_test_coreanalytics_rx), + KUNIT_CASE(rtk_test_crashlog_handshake_then_crash), + KUNIT_CASE(rtk_test_crashlog_report_only), + KUNIT_CASE(rtk_test_crashlog_unreadable), + KUNIT_CASE(rtk_test_crashlog_no_mapping), + KUNIT_CASE(rtk_test_crashlog_header_valid), + {} +}; + +static struct kunit_suite apple_rtkit_test_suite = { + .name = "apple-rtkit", + .init = rtk_test_init, + .exit = rtk_test_exit, + .test_cases = apple_rtkit_test_cases, +}; + +kunit_test_suite(apple_rtkit_test_suite); diff --git a/drivers/soc/apple/rtkit.c b/drivers/soc/apple/rtkit.c index e529b4d4dd4c6..0d0a414db0515 100644 --- a/drivers/soc/apple/rtkit.c +++ b/drivers/soc/apple/rtkit.c @@ -21,6 +21,10 @@ #include #include +#if IS_ENABLED(CONFIG_APPLE_RTKIT_KUNIT_TEST) +#include +#endif + enum { APPLE_RTKIT_PWR_STATE_OFF = 0x00, /* power off, cannot be restarted */ APPLE_RTKIT_PWR_STATE_SLEEP = 0x01, /* sleeping, can be restarted */ @@ -1752,6 +1756,10 @@ int apple_rtkit_send_message(struct apple_rtkit *rtk, u8 ep, u64 message, */ dma_wmb(); +#if IS_ENABLED(CONFIG_APPLE_RTKIT_KUNIT_TEST) + KUNIT_STATIC_STUB_REDIRECT(apple_rtkit_send_message, rtk, ep, message, + completion, atomic); +#endif return apple_mbox_send(rtk->mbox, msg, atomic); } EXPORT_SYMBOL_GPL(apple_rtkit_send_message); @@ -3549,3 +3557,7 @@ MODULE_AUTHOR("Sven Peter "); MODULE_DESCRIPTION("Apple RTKit driver"); #include "rtkit-v27-late.inc" + +#if IS_ENABLED(CONFIG_APPLE_RTKIT_KUNIT_TEST) +#include "rtkit-test.c" +#endif diff --git a/drivers/soc/apple/rtkit.kunitconfig b/drivers/soc/apple/rtkit.kunitconfig new file mode 100644 index 0000000000000..40593c9ce46bb --- /dev/null +++ b/drivers/soc/apple/rtkit.kunitconfig @@ -0,0 +1,7 @@ +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_ARM64_16K_PAGES=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_APPLE_RTKIT_KUNIT_TEST=y From 0790532fd6a54c30b6d83ae6fdd4b2f7013f2274 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:05 +1100 Subject: [PATCH 04/13] iommu: io-pgtable-dart: add KUnit tests The Apple DART page table code has no tests; apple-dart-test.c maps a single page. Add the io-pgtable-dart suite (15 cases, 31 with parameters), included from io-pgtable-dart.c: - the table layout chosen for DART1 4K/16K and DART2 16K granules and input sizes (levels, bits per level, 1 or 4 TTBRs), and the refused configurations; - exact leaf and table PTE encodings for both formats, against hand-computed values; - map/unmap/iova_to_phys across leaf table ends, at the top of an L1 table, through four levels and across the TTBR split, with -EEXIST, -EINVAL and -ERANGE refusals that write nothing; - that teardown frees every table page (NR_IOMMU_PAGES back to the baseline). Mutations caught: the DART2 output address shift, the index mask, the DART2 read/write bits swapped and a table page leaked at teardown. Signed-off-by: Ryan Murray --- drivers/iommu/Kconfig | 13 + drivers/iommu/io-pgtable-dart-test.c | 793 ++++++++++++++++++++++ drivers/iommu/io-pgtable-dart.c | 4 + drivers/iommu/io-pgtable-dart.kunitconfig | 4 + 4 files changed, 814 insertions(+) create mode 100644 drivers/iommu/io-pgtable-dart-test.c create mode 100644 drivers/iommu/io-pgtable-dart.kunitconfig diff --git a/drivers/iommu/Kconfig b/drivers/iommu/Kconfig index 4233b253b06e2..f2275eb0474db 100644 --- a/drivers/iommu/Kconfig +++ b/drivers/iommu/Kconfig @@ -81,6 +81,19 @@ config IOMMU_IO_PGTABLE_DART If unsure, say N here. +config IOMMU_IO_PGTABLE_DART_KUNIT_TEST + bool "KUnit tests for Apple DART page tables" if !KUNIT_ALL_TESTS + depends on IOMMU_IO_PGTABLE_DART && KUNIT=y + default KUNIT_ALL_TESTS + help + Enable KUnit tests for the Apple DART page table allocator. They + check the table layout chosen for each format, granule and input + size, the DART and DART2 PTE encodings, map/unmap/iova_to_phys + across table boundaries, rejection of invalid requests and that + teardown frees every table page. + + If unsure, say N here. + endmenu config IOMMU_DEBUGFS diff --git a/drivers/iommu/io-pgtable-dart-test.c b/drivers/iommu/io-pgtable-dart-test.c new file mode 100644 index 0000000000000..7a68c11003ebd --- /dev/null +++ b/drivers/iommu/io-pgtable-dart-test.c @@ -0,0 +1,793 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the Apple DART page table formats. + * + * Included by io-pgtable-dart.c so that the table walkers can be checked + * against hand-computed table indexes and PTE encodings. + */ +#include +#include +#include +#include +#include +#include + +/* Leaf subpage protection: start 0, end 0xfff (whole page). */ +#define DART_TEST_SUBPAGE_ALL (0xfffULL << 40) + +struct dart_test { + struct device *dev; + struct io_pgtable_cfg cfg; + struct io_pgtable_ops *ops; + unsigned int tlb_add_page; + unsigned int tlb_other; + unsigned long tlb_last_iova; + size_t tlb_last_granule; +}; + +static void dart_test_tlb_flush_all(void *cookie) +{ + struct dart_test *t = cookie; + + t->tlb_other++; +} + +static void dart_test_tlb_flush_walk(unsigned long iova, size_t size, + size_t granule, void *cookie) +{ + struct dart_test *t = cookie; + + t->tlb_other++; +} + +static void dart_test_tlb_add_page(struct iommu_iotlb_gather *gather, + unsigned long iova, size_t granule, + void *cookie) +{ + struct dart_test *t = cookie; + + t->tlb_add_page++; + t->tlb_last_iova = iova; + t->tlb_last_granule = granule; +} + +static const struct iommu_flush_ops dart_test_flush_ops = { + .tlb_flush_all = dart_test_tlb_flush_all, + .tlb_flush_walk = dart_test_tlb_flush_walk, + .tlb_add_page = dart_test_tlb_add_page, +}; + +KUNIT_DEFINE_ACTION_WRAPPER(dart_test_free_ops, free_io_pgtable_ops, + struct io_pgtable_ops *); + +/* Exact count of pages held by iommu_alloc_pages_sz(), including per-CPU deltas. */ +static long dart_test_iommu_pages(void) +{ + struct pglist_data *pgdat; + long pages = 0; + int cpu; + + for_each_online_pgdat(pgdat) { + pages += atomic_long_read(&pgdat->vm_stat[NR_IOMMU_PAGES]); + for_each_possible_cpu(cpu) + pages += per_cpu_ptr(pgdat->per_cpu_nodestats, + cpu)->vm_node_stat_diff[NR_IOMMU_PAGES]; + } + + return pages; +} + +/* Pages iommu_alloc_pages_sz() accounts for one table of a granule (4 for 16K on a 4K kernel). */ +static long dart_test_tbl_pages(size_t granule) +{ + return 1L << get_order(granule); +} + +static int dart_test_init(struct kunit *test) +{ + struct dart_test *t; + + t = kunit_kzalloc(test, sizeof(*t), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, t); + t->dev = kunit_device_register(test, "io-pgtable-dart-test"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, t->dev); + test->priv = t; + + return 0; +} + +static void dart_test_cfg(struct dart_test *t, size_t pgsize, u32 ias, u32 oas) +{ + t->cfg = (struct io_pgtable_cfg) { + .pgsize_bitmap = pgsize, + .ias = ias, + .oas = oas, + .coherent_walk = true, + .tlb = &dart_test_flush_ops, + .iommu_dev = t->dev, + }; +} + +static struct dart_io_pgtable *dart_test_alloc(struct kunit *test, + enum io_pgtable_fmt fmt, + size_t pgsize, u32 ias, u32 oas) +{ + struct dart_test *t = test->priv; + + dart_test_cfg(t, pgsize, ias, oas); + t->ops = alloc_io_pgtable_ops(fmt, &t->cfg, t); + KUNIT_ASSERT_NOT_NULL(test, t->ops); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, dart_test_free_ops, + t->ops), 0); + + return io_pgtable_ops_to_data(t->ops); +} + +static int dart_test_map(struct dart_test *t, unsigned long iova, + phys_addr_t paddr, size_t pgcount, int prot, + size_t *mapped) +{ + return t->ops->map_pages(t->ops, iova, paddr, t->cfg.pgsize_bitmap, + pgcount, prot, GFP_KERNEL, mapped); +} + +static size_t dart_test_unmap(struct dart_test *t, unsigned long iova, + size_t pgcount, struct iommu_iotlb_gather *gather) +{ + return t->ops->unmap_pages(t->ops, iova, t->cfg.pgsize_bitmap, pgcount, + gather); +} + +static phys_addr_t dart_test_phys(struct dart_test *t, unsigned long iova) +{ + return t->ops->iova_to_phys(t->ops, iova); +} + +/* Leaf PTE slot found by the driver's own walker. */ +static dart_iopte *dart_test_leaf(struct dart_io_pgtable *data, + unsigned long iova) +{ + dart_iopte *ptep = dart_get_last(data, iova); + + return ptep ? ptep + dart_get_last_index(data, iova) : NULL; +} + +/* Expected table PTE for a next-level table, encoded by hand. */ +static dart_iopte dart_test_table_pte(enum io_pgtable_fmt fmt, void *table) +{ + u64 pa = __pa(table); + + if (fmt == APPLE_DART) + return (pa & GENMASK_ULL(35, 12)) | 1; + return ((pa >> 4) & GENMASK_ULL(37, 10)) | 1; +} + +/* Decode a table PTE by hand. */ +static dart_iopte *dart_test_next(enum io_pgtable_fmt fmt, dart_iopte pte) +{ + if (fmt == APPLE_DART) + return __va(pte & GENMASK_ULL(35, 12)); + return __va((pte & GENMASK_ULL(37, 10)) << 4); +} + +struct dart_test_layout { + const char *name; + enum io_pgtable_fmt fmt; + size_t pgsize; + u32 ias, oas; + u32 n_ttbrs, n_levels; + int bits_per_level; +}; + +static const struct dart_test_layout dart_test_layouts[] = { + { "dart1-16k-ias32", APPLE_DART, SZ_16K, 32, 36, 1, 3, 11 }, + { "dart1-4k-ias32", APPLE_DART, SZ_4K, 32, 36, 4, 3, 9 }, + { "dart1-4k-ias30", APPLE_DART, SZ_4K, 30, 36, 1, 3, 9 }, + { "dart1-4k-ias36", APPLE_DART, SZ_4K, 36, 36, 1, 4, 9 }, + { "dart1-16k-ias36", APPLE_DART, SZ_16K, 36, 36, 1, 3, 11 }, + { "dart2-16k-ias36", APPLE_DART2, SZ_16K, 36, 42, 1, 3, 11 }, + { "dart2-16k-ias37", APPLE_DART2, SZ_16K, 37, 42, 1, 4, 11 }, + { "dart2-16k-ias42", APPLE_DART2, SZ_16K, 42, 42, 1, 4, 11 }, +}; + +static void dart_test_layout_desc(const struct dart_test_layout *l, char *desc) +{ + strscpy(desc, l->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(dart_test_layout, dart_test_layouts, dart_test_layout_desc); + +/* Each supported format/granule/ias picks the expected TTBR count and depth. */ +static void dart_test_alloc_layout(struct kunit *test) +{ + const struct dart_test_layout *l = test->param_value; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + u32 i; + + data = dart_test_alloc(test, l->fmt, l->pgsize, l->ias, l->oas); + KUNIT_EXPECT_EQ(test, data->iop.fmt, l->fmt); + KUNIT_EXPECT_EQ(test, t->cfg.apple_dart_cfg.n_ttbrs, l->n_ttbrs); + KUNIT_EXPECT_EQ(test, t->cfg.apple_dart_cfg.n_levels, l->n_levels); + KUNIT_EXPECT_EQ(test, data->bits_per_level, l->bits_per_level); + KUNIT_EXPECT_EQ(test, DART_GRANULE(data), l->pgsize); + + for (i = 0; i < DART_MAX_TABLES; i++) { + if (i >= l->n_ttbrs) { + KUNIT_EXPECT_NULL(test, data->pgd[i]); + continue; + } + KUNIT_ASSERT_NOT_NULL(test, data->pgd[i]); + KUNIT_EXPECT_PTR_EQ(test, t->cfg.apple_dart_cfg.ttbr[i], data->pgd[i]); + KUNIT_EXPECT_TRUE(test, IS_ALIGNED(__pa(data->pgd[i]), l->pgsize)); + KUNIT_EXPECT_TRUE(test, mem_is_zero(data->pgd[i], l->pgsize)); + } + KUNIT_EXPECT_EQ(test, t->tlb_other, 0U); +} + +struct dart_test_bad_cfg { + const char *name; + enum io_pgtable_fmt fmt; + size_t pgsize; + u32 ias, oas; + bool noncoherent; +}; + +static const struct dart_test_bad_cfg dart_test_bad_cfgs[] = { + { "noncoherent", APPLE_DART2, SZ_16K, 36, 42, true }, + { "oas40", APPLE_DART2, SZ_16K, 36, 40 }, + { "oas48", APPLE_DART2, SZ_16K, 36, 48 }, + { "ias-gt-oas", APPLE_DART, SZ_16K, 37, 36 }, + { "pgsize-64k", APPLE_DART2, SZ_64K, 36, 42 }, + { "pgsize-8k", APPLE_DART, SZ_8K, 32, 36 }, + { "pgsize-bitmap", APPLE_DART, SZ_4K | SZ_16K, 32, 36 }, + { "4k-ias42-too-deep", APPLE_DART2, SZ_4K, 42, 42 }, +}; + +static void dart_test_bad_cfg_desc(const struct dart_test_bad_cfg *b, char *desc) +{ + strscpy(desc, b->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(dart_test_bad_cfg, dart_test_bad_cfgs, dart_test_bad_cfg_desc); + +/* Unsupported walkers, widths and granules are refused without leaking pages. */ +static void dart_test_alloc_reject(struct kunit *test) +{ + const struct dart_test_bad_cfg *b = test->param_value; + struct dart_test *t = test->priv; + long before = dart_test_iommu_pages(); + struct io_pgtable_ops *ops; + + dart_test_cfg(t, b->pgsize, b->ias, b->oas); + t->cfg.coherent_walk = !b->noncoherent; + ops = alloc_io_pgtable_ops(b->fmt, &t->cfg, t); + KUNIT_EXPECT_NULL(test, ops); + if (ops) + free_io_pgtable_ops(ops); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages(), before); +} + +/* DART1 leaf PTEs: OA in bits 35:12, SP_DIS, NO_WRITE(7), NO_READ(8). */ +static void dart_test_pte_dart1(struct kunit *test) +{ + static const struct { + int prot; + dart_iopte bits; + } cases[] = { + { IOMMU_READ | IOMMU_WRITE, 0x003 }, + { IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE, 0x003 }, + { IOMMU_READ, 0x083 }, + { IOMMU_WRITE, 0x103 }, + }; + const phys_addr_t pa = 0x81234c000ULL; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + unsigned long iova; + dart_iopte *ptep; + int i; + + data = dart_test_alloc(test, APPLE_DART, SZ_16K, 32, 36); + for (i = 0; i < ARRAY_SIZE(cases); i++) { + iova = SZ_1M + i * SZ_16K; + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, pa, 1, cases[i].prot, NULL), 0); + ptep = dart_test_leaf(data, iova); + KUNIT_ASSERT_NOT_NULL(test, ptep); + KUNIT_EXPECT_EQ(test, *ptep, DART_TEST_SUBPAGE_ALL | pa | cases[i].bits); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, iova + 0x123), pa + 0x123); + } + + /* 4 KiB granule DART1: same encoding, 4 KiB aligned output address. */ + data = dart_test_alloc(test, APPLE_DART, SZ_4K, 32, 36); + KUNIT_ASSERT_EQ(test, dart_test_map(t, 0x3000, 0x876543000ULL, 1, + IOMMU_READ | IOMMU_WRITE, NULL), 0); + ptep = dart_test_leaf(data, 0x3000); + KUNIT_ASSERT_NOT_NULL(test, ptep); + KUNIT_EXPECT_EQ(test, *ptep, 0x000fff0876543003ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x3fff), 0x876543fffULL); +} + +/* DART2 leaf PTEs: OA >> 4 in bits 37:10, NO_CACHE(1), NO_WRITE(2), NO_READ(3). */ +static void dart_test_pte_dart2(struct kunit *test) +{ + static const struct { + int prot; + dart_iopte bits; + } cases[] = { + { IOMMU_READ | IOMMU_WRITE, 0x3 }, + { IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE, 0x1 }, + { IOMMU_READ | IOMMU_CACHE, 0x5 }, + { IOMMU_WRITE | IOMMU_CACHE, 0x9 }, + { IOMMU_READ, 0x7 }, + }; + const phys_addr_t pa = 0x2abcdef4000ULL; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + unsigned long iova; + dart_iopte *ptep; + int i; + + data = dart_test_alloc(test, APPLE_DART2, SZ_16K, 36, 42); + for (i = 0; i < ARRAY_SIZE(cases); i++) { + iova = SZ_1M + i * SZ_16K; + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, pa, 1, cases[i].prot, NULL), 0); + ptep = dart_test_leaf(data, iova); + KUNIT_ASSERT_NOT_NULL(test, ptep); + KUNIT_EXPECT_EQ(test, *ptep, 0x000fff2abcdef400ULL | cases[i].bits); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, iova + 0x3ff8), pa + 0x3ff8); + } + + /* The top of the 42-bit output space round-trips (bits 41:40 kept). */ + iova = SZ_2M; + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, 0x3ffffffc000ULL, 1, + IOMMU_READ | IOMMU_WRITE | IOMMU_CACHE, NULL), 0); + ptep = dart_test_leaf(data, iova); + KUNIT_ASSERT_NOT_NULL(test, ptep); + KUNIT_EXPECT_EQ(test, *ptep, 0x000fff3ffffffc01ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, iova + 1), 0x3ffffffc001ULL); +} + +/* Table PTEs carry only the next table's address and the valid bit. */ +static void dart_test_table_ptes(struct kunit *test) +{ + static const enum io_pgtable_fmt fmts[] = { APPLE_DART, APPLE_DART2 }; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte *leaf, *l1; + int i; + + for (i = 0; i < ARRAY_SIZE(fmts); i++) { + data = dart_test_alloc(test, fmts[i], SZ_16K, 32, fmts[i] == APPLE_DART ? 36 : 42); + /* L1 index 3 (iova >> 25), leaf index 5 (iova >> 14). */ + KUNIT_ASSERT_EQ(test, dart_test_map(t, 0x6014000, SZ_1G, 1, IOMMU_READ, NULL), 0); + l1 = data->pgd[0]; + leaf = dart_test_next(fmts[i], l1[3]); + KUNIT_ASSERT_NE(test, l1[3], 0ULL); + KUNIT_EXPECT_PTR_EQ(test, dart_test_leaf(data, 0x6014000), leaf + 5); + KUNIT_EXPECT_EQ(test, l1[3], dart_test_table_pte(fmts[i], leaf)); + KUNIT_EXPECT_EQ(test, l1[2], 0ULL); + KUNIT_EXPECT_EQ(test, l1[4], 0ULL); + KUNIT_EXPECT_NE(test, leaf[5], 0ULL); + KUNIT_EXPECT_EQ(test, leaf[4], 0ULL); + KUNIT_EXPECT_EQ(test, leaf[6], 0ULL); + } +} + +/* High L1 indexes on a 36-bit DART2 select their own tables (no aliasing). */ +static void dart_test_index_high_l1(struct kunit *test) +{ + const unsigned long hi = 0x802004000UL; /* L1 1025, leaf 1 */ + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte *l1, *leaf; + + data = dart_test_alloc(test, APPLE_DART2, SZ_16K, 36, 42); + KUNIT_ASSERT_EQ(test, dart_test_map(t, hi, 0x10000000, 1, IOMMU_READ, NULL), 0); + l1 = data->pgd[0]; + KUNIT_ASSERT_NE(test, l1[1025], 0ULL); + KUNIT_EXPECT_EQ(test, l1[1], 0ULL); + leaf = dart_test_next(APPLE_DART2, l1[1025]); + KUNIT_EXPECT_EQ(test, leaf[1], 0x000fff0001000007ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, hi), 0x10000000ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x2004000), 0ULL); + + /* The low alias is a different IOVA and maps independently. */ + KUNIT_ASSERT_EQ(test, dart_test_map(t, 0x2004000, 0x20000000, 1, IOMMU_READ, NULL), 0); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x2004000), 0x20000000ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, hi), 0x10000000ULL); + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, hi, 1, NULL), (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x2004000), 0x20000000ULL); +} + +/* 4-level DART2 (ias 42): three table levels below the TTBR. */ +static void dart_test_four_level(struct kunit *test) +{ + const unsigned long top = 0x3ffffffc000UL; /* L1 63, L2 2047, L3 2047 */ + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte *l1, *l2, *l3; + + data = dart_test_alloc(test, APPLE_DART2, SZ_16K, 42, 42); + KUNIT_ASSERT_EQ(test, t->cfg.apple_dart_cfg.n_levels, 4U); + KUNIT_ASSERT_EQ(test, dart_test_map(t, top, 0x4000, 1, IOMMU_READ | IOMMU_WRITE, NULL), 0); + KUNIT_ASSERT_EQ(test, dart_test_map(t, 0, 0x8000, 1, IOMMU_READ | IOMMU_WRITE, NULL), 0); + + /* L1 = iova >> 36, L2 = (iova >> 25) & 2047, L3 = (iova >> 14) & 2047. */ + l1 = data->pgd[0]; + KUNIT_ASSERT_NE(test, l1[63], 0ULL); + KUNIT_ASSERT_NE(test, l1[0], 0ULL); + l2 = dart_test_next(APPLE_DART2, l1[63]); + KUNIT_ASSERT_NE(test, l2[2047], 0ULL); + KUNIT_EXPECT_EQ(test, l1[63], dart_test_table_pte(APPLE_DART2, l2)); + l3 = dart_test_next(APPLE_DART2, l2[2047]); + KUNIT_EXPECT_EQ(test, l3[2047], 0x000fff0000000403ULL); + KUNIT_EXPECT_PTR_EQ(test, dart_test_leaf(data, top), l3 + 2047); + + KUNIT_EXPECT_EQ(test, dart_test_phys(t, top + 0x10), 0x4010ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x10), 0x8010ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, top - SZ_16K), 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, BIT(36)), 0ULL); + /* Beyond the single TTBR (iova >> 47 != 0). */ + KUNIT_EXPECT_EQ(test, dart_test_map(t, BIT(47), 0x4000, 1, IOMMU_READ, NULL), -ENOMEM); +} + +/* 4 KiB DART1 with ias 32 splits the space over four TTBRs at 1 GiB. */ +static void dart_test_four_ttbrs(struct kunit *test) +{ + const unsigned long iova = 0xc0203000UL; /* TTBR 3, L1 1, leaf 3 */ + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte *leaf; + size_t mapped = 0; + int i; + + data = dart_test_alloc(test, APPLE_DART, SZ_4K, 32, 36); + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, 0x87654000, 1, IOMMU_READ | IOMMU_WRITE, + &mapped), 0); + KUNIT_EXPECT_EQ(test, mapped, (size_t)SZ_4K); + for (i = 0; i < 3; i++) + KUNIT_EXPECT_TRUE(test, mem_is_zero(data->pgd[i], SZ_4K)); + KUNIT_ASSERT_NE(test, ((dart_iopte *)data->pgd[3])[1], 0ULL); + KUNIT_EXPECT_EQ(test, ((dart_iopte *)data->pgd[3])[0], 0ULL); + leaf = dart_test_next(APPLE_DART, ((dart_iopte *)data->pgd[3])[1]); + KUNIT_EXPECT_EQ(test, leaf[3], 0x000fff0087654003ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, iova + 0xabc), 0x87654abcULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, iova - SZ_1G), 0ULL); + + /* The last page of TTBR 0 and the first page of TTBR 1. */ + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_1G - SZ_4K, 0x1000, 1, IOMMU_READ, NULL), 0); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_1G, 0x2000, 1, IOMMU_READ, NULL), 0); + KUNIT_EXPECT_NE(test, ((dart_iopte *)data->pgd[0])[511], 0ULL); + KUNIT_EXPECT_NE(test, ((dart_iopte *)data->pgd[1])[0], 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_1G - 1), 0x1fffULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_1G), 0x2000ULL); + + /* IOVA 4 GiB would need a fifth TTBR. */ + mapped = 0; + KUNIT_EXPECT_EQ(test, dart_test_map(t, BIT_ULL(32), 0x1000, 1, IOMMU_READ, &mapped), + -ENOMEM); + KUNIT_EXPECT_EQ(test, mapped, (size_t)0); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, BIT_ULL(32)), 0ULL); +} + +/* pgcount mappings fill consecutive PTEs and stop at the leaf table's end. */ +static void dart_test_map_multi(struct kunit *test) +{ + const unsigned long start = SZ_32M - 2 * SZ_16K; /* leaf 2046 of L1 0 */ + const phys_addr_t pa = 0x80000000; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + size_t mapped = SZ_1M, left = 5; + unsigned long iova = start; + int calls = 0, i; + dart_iopte *ptep; + + data = dart_test_alloc(test, APPLE_DART2, SZ_16K, 36, 42); + + /* *mapped accumulates; the first call stops after 2 pages. */ + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, pa, left, IOMMU_READ | IOMMU_WRITE, + &mapped), 0); + KUNIT_EXPECT_EQ(test, mapped, (size_t)SZ_1M + 2 * SZ_16K); + + /* Continue as iommu_map() does until all pages are in. */ + mapped -= SZ_1M; + while (left) { + calls++; + left -= mapped / SZ_16K; + iova += mapped; + mapped = 0; + if (!left) + break; + KUNIT_ASSERT_EQ(test, dart_test_map(t, iova, pa + (iova - start), left, + IOMMU_READ | IOMMU_WRITE, &mapped), 0); + KUNIT_ASSERT_GT(test, mapped, (size_t)0); + } + KUNIT_EXPECT_EQ(test, calls, 2); + KUNIT_EXPECT_NE(test, ((dart_iopte *)data->pgd[0])[0], 0ULL); + KUNIT_EXPECT_NE(test, ((dart_iopte *)data->pgd[0])[1], 0ULL); + + for (i = 0; i < 5; i++) { + ptep = dart_test_leaf(data, start + i * SZ_16K); + KUNIT_ASSERT_NOT_NULL(test, ptep); + KUNIT_EXPECT_EQ(test, *ptep, 0x000fff0008000003ULL + i * (SZ_16K >> 4)); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, start + i * SZ_16K + 8), + pa + i * SZ_16K + 8); + } + KUNIT_EXPECT_EQ(test, dart_test_phys(t, start - SZ_16K), 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, start + 5 * SZ_16K), 0ULL); + + /* A large run in an empty leaf table fills all 2048 slots at once. */ + mapped = 0; + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_64M, 0, 4096, IOMMU_READ, &mapped), 0); + KUNIT_EXPECT_EQ(test, mapped, (size_t)SZ_32M); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_64M + SZ_32M - 1), (phys_addr_t)SZ_32M - 1); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_64M + SZ_32M), 0ULL); +} + +/* Mapping over a valid PTE fails without touching any slot of the range. */ +static void dart_test_map_exists(struct kunit *test) +{ + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte old, *ptep; + size_t mapped = 0; + int ret, i; + + data = dart_test_alloc(test, APPLE_DART2, SZ_16K, 36, 42); + KUNIT_ASSERT_EQ(test, dart_test_map(t, 0x10008000, 0x40000000, 1, IOMMU_READ, NULL), 0); + ptep = dart_test_leaf(data, 0x10008000); + KUNIT_ASSERT_NOT_NULL(test, ptep); + old = *ptep; + + kunit_warning_suppress(test) { + ret = dart_test_map(t, 0x10008000, 0x50000000, 1, IOMMU_READ | IOMMU_WRITE, + &mapped); + KUNIT_EXPECT_EQ(test, ret, -EEXIST); + /* Slot 2 of [0, 4) is taken: nothing of the range is written. */ + ret = dart_test_map(t, 0x10000000, 0x60000000, 4, IOMMU_READ, &mapped); + KUNIT_EXPECT_EQ(test, ret, -EEXIST); + KUNIT_EXPECT_SUPPRESSED_WARNING_COUNT(test, 2); + } + KUNIT_EXPECT_EQ(test, mapped, (size_t)0); + KUNIT_EXPECT_EQ(test, *ptep, old); + for (i = 0; i < 4; i++) + if (i != 2) + KUNIT_EXPECT_EQ(test, *(ptep - 2 + i), 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x10008000), 0x40000000ULL); + + /* After an unmap the same IOVA maps again. */ + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, 0x10008000, 1, NULL), (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, dart_test_map(t, 0x10008000, 0x50000000, 1, IOMMU_WRITE, NULL), 0); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x10008000), 0x50000000ULL); +} + +/* Bad sizes, protections and output addresses are rejected before any table is built. */ +static void dart_test_map_reject(struct kunit *test) +{ + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + long pages; + size_t mapped = 0; + int ret; + + data = dart_test_alloc(test, APPLE_DART, SZ_16K, 32, 36); + pages = dart_test_iommu_pages(); + + /* Neither read nor write: refused without a warning. */ + KUNIT_EXPECT_EQ(test, dart_test_map(t, 0, 0x4000, 1, 0, &mapped), -EINVAL); + KUNIT_EXPECT_EQ(test, dart_test_map(t, 0, 0x4000, 1, IOMMU_CACHE, &mapped), -EINVAL); + + kunit_warning_suppress(test) { + /* Only the single configured page size is accepted. */ + ret = t->ops->map_pages(t->ops, 0, 0x4000, SZ_4K, 1, IOMMU_READ, + GFP_KERNEL, &mapped); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + ret = t->ops->map_pages(t->ops, 0, 0x8000, SZ_32K, 1, IOMMU_READ, + GFP_KERNEL, &mapped); + KUNIT_EXPECT_EQ(test, ret, -EINVAL); + /* Output address at or past 2^oas. */ + ret = dart_test_map(t, 0, BIT_ULL(36), 1, IOMMU_READ, &mapped); + KUNIT_EXPECT_EQ(test, ret, -ERANGE); + /* A run that would cross 2^oas. */ + ret = dart_test_map(t, 0, BIT_ULL(36) - SZ_16K, 2, IOMMU_READ, &mapped); + KUNIT_EXPECT_EQ(test, ret, -ERANGE); + KUNIT_EXPECT_SUPPRESSED_WARNING_COUNT(test, 4); + } + + /* Beyond the single TTBR of a 16 KiB DART (iova >> 36). */ + KUNIT_EXPECT_EQ(test, dart_test_map(t, BIT_ULL(36), 0x4000, 1, IOMMU_READ, &mapped), + -ENOMEM); + KUNIT_EXPECT_EQ(test, mapped, (size_t)0); + KUNIT_EXPECT_TRUE(test, mem_is_zero(data->pgd[0], SZ_16K)); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages(), pages); + + /* The last page below 2^oas is fine. */ + KUNIT_EXPECT_EQ(test, dart_test_map(t, 0, BIT_ULL(36) - SZ_16K, 1, IOMMU_READ, &mapped), + 0); + KUNIT_EXPECT_EQ(test, mapped, (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0x3fff), BIT_ULL(36) - 1); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages(), pages + dart_test_tbl_pages(SZ_16K)); +} + +/* Unmap clears exactly the requested PTEs and queues one TLB page each. */ +static void dart_test_unmap_range(struct kunit *test) +{ + struct iommu_iotlb_gather gather; + struct dart_test *t = test->priv; + struct dart_io_pgtable *data; + dart_iopte *ptep; + size_t mapped = 0; + + data = dart_test_alloc(test, APPLE_DART, SZ_16K, 32, 36); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_1M, SZ_1G, 4, IOMMU_READ | IOMMU_WRITE, + &mapped), 0); + KUNIT_ASSERT_EQ(test, mapped, (size_t)SZ_64K); + ptep = dart_test_leaf(data, SZ_1M); + KUNIT_ASSERT_NOT_NULL(test, ptep); + + iommu_iotlb_gather_init(&gather); + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, SZ_1M + SZ_16K, 2, &gather), (size_t)SZ_32K); + KUNIT_EXPECT_NE(test, ptep[0], 0ULL); + KUNIT_EXPECT_EQ(test, ptep[1], 0ULL); + KUNIT_EXPECT_EQ(test, ptep[2], 0ULL); + KUNIT_EXPECT_NE(test, ptep[3], 0ULL); + KUNIT_EXPECT_EQ(test, t->tlb_add_page, 2U); + KUNIT_EXPECT_EQ(test, t->tlb_last_iova, (unsigned long)SZ_1M + 2 * SZ_16K); + KUNIT_EXPECT_EQ(test, t->tlb_last_granule, (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_1M), (phys_addr_t)SZ_1G); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_1M + SZ_16K), 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_1M + 3 * SZ_16K), + (phys_addr_t)SZ_1G + 3 * SZ_16K); + + /* A queued gather defers invalidation to the caller. */ + gather.queued = true; + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, SZ_1M, 1, &gather), (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, t->tlb_add_page, 2U); + KUNIT_EXPECT_EQ(test, ptep[0], 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, SZ_1M + 3 * SZ_16K, 1, NULL), (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, t->tlb_add_page, 3U); + KUNIT_EXPECT_TRUE(test, mem_is_zero(ptep, 4 * sizeof(*ptep))); + KUNIT_EXPECT_EQ(test, t->tlb_other, 0U); +} + +/* Unmap of holes, missing tables and runs past a leaf table end. */ +static void dart_test_unmap_partial(struct kunit *test) +{ + const unsigned long end = SZ_32M - SZ_16K; /* last leaf slot of L1 0 */ + struct dart_test *t = test->priv; + size_t size; + + dart_test_alloc(test, APPLE_DART2, SZ_16K, 36, 42); + KUNIT_ASSERT_EQ(test, dart_test_map(t, end, 0x40000000, 2, IOMMU_READ, NULL), 0); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_32M, 0x40004000, 2, IOMMU_READ, NULL), 0); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_64M, 0x50000000, 2, IOMMU_READ, NULL), 0); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_64M + 3 * SZ_16K, 0x50000000, 1, IOMMU_READ, + NULL), 0); + + /* A run crossing the leaf table end stops at it. */ + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, end, 3, NULL), (size_t)SZ_16K); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_32M), 0x40004000ULL); + + kunit_warning_suppress(test) { + /* A hole at slot 2 ends the run after two pages. */ + size = dart_test_unmap(t, SZ_64M, 4, NULL); + KUNIT_EXPECT_EQ(test, size, (size_t)SZ_32K); + /* No leaf table at all. */ + size = dart_test_unmap(t, SZ_1G, 1, NULL); + KUNIT_EXPECT_EQ(test, size, (size_t)0); + /* Nothing to do and wrong page size. */ + size = dart_test_unmap(t, SZ_32M, 0, NULL); + KUNIT_EXPECT_EQ(test, size, (size_t)0); + size = t->ops->unmap_pages(t->ops, SZ_32M, SZ_4K, 1, NULL); + KUNIT_EXPECT_EQ(test, size, (size_t)0); + /* Beyond the TTBR. */ + size = dart_test_unmap(t, BIT_ULL(36), 1, NULL); + KUNIT_EXPECT_EQ(test, size, (size_t)0); + KUNIT_EXPECT_SUPPRESSED_WARNING_COUNT(test, 5); + } + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_32M), 0x40004000ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_64M), 0ULL); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_64M + 3 * SZ_16K), 0x50000000ULL); + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, SZ_32M, 2, NULL), (size_t)SZ_32K); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_32M + SZ_16K), 0ULL); +} + +/* iova_to_phys() misses at each level of an otherwise populated table. */ +static void dart_test_iova_to_phys_miss(struct kunit *test) +{ + struct dart_test *t = test->priv; + + dart_test_alloc(test, APPLE_DART2, SZ_16K, 37, 42); + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0), 0ULL); + KUNIT_ASSERT_EQ(test, dart_test_map(t, SZ_32M + SZ_16K, 0x12340000, 1, IOMMU_READ, + NULL), 0); + /* Same leaf table, empty slot. */ + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_32M), 0ULL); + /* Same L2 table, no leaf table. */ + KUNIT_EXPECT_EQ(test, dart_test_phys(t, 0), 0ULL); + /* No L2 table under L1 index 1. */ + KUNIT_EXPECT_EQ(test, dart_test_phys(t, BIT_ULL(36) + SZ_32M + SZ_16K), 0ULL); + /* The offset within the page is kept. */ + KUNIT_EXPECT_EQ(test, dart_test_phys(t, SZ_32M + SZ_16K + 0x3fff), 0x12343fffULL); +} + +struct dart_test_teardown { + const char *name; + enum io_pgtable_fmt fmt; + size_t pgsize; + u32 ias, oas; + unsigned long iova[4]; + long tables; /* tables held after alloc + the maps */ +}; + +static const struct dart_test_teardown dart_test_teardowns[] = { + /* 1 root + 2 leaf tables. */ + { "dart1-16k", APPLE_DART, SZ_16K, 32, 36, { 0, SZ_16K, SZ_32M, SZ_32M + SZ_16K }, 3 }, + /* 4 roots + 4 leaf tables, one per TTBR. */ + { "dart1-4k-4ttbr", APPLE_DART, SZ_4K, 32, 36, { 0, SZ_1G, 2UL * SZ_1G, 3UL * SZ_1G }, 8 }, + /* 1 root + 2 L2 + 3 leaf tables. */ + { "dart2-16k-4level", APPLE_DART2, SZ_16K, 42, 42, + { 0, SZ_32M, BIT(36), BIT(36) + SZ_16K }, 6 }, +}; + +static void dart_test_teardown_desc(const struct dart_test_teardown *td, char *desc) +{ + strscpy(desc, td->name, KUNIT_PARAM_DESC_SIZE); +} + +KUNIT_ARRAY_PARAM(dart_test_teardown, dart_test_teardowns, dart_test_teardown_desc); + +/* Every table page allocated by map_pages() is released by free_io_pgtable_ops(). */ +static void dart_test_teardown_free(struct kunit *test) +{ + const struct dart_test_teardown *td = test->param_value; + struct dart_test *t = test->priv; + long before; + int i; + + before = dart_test_iommu_pages(); + dart_test_alloc(test, td->fmt, td->pgsize, td->ias, td->oas); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages() - before, + t->cfg.apple_dart_cfg.n_ttbrs * dart_test_tbl_pages(td->pgsize)); + for (i = 0; i < ARRAY_SIZE(td->iova); i++) + KUNIT_ASSERT_EQ(test, dart_test_map(t, td->iova[i], SZ_1G, 1, IOMMU_READ, NULL), 0); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages() - before, + td->tables * dart_test_tbl_pages(td->pgsize)); + + /* Unmap keeps the tables; the teardown frees them. */ + for (i = 0; i < ARRAY_SIZE(td->iova); i++) + KUNIT_EXPECT_EQ(test, dart_test_unmap(t, td->iova[i], 1, NULL), td->pgsize); + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages() - before, + td->tables * dart_test_tbl_pages(td->pgsize)); + + kunit_release_action(test, dart_test_free_ops, t->ops); + t->ops = NULL; + KUNIT_EXPECT_EQ(test, dart_test_iommu_pages(), before); +} + +static struct kunit_case io_pgtable_dart_test_cases[] = { + KUNIT_CASE_PARAM(dart_test_alloc_layout, dart_test_layout_gen_params), + KUNIT_CASE_PARAM(dart_test_alloc_reject, dart_test_bad_cfg_gen_params), + KUNIT_CASE(dart_test_pte_dart1), + KUNIT_CASE(dart_test_pte_dart2), + KUNIT_CASE(dart_test_table_ptes), + KUNIT_CASE(dart_test_index_high_l1), + KUNIT_CASE(dart_test_four_level), + KUNIT_CASE(dart_test_four_ttbrs), + KUNIT_CASE(dart_test_map_multi), + KUNIT_CASE(dart_test_map_exists), + KUNIT_CASE(dart_test_map_reject), + KUNIT_CASE(dart_test_unmap_range), + KUNIT_CASE(dart_test_unmap_partial), + KUNIT_CASE(dart_test_iova_to_phys_miss), + KUNIT_CASE_PARAM(dart_test_teardown_free, dart_test_teardown_gen_params), + {} +}; + +static struct kunit_suite io_pgtable_dart_test_suite = { + .name = "io-pgtable-dart", + .init = dart_test_init, + .test_cases = io_pgtable_dart_test_cases, +}; + +kunit_test_suite(io_pgtable_dart_test_suite); diff --git a/drivers/iommu/io-pgtable-dart.c b/drivers/iommu/io-pgtable-dart.c index ad817bf76c310..93d268710a11e 100644 --- a/drivers/iommu/io-pgtable-dart.c +++ b/drivers/iommu/io-pgtable-dart.c @@ -483,3 +483,7 @@ struct io_pgtable_init_fns io_pgtable_apple_dart_init_fns = { .alloc = apple_dart_alloc_pgtable, .free = apple_dart_free_pgtable, }; + +#if IS_ENABLED(CONFIG_IOMMU_IO_PGTABLE_DART_KUNIT_TEST) +#include "io-pgtable-dart-test.c" +#endif diff --git a/drivers/iommu/io-pgtable-dart.kunitconfig b/drivers/iommu/io-pgtable-dart.kunitconfig new file mode 100644 index 0000000000000..3171f991a8f45 --- /dev/null +++ b/drivers/iommu/io-pgtable-dart.kunitconfig @@ -0,0 +1,4 @@ +CONFIG_KUNIT=y +CONFIG_IOMMU_SUPPORT=y +CONFIG_IOMMU_IO_PGTABLE_DART=y +CONFIG_IOMMU_IO_PGTABLE_DART_KUNIT_TEST=y From 0615a4964cbeeb942718178977d24cc3dec86c2d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:06 +1100 Subject: [PATCH 05/13] rtc: macsmc: add KUnit tests Add tests for the time and alarm arithmetic: the 48-bit tick offset with its sign extension and wrap, the 64-bit seconds offset and its rounding to the nearest second, and the PMU alarm's value, mask and control byte writes. A static stub replaces the SMC counter read and a RAM-backed NVMEM device holds the offset and alarm cells. The tick case expects set_time to return 0 on success, so it needs "rtc: macsmc: return 0 from a successful set_time" first; without it the case fails on the byte count (6). Signed-off-by: Ryan Murray --- drivers/rtc/Kconfig | 13 + drivers/rtc/rtc-macsmc-test.c | 574 +++++++++++++++++++++++++++++ drivers/rtc/rtc-macsmc.c | 4 + drivers/rtc/rtc-macsmc.kunitconfig | 13 + 4 files changed, 604 insertions(+) create mode 100644 drivers/rtc/rtc-macsmc-test.c create mode 100644 drivers/rtc/rtc-macsmc.kunitconfig diff --git a/drivers/rtc/Kconfig b/drivers/rtc/Kconfig index a7e6eba6e7910..243c4a563798a 100644 --- a/drivers/rtc/Kconfig +++ b/drivers/rtc/Kconfig @@ -2121,6 +2121,19 @@ config RTC_DRV_MACSMC To compile this driver as a module, choose M here: the module will be called rtc-macsmc. +config RTC_DRV_MACSMC_KUNIT_TEST + bool "KUnit tests for the Apple SMC RTC" if !KUNIT_ALL_TESTS + depends on RTC_DRV_MACSMC=y && KUNIT=y + depends on MFD_MACSMC_KUNIT_TEST && NVMEM + default KUNIT_ALL_TESTS + help + Build tests for the Apple SMC RTC's time and alarm arithmetic: the + 48-bit tick offset with its sign extension and wrap, the 64-bit + seconds offset and its rounding, and the PMU alarm's value, mask + and control byte writes. A static stub replaces the SMC counter + read and a RAM-backed NVMEM device holds the offset and alarm + cells, so the tests need no Apple hardware. + config RTC_DRV_MSC313 tristate "MStar MSC313 RTC" depends on ARCH_MSTARV7 || COMPILE_TEST diff --git a/drivers/rtc/rtc-macsmc-test.c b/drivers/rtc/rtc-macsmc-test.c new file mode 100644 index 0000000000000..a71c72a95a77b --- /dev/null +++ b/drivers/rtc/rtc-macsmc-test.c @@ -0,0 +1,574 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple SMC RTC driver: the 48-bit tick and 64-bit + * seconds offset arithmetic and the PMU alarm programming. + * + * The CLKM counter comes from a static stub on apple_smc_read() (see + * MFD_MACSMC_KUNIT_TEST). The offset and alarm cells are real NVMEM cells of + * a RAM-backed NVMEM device, found through a cell lookup table, so the cell + * sizes and byte layouts are checked by the NVMEM core as on hardware. + * + * Included by rtc-macsmc.c. + */ + +#include +#include +#include +#include + +#define RTC_TEST_OFFSET 0 +#define RTC_TEST_CTRL 8 +#define RTC_TEST_MASK 9 +#define RTC_TEST_ALARM 12 +#define RTC_TEST_NVMEM_SIZE 16 + +#define RTC_TEST_TICKS BIT_ULL(RTC_SEC_SHIFT) +#define RTC_TEST_MASK48 GENMASK_ULL(RTC_BITS - 1, 0) + +/* 2023-11-14 22:13:20 UTC */ +#define RTC_TEST_T 1700000000LL + +struct macsmc_rtc_test_write { + unsigned int offset; + size_t bytes; + u8 val[8]; +}; + +struct macsmc_rtc_test { + struct apple_smc smc; + struct macsmc_rtc rtc; + struct device *dev; + u8 nvmem[RTC_TEST_NVMEM_SIZE]; + /* CLKM: the free-running 32768 Hz counter, and what its read returns */ + u64 clkm; + int clkm_ret; + /* NVMEM writes, in order; a write at fail_offset fails */ + struct macsmc_rtc_test_write writes[8]; + unsigned int nr_writes; + int fail_offset; + struct nvmem_cell_lookup lookups[4]; +}; + +static int macsmc_rtc_test_read(struct apple_smc *smc, smc_key key, void *buf, + size_t size) +{ + struct macsmc_rtc_test *ctx = container_of(smc, struct macsmc_rtc_test, smc); + struct kunit *test = kunit_get_current_test(); + u8 le[8]; + + KUNIT_EXPECT_EQ(test, key, SMC_KEY(CLKM)); + KUNIT_EXPECT_EQ(test, size, RTC_BYTES); + if (ctx->clkm_ret < 0) + return ctx->clkm_ret; + + put_unaligned_le64(ctx->clkm, le); + memcpy(buf, le, min(size, sizeof(le))); + return ctx->clkm_ret ?: size; +} + +static int macsmc_rtc_test_reg_read(void *priv, unsigned int offset, void *val, + size_t bytes) +{ + struct macsmc_rtc_test *ctx = priv; + + memcpy(val, ctx->nvmem + offset, bytes); + return 0; +} + +static int macsmc_rtc_test_reg_write(void *priv, unsigned int offset, void *val, + size_t bytes) +{ + struct macsmc_rtc_test *ctx = priv; + struct macsmc_rtc_test_write *w; + + if (offset == ctx->fail_offset) + return -EIO; + + if (ctx->nr_writes < ARRAY_SIZE(ctx->writes)) { + w = &ctx->writes[ctx->nr_writes]; + w->offset = offset; + w->bytes = bytes; + memcpy(w->val, val, min(bytes, sizeof(w->val))); + } + ctx->nr_writes++; + memcpy(ctx->nvmem + offset, val, bytes); + return 0; +} + +static void macsmc_rtc_test_del_lookups(void *data) +{ + struct macsmc_rtc_test *ctx = data; + + nvmem_del_cell_lookups(ctx->lookups, ARRAY_SIZE(ctx->lookups)); +} + +KUNIT_DEFINE_ACTION_WRAPPER(macsmc_rtc_test_cell_put, nvmem_cell_put, + struct nvmem_cell *); + +static struct nvmem_cell *macsmc_rtc_test_cell(struct kunit *test, + struct macsmc_rtc_test *ctx, + const char *id) +{ + struct nvmem_cell *cell = nvmem_cell_get(ctx->dev, id); + + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cell); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, macsmc_rtc_test_cell_put, + cell), 0); + return cell; +} + +/* + * An RTC whose offset cell holds @offset_bytes bytes: 6 for a tick offset, + * 8 for a seconds offset. + */ +static struct macsmc_rtc_test *macsmc_rtc_test_setup(struct kunit *test, + bool offset_in_seconds, + unsigned int offset_bytes) +{ + static const char * const names[] = { + "rtc_offset", "rtc_ctrl", "rtc_alarm_mask", "rtc_alarm", + }; + const unsigned int offsets[] = { + RTC_TEST_OFFSET, RTC_TEST_CTRL, RTC_TEST_MASK, RTC_TEST_ALARM, + }; + const unsigned int sizes[] = { offset_bytes, 1, 1, 4 }; + struct nvmem_config config = {}; + struct nvmem_cell_info *cells; + struct macsmc_rtc_test *ctx; + struct nvmem_device *nvmem; + struct device *provider; + int i; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + cells = kunit_kcalloc(test, ARRAY_SIZE(names), sizeof(*cells), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, cells); + ctx->fail_offset = -1; + mutex_init(&ctx->smc.mutex); + + for (i = 0; i < ARRAY_SIZE(names); i++) { + cells[i].name = names[i]; + cells[i].offset = offsets[i]; + cells[i].bytes = sizes[i]; + } + + provider = kunit_device_register(test, "nvmem"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, provider); + config.dev = provider; + config.name = "macsmc-rtc-test"; + config.id = NVMEM_DEVID_AUTO; + config.cells = cells; + config.ncells = ARRAY_SIZE(names); + config.ignore_wp = true; + config.reg_read = macsmc_rtc_test_reg_read; + config.reg_write = macsmc_rtc_test_reg_write; + config.size = RTC_TEST_NVMEM_SIZE; + config.priv = ctx; + nvmem = devm_nvmem_register(provider, &config); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, nvmem); + + ctx->dev = kunit_device_register(test, "rtc"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); + for (i = 0; i < ARRAY_SIZE(names); i++) { + ctx->lookups[i].nvmem_name = nvmem_dev_name(nvmem); + ctx->lookups[i].cell_name = names[i]; + ctx->lookups[i].dev_id = dev_name(ctx->dev); + ctx->lookups[i].con_id = names[i]; + } + nvmem_add_cell_lookups(ctx->lookups, ARRAY_SIZE(ctx->lookups)); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, macsmc_rtc_test_del_lookups, + ctx), 0); + + ctx->rtc.dev = ctx->dev; + ctx->rtc.smc = &ctx->smc; + ctx->rtc.offset_in_seconds = offset_in_seconds; + mutex_init(&ctx->rtc.alarm_lock); + ctx->rtc.rtc_offset = macsmc_rtc_test_cell(test, ctx, "rtc_offset"); + ctx->rtc.alarm_ctrl = macsmc_rtc_test_cell(test, ctx, "rtc_ctrl"); + ctx->rtc.alarm_mask = macsmc_rtc_test_cell(test, ctx, "rtc_alarm_mask"); + ctx->rtc.alarm_value = macsmc_rtc_test_cell(test, ctx, "rtc_alarm"); + dev_set_drvdata(ctx->dev, &ctx->rtc); + + kunit_activate_static_stub(test, apple_smc_read, macsmc_rtc_test_read); + return ctx; +} + +static void macsmc_rtc_test_put_tick_offset(struct macsmc_rtc_test *ctx, u64 off) +{ + u8 le[8]; + + put_unaligned_le64(off & RTC_TEST_MASK48, le); + memcpy(ctx->nvmem + RTC_TEST_OFFSET, le, RTC_BYTES); +} + +static u64 macsmc_rtc_test_tick_offset(struct macsmc_rtc_test *ctx) +{ + u8 le[8] = {}; + + memcpy(le, ctx->nvmem + RTC_TEST_OFFSET, RTC_BYTES); + return get_unaligned_le64(le); +} + +static time64_t macsmc_rtc_test_now(struct kunit *test, struct macsmc_rtc_test *ctx) +{ + struct rtc_time tm = {}; + int ret; + + ret = macsmc_rtc_get_time(ctx->dev, &tm); + KUNIT_EXPECT_GE(test, ret, 0); + if (ret < 0) + return S64_MIN; + return rtc_tm_to_time64(&tm); +} + +static int macsmc_rtc_test_set(struct macsmc_rtc_test *ctx, time64_t t) +{ + struct rtc_time tm; + + rtc_time64_to_tm(t, &tm); + return macsmc_rtc_set_time(ctx->dev, &tm); +} + +static void macsmc_rtc_test_expect_write(struct kunit *test, + struct macsmc_rtc_test *ctx, + unsigned int idx, unsigned int offset, + size_t bytes, u64 val) +{ + struct macsmc_rtc_test_write *w = &ctx->writes[idx]; + u8 le[8]; + + KUNIT_ASSERT_LT(test, idx, ctx->nr_writes); + put_unaligned_le64(val, le); + KUNIT_EXPECT_EQ_MSG(test, w->offset, offset, "write %u", idx); + KUNIT_EXPECT_EQ_MSG(test, w->bytes, bytes, "write %u", idx); + KUNIT_EXPECT_MEMEQ_MSG(test, w->val, le, bytes, "write %u", idx); +} + +/* Tick offset: time = sign_extend48(CLKM + offset) / 2^15, rounded down. */ +static void macsmc_rtc_test_tick_read(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + u64 ctr = 0x123456789abULL; + + ctx->clkm = ctr; + macsmc_rtc_test_put_tick_offset(ctx, (RTC_TEST_T << RTC_SEC_SHIFT) + 12345 - ctr); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); + + /* One tick before the next second, and the second itself. */ + ctx->clkm = ctr + RTC_TEST_TICKS - 12345 - 1; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); + ctx->clkm++; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T + 1); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); +} + +/* The sum is taken modulo 2^48: a carry out of bit 47 is not time. */ +static void macsmc_rtc_test_tick_wrap(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + + ctx->clkm = RTC_TEST_MASK48 + 1 - RTC_TEST_TICKS; + macsmc_rtc_test_put_tick_offset(ctx, (RTC_TEST_T << RTC_SEC_SHIFT) + RTC_TEST_TICKS); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); +} + +/* Set then read: the stored 6 bytes, and the set second starts at the set. */ +static void macsmc_rtc_test_tick_set(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + u64 ctr = 0x00ab12345678ULL; + + ctx->clkm = ctr; + /* .set_time returns 0, not the cell write's byte count. */ + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 1); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_OFFSET, RTC_BYTES, + ((RTC_TEST_T << RTC_SEC_SHIFT) - ctr) & RTC_TEST_MASK48); + + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); + ctx->clkm = ctr + RTC_TEST_TICKS - 1; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); + ctx->clkm = ctr + 3 * RTC_TEST_TICKS + 100; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T + 3); +} + +/* A time before 1970 is a negative 48-bit sum and must read back as such. */ +static void macsmc_rtc_test_tick_negative(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + struct rtc_time tm = {}; + + ctx->clkm = 1000 * RTC_TEST_TICKS + 5; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, -1), 0); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_tick_offset(ctx), + ((u64)-(1LL << RTC_SEC_SHIFT) - ctx->clkm) & RTC_TEST_MASK48); + + KUNIT_EXPECT_GE(test, macsmc_rtc_get_time(ctx->dev, &tm), 0); + KUNIT_EXPECT_EQ(test, tm.tm_year, 69); + KUNIT_EXPECT_EQ(test, tm.tm_mon, 11); + KUNIT_EXPECT_EQ(test, tm.tm_mday, 31); + KUNIT_EXPECT_EQ(test, tm.tm_hour, 23); + KUNIT_EXPECT_EQ(test, tm.tm_min, 59); + KUNIT_EXPECT_EQ(test, tm.tm_sec, 59); +} + +/* Seconds offset: time = CLKM / 2^15 + offset, offset a LE64 at the cell. */ +static void macsmc_rtc_test_secs_read(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + + put_unaligned_le64(RTC_TEST_T, ctx->nvmem + RTC_TEST_OFFSET); + ctx->clkm = 5 * RTC_TEST_TICKS + RTC_TEST_TICKS - 1; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T + 5); + + /* Bits above the counter's 48 are not read: CLKM is a 6-byte key. */ + ctx->clkm = BIT_ULL(RTC_BITS) | (7 * RTC_TEST_TICKS); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T + 7); +} + +/* An offset never written is not a time: reading it must fail. */ +static void macsmc_rtc_test_secs_unset(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + struct rtc_time tm; + + ctx->clkm = 1234 * RTC_TEST_TICKS; + KUNIT_EXPECT_EQ(test, macsmc_rtc_get_time(ctx->dev, &tm), -EINVAL); +} + +/* A seconds-mode offset cell shorter than 8 bytes is rejected, not half read. */ +static void macsmc_rtc_test_secs_short_cell(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, RTC_BYTES); + struct rtc_wkalrm alrm = { .enabled = 1 }; + struct rtc_time tm; + + memset(ctx->nvmem, 0x11, RTC_BYTES); + KUNIT_EXPECT_EQ(test, macsmc_rtc_get_time(ctx->dev, &tm), -EIO); + rtc_time64_to_tm(RTC_TEST_T, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), -EIO); + KUNIT_EXPECT_EQ(test, macsmc_rtc_read_alarm(ctx->dev, &alrm), -EIO); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); +} + +/* The seconds offset rounds the counter to the nearest second. */ +static void macsmc_rtc_test_secs_set(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + + ctx->clkm = 10 * RTC_TEST_TICKS + RTC_TEST_TICKS / 2 - 1; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), 0); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_OFFSET, 8, RTC_TEST_T - 10); + + ctx->clkm = 10 * RTC_TEST_TICKS + RTC_TEST_TICKS / 2; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), 0); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_OFFSET, 8, RTC_TEST_T - 11); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 2); + + /* Read back half a second later: at most half a second off. */ + ctx->clkm += RTC_TEST_TICKS / 2; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_now(test, ctx), RTC_TEST_T); +} + +/* CLKM failures and short replies fail the call and write nothing. */ +static void macsmc_rtc_test_clkm_errors(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + struct rtc_time tm; + + ctx->clkm_ret = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, macsmc_rtc_get_time(ctx->dev, &tm), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), -ETIMEDOUT); + + ctx->clkm_ret = 4; + KUNIT_EXPECT_EQ(test, macsmc_rtc_get_time(ctx->dev, &tm), -EIO); + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), -EIO); + + ctx->rtc.offset_in_seconds = true; + KUNIT_EXPECT_EQ(test, macsmc_rtc_test_set(ctx, RTC_TEST_T), -EIO); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); +} + +/* + * Arming: a latched event is cleared by writing it back, then the value + * (counter seconds, LE32), the mask and the control byte with EN | MONITOR. + * The PMU's other control bits are kept. + */ +static void macsmc_rtc_test_alarm_arm(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + struct rtc_wkalrm alrm = { .enabled = 1 }; + const s64 off = 1000000; + + /* A tick offset with a fraction: whole seconds are used. */ + macsmc_rtc_test_put_tick_offset(ctx, (off << RTC_SEC_SHIFT) + 1234); + ctx->nvmem[RTC_TEST_CTRL] = 0x80 | RTC_CTRL_ALARM_EVENT; + ctx->nvmem[RTC_TEST_MASK] = 1; + + rtc_time64_to_tm(off + 4321, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, ctx->rtc.alarm_secs, 4321); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 4); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_CTRL, 1, + 0x80 | RTC_CTRL_ALARM_EVENT); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_ALARM, 4, 4321); + macsmc_rtc_test_expect_write(test, ctx, 2, RTC_TEST_MASK, 1, 0); + macsmc_rtc_test_expect_write(test, ctx, 3, RTC_TEST_CTRL, 1, + 0x80 | RTC_CTRL_ALARM_EN | RTC_CTRL_MONITOR); +} + +/* A disabled alarm is remembered but disarms; enabling it arms the same second. */ +static void macsmc_rtc_test_alarm_disabled(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + struct rtc_wkalrm alrm = { .enabled = 0 }; + + put_unaligned_le64(RTC_TEST_T, ctx->nvmem + RTC_TEST_OFFSET); + /* Left armed by firmware, no event. */ + ctx->nvmem[RTC_TEST_CTRL] = RTC_CTRL_ALARM_EN | RTC_CTRL_MONITOR; + + rtc_time64_to_tm(RTC_TEST_T + 60, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, ctx->rtc.alarm_secs, 60); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 2); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_MASK, 1, 1); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_CTRL, 1, RTC_CTRL_MONITOR); + + ctx->nr_writes = 0; + KUNIT_EXPECT_EQ(test, macsmc_rtc_alarm_irq_enable(ctx->dev, 1), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 3); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_ALARM, 4, 60); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_MASK, 1, 0); + macsmc_rtc_test_expect_write(test, ctx, 2, RTC_TEST_CTRL, 1, + RTC_CTRL_ALARM_EN | RTC_CTRL_MONITOR); + + ctx->nr_writes = 0; + KUNIT_EXPECT_EQ(test, macsmc_rtc_alarm_irq_enable(ctx->dev, 0), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 2); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_CTRL, 1, RTC_CTRL_MONITOR); +} + +/* The 32-bit compare holds counter seconds 1..U32_MAX; others are refused. */ +static void macsmc_rtc_test_alarm_range(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + struct rtc_wkalrm alrm = { .enabled = 1 }; + const time64_t off = 86400; + + put_unaligned_le64(off, ctx->nvmem + RTC_TEST_OFFSET); + + rtc_time64_to_tm(off, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), -ERANGE); + rtc_time64_to_tm(off - 5, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), -ERANGE); + rtc_time64_to_tm(off + (time64_t)U32_MAX + 1, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), -ERANGE); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); + + rtc_time64_to_tm(off + 1, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(ctx->nvmem + RTC_TEST_ALARM), 1); + rtc_time64_to_tm(off + U32_MAX, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(ctx->nvmem + RTC_TEST_ALARM), U32_MAX); +} + +/* A negative tick offset moves the alarm's counter second forward. */ +static void macsmc_rtc_test_alarm_negative_offset(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, false, RTC_BYTES); + struct rtc_wkalrm alrm = { .enabled = 1 }; + + macsmc_rtc_test_put_tick_offset(ctx, (u64)-(5LL << RTC_SEC_SHIFT)); + rtc_time64_to_tm(100, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(ctx->nvmem + RTC_TEST_ALARM), 105); + + memset(&alrm, 0, sizeof(alrm)); + KUNIT_EXPECT_EQ(test, macsmc_rtc_read_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, rtc_tm_to_time64(&alrm.time), 100); + KUNIT_EXPECT_TRUE(test, alrm.enabled); + KUNIT_EXPECT_FALSE(test, alrm.pending); +} + +/* Reading decodes the value against the offset and the EN/EVENT bits. */ +static void macsmc_rtc_test_alarm_read(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + struct rtc_wkalrm alrm = {}; + + put_unaligned_le64(RTC_TEST_T, ctx->nvmem + RTC_TEST_OFFSET); + put_unaligned_le32(777, ctx->nvmem + RTC_TEST_ALARM); + ctx->nvmem[RTC_TEST_CTRL] = RTC_CTRL_ALARM_EN | RTC_CTRL_ALARM_EVENT; + KUNIT_EXPECT_EQ(test, macsmc_rtc_read_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_EQ(test, rtc_tm_to_time64(&alrm.time), RTC_TEST_T + 777); + KUNIT_EXPECT_TRUE(test, alrm.enabled); + KUNIT_EXPECT_TRUE(test, alrm.pending); + + ctx->nvmem[RTC_TEST_CTRL] = RTC_CTRL_MONITOR; + KUNIT_EXPECT_EQ(test, macsmc_rtc_read_alarm(ctx->dev, &alrm), 0); + KUNIT_EXPECT_FALSE(test, alrm.enabled); + KUNIT_EXPECT_FALSE(test, alrm.pending); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); +} + +/* The interrupt is one-shot: an event clears and disarms; no event is not ours. */ +static void macsmc_rtc_test_alarm_irq(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + const u8 armed = RTC_CTRL_ALARM_EN | RTC_CTRL_MONITOR; + + ctx->nvmem[RTC_TEST_CTRL] = armed; + KUNIT_EXPECT_EQ(test, macsmc_rtc_alarm_irq(0, &ctx->rtc), IRQ_NONE); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); + + ctx->nvmem[RTC_TEST_CTRL] = armed | RTC_CTRL_ALARM_EVENT; + KUNIT_EXPECT_EQ(test, macsmc_rtc_alarm_irq(0, &ctx->rtc), IRQ_HANDLED); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 3); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_CTRL, 1, + armed | RTC_CTRL_ALARM_EVENT); + macsmc_rtc_test_expect_write(test, ctx, 1, RTC_TEST_MASK, 1, 1); + macsmc_rtc_test_expect_write(test, ctx, 2, RTC_TEST_CTRL, 1, RTC_CTRL_MONITOR); +} + +/* A failed mask write leaves the alarm unarmed and reports the error. */ +static void macsmc_rtc_test_alarm_write_error(struct kunit *test) +{ + struct macsmc_rtc_test *ctx = macsmc_rtc_test_setup(test, true, 8); + struct rtc_wkalrm alrm = { .enabled = 1 }; + + put_unaligned_le64(RTC_TEST_T, ctx->nvmem + RTC_TEST_OFFSET); + ctx->fail_offset = RTC_TEST_MASK; + rtc_time64_to_tm(RTC_TEST_T + 10, &alrm.time); + KUNIT_EXPECT_EQ(test, macsmc_rtc_set_alarm(ctx->dev, &alrm), -EIO); + KUNIT_EXPECT_EQ(test, ctx->nvmem[RTC_TEST_CTRL], 0); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 1); + macsmc_rtc_test_expect_write(test, ctx, 0, RTC_TEST_ALARM, 4, 10); +} + +static struct kunit_case macsmc_rtc_test_cases[] = { + KUNIT_CASE(macsmc_rtc_test_tick_read), + KUNIT_CASE(macsmc_rtc_test_tick_wrap), + KUNIT_CASE(macsmc_rtc_test_tick_set), + KUNIT_CASE(macsmc_rtc_test_tick_negative), + KUNIT_CASE(macsmc_rtc_test_secs_read), + KUNIT_CASE(macsmc_rtc_test_secs_unset), + KUNIT_CASE(macsmc_rtc_test_secs_short_cell), + KUNIT_CASE(macsmc_rtc_test_secs_set), + KUNIT_CASE(macsmc_rtc_test_clkm_errors), + KUNIT_CASE(macsmc_rtc_test_alarm_arm), + KUNIT_CASE(macsmc_rtc_test_alarm_disabled), + KUNIT_CASE(macsmc_rtc_test_alarm_range), + KUNIT_CASE(macsmc_rtc_test_alarm_negative_offset), + KUNIT_CASE(macsmc_rtc_test_alarm_read), + KUNIT_CASE(macsmc_rtc_test_alarm_irq), + KUNIT_CASE(macsmc_rtc_test_alarm_write_error), + {} +}; + +static struct kunit_suite macsmc_rtc_test_suite = { + .name = "macsmc-rtc", + .test_cases = macsmc_rtc_test_cases, +}; + +kunit_test_suite(macsmc_rtc_test_suite); diff --git a/drivers/rtc/rtc-macsmc.c b/drivers/rtc/rtc-macsmc.c index 690a4a84ff90e..0b83e6e609d67 100644 --- a/drivers/rtc/rtc-macsmc.c +++ b/drivers/rtc/rtc-macsmc.c @@ -482,3 +482,7 @@ module_platform_driver(macsmc_rtc_driver); MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("Apple SMC RTC driver"); MODULE_AUTHOR("Hector Martin "); + +#if IS_ENABLED(CONFIG_RTC_DRV_MACSMC_KUNIT_TEST) +#include "rtc-macsmc-test.c" +#endif diff --git a/drivers/rtc/rtc-macsmc.kunitconfig b/drivers/rtc/rtc-macsmc.kunitconfig new file mode 100644 index 0000000000000..08faff88f7bd8 --- /dev/null +++ b/drivers/rtc/rtc-macsmc.kunitconfig @@ -0,0 +1,13 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/rtc/rtc-macsmc.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_MAILBOX=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_MFD_MACSMC=y +CONFIG_MFD_MACSMC_KUNIT_TEST=y +CONFIG_NVMEM=y +CONFIG_RTC_CLASS=y +CONFIG_RTC_DRV_MACSMC=y +CONFIG_RTC_DRV_MACSMC_KUNIT_TEST=y From cd74f48616aa6eab1f353cee98cfb265b44ff3dc Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:06 +1100 Subject: [PATCH 06/13] gpio: macsmc: add KUnit tests Add tests for the gPxx key names of the pins, the output command words, the J700 pcIO and J713 radio lines with their remembered levels, the DT output and pcIO templates, the valid line mask and the pcIO output-command chip. A static stub replaces SMC writes. Not covered: lookups that go through apple_smc_get_key_by_index() and apple_smc_rw(), which have no stub reachable from outside the MFD. Signed-off-by: Ryan Murray --- drivers/gpio/Kconfig | 13 + drivers/gpio/gpio-macsmc-test.c | 467 +++++++++++++++++++++++++++ drivers/gpio/gpio-macsmc.c | 4 + drivers/gpio/gpio-macsmc.kunitconfig | 12 + 4 files changed, 496 insertions(+) create mode 100644 drivers/gpio/gpio-macsmc-test.c create mode 100644 drivers/gpio/gpio-macsmc.kunitconfig diff --git a/drivers/gpio/Kconfig b/drivers/gpio/Kconfig index a48586bb8edba..b35f8bbe36962 100644 --- a/drivers/gpio/Kconfig +++ b/drivers/gpio/Kconfig @@ -1557,6 +1557,19 @@ config GPIO_MACSMC This driver can also be built as a module. If so, the module will be called gpio-macsmc. +config GPIO_MACSMC_KUNIT_TEST + bool "KUnit tests for the Apple SMC GPIO driver" if !KUNIT_ALL_TESTS + depends on GPIO_MACSMC=y && KUNIT=y + depends on MFD_MACSMC_KUNIT_TEST + default KUNIT_ALL_TESTS + help + Build tests for the Apple SMC GPIO driver: the gPxx key names of + the pins, the output command words, the J700 pcIO and J713 radio + lines with their remembered levels, the DT output and pcIO + templates, the valid line mask and the pcIO output-command chip. + A static stub replaces SMC writes, so the tests need no Apple + hardware. + config GPIO_MADERA tristate "Cirrus Logic Madera class codecs" depends on PINCTRL_MADERA diff --git a/drivers/gpio/gpio-macsmc-test.c b/drivers/gpio/gpio-macsmc-test.c new file mode 100644 index 0000000000000..50482dd40e563 --- /dev/null +++ b/drivers/gpio/gpio-macsmc-test.c @@ -0,0 +1,467 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple SMC GPIO driver: the gPxx key names, the output + * command words, the board-specific lines (J700 pcIO outputs, the J713 radio + * line) with their cached levels, the DT command templates and the + * pcIO output-command variant. + * + * SMC writes go to a static stub on apple_smc_write() (see + * MFD_MACSMC_KUNIT_TEST); the gpio_chip is registered with gpiolib so the + * driver's callbacks run on a real chip. The SMC has no keys here, so no + * line needs an SMC read. + * + * Included by gpio-macsmc.c. + */ + +#include +#include +#include +#include + +#define GPIO_TEST_GP ((smc_key)_SMC_KEY("gP\0\0")) +#define GPIO_TEST_GPL ((smc_key)_SMC_KEY("gp\0\0")) + +struct macsmc_gpio_test_write { + smc_key key; + size_t size; + u64 val; +}; + +struct macsmc_gpio_test { + struct apple_smc smc; + u8 shmem[256]; + /* + * The driver state, and the pcIO commands it points at, live in ctx: + * ctx is allocated before the device, so they outlive the gpio_chip + * that the device's devres removes at the end of the case. + */ + struct macsmc_gpio gpio; + u64 commands[2]; + struct macsmc_gpio *smcgp; + struct device *dev; + struct software_node swnode; + struct macsmc_gpio_test_write writes[8]; + unsigned int nr_writes; + int write_ret; +}; + +static int macsmc_gpio_test_write(struct apple_smc *smc, smc_key key, + const void *buf, size_t size) +{ + struct macsmc_gpio_test *ctx = container_of(smc, struct macsmc_gpio_test, smc); + struct macsmc_gpio_test_write *w; + + if (ctx->nr_writes < ARRAY_SIZE(ctx->writes)) { + w = &ctx->writes[ctx->nr_writes]; + w->key = key; + w->size = size; + w->val = 0; + memcpy(&w->val, buf, min(size, sizeof(w->val))); + } + ctx->nr_writes++; + return ctx->write_ret; +} + +KUNIT_DEFINE_ACTION_WRAPPER(macsmc_gpio_test_remove_swnode, device_remove_software_node, + struct device *); +KUNIT_DEFINE_ACTION_WRAPPER(macsmc_gpio_test_unregister_swnode, software_node_unregister, + const struct software_node *); + +static struct macsmc_gpio_test *macsmc_gpio_test_alloc(struct kunit *test, + const char *name, + const struct property_entry *props) +{ + struct macsmc_gpio_test *ctx; + int ret; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + mutex_init(&ctx->smc.mutex); + spin_lock_init(&ctx->smc.lock); + /* Any SMC command fails: the SMC never booted. */ + ctx->smc.shmem.iomem = (void __force __iomem *)ctx->shmem; + + /* + * The gpiochip's device shares the parent's fwnode and drops its + * reference after the parent's devres runs, so the node is registered + * before the device and unregistered after it is gone. A managed node + * would get its reference dropped once per device. + */ + if (props) { + ctx->swnode.properties = props; + KUNIT_ASSERT_EQ(test, software_node_register(&ctx->swnode), 0); + ret = kunit_add_action_or_reset(test, macsmc_gpio_test_unregister_swnode, + &ctx->swnode); + KUNIT_ASSERT_EQ(test, ret, 0); + } + + ctx->dev = kunit_device_register(test, name); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); + if (props) { + KUNIT_ASSERT_EQ(test, device_add_software_node(ctx->dev, &ctx->swnode), 0); + ret = kunit_add_action_or_reset(test, macsmc_gpio_test_remove_swnode, ctx->dev); + KUNIT_ASSERT_EQ(test, ret, 0); + } + + ctx->smcgp = &ctx->gpio; + ctx->smcgp->dev = ctx->dev; + ctx->smcgp->smc = &ctx->smc; + mutex_init(&ctx->smcgp->j713_reg_on_lock); + + kunit_activate_static_stub(test, apple_smc_write, macsmc_gpio_test_write); + return ctx; +} + +/* The chip macsmc_gpio_probe() registers, on an SMC without GPIO keys. */ +static void macsmc_gpio_test_register(struct kunit *test, struct macsmc_gpio_test *ctx, + smc_key base_key, bool j700, bool j713) +{ + struct macsmc_gpio *smcgp = ctx->smcgp; + + smcgp->base_key = base_key; + smcgp->j700_pcio = j700; + smcgp->j713 = j713; + KUNIT_ASSERT_EQ(test, macsmc_gpio_parse_templates(smcgp), 0); + + smcgp->gc.label = "macsmc-gpio-test"; + smcgp->gc.owner = THIS_MODULE; + smcgp->gc.get = macsmc_gpio_get; + smcgp->gc.set = macsmc_gpio_set; + smcgp->gc.get_direction = macsmc_gpio_get_direction; + smcgp->gc.init_valid_mask = macsmc_gpio_init_valid_mask; + smcgp->gc.can_sleep = true; + smcgp->gc.ngpio = MAX_GPIO; + smcgp->gc.base = -1; + smcgp->gc.parent = ctx->dev; + KUNIT_ASSERT_EQ(test, devm_gpiochip_add_data(ctx->dev, &smcgp->gc, smcgp), 0); +} + +static void macsmc_gpio_test_expect_write(struct kunit *test, + struct macsmc_gpio_test *ctx, + unsigned int idx, smc_key key, + size_t size, u64 val) +{ + KUNIT_ASSERT_LT(test, idx, ctx->nr_writes); + KUNIT_EXPECT_EQ_MSG(test, ctx->writes[idx].key, key, "write %u", idx); + KUNIT_EXPECT_EQ_MSG(test, ctx->writes[idx].size, size, "write %u", idx); + KUNIT_EXPECT_EQ_MSG(test, ctx->writes[idx].val, val, "write %u", idx); +} + +/* Pin numbers become two lowercase hex digits after the base key. */ +static void macsmc_gpio_test_key_name(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GP, 0), _SMC_KEY("gP00")); + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GP, 0x0a), _SMC_KEY("gP0a")); + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GP, 0x13), _SMC_KEY("gP13")); + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GP, 0x3f), _SMC_KEY("gP3f")); + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GPL, 0x05), _SMC_KEY("gp05")); + KUNIT_EXPECT_EQ(test, macsmc_gpio_key(GPIO_TEST_GPL, 0xc1), _SMC_KEY("gpc1")); +} + +/* Key names parse back to pin numbers; non-hex names are rejected. */ +static void macsmc_gpio_test_key_nr(struct kunit *test) +{ + unsigned int i; + + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gP13")), 0x13); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gP0a")), 10); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gP0A")), 10); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gp3f")), 63); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gPzz")), -1); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gPg0")), -1); + KUNIT_EXPECT_EQ(test, macsmc_gpio_nr(_SMC_KEY("gP0-")), -1); + + for (i = 0; i < MAX_GPIO; i++) + KUNIT_EXPECT_EQ_MSG(test, macsmc_gpio_nr(macsmc_gpio_key(GPIO_TEST_GP, i)), i, + "pin %u", i); +} + +/* A plain line is set with a CMD_OUTPUT word carrying the level in bit 0. */ +static void macsmc_gpio_test_set_plain(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = macsmc_gpio_test_alloc(test, "gpio", NULL); + struct gpio_chip *gc = &ctx->smcgp->gc; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, false, false); + KUNIT_EXPECT_EQ(test, gc->set(gc, 5, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, 0x2c, 0), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 2); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("gP05"), 4, CMD_OUTPUT | 1); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("gP2c"), 4, CMD_OUTPUT); + + ctx->write_ret = -EIO; + KUNIT_EXPECT_EQ(test, gc->set(gc, 5, 1), -EIO); +} + +/* On the J713 family gP13 is the radio's reg_on: template | level, cached. */ +static void macsmc_gpio_test_j713_reg_on(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = macsmc_gpio_test_alloc(test, "gpio", NULL); + struct gpio_chip *gc = &ctx->smcgp->gc; + const unsigned int pin = MACSMC_J713_RADIO_REG_ON_GPIO; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, false, true); + KUNIT_EXPECT_EQ(test, gc->get_direction(gc, pin), GPIO_LINE_DIRECTION_OUT); + /* No readback: nothing is known before the first write. */ + KUNIT_EXPECT_EQ(test, gc->get(gc, pin), -EOPNOTSUPP); + + KUNIT_EXPECT_EQ(test, gc->set(gc, pin, 1), 0); + KUNIT_EXPECT_EQ(test, gc->get(gc, pin), 1); + KUNIT_EXPECT_EQ(test, gc->set(gc, pin, 0), 0); + KUNIT_EXPECT_EQ(test, gc->get(gc, pin), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 2); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("gP13"), 4, + MACSMC_J713_RADIO_REG_ON_TEMPLATE | 1); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("gP13"), 4, + MACSMC_J713_RADIO_REG_ON_TEMPLATE); + + /* A failed write does not change the reported level. */ + ctx->write_ret = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, gc->set(gc, pin, 1), -ETIMEDOUT); + KUNIT_EXPECT_EQ(test, gc->get(gc, pin), 0); +} + +/* The radio line is gP13 only: not gp13, not another gP pin. */ +static void macsmc_gpio_test_j713_other_lines(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = macsmc_gpio_test_alloc(test, "gpio", NULL); + struct gpio_chip *gc = &ctx->smcgp->gc; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GPL, false, true); + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J713_RADIO_REG_ON_GPIO, 1), 0); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("gp13"), 4, CMD_OUTPUT | 1); + + ctx->smcgp->base_key = GPIO_TEST_GP; + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J713_RADIO_REG_ON_GPIO - 1, 1), 0); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("gP12"), 4, CMD_OUTPUT | 1); + + /* Without the J713 flag gP13 is a plain line too. */ + ctx->smcgp->j713 = false; + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J713_RADIO_REG_ON_GPIO, 0), 0); + macsmc_gpio_test_expect_write(test, ctx, 2, _SMC_KEY("gP13"), 4, CMD_OUTPUT); +} + +static const u32 macsmc_gpio_test_out_tmpl[] = { 5, 0x00a00000, 0x3e, 0x00300000 }; + +static const struct property_entry macsmc_gpio_test_out_props[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,output-templates", macsmc_gpio_test_out_tmpl), + {} +}; + +/* apple,output-templates: pairs; the write is template | level. */ +static void macsmc_gpio_test_output_template(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = + macsmc_gpio_test_alloc(test, "gpio", macsmc_gpio_test_out_props); + struct gpio_chip *gc = &ctx->smcgp->gc; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, false, false); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, 5)); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, 0x3e)); + KUNIT_EXPECT_FALSE(test, gpiochip_line_is_valid(gc, 6)); + KUNIT_EXPECT_EQ(test, gc->get_direction(gc, 5), GPIO_LINE_DIRECTION_OUT); + + KUNIT_EXPECT_EQ(test, gc->set(gc, 5, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, 0x3e, 0), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 2); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("gP05"), 4, 0x00a00001); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("gP3e"), 4, 0x00300000); + + ctx->write_ret = -EIO; + KUNIT_EXPECT_EQ(test, gc->set(gc, 5, 0), -EIO); +} + +static const u32 macsmc_gpio_test_pcio_tmpl[] = { 21, 0x40000, 0x150000 }; + +static const struct property_entry macsmc_gpio_test_pcio_props[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,output-templates", macsmc_gpio_test_out_tmpl), + PROPERTY_ENTRY_U32_ARRAY("apple,pcio-templates", macsmc_gpio_test_pcio_tmpl), + {} +}; + +/* + * J700: pins 19 and 8 and the pcio-templates pins are eight-byte pcIO + * writes, hi << 32 | lo | level, whose level is remembered for reads. + */ +static void macsmc_gpio_test_j700_pcio(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = + macsmc_gpio_test_alloc(test, "gpio", macsmc_gpio_test_pcio_props); + struct gpio_chip *gc = &ctx->smcgp->gc; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, true, false); + KUNIT_EXPECT_EQ(test, gc->get_direction(gc, MACSMC_J700_AFE_RESET_GPIO), + GPIO_LINE_DIRECTION_OUT); + + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J700_AFE_RESET_GPIO, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J700_RADIO_REG_ON_GPIO, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, 21, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J700_AFE_RESET_GPIO, 0), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 4); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("pcIO"), 8, + ((u64)MACSMC_J700_AFE_RESET_HI << 32) | + MACSMC_J700_AFE_RESET_LO | 1); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("pcIO"), 8, + ((u64)MACSMC_J700_RADIO_REG_ON_HI << 32) | + MACSMC_J700_RADIO_REG_ON_LO | 1); + macsmc_gpio_test_expect_write(test, ctx, 2, _SMC_KEY("pcIO"), 8, + (0x150000ULL << 32) | 0x40000 | 1); + macsmc_gpio_test_expect_write(test, ctx, 3, _SMC_KEY("pcIO"), 8, + ((u64)MACSMC_J700_AFE_RESET_HI << 32) | + MACSMC_J700_AFE_RESET_LO); + + KUNIT_EXPECT_EQ(test, gc->get(gc, MACSMC_J700_AFE_RESET_GPIO), 0); + KUNIT_EXPECT_EQ(test, gc->get(gc, MACSMC_J700_RADIO_REG_ON_GPIO), 1); + KUNIT_EXPECT_EQ(test, gc->get(gc, 21), 1); + + /* A failed write keeps the remembered level. */ + ctx->write_ret = -EIO; + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J700_RADIO_REG_ON_GPIO, 0), -EIO); + KUNIT_EXPECT_EQ(test, gc->get(gc, MACSMC_J700_RADIO_REG_ON_GPIO), 1); + + /* An output template still wins over pcIO for its own pin. */ + ctx->write_ret = 0; + KUNIT_EXPECT_EQ(test, gc->set(gc, 5, 1), 0); + macsmc_gpio_test_expect_write(test, ctx, 5, _SMC_KEY("gP05"), 4, 0x00a00001); +} + +/* The valid mask is the board's fixed lines plus the templated ones. */ +static void macsmc_gpio_test_valid_mask(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = + macsmc_gpio_test_alloc(test, "gpio", macsmc_gpio_test_pcio_props); + struct gpio_chip *gc = &ctx->smcgp->gc; + unsigned int i, valid = 0; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, true, false); + for (i = 0; i < MAX_GPIO; i++) + valid += gpiochip_line_is_valid(gc, i); + KUNIT_EXPECT_EQ(test, valid, 5); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, MACSMC_J700_AFE_RESET_GPIO)); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, MACSMC_J700_RADIO_REG_ON_GPIO)); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, 21)); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, 5)); + KUNIT_EXPECT_TRUE(test, gpiochip_line_is_valid(gc, 0x3e)); + KUNIT_EXPECT_EQ(test, ctx->nr_writes, 0); +} + +/* Off the J700, pcio-templates do nothing: those pins are plain gPxx lines. */ +static void macsmc_gpio_test_pcio_template_not_j700(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = + macsmc_gpio_test_alloc(test, "gpio", macsmc_gpio_test_pcio_props); + struct gpio_chip *gc = &ctx->smcgp->gc; + + macsmc_gpio_test_register(test, ctx, GPIO_TEST_GP, false, false); + KUNIT_EXPECT_FALSE(test, gpiochip_line_is_valid(gc, 21)); + KUNIT_EXPECT_FALSE(test, gpiochip_line_is_valid(gc, MACSMC_J700_AFE_RESET_GPIO)); + KUNIT_EXPECT_EQ(test, gc->set(gc, 21, 1), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, MACSMC_J700_AFE_RESET_GPIO, 1), 0); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("gP15"), 4, CMD_OUTPUT | 1); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("gP13"), 4, CMD_OUTPUT | 1); +} + +static int macsmc_gpio_test_parse(struct kunit *test, const char *name, + const struct property_entry *props) +{ + struct macsmc_gpio_test *ctx = macsmc_gpio_test_alloc(test, name, props); + + return macsmc_gpio_parse_templates(ctx->smcgp); +} + +/* Malformed template lists are refused, the pin bound is 0..63. */ +static void macsmc_gpio_test_template_errors(struct kunit *test) +{ + static const u32 odd[] = { 5, 0x00a00000, 6 }; + static const u32 pin64[] = { 64, 0x00a00000 }; + static const u32 pin63[] = { 63, 0x00a00000 }; + static const u32 pcio_short[] = { 21, 0x40000, 0x150000, 22 }; + static const u32 pcio_pin64[] = { 64, 0x40000, 0x150000 }; + const struct property_entry p_odd[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,output-templates", odd), {} + }; + const struct property_entry p_pin64[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,output-templates", pin64), {} + }; + const struct property_entry p_pin63[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,output-templates", pin63), {} + }; + const struct property_entry p_pcio_short[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,pcio-templates", pcio_short), {} + }; + const struct property_entry p_pcio_pin64[] = { + PROPERTY_ENTRY_U32_ARRAY("apple,pcio-templates", pcio_pin64), {} + }; + + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse0", p_odd), -EINVAL); + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse1", p_pin64), -EINVAL); + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse2", p_pin63), 0); + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse3", p_pcio_short), -EINVAL); + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse4", p_pcio_pin64), -EINVAL); + KUNIT_EXPECT_EQ(test, macsmc_gpio_test_parse(test, "parse5", NULL), 0); +} + +/* apple,smc-pcio-gpio: line N writes output_commands[N] | level as LE64 to pcIO. */ +static void macsmc_gpio_test_pcio_outputs(struct kunit *test) +{ + struct macsmc_gpio_test *ctx = macsmc_gpio_test_alloc(test, "gpio", NULL); + struct macsmc_gpio *smcgp = ctx->smcgp; + struct gpio_chip *gc = &smcgp->gc; + static const u64 commands[] = { 0x0013000000010000ULL, 0x0008000000800000ULL }; + + BUILD_BUG_ON(sizeof(commands) != sizeof(ctx->commands)); + memcpy(ctx->commands, commands, sizeof(commands)); + smcgp->output_commands = ctx->commands; + + /* As macsmc_pcio_probe() sets it up. */ + gc->label = "macsmc-pcio-output-test"; + gc->owner = THIS_MODULE; + gc->get = macsmc_pcio_get; + gc->set = macsmc_pcio_set; + gc->direction_output = macsmc_pcio_set; + gc->get_direction = macsmc_pcio_get_direction; + gc->can_sleep = true; + gc->ngpio = ARRAY_SIZE(commands); + gc->base = -1; + gc->parent = ctx->dev; + KUNIT_ASSERT_EQ(test, devm_gpiochip_add_data(ctx->dev, gc, smcgp), 0); + + KUNIT_EXPECT_EQ(test, gc->get_direction(gc, 1), GPIO_LINE_DIRECTION_OUT); + KUNIT_EXPECT_EQ(test, gc->get(gc, 0), -EOPNOTSUPP); + + /* A positive status from the write is success. */ + ctx->write_ret = 8; + KUNIT_EXPECT_EQ(test, gc->set(gc, 0, 1), 0); + ctx->write_ret = 0; + KUNIT_EXPECT_EQ(test, gc->direction_output(gc, 1, 0), 0); + KUNIT_EXPECT_EQ(test, gc->set(gc, 1, 1), 0); + KUNIT_ASSERT_EQ(test, ctx->nr_writes, 3); + macsmc_gpio_test_expect_write(test, ctx, 0, _SMC_KEY("pcIO"), 8, commands[0] | 1); + macsmc_gpio_test_expect_write(test, ctx, 1, _SMC_KEY("pcIO"), 8, commands[1]); + macsmc_gpio_test_expect_write(test, ctx, 2, _SMC_KEY("pcIO"), 8, commands[1] | 1); + + ctx->write_ret = -EBUSY; + KUNIT_EXPECT_EQ(test, gc->set(gc, 0, 0), -EBUSY); +} + +static struct kunit_case macsmc_gpio_test_cases[] = { + KUNIT_CASE(macsmc_gpio_test_key_name), + KUNIT_CASE(macsmc_gpio_test_key_nr), + KUNIT_CASE(macsmc_gpio_test_set_plain), + KUNIT_CASE(macsmc_gpio_test_j713_reg_on), + KUNIT_CASE(macsmc_gpio_test_j713_other_lines), + KUNIT_CASE(macsmc_gpio_test_output_template), + KUNIT_CASE(macsmc_gpio_test_j700_pcio), + KUNIT_CASE(macsmc_gpio_test_valid_mask), + KUNIT_CASE(macsmc_gpio_test_pcio_template_not_j700), + KUNIT_CASE(macsmc_gpio_test_template_errors), + KUNIT_CASE(macsmc_gpio_test_pcio_outputs), + {} +}; + +static struct kunit_suite macsmc_gpio_test_suite = { + .name = "macsmc-gpio", + .test_cases = macsmc_gpio_test_cases, +}; + +kunit_test_suite(macsmc_gpio_test_suite); diff --git a/drivers/gpio/gpio-macsmc.c b/drivers/gpio/gpio-macsmc.c index 434ed549d4c1e..68b1802a1eacf 100644 --- a/drivers/gpio/gpio-macsmc.c +++ b/drivers/gpio/gpio-macsmc.c @@ -599,3 +599,7 @@ module_platform_driver(macsmc_gpio_driver); MODULE_AUTHOR("Hector Martin "); MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("Apple SMC GPIO driver"); + +#if IS_ENABLED(CONFIG_GPIO_MACSMC_KUNIT_TEST) +#include "gpio-macsmc-test.c" +#endif diff --git a/drivers/gpio/gpio-macsmc.kunitconfig b/drivers/gpio/gpio-macsmc.kunitconfig new file mode 100644 index 0000000000000..1b9e736fdd0e7 --- /dev/null +++ b/drivers/gpio/gpio-macsmc.kunitconfig @@ -0,0 +1,12 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/gpio/gpio-macsmc.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_MAILBOX=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_MFD_MACSMC=y +CONFIG_MFD_MACSMC_KUNIT_TEST=y +CONFIG_GPIOLIB=y +CONFIG_GPIO_MACSMC=y +CONFIG_GPIO_MACSMC_KUNIT_TEST=y From 43dd5ccc8337c50f7a107add3298334de7b8ea63 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:07 +1100 Subject: [PATCH 07/13] power: reset: macsmc: add KUnit tests Add tests for the MBSE key and the boot_stage and shutdown_flag writes before a restart or power off, the clearing of the boot error and panic counters, the refusal of atomic writes from a non-atomic SMC, and the ac_power_mode attribute's read-modify-write of the power-on policy byte. A static stub replaces SMC writes and a RAM-backed NVMEM device holds the PMU cells. Signed-off-by: Ryan Murray --- drivers/power/reset/Kconfig | 13 + drivers/power/reset/macsmc-reboot-test.c | 454 ++++++++++++++++++ drivers/power/reset/macsmc-reboot.c | 4 + drivers/power/reset/macsmc-reboot.kunitconfig | 13 + 4 files changed, 484 insertions(+) create mode 100644 drivers/power/reset/macsmc-reboot-test.c create mode 100644 drivers/power/reset/macsmc-reboot.kunitconfig diff --git a/drivers/power/reset/Kconfig b/drivers/power/reset/Kconfig index bce996bbef28f..3cc66edaf551a 100644 --- a/drivers/power/reset/Kconfig +++ b/drivers/power/reset/Kconfig @@ -149,6 +149,19 @@ config POWER_RESET_MACSMC Say Y here if you have an Apple Silicon Mac. +config POWER_RESET_MACSMC_KUNIT_TEST + bool "KUnit tests for the Apple SMC reboot driver" if !KUNIT_ALL_TESTS + depends on POWER_RESET_MACSMC=y && KUNIT=y + depends on MFD_MACSMC_KUNIT_TEST && NVMEM + default KUNIT_ALL_TESTS + help + Build tests for the Apple SMC reboot driver: the MBSE key and the + boot_stage and shutdown_flag writes before a restart or power off, + the clearing of the boot error and panic counters, and the + ac_power_mode attribute's read-modify-write of the power-on policy + byte. A static stub replaces SMC writes and a RAM-backed NVMEM + device holds the PMU cells, so the tests need no Apple hardware. + config POWER_RESET_MSM bool "Qualcomm MSM power-off driver" depends on ARCH_QCOM diff --git a/drivers/power/reset/macsmc-reboot-test.c b/drivers/power/reset/macsmc-reboot-test.c new file mode 100644 index 0000000000000..e4db004ec6ec1 --- /dev/null +++ b/drivers/power/reset/macsmc-reboot-test.c @@ -0,0 +1,454 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple SMC reboot driver: the MBSE key and NVMEM flag + * sequence before a restart or power off, the boot error and panic counters, + * and the ac_power_mode attribute over the PMU's power-on policy byte. + * + * SMC writes go to a static stub on apple_smc_write() (see + * MFD_MACSMC_KUNIT_TEST). The PMU cells are real NVMEM cells of a RAM-backed + * NVMEM device, found through a cell lookup table. + * + * Included by macsmc-reboot.c. + */ + +#include +#include +#include +#include +#include + +enum { + REBOOT_TEST_SHUTDOWN_FLAG, + REBOOT_TEST_BOOT_STAGE, + REBOOT_TEST_BOOT_ERROR_COUNT, + REBOOT_TEST_PANIC_COUNT, + REBOOT_TEST_PM_SETTING, + REBOOT_TEST_NR_CELLS, +}; + +static const char * const macsmc_reboot_test_cells[] = { + [REBOOT_TEST_SHUTDOWN_FLAG] = "shutdown_flag", + [REBOOT_TEST_BOOT_STAGE] = "boot_stage", + [REBOOT_TEST_BOOT_ERROR_COUNT] = "boot_error_count", + [REBOOT_TEST_PANIC_COUNT] = "panic_count", + [REBOOT_TEST_PM_SETTING] = "pm_setting", +}; + +struct macsmc_reboot_test_write { + u32 where; /* SMC key, or NVMEM offset */ + size_t size; + u32 val; +}; + +struct macsmc_reboot_test { + struct apple_smc smc; + u8 shmem[256]; + struct macsmc_reboot reboot; + struct device *dev; + u8 nvmem[REBOOT_TEST_NR_CELLS]; + /* NVMEM writes and SMC writes, each in order */ + struct macsmc_reboot_test_write nv_writes[8]; + unsigned int nr_nv_writes; + struct macsmc_reboot_test_write smc_writes[4]; + unsigned int nr_smc_writes; + int smc_ret; + int fail_offset; + struct nvmem_cell_lookup lookups[REBOOT_TEST_NR_CELLS]; +}; + +static int macsmc_reboot_test_smc_write(struct apple_smc *smc, smc_key key, + const void *buf, size_t size) +{ + struct macsmc_reboot_test *ctx = container_of(smc, struct macsmc_reboot_test, smc); + struct macsmc_reboot_test_write *w; + + if (ctx->nr_smc_writes < ARRAY_SIZE(ctx->smc_writes)) { + w = &ctx->smc_writes[ctx->nr_smc_writes]; + w->where = key; + w->size = size; + w->val = 0; + memcpy(&w->val, buf, min(size, sizeof(w->val))); + } + ctx->nr_smc_writes++; + return ctx->smc_ret; +} + +static int macsmc_reboot_test_reg_read(void *priv, unsigned int offset, void *val, + size_t bytes) +{ + struct macsmc_reboot_test *ctx = priv; + + memcpy(val, ctx->nvmem + offset, bytes); + return 0; +} + +static int macsmc_reboot_test_reg_write(void *priv, unsigned int offset, void *val, + size_t bytes) +{ + struct macsmc_reboot_test *ctx = priv; + struct macsmc_reboot_test_write *w; + + if (offset == ctx->fail_offset) + return -EIO; + if (ctx->nr_nv_writes < ARRAY_SIZE(ctx->nv_writes)) { + w = &ctx->nv_writes[ctx->nr_nv_writes]; + w->where = offset; + w->size = bytes; + w->val = *(u8 *)val; + } + ctx->nr_nv_writes++; + memcpy(ctx->nvmem + offset, val, bytes); + return 0; +} + +static void macsmc_reboot_test_del_lookups(void *data) +{ + struct macsmc_reboot_test *ctx = data; + + nvmem_del_cell_lookups(ctx->lookups, ARRAY_SIZE(ctx->lookups)); +} + +KUNIT_DEFINE_ACTION_WRAPPER(macsmc_reboot_test_cell_put, nvmem_cell_put, + struct nvmem_cell *); + +static struct nvmem_cell *macsmc_reboot_test_cell(struct kunit *test, + struct macsmc_reboot_test *ctx, + unsigned int idx) +{ + struct nvmem_cell *cell = nvmem_cell_get(ctx->dev, macsmc_reboot_test_cells[idx]); + + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, cell); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, macsmc_reboot_test_cell_put, + cell), 0); + return cell; +} + +/* A reboot handler with every cell, as macsmc_reboot_probe() leaves it. */ +static struct macsmc_reboot_test *macsmc_reboot_test_setup(struct kunit *test) +{ + struct nvmem_config config = {}; + struct nvmem_cell_info *cells; + struct macsmc_reboot_test *ctx; + struct nvmem_device *nvmem; + struct device *provider; + int i; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + cells = kunit_kcalloc(test, REBOOT_TEST_NR_CELLS, sizeof(*cells), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, cells); + ctx->fail_offset = -1; + mutex_init(&ctx->smc.mutex); + spin_lock_init(&ctx->smc.lock); + /* Any SMC command fails: the SMC never booted. */ + ctx->smc.shmem.iomem = (void __force __iomem *)ctx->shmem; + + for (i = 0; i < REBOOT_TEST_NR_CELLS; i++) { + cells[i].name = macsmc_reboot_test_cells[i]; + cells[i].offset = i; + cells[i].bytes = 1; + } + + provider = kunit_device_register(test, "nvmem"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, provider); + config.dev = provider; + config.name = "macsmc-reboot-test"; + config.id = NVMEM_DEVID_AUTO; + config.cells = cells; + config.ncells = REBOOT_TEST_NR_CELLS; + config.ignore_wp = true; + config.reg_read = macsmc_reboot_test_reg_read; + config.reg_write = macsmc_reboot_test_reg_write; + config.size = REBOOT_TEST_NR_CELLS; + config.priv = ctx; + nvmem = devm_nvmem_register(provider, &config); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, nvmem); + + ctx->dev = kunit_device_register(test, "reboot"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); + for (i = 0; i < REBOOT_TEST_NR_CELLS; i++) { + ctx->lookups[i].nvmem_name = nvmem_dev_name(nvmem); + ctx->lookups[i].cell_name = macsmc_reboot_test_cells[i]; + ctx->lookups[i].dev_id = dev_name(ctx->dev); + ctx->lookups[i].con_id = macsmc_reboot_test_cells[i]; + } + nvmem_add_cell_lookups(ctx->lookups, ARRAY_SIZE(ctx->lookups)); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, macsmc_reboot_test_del_lookups, + ctx), 0); + + ctx->reboot.dev = ctx->dev; + ctx->reboot.smc = &ctx->smc; + mutex_init(&ctx->reboot.pm_setting_lock); + for (i = 0; i < ARRAY_SIZE(nvmem_names); i++) { + KUNIT_ASSERT_STREQ(test, nvmem_names[i], macsmc_reboot_test_cells[i]); + ctx->reboot.nvm_cells[i] = macsmc_reboot_test_cell(test, ctx, i); + } + ctx->reboot.pm_setting = macsmc_reboot_test_cell(test, ctx, REBOOT_TEST_PM_SETTING); + ctx->reboot.reboot_notify.notifier_call = macsmc_reboot_notify; + dev_set_drvdata(ctx->dev, &ctx->reboot); + + kunit_activate_static_stub(test, apple_smc_write, macsmc_reboot_test_smc_write); + return ctx; +} + +static int macsmc_reboot_test_notify(struct macsmc_reboot_test *ctx, unsigned long action) +{ + return macsmc_reboot_notify(&ctx->reboot.reboot_notify, action, NULL); +} + +static void macsmc_reboot_test_expect_nv(struct kunit *test, struct macsmc_reboot_test *ctx, + unsigned int idx, unsigned int cell, u8 val) +{ + KUNIT_ASSERT_LT(test, idx, ctx->nr_nv_writes); + KUNIT_EXPECT_EQ_MSG(test, ctx->nv_writes[idx].where, cell, "write %u", idx); + KUNIT_EXPECT_EQ_MSG(test, ctx->nv_writes[idx].size, 1, "write %u", idx); + KUNIT_EXPECT_EQ_MSG(test, ctx->nv_writes[idx].val, val, "write %u", idx); +} + +static void macsmc_reboot_test_expect_mbse(struct kunit *test, struct macsmc_reboot_test *ctx, + smc_key val) +{ + KUNIT_ASSERT_EQ(test, ctx->nr_smc_writes, 1); + KUNIT_EXPECT_EQ(test, ctx->smc_writes[0].where, SMC_KEY(MBSE)); + KUNIT_EXPECT_EQ(test, ctx->smc_writes[0].size, sizeof(u32)); + KUNIT_EXPECT_EQ(test, ctx->smc_writes[0].val, val); +} + +/* Restart: MBSE = rest, a clean boot_stage and shutdown_flag 0 (power back on). */ +static void macsmc_reboot_test_notify_restart(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_BOOT_STAGE] = BOOT_STAGE_KERNEL_STARTED; + ctx->nvmem[REBOOT_TEST_SHUTDOWN_FLAG] = 1; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_RESTART), NOTIFY_OK); + macsmc_reboot_test_expect_mbse(test, ctx, SMC_KEY(rest)); + KUNIT_ASSERT_EQ(test, ctx->nr_nv_writes, 2); + macsmc_reboot_test_expect_nv(test, ctx, 0, REBOOT_TEST_BOOT_STAGE, BOOT_STAGE_SHUTDOWN); + macsmc_reboot_test_expect_nv(test, ctx, 1, REBOOT_TEST_SHUTDOWN_FLAG, 0); +} + +/* Power off: MBSE = offw, a clean boot_stage and shutdown_flag 1 (stay off). */ +static void macsmc_reboot_test_notify_power_off(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_BOOT_STAGE] = BOOT_STAGE_KERNEL_STARTED; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_POWER_OFF), NOTIFY_OK); + macsmc_reboot_test_expect_mbse(test, ctx, SMC_KEY(offw)); + KUNIT_ASSERT_EQ(test, ctx->nr_nv_writes, 2); + macsmc_reboot_test_expect_nv(test, ctx, 0, REBOOT_TEST_BOOT_STAGE, BOOT_STAGE_SHUTDOWN); + macsmc_reboot_test_expect_nv(test, ctx, 1, REBOOT_TEST_SHUTDOWN_FLAG, 1); +} + +/* A halt is not ours to prepare: nothing is written. */ +static void macsmc_reboot_test_notify_other(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_HALT), NOTIFY_DONE); + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_DOWN + 100), NOTIFY_DONE); + KUNIT_EXPECT_EQ(test, ctx->nr_smc_writes, 0); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); +} + +/* Missing cells are skipped; MBSE is still written. */ +static void macsmc_reboot_test_notify_no_cells(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->reboot.nvm.shutdown_flag = NULL; + ctx->reboot.nvm.boot_stage = NULL; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_POWER_OFF), NOTIFY_OK); + macsmc_reboot_test_expect_mbse(test, ctx, SMC_KEY(offw)); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); +} + +/* A failed MBSE write does not stop the PMU flags from being written. */ +static void macsmc_reboot_test_notify_mbse_error(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->smc_ret = -ETIMEDOUT; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_POWER_OFF), NOTIFY_OK); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 2); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_SHUTDOWN_FLAG], 1); + + /* Nor does a failed boot_stage write stop shutdown_flag. */ + ctx->smc_ret = 0; + ctx->fail_offset = REBOOT_TEST_BOOT_STAGE; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_notify(ctx, SYS_RESTART), NOTIFY_OK); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_SHUTDOWN_FLAG], 0); +} + +/* Logged boot errors and panics are cleared: panic_count first. */ +static void macsmc_reboot_test_error_counts(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_BOOT_ERROR_COUNT] = 2; + ctx->nvmem[REBOOT_TEST_PANIC_COUNT] = 0; + macsmc_power_init_error_counts(&ctx->reboot); + KUNIT_ASSERT_EQ(test, ctx->nr_nv_writes, 2); + macsmc_reboot_test_expect_nv(test, ctx, 0, REBOOT_TEST_PANIC_COUNT, 0); + macsmc_reboot_test_expect_nv(test, ctx, 1, REBOOT_TEST_BOOT_ERROR_COUNT, 0); + + ctx->nr_nv_writes = 0; + ctx->nvmem[REBOOT_TEST_PANIC_COUNT] = 0xff; + macsmc_power_init_error_counts(&ctx->reboot); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 2); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_PANIC_COUNT], 0); + + /* Nothing logged: nothing written. */ + ctx->nr_nv_writes = 0; + macsmc_power_init_error_counts(&ctx->reboot); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); +} + +/* Without both counter cells the counters are left alone. */ +static void macsmc_reboot_test_error_counts_missing(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_BOOT_ERROR_COUNT] = 3; + ctx->nvmem[REBOOT_TEST_PANIC_COUNT] = 4; + ctx->reboot.nvm.panic_count = NULL; + macsmc_power_init_error_counts(&ctx->reboot); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_BOOT_ERROR_COUNT], 3); +} + +/* Bit 5 clear powers on at connect; otherwise bit 0 picks off or restore. */ +static void macsmc_reboot_test_ac_mode_decode(struct kunit *test) +{ + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0x21), AC_POWER_OFF); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0xff), AC_POWER_OFF); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0x20), AC_POWER_RESTORE); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0xfe), AC_POWER_RESTORE); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0x01), AC_POWER_ALWAYS); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0x00), AC_POWER_ALWAYS); + KUNIT_EXPECT_EQ(test, macsmc_ac_power_mode(0xde), AC_POWER_ALWAYS); +} + +static void macsmc_reboot_test_expect_show(struct kunit *test, struct macsmc_reboot_test *ctx, + u8 setting, const char *expect) +{ + char *buf = kunit_kzalloc(test, PAGE_SIZE, GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, buf); + ctx->nvmem[REBOOT_TEST_PM_SETTING] = setting; + KUNIT_EXPECT_EQ(test, ac_power_mode_show(ctx->dev, &dev_attr_ac_power_mode, buf), + strlen(expect)); + KUNIT_EXPECT_STREQ(test, buf, expect); +} + +static void macsmc_reboot_test_ac_mode_show(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + macsmc_reboot_test_expect_show(test, ctx, 0x21, "[off] restore always\n"); + macsmc_reboot_test_expect_show(test, ctx, 0xa0, "off [restore] always\n"); + macsmc_reboot_test_expect_show(test, ctx, 0x80, "off restore [always]\n"); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); +} + +static ssize_t macsmc_reboot_test_store(struct macsmc_reboot_test *ctx, const char *buf) +{ + return ac_power_mode_store(ctx->dev, &dev_attr_ac_power_mode, buf, strlen(buf)); +} + +/* A store changes bits 0 and 5 only, and only when the mode changes. */ +static void macsmc_reboot_test_ac_mode_store(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_PM_SETTING] = 0x80 | PM_SETTING_AC_POWER_MASK; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "restore\n"), 8); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_PM_SETTING], 0xa0); + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "always"), 6); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_PM_SETTING], 0x81); + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "off"), 3); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_PM_SETTING], 0xa1); + KUNIT_ASSERT_EQ(test, ctx->nr_nv_writes, 3); + macsmc_reboot_test_expect_nv(test, ctx, 0, REBOOT_TEST_PM_SETTING, 0xa0); + + /* Unchanged: no write. */ + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "off\n"), 4); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 3); +} + +static void macsmc_reboot_test_ac_mode_store_errors(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + + ctx->nvmem[REBOOT_TEST_PM_SETTING] = 0x21; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "on"), -EINVAL); + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, ""), -EINVAL); + KUNIT_EXPECT_EQ(test, ctx->nr_nv_writes, 0); + + ctx->fail_offset = REBOOT_TEST_PM_SETTING; + KUNIT_EXPECT_EQ(test, macsmc_reboot_test_store(ctx, "always"), -EIO); + KUNIT_EXPECT_EQ(test, ctx->nvmem[REBOOT_TEST_PM_SETTING], 0x21); +} + +/* ac_power_mode exists only with a pm_setting cell. */ +static void macsmc_reboot_test_ac_mode_visible(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + struct attribute *attr = &dev_attr_ac_power_mode.attr; + + KUNIT_EXPECT_EQ(test, macsmc_reboot_attr_visible(&ctx->dev->kobj, attr, 0), 0644); + ctx->reboot.pm_setting = NULL; + KUNIT_EXPECT_EQ(test, macsmc_reboot_attr_visible(&ctx->dev->kobj, attr, 0), 0); + dev_set_drvdata(ctx->dev, NULL); + KUNIT_EXPECT_EQ(test, macsmc_reboot_attr_visible(&ctx->dev->kobj, attr, 0), 0); +} + +/* + * off1 and phra are atomic writes. On a booted SMC that has not entered + * atomic mode they are refused, and the handlers return at once instead of + * waiting for the power to go (mdelay(100), then a warning). + */ +static void macsmc_reboot_test_atomic_refused(struct kunit *test) +{ + struct macsmc_reboot_test *ctx = macsmc_reboot_test_setup(test); + struct sys_off_data data = { .cb_data = &ctx->reboot }; + ktime_t start; + + ctx->smc.boot_stage = APPLE_SMC_INITIALIZED; + ctx->smc.atomic_mode = false; + /* What refuses is the atomic mode check, not the boot stage. */ + KUNIT_ASSERT_EQ(test, apple_smc_write_u32_atomic(&ctx->smc, SMC_KEY(MBSE), + SMC_KEY(off1)), -EIO); + + start = ktime_get(); + KUNIT_EXPECT_EQ(test, macsmc_power_off(&data), NOTIFY_OK); + KUNIT_EXPECT_LT(test, ktime_ms_delta(ktime_get(), start), 50); + start = ktime_get(); + KUNIT_EXPECT_EQ(test, macsmc_restart(&data), NOTIFY_OK); + KUNIT_EXPECT_LT(test, ktime_ms_delta(ktime_get(), start), 50); +} + +static struct kunit_case macsmc_reboot_test_cases[] = { + KUNIT_CASE(macsmc_reboot_test_notify_restart), + KUNIT_CASE(macsmc_reboot_test_notify_power_off), + KUNIT_CASE(macsmc_reboot_test_notify_other), + KUNIT_CASE(macsmc_reboot_test_notify_no_cells), + KUNIT_CASE(macsmc_reboot_test_notify_mbse_error), + KUNIT_CASE(macsmc_reboot_test_error_counts), + KUNIT_CASE(macsmc_reboot_test_error_counts_missing), + KUNIT_CASE(macsmc_reboot_test_ac_mode_decode), + KUNIT_CASE(macsmc_reboot_test_ac_mode_show), + KUNIT_CASE(macsmc_reboot_test_ac_mode_store), + KUNIT_CASE(macsmc_reboot_test_ac_mode_store_errors), + KUNIT_CASE(macsmc_reboot_test_ac_mode_visible), + KUNIT_CASE(macsmc_reboot_test_atomic_refused), + {} +}; + +static struct kunit_suite macsmc_reboot_test_suite = { + .name = "macsmc-reboot", + .test_cases = macsmc_reboot_test_cases, +}; + +kunit_test_suite(macsmc_reboot_test_suite); diff --git a/drivers/power/reset/macsmc-reboot.c b/drivers/power/reset/macsmc-reboot.c index a2e1422e05bd8..c89c0d892b7f3 100644 --- a/drivers/power/reset/macsmc-reboot.c +++ b/drivers/power/reset/macsmc-reboot.c @@ -413,3 +413,7 @@ module_platform_driver(macsmc_reboot_driver); MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("Apple SMC reboot/poweroff driver"); MODULE_AUTHOR("Hector Martin "); + +#if IS_ENABLED(CONFIG_POWER_RESET_MACSMC_KUNIT_TEST) +#include "macsmc-reboot-test.c" +#endif diff --git a/drivers/power/reset/macsmc-reboot.kunitconfig b/drivers/power/reset/macsmc-reboot.kunitconfig new file mode 100644 index 0000000000000..3af2e4d04a7eb --- /dev/null +++ b/drivers/power/reset/macsmc-reboot.kunitconfig @@ -0,0 +1,13 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/power/reset/macsmc-reboot.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_MAILBOX=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_MFD_MACSMC=y +CONFIG_MFD_MACSMC_KUNIT_TEST=y +CONFIG_NVMEM=y +CONFIG_POWER_RESET=y +CONFIG_POWER_RESET_MACSMC=y +CONFIG_POWER_RESET_MACSMC_KUNIT_TEST=y From 2be1d7ba37818e498335255635e9bc6cdc90d538 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:08 +1100 Subject: [PATCH 08/13] Input: macsmc-input - add KUnit tests Add tests for the decoding of the SMC's power button and lid notifications and their handling as wake events while the system goes to sleep, including the lid-open check against MSLD and the settle time. A static stub replaces SMC reads. The tests report KEY_POWER and SW_LID through a real input device and touch global suspend state (pm_wakeup_clear(), pm_system_wakeup()), so they skip once the system is running and only run at boot, before user space. Not covered: the MSLD resync after resume and the dark-wake refusal in .prepare, which need apple_smc_key_exists() to succeed. Signed-off-by: Ryan Murray --- drivers/input/misc/Kconfig | 15 + drivers/input/misc/macsmc-input-test.c | 414 ++++++++++++++++++++ drivers/input/misc/macsmc-input.c | 4 + drivers/input/misc/macsmc-input.kunitconfig | 15 + 4 files changed, 448 insertions(+) create mode 100644 drivers/input/misc/macsmc-input-test.c create mode 100644 drivers/input/misc/macsmc-input.kunitconfig diff --git a/drivers/input/misc/Kconfig b/drivers/input/misc/Kconfig index aad2bc5fb0eb6..d7844492bdec1 100644 --- a/drivers/input/misc/Kconfig +++ b/drivers/input/misc/Kconfig @@ -1034,4 +1034,19 @@ config INPUT_MACSMC_INPUT To compile this driver as a module, choose M here: the module will be called macsmc-input. +config INPUT_MACSMC_INPUT_KUNIT_TEST + bool "KUnit tests for the Apple SMC lid/buttons driver" if !KUNIT_ALL_TESTS + depends on INPUT_MACSMC_INPUT=y && KUNIT=y + depends on MFD_MACSMC_KUNIT_TEST && SUSPEND + default KUNIT_ALL_TESTS + help + Build tests for the Apple SMC input driver: the decoding of the + SMC's power button and lid notifications, and their handling as + wake events while the system goes to sleep, including the lid-open + check against MSLD and the settle time. A static stub replaces SMC + reads, so the tests need no Apple hardware. + The tests report power button presses and lid changes through an + input device and change global suspend state, so they run only at + boot, before user space, and skip when run later. + endif diff --git a/drivers/input/misc/macsmc-input-test.c b/drivers/input/misc/macsmc-input-test.c new file mode 100644 index 0000000000000..5e1dedd0ab3be --- /dev/null +++ b/drivers/input/misc/macsmc-input-test.c @@ -0,0 +1,414 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the Apple SMC input driver: decoding of the SMC's button + * and lid notifications into KEY_POWER and SW_LID, and the sleep window in + * which they are wake events instead, with the lid-open confirmation + * against MSLD and the settle time. + * + * MSLD reads go to a static stub on apple_smc_read() (see + * MFD_MACSMC_KUNIT_TEST). Events go to a registered input device; wakeups + * are seen on the device's wakeup source and, for hard wakeups, through + * pm_wakeup_pending(). + * + * The cases touch global PM state (pm_abort_suspend, the dark wake flag) + * and report KEY_POWER and SW_LID through a real input device, which a + * running system's logind would act on by powering off or suspending. So + * the suite runs only at boot, before user space; run later (from the + * kunit debugfs interface or a module) it skips every case. + * + * Included by macsmc-input.c. + */ + +#include +#include +#include + +#define INPUT_TEST_EV(type, hi, lo) (((type) << 16) | ((hi) << 8) | (lo)) +#define INPUT_TEST_BTN(button, state) INPUT_TEST_EV(SMC_EV_BTN, button, state) +#define INPUT_TEST_LID(closed, lo) INPUT_TEST_EV(SMC_EV_LID, closed, lo) + +struct macsmc_input_test { + struct apple_smc smc; + u8 shmem[256]; + struct macsmc_input smcin; + /* MSLD: 1 while the lid is closed, and what its read returns */ + u8 msld; + int msld_ret; + unsigned int msld_reads; + unsigned int saved_flags; +}; + +static int macsmc_input_test_read(struct apple_smc *smc, smc_key key, void *buf, + size_t size) +{ + struct macsmc_input_test *ctx = container_of(smc, struct macsmc_input_test, smc); + struct kunit *test = kunit_get_current_test(); + + KUNIT_EXPECT_EQ(test, key, SMC_KEY(MSLD)); + KUNIT_EXPECT_EQ(test, size, 1); + ctx->msld_reads++; + if (ctx->msld_ret < 0) + return ctx->msld_ret; + *(u8 *)buf = ctx->msld; + return size; +} + +static void macsmc_input_test_exit(void *data) +{ + struct macsmc_input_test *ctx = data; + + pm_suspend_global_flags = ctx->saved_flags; + pm_wakeup_clear(0); +} + +static struct macsmc_input_test *macsmc_input_test_setup(struct kunit *test) +{ + struct macsmc_input_test *ctx; + struct macsmc_input *smcin; + struct device *dev; + + ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ctx); + mutex_init(&ctx->smc.mutex); + spin_lock_init(&ctx->smc.lock); + /* SMC commands other than the stubbed read fail: key_exists() is false. */ + ctx->smc.shmem.iomem = (void __force __iomem *)ctx->shmem; + ctx->saved_flags = pm_suspend_global_flags; + pm_wakeup_clear(0); + KUNIT_ASSERT_EQ(test, kunit_add_action_or_reset(test, macsmc_input_test_exit, ctx), 0); + + dev = kunit_device_register(test, "input"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, dev); + KUNIT_ASSERT_EQ(test, devm_device_init_wakeup(dev), 0); + + smcin = &ctx->smcin; + smcin->dev = dev; + smcin->smc = &ctx->smc; + smcin->nb.notifier_call = macsmc_input_event; + smcin->pm_nb.notifier_call = macsmc_input_pm_notify; + mutex_init(&smcin->lid_lock); + dev_set_drvdata(dev, smcin); + + smcin->input = devm_input_allocate_device(dev); + KUNIT_ASSERT_NOT_NULL(test, smcin->input); + smcin->input->name = "macsmc-input-test"; + input_set_capability(smcin->input, EV_SW, SW_LID); + input_set_capability(smcin->input, EV_KEY, KEY_POWER); + KUNIT_ASSERT_EQ(test, input_register_device(smcin->input), 0); + + kunit_activate_static_stub(test, apple_smc_read, macsmc_input_test_read); + return ctx; +} + +static int macsmc_input_test_event(struct macsmc_input_test *ctx, unsigned long event) +{ + return macsmc_input_event(&ctx->smcin.nb, event, NULL); +} + +static bool macsmc_input_test_key(struct macsmc_input_test *ctx) +{ + return test_bit(KEY_POWER, ctx->smcin.input->key); +} + +static bool macsmc_input_test_lid(struct macsmc_input_test *ctx) +{ + return test_bit(SW_LID, ctx->smcin.input->sw); +} + +static unsigned long macsmc_input_test_wake_events(struct macsmc_input_test *ctx) +{ + return ctx->smcin.dev->power.wakeup->event_count; +} + +/* Was a hard wakeup (one that aborts a suspend) asked for? Clears it. */ +static bool macsmc_input_test_hard_wake(void) +{ + bool pending = pm_wakeup_pending(); + + pm_wakeup_clear(0); + return pending; +} + +static void macsmc_input_test_sleep(struct macsmc_input_test *ctx, unsigned int settle_ms, + unsigned int slept_ms) +{ + ctx->smcin.lid_settle_ms = settle_ms; + ctx->smcin.wakeup_mode = true; + ctx->smcin.sleep_start = ktime_sub_ms(ktime_get_boottime(), slept_ms); +} + +/* Only the button and lid event types are this driver's. */ +static void macsmc_input_test_dispatch(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + KUNIT_EXPECT_EQ(test, macsmc_input_test_event(ctx, INPUT_TEST_EV(0x7202, 0x01, 0x01)), + NOTIFY_DONE); + KUNIT_EXPECT_EQ(test, macsmc_input_test_event(ctx, INPUT_TEST_EV(0x7101, 0x01, 0x01)), + NOTIFY_DONE); + KUNIT_EXPECT_EQ(test, macsmc_input_test_event(ctx, INPUT_TEST_EV(0x0000, 0x01, 0x01)), + NOTIFY_DONE); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_lid(ctx)); + KUNIT_EXPECT_EQ(test, macsmc_input_test_wake_events(ctx), 0); + + KUNIT_EXPECT_EQ(test, macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER, 1)), + NOTIFY_OK); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_EQ(test, macsmc_input_test_event(ctx, INPUT_TEST_LID(1, 0)), NOTIFY_OK); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_lid(ctx)); +} + +/* Power and Touch ID buttons: bits 15:8 the button, any nonzero low byte is down. */ +static void macsmc_input_test_power_button(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER, 1)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_key(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER, 0)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_TOUCHID, 0x80)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_key(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_TOUCHID, 0)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + + /* Awake, presses are wakeup events but never hard wakeups. */ + KUNIT_EXPECT_EQ(test, macsmc_input_test_wake_events(ctx), 4); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); +} + +/* "Held" notices and unknown buttons are not key presses. */ +static void macsmc_input_test_other_buttons(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER_HELD_SHORT, 1)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + /* The long hold's release, never its press: that powers off. */ + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER_HELD_LONG, 0)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_BTN(0x07, 1)); + macsmc_input_test_event(ctx, INPUT_TEST_BTN(0x02, 1)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_EQ(test, macsmc_input_test_wake_events(ctx), 0); +} + +/* In the sleep window a press is a hard wakeup and no KEY_POWER. */ +static void macsmc_input_test_button_in_sleep(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_sleep(ctx, 0, 0); + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_TOUCHID, 1)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_hard_wake()); + + /* A release does not wake. */ + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_TOUCHID, 0)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); + KUNIT_EXPECT_EQ(test, macsmc_input_test_wake_events(ctx), 2); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 0); +} + +/* Lid: bits 15:8 nonzero is closed; the low byte is not the state. */ +static void macsmc_input_test_lid_awake(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_event(ctx, INPUT_TEST_LID(1, 0)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_lid(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_lid(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0x80, 0)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_lid(ctx)); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 0xff)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_lid(ctx)); + + /* Awake, MSLD is not consulted and nothing is a hard wakeup. */ + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 0); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); +} + +/* Closing the lid in the sleep window is neither reported nor a wakeup. */ +static void macsmc_input_test_lid_close_in_sleep(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_sleep(ctx, 0, 0); + macsmc_input_test_event(ctx, INPUT_TEST_LID(1, 0)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_lid(ctx)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 0); + KUNIT_EXPECT_FALSE(test, ctx->smcin.lid_held); +} + +/* An open report while MSLD still says closed is held, not a wakeup. */ +static void macsmc_input_test_lid_open_msld_closed(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_event(ctx, INPUT_TEST_LID(1, 0)); + macsmc_input_test_sleep(ctx, 0, 5000); + ctx->msld = 1; + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 1); + KUNIT_EXPECT_TRUE(test, ctx->smcin.lid_held); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_lid(ctx)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); + KUNIT_EXPECT_EQ(test, macsmc_input_test_wake_events(ctx), 1); +} + +/* With a settle time, an open within it is held; after it, it wakes. */ +static void macsmc_input_test_lid_open_settle(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_event(ctx, INPUT_TEST_LID(1, 0)); + macsmc_input_test_sleep(ctx, LID_WAKE_SETTLE_MS_J716S, 0); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_TRUE(test, ctx->smcin.lid_held); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); + + ctx->smcin.lid_held = false; + ctx->smcin.sleep_start = ktime_sub_ms(ktime_get_boottime(), + LID_WAKE_SETTLE_MS_J716S + 500); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_FALSE(test, ctx->smcin.lid_held); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_hard_wake()); + /* Reported by .complete from MSLD, not here. */ + KUNIT_EXPECT_TRUE(test, macsmc_input_test_lid(ctx)); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 2); +} + +/* Without a settle time an open with MSLD open wakes at once. */ +static void macsmc_input_test_lid_open_wakes(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + + macsmc_input_test_sleep(ctx, 0, 0); + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_hard_wake()); + KUNIT_EXPECT_FALSE(test, ctx->smcin.lid_held); + + /* An unreadable MSLD does not hold the report back. */ + ctx->msld_ret = -ETIMEDOUT; + macsmc_input_test_event(ctx, INPUT_TEST_LID(0, 1)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_hard_wake()); + KUNIT_EXPECT_FALSE(test, ctx->smcin.lid_held); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 2); +} + +/* The PM notifier opens the window at PM_SUSPEND_PREPARE and closes it after. */ +static void macsmc_input_test_pm_notify(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + struct macsmc_input *smcin = &ctx->smcin; + ktime_t before = ktime_get_boottime(); + + smcin->lid_held = true; + KUNIT_EXPECT_EQ(test, macsmc_input_pm_notify(&smcin->pm_nb, PM_SUSPEND_PREPARE, NULL), + NOTIFY_DONE); + KUNIT_EXPECT_TRUE(test, smcin->wakeup_mode); + KUNIT_EXPECT_FALSE(test, smcin->lid_held); + KUNIT_EXPECT_GE(test, ktime_to_ns(smcin->sleep_start), ktime_to_ns(before)); + + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER, 1)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_hard_wake()); + + smcin->dark = true; + smcin->lid_held = true; + KUNIT_EXPECT_EQ(test, macsmc_input_pm_notify(&smcin->pm_nb, PM_POST_SUSPEND, NULL), + NOTIFY_DONE); + KUNIT_EXPECT_FALSE(test, smcin->wakeup_mode); + KUNIT_EXPECT_FALSE(test, smcin->dark); + KUNIT_EXPECT_FALSE(test, smcin->lid_held); + + /* Other actions change nothing. */ + macsmc_input_pm_notify(&smcin->pm_nb, PM_HIBERNATION_PREPARE, NULL); + KUNIT_EXPECT_FALSE(test, smcin->wakeup_mode); + + macsmc_input_test_event(ctx, INPUT_TEST_BTN(BTN_POWER, 1)); + KUNIT_EXPECT_TRUE(test, macsmc_input_test_key(ctx)); + KUNIT_EXPECT_FALSE(test, macsmc_input_test_hard_wake()); +} + +/* .prepare opens the window; a full .complete closes it and drops a held open. */ +static void macsmc_input_test_pm_prepare_complete(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + struct macsmc_input *smcin = &ctx->smcin; + + pm_suspend_global_flags &= ~PM_SUSPEND_FLAG_DARK_WAKE; + KUNIT_EXPECT_EQ(test, macsmc_input_pm_prepare(smcin->dev), 0); + KUNIT_EXPECT_TRUE(test, smcin->wakeup_mode); + + smcin->lid_held = true; + macsmc_input_pm_complete(smcin->dev); + KUNIT_EXPECT_FALSE(test, smcin->wakeup_mode); + KUNIT_EXPECT_FALSE(test, smcin->lid_held); + KUNIT_EXPECT_FALSE(test, smcin->dark); +} + +/* + * A dark wake keeps the window and the held open, and marks the next + * .prepare to recheck the lid unless MSLD reads open. + */ +static void macsmc_input_test_pm_dark_wake(struct kunit *test) +{ + struct macsmc_input_test *ctx = macsmc_input_test_setup(test); + struct macsmc_input *smcin = &ctx->smcin; + + KUNIT_EXPECT_EQ(test, macsmc_input_pm_prepare(smcin->dev), 0); + smcin->lid_held = true; + pm_set_dark_wake(); + + ctx->msld = 1; + macsmc_input_pm_complete(smcin->dev); + KUNIT_EXPECT_TRUE(test, smcin->wakeup_mode); + KUNIT_EXPECT_TRUE(test, smcin->lid_held); + KUNIT_EXPECT_TRUE(test, smcin->dark); + + ctx->msld = 0; + macsmc_input_pm_complete(smcin->dev); + KUNIT_EXPECT_FALSE(test, smcin->dark); + + ctx->msld_ret = -EIO; + macsmc_input_pm_complete(smcin->dev); + KUNIT_EXPECT_TRUE(test, smcin->dark); + KUNIT_EXPECT_EQ(test, ctx->msld_reads, 3); + KUNIT_EXPECT_TRUE(test, smcin->wakeup_mode); +} + +static int macsmc_input_test_init(struct kunit *test) +{ + if (system_state == SYSTEM_RUNNING) + kunit_skip(test, "reports KEY_POWER/SW_LID and changes PM state: boot only"); + return 0; +} + +static struct kunit_case macsmc_input_test_cases[] = { + KUNIT_CASE(macsmc_input_test_dispatch), + KUNIT_CASE(macsmc_input_test_power_button), + KUNIT_CASE(macsmc_input_test_other_buttons), + KUNIT_CASE(macsmc_input_test_button_in_sleep), + KUNIT_CASE(macsmc_input_test_lid_awake), + KUNIT_CASE(macsmc_input_test_lid_close_in_sleep), + KUNIT_CASE(macsmc_input_test_lid_open_msld_closed), + KUNIT_CASE(macsmc_input_test_lid_open_settle), + KUNIT_CASE(macsmc_input_test_lid_open_wakes), + KUNIT_CASE(macsmc_input_test_pm_notify), + KUNIT_CASE(macsmc_input_test_pm_prepare_complete), + KUNIT_CASE(macsmc_input_test_pm_dark_wake), + {} +}; + +static struct kunit_suite macsmc_input_test_suite = { + .name = "macsmc-input", + .init = macsmc_input_test_init, + .test_cases = macsmc_input_test_cases, +}; + +kunit_test_suite(macsmc_input_test_suite); diff --git a/drivers/input/misc/macsmc-input.c b/drivers/input/misc/macsmc-input.c index 0971ac3085c29..eaf7655832dbc 100644 --- a/drivers/input/misc/macsmc-input.c +++ b/drivers/input/misc/macsmc-input.c @@ -401,3 +401,7 @@ MODULE_AUTHOR("Hector Martin "); MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("Apple SMC input driver"); MODULE_ALIAS("platform:macsmc-input"); + +#if IS_ENABLED(CONFIG_INPUT_MACSMC_INPUT_KUNIT_TEST) +#include "macsmc-input-test.c" +#endif diff --git a/drivers/input/misc/macsmc-input.kunitconfig b/drivers/input/misc/macsmc-input.kunitconfig new file mode 100644 index 0000000000000..7f809e65a5730 --- /dev/null +++ b/drivers/input/misc/macsmc-input.kunitconfig @@ -0,0 +1,15 @@ +# ./tools/testing/kunit/kunit.py run --arch=arm64 --kunitconfig=drivers/input/misc/macsmc-input.kunitconfig +CONFIG_KUNIT=y +CONFIG_ARCH_APPLE=y +CONFIG_OF=y +CONFIG_MAILBOX=y +CONFIG_APPLE_MAILBOX=y +CONFIG_APPLE_RTKIT=y +CONFIG_MFD_MACSMC=y +CONFIG_MFD_MACSMC_KUNIT_TEST=y +CONFIG_PM=y +CONFIG_SUSPEND=y +CONFIG_INPUT=y +CONFIG_INPUT_MISC=y +CONFIG_INPUT_MACSMC_INPUT=y +CONFIG_INPUT_MACSMC_INPUT_KUNIT_TEST=y From ec4ba77ff81baa61b448a72f242a4de9e3fec5e5 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:08 +1100 Subject: [PATCH 09/13] drm: apple: add DCP parser bounds tests parse_display_metadata(), parse_panel_product_metadata(), parse_array_count(), parse_dptx_caps(), the system log mnits parsers, the timing colour and id catalogs, parse_panel_edid_data(), dcp_mode_default_above() and the audio element parsers had no tests. Add the apple-dcp-parser-bounds suite (22 cases). Besides the decoded values, every case feeds each strict prefix of a valid blob and expects a clean error, so a parser that reads past the end of a truncated blob fails. It also covers the framing and depth limits of the skipper, and channel layouts whose counts the u32 mask has no bit for (fixed earlier in this series): 32, 33, 34, 63, 64, -1, -31 and 2^32 + 1 must neither set a bit nor alias a small count, and a layout claiming 2^32 + 8 channels must not be taken for the 8-channel one. Mutations caught: the depth limit off by one, an id list bound off by one, raw EDID bytes beyond the length kept and a one-byte over-read in parse_bytes(). Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/Kconfig | 3 + drivers/gpu/drm/apple/Makefile | 1 + drivers/gpu/drm/apple/parser-bounds-test.c | 1416 ++++++++++++++++++++ 3 files changed, 1420 insertions(+) create mode 100644 drivers/gpu/drm/apple/parser-bounds-test.c diff --git a/drivers/gpu/drm/apple/Kconfig b/drivers/gpu/drm/apple/Kconfig index 99632ffe1535c..6115091a8f768 100644 --- a/drivers/gpu/drm/apple/Kconfig +++ b/drivers/gpu/drm/apple/Kconfig @@ -110,6 +110,9 @@ config DRM_APPLE_PARSER_KUNIT_TEST help Build tests for AFKv2 lengths, DMA ownership and reply correlation, legacy EPIC replies, and H17P IOMFB callback envelopes and sizes. + Also check that the DCP dictionary parsers (display metadata, + DPTX capabilities, log events, timing catalogs, EDID properties + and audio elements) reject truncated and malformed blobs. The tests use allocated buffers and fake devices and do not require an Apple display controller or any firmware. diff --git a/drivers/gpu/drm/apple/Makefile b/drivers/gpu/drm/apple/Makefile index a6687d7cccd65..c567455087553 100644 --- a/drivers/gpu/drm/apple/Makefile +++ b/drivers/gpu/drm/apple/Makefile @@ -51,6 +51,7 @@ obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += afk-service-test.o obj-$(CONFIG_DRM_APPLE_KUNIT_TEST) += dcp_cec_test.o obj-$(CONFIG_DRM_APPLE_PARSER_KUNIT_TEST) += afkv2-test.o +appledrm-$(CONFIG_DRM_APPLE_PARSER_KUNIT_TEST) += parser-bounds-test.o appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += parser-test.o appledrm-$(CONFIG_DRM_APPLE_DISPLAY_KUNIT_TEST) += hotplug-test.o diff --git a/drivers/gpu/drm/apple/parser-bounds-test.c b/drivers/gpu/drm/apple/parser-bounds-test.c new file mode 100644 index 0000000000000..2c4db5f99eaa8 --- /dev/null +++ b/drivers/gpu/drm/apple/parser-bounds-test.c @@ -0,0 +1,1416 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * KUnit tests for the DCP serialized dictionary parsers that the other parser + * suites do not call: display metadata, DPTX capabilities, system log events, + * timing catalogs, panel EDID properties and audio elements. Firmware hands + * these blobs to the driver, so beyond the accepted shapes every parser must + * fail on every truncation of a valid blob instead of reading past its end. + * + * All values are synthetic. + */ + +#include +#include +#include +#include +#include +#include + +#if IS_ENABLED(CONFIG_DRM_APPLE_AUDIO) +#include +#endif + +#include "dcp-peer-v27.h" +#include "parser.h" + +/* Tag: size in bits 0-23, type in 24-28, padding in 29-30, last in 31. */ +#define PB_DICT 1 +#define PB_ARRAY 2 +#define PB_INT64 4 +#define PB_STRING 9 +#define PB_BLOB 10 +#define PB_BOOL 11 +#define PB_CAP 8192 + +struct pb { + struct kunit *test; + u8 *data; + u32 len; +}; + +static struct pb *pb_new(struct kunit *test, bool header) +{ + struct pb *b = kunit_kzalloc(test, sizeof(*b), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, b); + b->data = kunit_kzalloc(test, PB_CAP, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, b->data); + b->test = test; + if (header) { + put_unaligned_le32(0xd3, b->data); + b->len = 4; + } + return b; +} + +static void pb_raw(struct pb *b, const void *bytes, u32 n) +{ + KUNIT_ASSERT_LE(b->test, b->len + n, PB_CAP); + memcpy(b->data + b->len, bytes, n); + b->len += n; +} + +static void pb_word(struct pb *b, u32 word) +{ + b->len = round_up(b->len, 4); + KUNIT_ASSERT_LE(b->test, b->len + 4, PB_CAP); + put_unaligned_le32(word, b->data + b->len); + b->len += 4; +} + +static void pb_tag(struct pb *b, u32 type, u32 size) +{ + pb_word(b, size | type << 24); +} + +static void pb_str(struct pb *b, const char *s) +{ + pb_tag(b, PB_STRING, strlen(s)); + pb_raw(b, s, strlen(s)); +} + +static void pb_int(struct pb *b, s64 value) +{ + u8 raw[8]; + + pb_tag(b, PB_INT64, 0); + put_unaligned_le64(value, raw); + pb_raw(b, raw, sizeof(raw)); +} + +static void pb_kint(struct pb *b, const char *key, s64 value) +{ + pb_str(b, key); + pb_int(b, value); +} + +static void pb_kbool(struct pb *b, const char *key, bool value) +{ + pb_str(b, key); + pb_tag(b, PB_BOOL, value); +} + +static void pb_kstr(struct pb *b, const char *key, const char *value) +{ + pb_str(b, key); + pb_str(b, value); +} + +typedef int (*pb_parse_fn)(const u8 *data, size_t len, void *priv); + +/* + * Every strict prefix of @b must fail. The bytes after the prefix stay in + * place and complete a valid blob, so a parser that reads past its length + * succeeds instead. Each prefix also runs from an exact-size allocation, + * which KASAN checks when enabled. + */ +static void pb_expect_prefixes_fail(struct pb *b, pb_parse_fn fn, void *priv) +{ + struct kunit *test = b->test; + u32 len; + + for (len = 0; len < b->len; len++) { + u8 *copy; + + KUNIT_EXPECT_LT_MSG(test, fn(b->data, len, priv), 0, + "prefix %u of %u", len, b->len); + if (!len) + continue; + copy = kmemdup(b->data, len, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, copy); + KUNIT_EXPECT_LT_MSG(test, fn(copy, len, priv), 0, + "exact prefix %u of %u", len, b->len); + kfree(copy); + } +} + +/* A parser that reports an error leaves its output alone. */ +static void pb_expect_untouched(struct kunit *test, const void *out, size_t size) +{ + KUNIT_EXPECT_NULL(test, memchr_inv(out, 0xa5, size)); +} + +/* Serialized framing */ + +static bool pb_complete(struct pb *b) +{ + return dcp_property_complete(b->data, b->len, b->len); +} + +static void parser_bounds_framing_test(struct kunit *test) +{ + struct pb *b; + + /* The last-element flag in bit 31 is accepted. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_str(b, "Key"); + pb_word(b, PB_INT64 << 24 | BIT(31)); + pb_raw(b, "\0\0\0\0\0\0\0\0", 8); + KUNIT_EXPECT_TRUE(test, pb_complete(b)); + + /* Padding bits 29 and 30 must be clear. */ + b = pb_new(test, true); + pb_word(b, PB_BOOL << 24 | BIT(29)); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + b = pb_new(test, true); + pb_word(b, PB_BOOL << 24 | BIT(30)); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + + /* Types the serializer does not define. */ + b = pb_new(test, true); + pb_tag(b, 3, 0); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + b = pb_new(test, true); + pb_tag(b, 0, 0); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + + /* An integer is eight bytes whatever its tag size says. */ + b = pb_new(test, true); + pb_tag(b, PB_INT64, 4); + pb_raw(b, "\1\0\0\0", 4); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + + /* A string or blob longer than the bytes left. */ + b = pb_new(test, true); + pb_tag(b, PB_STRING, 5); + pb_raw(b, "abcd", 4); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + b = pb_new(test, true); + pb_tag(b, PB_BLOB, 0xffffff); + pb_raw(b, "abcd", 4); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + + /* The largest dictionary count, doubled for its keys, still ends at the blob. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 0xffffff); + pb_kint(b, "Key", 1); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); +} + +static void pb_nest(struct pb *b, unsigned int depth) +{ + unsigned int i; + + for (i = 0; i < depth; i++) + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_BOOL, 1); +} + +/* The skipper bounds its recursion at 32 levels: 31 containers fit. */ +static void parser_bounds_depth_test(struct kunit *test) +{ + struct pb *b; + + b = pb_new(test, true); + pb_nest(b, 31); + KUNIT_EXPECT_TRUE(test, pb_complete(b)); + + b = pb_new(test, true); + pb_nest(b, 32); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); + + b = pb_new(test, true); + pb_nest(b, 1000); + KUNIT_EXPECT_FALSE(test, pb_complete(b)); +} + +static void parser_bounds_array_count_test(struct kunit *test) +{ + struct dcp_parse_ctx ctx; + struct pb *b; + u32 count = 0xa5a5a5a5; + + b = pb_new(test, true); + pb_tag(b, PB_ARRAY, 3); + pb_int(b, 1); + pb_int(b, 2); + pb_int(b, 3); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_array_count(&ctx, &count), 0); + KUNIT_EXPECT_EQ(test, count, 3); + /* The cursor is not consumed. */ + KUNIT_EXPECT_EQ(test, ctx.pos, 4); + + /* Only the tag is read: a count beyond the blob is the caller's to bound. */ + b = pb_new(test, true); + pb_tag(b, PB_ARRAY, 0xffffff); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_array_count(&ctx, &count), 0); + KUNIT_EXPECT_EQ(test, count, 0xffffff); + + count = 0xa5a5a5a5; + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_array_count(&ctx, &count), -EINVAL); + KUNIT_ASSERT_EQ(test, parse(b->data, 6, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_array_count(&ctx, &count), -EINVAL); + KUNIT_EXPECT_EQ(test, count, 0xa5a5a5a5); +} + +/* DisplayAttributes */ + +static void pb_point(struct pb *b, const char *key, s64 x, s64 y, s64 gamma) +{ + pb_str(b, key); + pb_tag(b, PB_DICT, gamma ? 3 : 2); + pb_kint(b, "X", x); + pb_kint(b, "Y", y); + if (gamma) + pb_kint(b, "Gamma", gamma); +} + +static void pb_product(struct pb *b, const char *manufacturer, s64 product, + const char *name) +{ + pb_tag(b, PB_DICT, 7); + pb_kstr(b, "ManufacturerID", manufacturer); + pb_kint(b, "ProductID", product); + pb_kstr(b, "ProductName", name); + pb_kint(b, "SerialNumber", 7); + pb_kint(b, "WeekOfManufacture", 10); + pb_kint(b, "YearOfManufacture", 2024); + pb_kstr(b, "AlphanumericSerialNumber", "SN0001"); +} + +static struct pb *pb_display_attributes(struct kunit *test) +{ + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_DICT, 10); + pb_kint(b, "MaxHorizontalImageSize", 60); + pb_kint(b, "MaxVerticalImageSize", 34); + pb_str(b, "Chromaticity"); + pb_tag(b, PB_DICT, 3); + pb_point(b, "Red", 42000, 21000, 0); + pb_point(b, "Green", 20000, 45000, 0); + pb_point(b, "Blue", 10000, 4000, 0); + pb_point(b, "DefaultWhitePoint", 20500, 21500, 144179); + pb_kbool(b, "SupportsPQEOTF", true); + pb_kbool(b, "SupportsHDRStaticMetadataType1", true); + pb_kint(b, "SupportsBT2020RGB", 1); + pb_str(b, "Luminance"); + pb_tag(b, PB_DICT, 3); + pb_kint(b, "Max", 600 << 16); + pb_kint(b, "MaxFrameAverage", 400 << 16); + pb_kint(b, "Min", 1 << 12); + pb_kstr(b, "Unknown", "ignored"); + pb_str(b, "ProductAttributes"); + pb_product(b, "TST", 0x1234, "Synthetic"); + return b; +} + +static int pb_run_display_metadata(const u8 *data, size_t len, void *priv) +{ + struct dcp_parse_ctx ctx; + int ret = parse(data, len, &ctx); + + return ret ?: parse_display_metadata(&ctx, priv); +} + +static void parser_bounds_metadata_test(struct kunit *test) +{ + struct pb *b = pb_display_attributes(test); + struct dcp_display_metadata md; + + memset(&md, 0xa5, sizeof(md)); + KUNIT_ASSERT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), 0); + KUNIT_EXPECT_EQ(test, md.width_cm, 60); + KUNIT_EXPECT_EQ(test, md.height_cm, 34); + KUNIT_EXPECT_EQ(test, md.chromaticity[0][0], 42000); + KUNIT_EXPECT_EQ(test, md.chromaticity[1][1], 45000); + KUNIT_EXPECT_EQ(test, md.chromaticity[2][1], 4000); + KUNIT_EXPECT_EQ(test, md.white[0], 20500); + KUNIT_EXPECT_EQ(test, md.white[1], 21500); + KUNIT_EXPECT_EQ(test, md.gamma, 144179); + KUNIT_EXPECT_STREQ(test, md.manufacturer, "TST"); + KUNIT_EXPECT_EQ(test, md.product, 0x1234); + KUNIT_EXPECT_STREQ(test, md.name, "Synthetic"); + KUNIT_EXPECT_STREQ(test, md.serial_text, "SN0001"); + KUNIT_EXPECT_EQ(test, md.serial, 7); + KUNIT_EXPECT_EQ(test, md.week, 10); + KUNIT_EXPECT_EQ(test, md.year, 2024); + KUNIT_EXPECT_TRUE(test, md.pq); + KUNIT_EXPECT_TRUE(test, md.static_metadata_type1); + KUNIT_EXPECT_TRUE(test, md.bt2020_rgb); + KUNIT_EXPECT_EQ(test, md.max_luminance, 600 << 16); + KUNIT_EXPECT_EQ(test, md.max_fall, 400 << 16); + KUNIT_EXPECT_EQ(test, md.min_luminance, 1 << 12); + KUNIT_EXPECT_EQ(test, md.defaults, 0); +} + +static void parser_bounds_metadata_truncated_test(struct kunit *test) +{ + struct pb *b = pb_display_attributes(test); + struct dcp_display_metadata md; + + memset(&md, 0xa5, sizeof(md)); + pb_expect_prefixes_fail(b, pb_run_display_metadata, &md); + pb_expect_untouched(test, &md, sizeof(md)); +} + +/* Optional values out of range fall back to EDID defaults; identity is required. */ +static void parser_bounds_metadata_defaults_test(struct kunit *test) +{ + struct dcp_display_metadata md; + struct pb *b; + + b = pb_new(test, true); + pb_tag(b, PB_DICT, 6); + pb_kint(b, "MaxHorizontalImageSize", 256); + pb_kint(b, "MaxVerticalImageSize", 34); + /* Primaries without a white point are no colour description. */ + pb_str(b, "Chromaticity"); + pb_tag(b, PB_DICT, 3); + pb_point(b, "Red", 42000, 21000, 0); + pb_point(b, "Green", 20000, 45000, 0); + pb_point(b, "Blue", 10000, 4000, 0); + /* A minimum at the maximum is no luminance range. */ + pb_str(b, "Luminance"); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "Max", 100); + pb_kint(b, "Min", 100); + pb_kstr(b, "SupportsBT2020RGB", "yes"); + pb_str(b, "ProductAttributes"); + pb_tag(b, PB_DICT, 2); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 1); + + KUNIT_ASSERT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), 0); + KUNIT_EXPECT_EQ(test, md.width_cm, 0); + KUNIT_EXPECT_EQ(test, md.height_cm, 0); + KUNIT_EXPECT_EQ(test, md.chromaticity[0][0], 0); + KUNIT_EXPECT_EQ(test, md.max_luminance, 0); + KUNIT_EXPECT_FALSE(test, md.bt2020_rgb); + KUNIT_EXPECT_EQ(test, md.defaults, + DCP_METADATA_DEFAULT_SIZE | DCP_METADATA_DEFAULT_COLOR | + DCP_METADATA_DEFAULT_NAME | DCP_METADATA_DEFAULT_DATE); + + /* No ProductAttributes at all. */ + memset(&md, 0xa5, sizeof(md)); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "MaxHorizontalImageSize", 60); + pb_kint(b, "MaxVerticalImageSize", 34); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + pb_expect_untouched(test, &md, sizeof(md)); +} + +static void parser_bounds_metadata_keys_test(struct kunit *test) +{ + struct dcp_display_metadata md; + char key[80]; + struct pb *b; + + memset(&md, 0xa5, sizeof(md)); + + /* A repeated key. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kint(b, "MaxHorizontalImageSize", 60); + pb_kint(b, "MaxHorizontalImageSize", 61); + pb_str(b, "ProductAttributes"); + pb_product(b, "TST", 1, "Synthetic"); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + /* A key with a control character. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "Odd\nKey", 1); + pb_str(b, "ProductAttributes"); + pb_product(b, "TST", 1, "Synthetic"); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + /* An empty key and one longer than the key buffer. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "", 1); + pb_str(b, "ProductAttributes"); + pb_product(b, "TST", 1, "Synthetic"); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + memset(key, 'K', sizeof(key)); + key[64] = 0; + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, key, 1); + pb_str(b, "ProductAttributes"); + pb_product(b, "TST", 1, "Synthetic"); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + /* A key of the wrong type. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_int(b, 1); + pb_int(b, 1); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + /* An array where the dictionary goes. */ + b = pb_new(test, true); + pb_tag(b, PB_ARRAY, 0); + KUNIT_EXPECT_EQ(test, pb_run_display_metadata(b->data, b->len, &md), -EINVAL); + + pb_expect_untouched(test, &md, sizeof(md)); +} + +static int pb_run_panel_product(const u8 *data, size_t len, void *priv) +{ + struct dcp_parse_ctx ctx; + int ret = parse(data, len, &ctx); + + return ret ?: parse_panel_product_metadata(&ctx, priv); +} + +static void parser_bounds_product_test(struct kunit *test) +{ + struct dcp_display_metadata md; + char label[257]; + struct pb *b; + + /* A panel label is cut to a descriptor; its date is not read. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 4); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 0xffff); + pb_kstr(b, "ProductName", "Synthetic Panel Label"); + pb_kstr(b, "WeekOfManufacture", "not a number"); + KUNIT_ASSERT_EQ(test, pb_run_panel_product(b->data, b->len, &md), 0); + KUNIT_EXPECT_STREQ(test, md.manufacturer, "TST"); + KUNIT_EXPECT_EQ(test, md.product, 0xffff); + KUNIT_EXPECT_STREQ(test, md.name, "Synthetic Pan"); + KUNIT_EXPECT_EQ(test, md.week, 0); + + /* A blank label reads as absent. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 1); + pb_kstr(b, "ProductName", " "); + KUNIT_ASSERT_EQ(test, pb_run_panel_product(b->data, b->len, &md), 0); + KUNIT_EXPECT_EQ(test, md.name[0], 0); + + /* The legacy ID alone gives the manufacturer: TST = 20 << 10 | 19 << 5 | 20. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "LegacyManufacturerID", 20 << 10 | 19 << 5 | 20); + pb_kint(b, "ProductID", 1); + KUNIT_ASSERT_EQ(test, pb_run_panel_product(b->data, b->len, &md), 0); + KUNIT_EXPECT_STREQ(test, md.manufacturer, "TST"); + + memset(&md, 0xa5, sizeof(md)); + + /* A legacy ID that disagrees with the manufacturer. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "LegacyManufacturerID", 1 << 10 | 1 << 5 | 1); + pb_kint(b, "ProductID", 1); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + + /* Not three capitals; a product beyond 16 bits; no product. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kstr(b, "ManufacturerID", "tst"); + pb_kint(b, "ProductID", 1); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kstr(b, "ManufacturerID", "TSTX"); + pb_kint(b, "ProductID", 1); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 0x10000); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kstr(b, "ManufacturerID", "TST"); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + + /* A label longer than 255 bytes or with a control character. */ + memset(label, 'L', sizeof(label)); + label[256] = 0; + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 1); + pb_kstr(b, "ProductName", label); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kstr(b, "ManufacturerID", "TST"); + pb_kint(b, "ProductID", 1); + pb_kstr(b, "ProductName", "Tab\there"); + KUNIT_EXPECT_EQ(test, pb_run_panel_product(b->data, b->len, &md), -EINVAL); + + pb_expect_untouched(test, &md, sizeof(md)); + + b = pb_new(test, true); + pb_product(b, "TST", 1, "Synthetic"); + pb_expect_prefixes_fail(b, pb_run_panel_product, &md); + pb_expect_untouched(test, &md, sizeof(md)); +} + +/* DPTX port capabilities */ + +static int pb_run_dptx_caps(const u8 *data, size_t len, void *priv) +{ + struct dcp_parse_ctx ctx; + int ret = parse(data, len, &ctx); + + return ret ?: parse_dptx_caps(&ctx, priv); +} + +static void parser_bounds_dptx_caps_test(struct kunit *test) +{ + struct dcp_dptx_caps caps; + struct pb *b; + + b = pb_new(test, true); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "MaxPixelWidth", 5120); + pb_str(b, "Nested"); + pb_tag(b, PB_ARRAY, 2); + pb_tag(b, PB_DICT, 0); + pb_int(b, 3); + pb_kint(b, "MaxTotalPixelRate", 1000000); + pb_kint(b, "MaxActivePixelRate", U32_MAX); + KUNIT_ASSERT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), 0); + KUNIT_EXPECT_EQ(test, caps.width, 5120); + KUNIT_EXPECT_EQ(test, caps.total_rate, 1000000); + KUNIT_EXPECT_EQ(test, caps.active_rate, U32_MAX); + + memset(&caps, 0xa5, sizeof(caps)); + pb_expect_prefixes_fail(b, pb_run_dptx_caps, &caps); + + /* A missing limit. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "MaxPixelWidth", 5120); + pb_kint(b, "MaxTotalPixelRate", 1000000); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -ENOENT); + + /* A repeated limit. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "MaxPixelWidth", 5120); + pb_kint(b, "MaxPixelWidth", 4096); + pb_kint(b, "MaxTotalPixelRate", 1000000); + pb_kint(b, "MaxActivePixelRate", 1000000); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -EINVAL); + + /* Zero, beyond 32 bits, negative, or not an integer. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kint(b, "MaxPixelWidth", 0); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kint(b, "MaxTotalPixelRate", (s64)U32_MAX + 1); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kint(b, "MaxActivePixelRate", -1); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kstr(b, "MaxPixelWidth", "5120"); + KUNIT_EXPECT_EQ(test, pb_run_dptx_caps(b->data, b->len, &caps), -EINVAL); + + pb_expect_untouched(test, &caps, sizeof(caps)); +} + +/* System log brightness events */ + +static struct pb *pb_mnits_event(struct kunit *test, const char *event, s64 mnits) +{ + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_DICT, 5); + pb_kstr(b, "logEvent", event); + pb_kint(b, "timestamp", 1234); + pb_kint(b, "iDAC", 56); + pb_str(b, "extra"); + pb_tag(b, PB_DICT, 1); + pb_kbool(b, "x", false); + pb_kint(b, "mNits", mnits); + return b; +} + +static int pb_run_mnits(const u8 *data, size_t len, void *priv) +{ + struct dcp_parse_ctx ctx; + int ret = parse(data, len, &ctx); + + return ret ?: parse_system_log_mnits(&ctx, priv); +} + +static void parser_bounds_mnits_test(struct kunit *test) +{ + struct dcp_system_ev_mnits entry; + struct pb *b; + + b = pb_mnits_event(test, "Display (Event Forward)", 500000); + KUNIT_ASSERT_EQ(test, pb_run_mnits(b->data, b->len, &entry), 0); + KUNIT_EXPECT_EQ(test, entry.millinits, 500000); + KUNIT_EXPECT_EQ(test, entry.idac, 56); + KUNIT_EXPECT_EQ(test, entry.timestamp, 1234); + + memset(&entry, 0xa5, sizeof(entry)); + pb_expect_prefixes_fail(b, pb_run_mnits, &entry); + + b = pb_mnits_event(test, "Display (Event Forward) ", 500000); + KUNIT_EXPECT_EQ(test, pb_run_mnits(b->data, b->len, &entry), -EINVAL); + b = pb_mnits_event(test, "Display (Event Forward)", -1); + KUNIT_EXPECT_EQ(test, pb_run_mnits(b->data, b->len, &entry), -EINVAL); + b = pb_mnits_event(test, "Display (Event Forward)", (s64)U32_MAX + 1); + KUNIT_EXPECT_EQ(test, pb_run_mnits(b->data, b->len, &entry), -ERANGE); + + /* No timestamp. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 3); + pb_kstr(b, "logEvent", "Display (Event Forward)"); + pb_kint(b, "iDAC", 56); + pb_kint(b, "mNits", 1); + KUNIT_EXPECT_EQ(test, pb_run_mnits(b->data, b->len, &entry), -EINVAL); + + pb_expect_untouched(test, &entry, sizeof(entry)); +} + +static int pb_run_mnits_pairs(const u8 *data, size_t len, void *priv) +{ + return parse_system_log_mnits_pairs(data, len, priv); +} + +/* Header-less key/value pairs, read up to the first one that does not parse. */ +static void parser_bounds_mnits_pairs_test(struct kunit *test) +{ + struct dcp_system_ev_mnits entry; + struct pb *b; + + b = pb_new(test, false); + pb_kint(b, "timestamp", 99); + pb_kint(b, "iDAC", -5); + pb_kstr(b, "other", "value"); + pb_kint(b, "mNits", 250); + KUNIT_ASSERT_EQ(test, pb_run_mnits_pairs(b->data, b->len, &entry), 0); + KUNIT_EXPECT_EQ(test, entry.millinits, 250); + KUNIT_EXPECT_EQ(test, entry.idac, 0); + KUNIT_EXPECT_EQ(test, entry.timestamp, 99); + + /* mNits comes last, so no prefix holds all of it. */ + memset(&entry, 0xa5, sizeof(entry)); + pb_expect_prefixes_fail(b, pb_run_mnits_pairs, &entry); + pb_expect_untouched(test, &entry, sizeof(entry)); + + /* A key whose length runs past the end stops the walk before mNits. */ + b = pb_new(test, false); + pb_tag(b, PB_STRING, 0x1000); + pb_raw(b, "mNits", 5); + pb_kint(b, "mNits", 250); + KUNIT_EXPECT_EQ(test, pb_run_mnits_pairs(b->data, b->len, &entry), -EINVAL); + + /* A value of the wrong type stops it too. */ + b = pb_new(test, false); + pb_kstr(b, "iDAC", "56"); + pb_kint(b, "mNits", 250); + KUNIT_EXPECT_EQ(test, pb_run_mnits_pairs(b->data, b->len, &entry), -EINVAL); + + b = pb_new(test, false); + pb_kint(b, "mNits", (s64)U32_MAX + 1); + KUNIT_EXPECT_EQ(test, pb_run_mnits_pairs(b->data, b->len, &entry), -EINVAL); + pb_expect_untouched(test, &entry, sizeof(entry)); +} + +/* TimingElements catalogs */ + +static void pb_dimension(struct pb *b, const char *key, s64 active, s64 total) +{ + pb_str(b, key); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "Active", active); + pb_kint(b, "Total", total); + pb_kint(b, "FrontPorch", 8); + pb_kint(b, "SyncWidth", 4); +} + +static struct pb *pb_timing_ids(struct kunit *test) +{ + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_ARRAY, 4); + pb_tag(b, PB_DICT, 3); + pb_kint(b, "ID", 3); + pb_dimension(b, "HorizontalAttributes", 1920, 2200); + pb_dimension(b, "VerticalAttributes", 1080, 1125); + /* Malformed entries are skipped: an ID of the wrong type, one beyond 32 bits. */ + pb_tag(b, PB_DICT, 1); + pb_kstr(b, "ID", "4"); + pb_tag(b, PB_DICT, 1); + pb_kint(b, "ID", (s64)U32_MAX + 5); + /* No size: zero. */ + pb_tag(b, PB_DICT, 2); + pb_kbool(b, "IsPreferred", true); + pb_kint(b, "ID", 9); + return b; +} + +static int pb_run_timing_ids(const u8 *data, size_t len, void *priv) +{ + return dcp_parse_timing_ids(data, len, priv, 4); +} + +static void parser_bounds_timing_ids_test(struct kunit *test) +{ + struct dcp_timing_id ids[4]; + struct pb *b = pb_timing_ids(test); + + memset(ids, 0xa5, sizeof(ids)); + KUNIT_ASSERT_EQ(test, dcp_parse_timing_ids(b->data, b->len, ids, 4), 2); + KUNIT_EXPECT_EQ(test, ids[0].id, 3); + KUNIT_EXPECT_EQ(test, ids[0].width, 1920); + KUNIT_EXPECT_EQ(test, ids[0].height, 1080); + KUNIT_EXPECT_EQ(test, ids[1].id, 9); + KUNIT_EXPECT_EQ(test, ids[1].width, 0); + KUNIT_EXPECT_EQ(test, ids[1].height, 0); + pb_expect_untouched(test, &ids[2], 2 * sizeof(ids[0])); + + /* At most @max are written. */ + memset(ids, 0xa5, sizeof(ids)); + KUNIT_EXPECT_EQ(test, dcp_parse_timing_ids(b->data, b->len, ids, 1), 1); + KUNIT_EXPECT_EQ(test, ids[0].id, 3); + pb_expect_untouched(test, &ids[1], 3 * sizeof(ids[0])); + KUNIT_EXPECT_EQ(test, dcp_parse_timing_ids(b->data, b->len, ids, 0), 0); + + /* Every truncation ends in a skip that cannot finish. */ + pb_expect_prefixes_fail(b, pb_run_timing_ids, ids); + + /* A dictionary is no catalog. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 0); + KUNIT_EXPECT_EQ(test, dcp_parse_timing_ids(b->data, b->len, ids, 4), -EINVAL); +} + +#define PB_MAX_COLORS 8 + +struct pb_colors { + unsigned int count; + struct dcp_color_element e[PB_MAX_COLORS]; +}; + +static void pb_collect_color(void *data, const struct dcp_color_element *e) +{ + struct pb_colors *c = data; + + if (c->count < PB_MAX_COLORS) + c->e[c->count] = *e; + c->count++; +} + +static void pb_color(struct pb *b, s64 id, s64 eotf) +{ + pb_tag(b, PB_DICT, 5); + pb_kint(b, "ID", id); + pb_kint(b, "Depth", 10); + pb_kint(b, "EOTF", eotf); + pb_kbool(b, "IsVirtual", false); + pb_kint(b, "Score", 100 + id); +} + +static struct pb *pb_timing_colors(struct kunit *test) +{ + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_ARRAY, 3); + /* A malformed entry that would match. */ + pb_tag(b, PB_DICT, 2); + pb_kint(b, "ID", 5); + pb_kstr(b, "IsInterlaced", "no"); + /* Another timing. */ + pb_tag(b, PB_DICT, 2); + pb_kint(b, "ID", 4); + pb_str(b, "ColorModes"); + pb_tag(b, PB_ARRAY, 1); + pb_color(b, 99, 0); + /* The timing, its colours before its ID. */ + pb_tag(b, PB_DICT, 5); + pb_str(b, "ColorModes"); + pb_tag(b, PB_ARRAY, 2); + pb_color(b, 10, 0); + pb_color(b, 11, 2); + pb_str(b, "UnsafeColorElementIDs"); + pb_tag(b, PB_ARRAY, 1); + pb_int(b, 11); + pb_str(b, "DSCRequiredColorElementIDs"); + pb_tag(b, PB_ARRAY, 1); + pb_int(b, 10); + pb_kbool(b, "IsInterlaced", true); + pb_kint(b, "ID", 5); + return b; +} + +static int pb_run_timing_colors(const u8 *data, size_t len, void *priv) +{ + struct pb_colors *c = priv; + + c->count = 0; + return dcp_parse_timing_colors(data, len, 5, pb_collect_color, c, NULL); +} + +static void parser_bounds_timing_colors_test(struct kunit *test) +{ + struct pb *b = pb_timing_colors(test); + struct pb_colors *c = kunit_kzalloc(test, sizeof(*c), GFP_KERNEL); + bool interlaced = false; + + KUNIT_ASSERT_NOT_NULL(test, c); + KUNIT_ASSERT_EQ(test, dcp_parse_timing_colors(b->data, b->len, 5, pb_collect_color, + c, &interlaced), 0); + KUNIT_EXPECT_TRUE(test, interlaced); + KUNIT_ASSERT_EQ(test, c->count, 2); + KUNIT_EXPECT_EQ(test, c->e[0].id, 10); + KUNIT_EXPECT_EQ(test, c->e[0].depth, 10); + KUNIT_EXPECT_EQ(test, c->e[0].score, 110); + KUNIT_EXPECT_EQ(test, c->e[0].range, -1); + KUNIT_EXPECT_FALSE(test, c->e[0].is_virtual); + KUNIT_EXPECT_FALSE(test, c->e[0].unsafe); + KUNIT_EXPECT_TRUE(test, c->e[0].dsc_required); + KUNIT_EXPECT_EQ(test, c->e[1].id, 11); + KUNIT_EXPECT_EQ(test, c->e[1].eotf, 2); + KUNIT_EXPECT_TRUE(test, c->e[1].unsafe); + KUNIT_EXPECT_FALSE(test, c->e[1].dsc_required); + + c->count = 0; + KUNIT_EXPECT_EQ(test, dcp_parse_timing_colors(b->data, b->len, 6, pb_collect_color, + c, NULL), -ENOENT); + KUNIT_EXPECT_EQ(test, c->count, 0); + + pb_expect_prefixes_fail(b, pb_run_timing_colors, c); +} + +/* + * The restricted ID lists hold 64 entries each: further IDs are dropped, not + * written over the neighbouring list. + */ +static void parser_bounds_timing_colors_lists_test(struct kunit *test) +{ + struct pb_colors *c = kunit_kzalloc(test, sizeof(*c), GFP_KERNEL); + struct pb *b = pb_new(test, true); + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, c); + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "ID", 1); + pb_str(b, "DSCRequiredColorElementIDs"); + pb_tag(b, PB_ARRAY, 1); + pb_int(b, 10); + pb_str(b, "UnsafeColorElementIDs"); + pb_tag(b, PB_ARRAY, 65); + for (i = 0; i < 64; i++) + pb_int(b, 1000 + i); + pb_int(b, 11); + pb_str(b, "ColorModes"); + pb_tag(b, PB_ARRAY, 2); + pb_color(b, 10, 0); + pb_color(b, 11, 0); + + KUNIT_ASSERT_EQ(test, dcp_parse_timing_colors(b->data, b->len, 1, pb_collect_color, + c, NULL), 0); + KUNIT_ASSERT_EQ(test, c->count, 2); + KUNIT_EXPECT_TRUE(test, c->e[0].dsc_required); + KUNIT_EXPECT_FALSE(test, c->e[0].unsafe); + KUNIT_EXPECT_FALSE(test, c->e[1].dsc_required); + KUNIT_EXPECT_FALSE(test, c->e[1].unsafe); + + /* A list entry of the wrong type makes the entry malformed. */ + b = pb_new(test, true); + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "ID", 1); + pb_str(b, "UnsafeColorElementIDs"); + pb_tag(b, PB_ARRAY, 1); + pb_str(b, "11"); + c->count = 0; + KUNIT_EXPECT_EQ(test, dcp_parse_timing_colors(b->data, b->len, 1, pb_collect_color, + c, NULL), -ENOENT); + KUNIT_EXPECT_EQ(test, c->count, 0); +} + +/* Panel EDID properties */ + +static void pb_edid(u8 *edid, unsigned int blocks) +{ + memset(edid, 0, blocks * 128); + memcpy(edid, "\x00\xff\xff\xff\xff\xff\xff\x00", 8); + edid[126] = blocks - 1; +} + +static void pb_kedid(struct pb *b, const char *key, const u8 *edid, u32 size) +{ + pb_str(b, key); + pb_tag(b, PB_BLOB, size); + pb_raw(b, edid, size); +} + +static void parser_bounds_edid_raw_test(struct kunit *test) +{ + u8 *edid = kunit_kzalloc(test, 4224, GFP_KERNEL); + const u8 *found = NULL; + size_t size = 0; + + KUNIT_ASSERT_NOT_NULL(test, edid); + pb_edid(edid, 2); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 256, &found, &size), 0); + KUNIT_EXPECT_PTR_EQ(test, found, (const u8 *)edid); + KUNIT_EXPECT_EQ(test, size, 256); + /* Trailing bytes after the extensions are not EDID. */ + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 300, &found, &size), 0); + KUNIT_EXPECT_EQ(test, size, 256); + + /* Extension blocks the buffer does not hold. */ + found = NULL; + size = 0; + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 255, &found, &size), -EINVAL); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 128, &found, &size), -EINVAL); + /* 33 blocks exceed the 4 KiB bound even when present. */ + pb_edid(edid, 33); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 4224, &found, &size), -EINVAL); + pb_edid(edid, 32); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(edid, 4096, &found, &size), 0); + KUNIT_EXPECT_EQ(test, size, 4096); + + /* Fewer than 128 bytes is no raw EDID, and no serialized blob either. */ + found = NULL; + size = 0; + pb_edid(edid, 1); + KUNIT_EXPECT_LT(test, parse_panel_edid_data(edid, 127, &found, &size), 0); + KUNIT_EXPECT_NULL(test, found); + KUNIT_EXPECT_EQ(test, size, 0); +} + +static int pb_run_edid(const u8 *data, size_t len, void *priv) +{ + const u8 *edid; + size_t size; + + return parse_panel_edid_data(data, len, &edid, &size); +} + +static void parser_bounds_edid_serialized_test(struct kunit *test) +{ + u8 *edid = kunit_kzalloc(test, 384, GFP_KERNEL); + const u8 *found; + unsigned int i; + size_t size; + struct pb *b; + + KUNIT_ASSERT_NOT_NULL(test, edid); + pb_edid(edid, 2); + + /* A blob at the root. */ + b = pb_new(test, true); + pb_tag(b, PB_BLOB, 256); + pb_raw(b, edid, 256); + KUNIT_ASSERT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), 0); + KUNIT_EXPECT_PTR_EQ(test, found, (const u8 *)b->data + 8); + KUNIT_EXPECT_EQ(test, size, 256); + + /* A named blob in a nested dictionary, after other values. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "Other", 1); + pb_str(b, "Properties"); + pb_tag(b, PB_DICT, 2); + pb_kedid(b, "NotEDID", edid, 128); + pb_kedid(b, "IODisplayEDID", edid, 256); + KUNIT_ASSERT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), 0); + KUNIT_EXPECT_EQ(test, size, 256); + KUNIT_EXPECT_EQ(test, memcmp(found, edid, 256), 0); + pb_expect_prefixes_fail(b, pb_run_edid, NULL); + + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "edid", edid, 256); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), 0); + + /* No EDID key. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "EDIDs", edid, 256); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -ENOENT); + + /* Sizes that are no whole EDID, or disagree with its extension count. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "EDID", edid, 130); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "EDID", edid, 384); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -EINVAL); + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "EDID", edid + 1, 128); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -EINVAL); + + /* A blob size beyond the bytes present. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 1); + pb_str(b, "EDID"); + pb_tag(b, PB_BLOB, 256); + pb_raw(b, edid, 128); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -EINVAL); + + /* Deeper than four dictionaries. */ + b = pb_new(test, true); + for (i = 0; i < 5; i++) { + pb_tag(b, PB_DICT, 1); + pb_str(b, "Nested"); + } + pb_tag(b, PB_DICT, 1); + pb_kedid(b, "EDID", edid, 128); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -E2BIG); + + /* More entries than the walk budget. */ + b = pb_new(test, true); + pb_tag(b, PB_DICT, 64); + for (i = 0; i < 64; i++) + pb_kint(b, "N", i); + KUNIT_EXPECT_EQ(test, parse_panel_edid_data(b->data, b->len, &found, &size), -E2BIG); +} + +/* Mode ranking */ + +static void pb_mode(struct dcp_display_mode *m, int clock, u16 htotal, u16 vtotal, + bool preferred) +{ + memset(m, 0, sizeof(*m)); + m->mode.clock = clock; + m->mode.htotal = htotal; + m->mode.vtotal = vtotal; + m->firmware_preferred = preferred; +} + +static void parser_bounds_default_above_test(struct kunit *test) +{ + struct dcp_display_mode a, b; + + /* The higher refresh rate first, whatever the preference or score. */ + pb_mode(&a, 297000, 2200, 1125, false); + pb_mode(&b, 148500, 2200, 1125, true); + KUNIT_EXPECT_TRUE(test, dcp_mode_default_above(&a, 0, &b, 100)); + KUNIT_EXPECT_FALSE(test, dcp_mode_default_above(&b, 100, &a, 0)); + + /* Same rate from different totals: IsPreferred, then the score. */ + pb_mode(&a, 297000, 4400, 1125, false); + KUNIT_EXPECT_FALSE(test, dcp_mode_default_above(&a, 100, &b, 0)); + KUNIT_EXPECT_TRUE(test, dcp_mode_default_above(&b, 0, &a, 100)); + a.firmware_preferred = true; + KUNIT_EXPECT_TRUE(test, dcp_mode_default_above(&a, 1, &b, 0)); + KUNIT_EXPECT_FALSE(test, dcp_mode_default_above(&a, 0, &b, 0)); + + /* The cross products do not wrap at the largest timings. */ + pb_mode(&a, INT_MAX, U16_MAX, U16_MAX, false); + pb_mode(&b, INT_MAX - 1, U16_MAX, U16_MAX, false); + KUNIT_EXPECT_TRUE(test, dcp_mode_default_above(&a, 0, &b, 0)); + KUNIT_EXPECT_FALSE(test, dcp_mode_default_above(&b, 0, &a, 0)); +} + +#if IS_ENABLED(CONFIG_DRM_APPLE_AUDIO) +/* Audio elements */ + +static void pb_layout(struct pb *b, s64 nchans, const char * const *labels, + unsigned int nlabels) +{ + unsigned int i; + + pb_tag(b, PB_DICT, 2); + pb_kint(b, "ActiveChannelCount", nchans); + pb_str(b, "ChannelLayout"); + pb_tag(b, PB_ARRAY, nlabels); + for (i = 0; i < nlabels; i++) + pb_str(b, labels[i]); +} + +static const char * const pb_stereo[] = { "Front Left", "Front Right" }; +static const char * const pb_surround[] = { + "Front Left", "Front Right", "Front Center", "Low Frequency Effects", + "Rear Left", "Rear Right", "Side Left", "Rear Center", +}; + +static void pb_avep(struct pb *b, s64 rate, s64 sample_size, const char *cookie_key, + u32 cookie_size) +{ + u8 cookie[DCP_SOUND_COOKIE_MAX + 4]; + unsigned int i; + + for (i = 0; i < sizeof(cookie); i++) + cookie[i] = i + 1; + pb_tag(b, PB_DICT, 5); + pb_kint(b, "StreamSampleRate", rate); + pb_kint(b, "SampleSize", sample_size); + pb_kstr(b, "Other", "skipped"); + pb_str(b, "AudioChannelLayoutElements"); + pb_tag(b, PB_ARRAY, 2); + pb_layout(b, 2, pb_stereo, ARRAY_SIZE(pb_stereo)); + pb_layout(b, 8, pb_surround, ARRAY_SIZE(pb_surround)); + pb_str(b, cookie_key); + pb_tag(b, PB_BLOB, cookie_size); + pb_raw(b, cookie, cookie_size); +} + +static struct pb *pb_audio(struct kunit *test, u32 cookie_size, bool unmatched) +{ + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_ARRAY, unmatched ? 3 : 2); + pb_avep(b, 44100, 16, "ElementData", cookie_size); + pb_avep(b, 48000, 24, "ElementData", cookie_size); + /* A rate ALSA has no bit for and a sample size it has no format for. */ + if (unmatched) + pb_avep(b, 12345, 18, "ElementData", cookie_size); + return b; +} + +static const struct dcp_sound_format_mask pb_any = { + .formats = ~0ULL, .rates = ~0U, .nchans = ~0U, +}; + +/* + * Channel counts the firmware reports but the u32 channel mask has no bit + * for (32 and up, negative, wider than 32 bits) match nothing; they must not + * wrap onto the bit of a small count (1 << 33 is 1 << 1 on arm64). + */ +static void parser_bounds_sound_wide_layouts_test(struct kunit *test) +{ + static const s64 counts[] = { 2, 31, 32, 33, 34, 63, 64, -1, -31, 0x100000001LL }; + struct dcp_sound_format_mask sieve = pb_any, hits; + struct dcp_parse_ctx ctx; + struct pb *b = pb_new(test, true); + unsigned int i; + + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 3); + pb_kint(b, "StreamSampleRate", 48000); + pb_kint(b, "SampleSize", 16); + pb_str(b, "AudioChannelLayoutElements"); + pb_tag(b, PB_ARRAY, ARRAY_SIZE(counts)); + for (i = 0; i < ARRAY_SIZE(counts); i++) { + pb_tag(b, PB_DICT, 1); + pb_kint(b, "ActiveChannelCount", counts[i]); + } + + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_constraints(&ctx, &sieve, &hits), 0); + KUNIT_EXPECT_EQ(test, hits.nchans, BIT(2) | BIT(31)); + + /* No layout has 0 or 1 channels: a sieve for those matches no element */ + sieve.nchans = BIT(0) | BIT(1); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_constraints(&ctx, &sieve, &hits), 0); + KUNIT_EXPECT_EQ(test, hits.nchans, 0U); + KUNIT_EXPECT_EQ(test, hits.rates, 0U); +} + +/* + * A count wider than 32 bits is not the low 32 bits of itself: a layout + * claiming 0x100000008 channels must not be taken for the 8-channel one + * and replace its channel map. + */ +static void parser_bounds_sound_wide_layout_map_test(struct kunit *test) +{ + struct dcp_sound_format_mask sieve = { + .formats = SNDRV_PCM_FMTBIT_S16, + .rates = SNDRV_PCM_RATE_48000, + .nchans = BIT(8), + }; + u8 data[DCP_SOUND_COOKIE_SIZE] = { 1 }; + struct snd_pcm_chmap_elem chmap = {}; + struct dcp_sound_cookie cookie = {}; + struct dcp_parse_ctx ctx; + struct pb *b = pb_new(test, true); + + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "StreamSampleRate", 48000); + pb_kint(b, "SampleSize", 16); + pb_str(b, "AudioChannelLayoutElements"); + pb_tag(b, PB_ARRAY, 2); + pb_layout(b, 8, pb_surround, ARRAY_SIZE(pb_surround)); + pb_layout(b, 0x100000008LL, pb_stereo, ARRAY_SIZE(pb_stereo)); + pb_str(b, "ElementData"); + pb_tag(b, PB_BLOB, sizeof(data)); + pb_raw(b, data, sizeof(data)); + + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), 1); + KUNIT_EXPECT_EQ(test, chmap.channels, 8); + KUNIT_EXPECT_EQ(test, chmap.map[3], SNDRV_CHMAP_LFE); +} + +static void parser_bounds_sound_constraints_test(struct kunit *test) +{ + struct dcp_sound_format_mask sieve = pb_any, hits; + struct dcp_parse_ctx ctx; + struct pb *b = pb_audio(test, DCP_SOUND_COOKIE_SIZE, true); + u32 len; + + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_constraints(&ctx, &sieve, &hits), 0); + KUNIT_EXPECT_EQ(test, hits.rates, SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000); + KUNIT_EXPECT_EQ(test, hits.formats, SNDRV_PCM_FMTBIT_S16 | SNDRV_PCM_FMTBIT_S24); + KUNIT_EXPECT_EQ(test, hits.nchans, BIT(2) | BIT(8)); + + sieve.rates = SNDRV_PCM_RATE_48000; + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_constraints(&ctx, &sieve, &hits), 0); + KUNIT_EXPECT_EQ(test, hits.rates, SNDRV_PCM_RATE_48000); + KUNIT_EXPECT_EQ(test, hits.formats, SNDRV_PCM_FMTBIT_S24); + + /* The parser reports a truncation instead of the elements it did read. */ + sieve = pb_any; + for (len = 4; len < b->len; len++) { + KUNIT_ASSERT_EQ(test, parse(b->data, len, &ctx), 0); + KUNIT_EXPECT_LT_MSG(test, parse_sound_constraints(&ctx, &sieve, &hits), 0, + "prefix %u of %u", len, b->len); + } +} + +static void parser_bounds_sound_mode_test(struct kunit *test) +{ + struct dcp_sound_format_mask sieve = { + .formats = SNDRV_PCM_FMTBIT_S24, + .rates = SNDRV_PCM_RATE_48000, + .nchans = BIT(8), + }; + struct snd_pcm_chmap_elem chmap = {}; + struct dcp_sound_cookie cookie = {}; + struct dcp_parse_ctx ctx; + struct pb *b = pb_audio(test, DCP_SOUND_COOKIE_SIZE, true); + u32 len; + + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), 1); + KUNIT_ASSERT_EQ(test, chmap.channels, 8); + KUNIT_EXPECT_EQ(test, chmap.map[0], SNDRV_CHMAP_FL); + KUNIT_EXPECT_EQ(test, chmap.map[3], SNDRV_CHMAP_LFE); + /* A label the table does not name. */ + KUNIT_EXPECT_EQ(test, chmap.map[6], SNDRV_CHMAP_UNKNOWN); + KUNIT_EXPECT_EQ(test, chmap.map[7], SNDRV_CHMAP_RC); + KUNIT_EXPECT_EQ(test, cookie.data[0], 1); + KUNIT_EXPECT_EQ(test, cookie.data[DCP_SOUND_COOKIE_SIZE - 1], DCP_SOUND_COOKIE_SIZE); + + /* No element matches. */ + sieve.rates = SNDRV_PCM_RATE_96000; + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), 0); + sieve.rates = SNDRV_PCM_RATE_48000; + + /* Link data shorter than the service takes. */ + b = pb_audio(test, DCP_SOUND_COOKIE_SIZE - 1, true); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_EXPECT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), -EINVAL); + +#if IS_ENABLED(CONFIG_DRM_APPLE_DCP_T6030_AUDIO) + /* The 14.7 external role takes 32 bytes. */ + b = pb_audio(test, DCP_SOUND_COOKIE_SIZE, true); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + ctx.v14_7_audio = true; + KUNIT_EXPECT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), -EINVAL); + b = pb_audio(test, DCP_SOUND_COOKIE_SIZE_V14_7, true); + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + ctx.v14_7_audio = true; + KUNIT_ASSERT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), 1); + KUNIT_EXPECT_EQ(test, cookie.data[DCP_SOUND_COOKIE_SIZE_V14_7 - 1], + DCP_SOUND_COOKIE_SIZE_V14_7); +#endif + + /* The matching element is the last: no prefix holds all of it. */ + b = pb_audio(test, DCP_SOUND_COOKIE_SIZE, false); + for (len = 4; len < b->len; len++) { + KUNIT_ASSERT_EQ(test, parse(b->data, len, &ctx), 0); + KUNIT_EXPECT_LT_MSG(test, parse_sound_mode(&ctx, &sieve, &chmap, &cookie), 0, + "prefix %u of %u", len, b->len); + } +} + +/* A layout with more labels than a channel map holds is cut at the map. */ +static void parser_bounds_sound_chmap_test(struct kunit *test) +{ + struct dcp_sound_format_mask sieve = pb_any; + struct snd_pcm_chmap_elem chmap = {}; + struct dcp_parse_ctx ctx; + struct pb *b = pb_new(test, true); + unsigned int i; + + sieve.nchans = BIT(2); + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 4); + pb_kint(b, "StreamSampleRate", 48000); + pb_kint(b, "SampleSize", 24); + pb_str(b, "AudioChannelLayoutElements"); + pb_tag(b, PB_ARRAY, 1); + pb_tag(b, PB_DICT, 2); + pb_kint(b, "ActiveChannelCount", 2); + pb_str(b, "ChannelLayout"); + pb_tag(b, PB_ARRAY, ARRAY_SIZE(chmap.map) + 5); + for (i = 0; i < ARRAY_SIZE(chmap.map) + 5; i++) + pb_str(b, i & 1 ? "Front Right" : "Front Left"); + pb_str(b, "ElementData"); + pb_tag(b, PB_BLOB, DCP_SOUND_COOKIE_MAX); + pb_raw(b, "abcdefghijklmnopqrstuvwxyz0123456789", DCP_SOUND_COOKIE_MAX); + + KUNIT_ASSERT_EQ(test, parse(b->data, b->len, &ctx), 0); + KUNIT_ASSERT_EQ(test, parse_sound_mode(&ctx, &sieve, &chmap, NULL), 1); + KUNIT_EXPECT_EQ(test, chmap.channels, ARRAY_SIZE(chmap.map)); + KUNIT_EXPECT_EQ(test, chmap.map[ARRAY_SIZE(chmap.map) - 1], SNDRV_CHMAP_FL); +} +#endif + +static struct kunit_case parser_bounds_cases[] = { + KUNIT_CASE(parser_bounds_framing_test), + KUNIT_CASE(parser_bounds_depth_test), + KUNIT_CASE(parser_bounds_array_count_test), + KUNIT_CASE(parser_bounds_metadata_test), + KUNIT_CASE(parser_bounds_metadata_truncated_test), + KUNIT_CASE(parser_bounds_metadata_defaults_test), + KUNIT_CASE(parser_bounds_metadata_keys_test), + KUNIT_CASE(parser_bounds_product_test), + KUNIT_CASE(parser_bounds_dptx_caps_test), + KUNIT_CASE(parser_bounds_mnits_test), + KUNIT_CASE(parser_bounds_mnits_pairs_test), + KUNIT_CASE(parser_bounds_timing_ids_test), + KUNIT_CASE(parser_bounds_timing_colors_test), + KUNIT_CASE(parser_bounds_timing_colors_lists_test), + KUNIT_CASE(parser_bounds_edid_raw_test), + KUNIT_CASE(parser_bounds_edid_serialized_test), + KUNIT_CASE(parser_bounds_default_above_test), +#if IS_ENABLED(CONFIG_DRM_APPLE_AUDIO) + KUNIT_CASE(parser_bounds_sound_constraints_test), + KUNIT_CASE(parser_bounds_sound_wide_layouts_test), + KUNIT_CASE(parser_bounds_sound_wide_layout_map_test), + KUNIT_CASE(parser_bounds_sound_mode_test), + KUNIT_CASE(parser_bounds_sound_chmap_test), +#endif + {} +}; + +static struct kunit_suite parser_bounds_suite = { + .name = "apple-dcp-parser-bounds", + .test_cases = parser_bounds_cases, +}; + +kunit_test_suite(parser_bounds_suite); From 92f0abe9dce376a4f41e0ea5654d9824da7141d0 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:09 +1100 Subject: [PATCH 10/13] media: apple: ave: add IPC and writer KUnit tests Add two suites for the input the AVE driver takes from the firmware and from user space: apple-ave-ipc (20 cases), included from ave-ipc.c: hello words, channel tables with overlapping or out-of-range rings, ring index wrap, full and empty rings, command acks and messages outside the shared window, log lines and shared-memory requests, including the near-4 GiB requests fixed earlier in this series. apple-ave-writer (8 cases): the 6070 Start and Process builders refuse out-of-range session counts, unaligned buffers and short codec state before they write anything. The shared window and the mailbox are kernel memory; no firmware or encoder hardware is needed. Signed-off-by: Ryan Murray --- drivers/media/platform/apple/ave/Kconfig | 14 + drivers/media/platform/apple/ave/Makefile | 1 + .../media/platform/apple/ave/ave-ipc-test.c | 1129 +++++++++++++++++ drivers/media/platform/apple/ave/ave-ipc.c | 4 + .../platform/apple/ave/ave-writer-test.c | 438 +++++++ 5 files changed, 1586 insertions(+) create mode 100644 drivers/media/platform/apple/ave/ave-ipc-test.c create mode 100644 drivers/media/platform/apple/ave/ave-writer-test.c diff --git a/drivers/media/platform/apple/ave/Kconfig b/drivers/media/platform/apple/ave/Kconfig index 0924ce4621027..c4c4c5038d66a 100644 --- a/drivers/media/platform/apple/ave/Kconfig +++ b/drivers/media/platform/apple/ave/Kconfig @@ -44,3 +44,17 @@ config VIDEO_APPLE_AVE_CMD_KUNIT_TEST entropy interleave, alignment refusal, seven-channel discovery and encoding refusal. These tests run without firmware or encoder hardware. + +config VIDEO_APPLE_AVE_IPC_KUNIT_TEST + bool "KUnit tests for Apple AVE firmware and userspace input checks" if !KUNIT_ALL_TESTS + depends on KUNIT=y && VIDEO_APPLE_AVE=y + default KUNIT_ALL_TESTS + help + Feed malformed firmware input to the AVE IPC layer: hello words, + channel tables with overlapping or out-of-range rings, ring index + wrap, full and empty rings, command acks and messages outside the + shared window, log lines and shared-memory requests. Also test that + the 6070 Start and Process builders refuse out-of-range session + counts, unaligned buffers and short codec state before writing. + The tests use kernel memory for the shared window and the mailbox + and run without firmware or encoder hardware. diff --git a/drivers/media/platform/apple/ave/Makefile b/drivers/media/platform/apple/ave/Makefile index 03d3b1bba4978..237f51e0e0f30 100644 --- a/drivers/media/platform/apple/ave/Makefile +++ b/drivers/media/platform/apple/ave/Makefile @@ -5,3 +5,4 @@ obj-$(CONFIG_VIDEO_APPLE_AVE) += apple-ave-dma.o apple-ave-y := ave-drv.o ave-fw.o ave-ipc.o ave-cmd.o ave-writer.o ave-abi.o ave-layout.o ave-image.o ave-sess.o ave-v4l2.o ave-vb2.o ave-mctf.o ave-mctf-v4l2.o ave-cmp420.o obj-$(CONFIG_VIDEO_APPLE_AVE_KUNIT_TEST) += ave-sizes-test.o ave-recovery-test.o obj-$(CONFIG_VIDEO_APPLE_AVE_CMD_KUNIT_TEST) += ave-abi-test.o ave-mctf-test.o ave-cmp420-test.o +obj-$(CONFIG_VIDEO_APPLE_AVE_IPC_KUNIT_TEST) += ave-writer-test.o diff --git a/drivers/media/platform/apple/ave/ave-ipc-test.c b/drivers/media/platform/apple/ave/ave-ipc-test.c new file mode 100644 index 0000000000000..40f32562ff3b9 --- /dev/null +++ b/drivers/media/platform/apple/ave/ave-ipc-test.c @@ -0,0 +1,1129 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the AVE IPC parsers and bounds checks: everything the + * firmware writes into the shared window (hello words, channel tables, ring + * slots, acks, messages, shared-memory requests) must stay inside it. + * + * Included at the end of ave-ipc.c to reach its static helpers. The shared + * window and the mailbox are plain kernel memory; no hardware is touched. + * + * Copyright The Aurora Silicon Contributors + */ +#include +#include + +#define T_FW_BASE 0x100000000ULL +/* Large enough to hold the whole 6070 command area. */ +#define T_IPC_BYTES 0x160000 +/* Bytes past ipc.size kept as a canary: nothing may write there. */ +#define T_CANARY_BYTES SZ_16K +#define T_CANARY 0xa5 + +struct t_ipc { + struct ave_dev *ave; + struct ave_fw_transport *t; + struct ave_fw_abi *abi; + struct ave_fw_layout *layout; +}; + +/* A device with a private copy of @base's layout, ABI and transport. */ +static void t_ipc_init(struct kunit *test, struct t_ipc *ti, + const struct ave_fw_layout *base, size_t ipc_bytes) +{ + struct ave_dev *ave = kunit_kzalloc(test, sizeof(*ave), GFP_KERNEL); + static atomic_t seq = ATOMIC_INIT(0); + char name[32]; + + KUNIT_ASSERT_NOT_NULL(test, ave); + ti->ave = ave; + ti->t = kunit_kmalloc(test, sizeof(*ti->t), GFP_KERNEL); + ti->abi = kunit_kmalloc(test, sizeof(*ti->abi), GFP_KERNEL); + ti->layout = kunit_kmalloc(test, sizeof(*ti->layout), GFP_KERNEL); + KUNIT_ASSERT_TRUE(test, ti->t && ti->abi && ti->layout); + *ti->layout = *base; + *ti->abi = *base->abi; + *ti->t = *base->abi->transport; + ti->abi->transport = ti->t; + ti->layout->abi = ti->abi; + ave->layout = ti->layout; + ave->variant = &ave_t6000; + + /* Several devices per case; names must be unique. */ + snprintf(name, sizeof(name), "apple-ave-ipc-%d", atomic_inc_return(&seq)); + ave->dev = kunit_device_register(test, name); + KUNIT_ASSERT_FALSE(test, IS_ERR(ave->dev)); + ave->ipc.cpu = kunit_kzalloc(test, ipc_bytes + T_CANARY_BYTES, + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, ave->ipc.cpu); + memset(ave->ipc.cpu + ipc_bytes, T_CANARY, T_CANARY_BYTES); + ave->ipc.size = ipc_bytes; + ave->ipc_fw_base = T_FW_BASE; + ave->mbox = (void __iomem __force *)kunit_kzalloc(test, SZ_4K, + GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, (void __force *)ave->mbox); + spin_lock_init(&ave->irq_lock); + init_waitqueue_head(&ave->irq_wait); + ave->fw_state = AVE_FW_RUNNING; +} + +static void t_canary_intact(struct kunit *test, struct ave_dev *ave) +{ + KUNIT_EXPECT_NULL(test, memchr_inv(ave->ipc.cpu + ave->ipc.size, + T_CANARY, T_CANARY_BYTES)); +} + +static __le64 *t_slot(struct ave_dev *ave, const struct ave_ring *r, + unsigned int n) +{ + return ave->ipc.cpu + r->offset + n * AVE_RING_SLOT_BYTES; +} + +/* Lay out one ring as ave_ipc_parse_channels() leaves it. */ +static void t_ring(struct ave_dev *ave, unsigned int id, u32 offset, + u32 slots, u32 doorbell, bool to_host) +{ + struct ave_ring *r = &ave->ring[id]; + + *r = (struct ave_ring){ + .mode = to_host ? 0 : 1, + .doorbell = doorbell, + .slots = slots, + .offset = AVE_IPC_CHANNEL_OFF + offset, + .consumer = to_host ? 0 : -1, + .producer = to_host ? -1 : 0, + }; + /* + * Bit 0 set: a host-to-firmware slot is free for the host, a + * firmware-to-host slot still belongs to the firmware. + */ + for (unsigned int n = 0; n < slots; n++) + *t_slot(ave, r, n) = cpu_to_le64(1); +} + +/* IO and IO_T2H with four slots each, as on 6070. */ +static void t_rings(struct ave_dev *ave) +{ + memset(ave->ring, 0, sizeof(ave->ring)); + t_ring(ave, AVE_RING_IO, 0x800, 4, 1, false); + t_ring(ave, AVE_RING_T2H, 0xa00, 4, 3, true); +} + +/* Play the firmware: post @addr/@len to the host in ring slot @n. */ +static void t_fw_post(struct ave_dev *ave, unsigned int id, unsigned int n, + u64 addr, u64 len) +{ + __le64 *slot = t_slot(ave, &ave->ring[id], n); + + slot[1] = cpu_to_le64(len); + slot[2] = 0; + /* Host-to-firmware slots are acked by setting bit 0, others by clearing it. */ + slot[0] = cpu_to_le64(addr | ave->ring[id].mode); +} + +static void t_ring_indices_valid(struct kunit *test, const struct ave_ring *r) +{ + KUNIT_EXPECT_GE(test, r->consumer, -1); + KUNIT_EXPECT_LT(test, r->consumer, (int)r->slots); + KUNIT_EXPECT_GE(test, r->producer, -1); + KUNIT_EXPECT_LT(test, r->producer, (int)r->slots); +} + +/* 9003 hello: the descriptor area and the heap are both bounded. */ +static void ave_ipc_test_hello_9003(struct kunit *test) +{ + const struct ave_fw_transport *t = ave_abi_9003.transport; + u32 min = t->descriptors * AVE_CHAN_DESC_STRIDE; + u32 max = AVE_IPC_HANDSHAKE_OFF - AVE_IPC_CHANNEL_OFF; + u32 hello[4] = { t->hello[0], min, t->hello[2], SZ_1M }; + + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), 0); + hello[1] = min - 1; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[1] = max; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), 0); + /* A channel area running into the handshake block. */ + hello[1] = max + 1; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[1] = U32_MAX; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[1] = min; + /* 9003 always asks for a heap, never more than 4 MiB. */ + hello[3] = 0; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[3] = 4 * SZ_1M; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), 0); + hello[3] = 4 * SZ_1M + 1; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[3] = U32_MAX; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[3] = SZ_1M; + hello[0] = t->hello[0] + 1; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); + hello[0] = t->hello[0]; + hello[2] = 0; + KUNIT_EXPECT_EQ(test, ave_ipc_check_hello(t, hello), -EPROTO); +} + +/* A bad hello is refused before the mailbox or the window are touched. */ +static void ave_ipc_test_negotiate_bad_hello(struct kunit *test) +{ + struct t_ipc ti; + u32 hello[4]; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + memcpy(hello, ti.t->hello, sizeof(hello)); + hello[1]++; + KUNIT_EXPECT_EQ(test, ave_ipc_negotiate(ti.ave, hello), -EPROTO); + KUNIT_EXPECT_EQ(test, readl(ti.ave->mbox + AVE_MBOX_DOORBELL), 0U); + KUNIT_EXPECT_EQ(test, ti.ave->channel_bytes, 0U); + /* A heap larger than 4 MiB is not allocated either. */ + memcpy(hello, ti.t->hello, sizeof(hello)); + hello[3] = 4 * SZ_1M + 1; + KUNIT_EXPECT_EQ(test, ave_ipc_negotiate(ti.ave, hello), -EPROTO); + KUNIT_EXPECT_NULL(test, ti.ave->heap.cpu); +} + +/* + * The fake mailbox answers with the words the host wrote, so the IPC window + * address the "firmware" reports is ipc.dma. It must be 16 KiB aligned and + * the whole window must fit below 2^64. + */ +static void ave_ipc_test_negotiate_window(struct kunit *test) +{ + static const u64 bad[] = { + 0, T_FW_BASE + SZ_4K, 0xffffffffffffc000ULL, + }; + struct t_ipc ti; + u8 *hs; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + hs = ti.ave->ipc.cpu + AVE_IPC_HANDSHAKE_OFF; + for (unsigned int i = 0; i < ARRAY_SIZE(bad); i++) { + ti.ave->ipc.dma = bad[i]; + memset(ti.ave->ipc.cpu + AVE_IPC_CHANNEL_OFF, T_CANARY, 0x100); + KUNIT_EXPECT_EQ(test, ave_ipc_negotiate(ti.ave, ti.t->hello), + -EPROTO); + /* Nothing was cleared or handed to the firmware. */ + KUNIT_EXPECT_EQ(test, + *(u8 *)(ti.ave->ipc.cpu + AVE_IPC_CHANNEL_OFF), + T_CANARY); + } + + /* + * A good window gets the handshake block, but the echoed handshake + * address is not the channel area: refused before any channel is parsed. + */ + ti.ave->ipc.dma = T_FW_BASE; + KUNIT_EXPECT_EQ(test, ave_ipc_negotiate(ti.ave, ti.t->hello), -EPROTO); + KUNIT_EXPECT_EQ(test, ti.ave->ipc_fw_base, T_FW_BASE); + KUNIT_EXPECT_EQ(test, ti.ave->channel_bytes, ti.t->hello[1]); + KUNIT_EXPECT_EQ(test, get_unaligned_le64(hs + AVE_HS_CHANNELS), + T_FW_BASE + AVE_IPC_CHANNEL_OFF); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(hs + AVE_HS_DEVICE_TYPE), + ave_t6000.device_type); + KUNIT_EXPECT_EQ(test, ti.ave->ring[AVE_RING_IO].slots, 0U); + t_canary_intact(test, ti.ave); +} + +/* A two-descriptor (9003-style) table: IO then IO_T2H. */ +#define T_CHAN_BYTES 0x1000 + +static u8 *t_desc(struct ave_dev *ave, unsigned int i) +{ + return ave->ipc.cpu + AVE_IPC_CHANNEL_OFF + i * AVE_CHAN_DESC_STRIDE; +} + +static void t_write_desc(struct ave_dev *ave, unsigned int i, const char *name, + u32 dir, u32 doorbell, u32 slots, u64 addr) +{ + u8 *desc = t_desc(ave, i); + + memset(desc, 0, AVE_CHAN_DESC_STRIDE); + strscpy(desc, name, AVE_CHAN_DESC_NAME_LEN); + put_unaligned_le32(dir, desc + AVE_CHAN_DESC_DIR); + put_unaligned_le32(doorbell, desc + AVE_CHAN_DESC_IRQ); + put_unaligned_le32(slots, desc + AVE_CHAN_DESC_SLOTS); + put_unaligned_le64(addr, desc + AVE_CHAN_DESC_ADDR); +} + +static u64 t_chan_addr(u32 off) +{ + return T_FW_BASE + AVE_IPC_CHANNEL_OFF + off; +} + +static void t_table_9003(struct ave_dev *ave) +{ + t_write_desc(ave, 0, "IO", 0, 1, 8, t_chan_addr(0x200)); + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, t_chan_addr(0x400)); +} + +static void t_channels_init(struct kunit *test, struct t_ipc *ti) +{ + t_ipc_init(test, ti, &ave_layout_9003_78_0, T_IPC_BYTES); + ti->ave->channel_bytes = T_CHAN_BYTES; + t_table_9003(ti->ave); + KUNIT_ASSERT_EQ(test, ave_ipc_parse_channels(ti->ave), 0); +} + +static void ave_ipc_test_channels_9003(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + + t_channels_init(test, &ti); + ave = ti.ave; + KUNIT_EXPECT_STREQ(test, ave->ring[AVE_RING_IO].name, "IO"); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].offset, + AVE_IPC_CHANNEL_OFF + 0x200); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].mode, 1U); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].producer, 0); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].consumer, -1); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_T2H].mode, 0U); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_T2H].producer, -1); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_T2H].consumer, 0); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_SMALLOC].slots, 0U); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_LOG].slots, 0U); + for (unsigned int n = 0; n < 8; n++) + KUNIT_EXPECT_EQ(test, + le64_to_cpu(*t_slot(ave, &ave->ring[AVE_RING_IO], n)), + 1ULL); + /* The slot after the ring is not handed over. */ + KUNIT_EXPECT_EQ(test, + le64_to_cpu(*t_slot(ave, &ave->ring[AVE_RING_IO], 8)), + 0ULL); + + /* The last ring may end exactly at the end of the channel area. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(T_CHAN_BYTES - 8 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + /* Doorbell 31 is the last mailbox bit. */ + t_write_desc(ave, 1, "IO_T2H", 1, 31, 8, t_chan_addr(0x400)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_T2H].doorbell, 31U); + /* Order does not matter on a table with no fixed indices. */ + t_write_desc(ave, 0, "IO_T2H", 1, 3, 8, t_chan_addr(0x400)); + t_write_desc(ave, 1, "IO", 0, 1, 8, t_chan_addr(0x200)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].offset, + AVE_IPC_CHANNEL_OFF + 0x200); +} + +/* Every malformed descriptor the firmware could write is refused. */ +static void ave_ipc_test_channels_malformed(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + u8 *desc; + + t_channels_init(test, &ti); + ave = ti.ave; + desc = t_desc(ave, 0); + + /* A name with no terminating NUL in its 64 bytes. */ + memset(desc, 'A', AVE_CHAN_DESC_NAME_LEN); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + /* A two-channel table has no room for unknown channels. */ + t_write_desc(ave, 0, "DEBUG", 0, 1, 8, t_chan_addr(0x200)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + /* Wrong direction. */ + put_unaligned_le32(1, desc + AVE_CHAN_DESC_DIR); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + put_unaligned_le32(2, desc + AVE_CHAN_DESC_DIR); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + /* Doorbells outside the 32-bit doorbell register, or none for IO. */ + put_unaligned_le32(32, desc + AVE_CHAN_DESC_IRQ); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + put_unaligned_le32(U32_MAX, desc + AVE_CHAN_DESC_IRQ); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + put_unaligned_le32(0, desc + AVE_CHAN_DESC_IRQ); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + /* No slots. */ + put_unaligned_le32(0, desc + AVE_CHAN_DESC_SLOTS); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* More slots than the channel area holds (slots * 64 wraps in u32). */ + put_unaligned_le32(T_CHAN_BYTES / AVE_RING_SLOT_BYTES + 1, + desc + AVE_CHAN_DESC_SLOTS); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + put_unaligned_le32(0x04000000, desc + AVE_CHAN_DESC_SLOTS); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + put_unaligned_le32(U32_MAX, desc + AVE_CHAN_DESC_SLOTS); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + /* Two IO channels and no IO_T2H. */ + t_write_desc(ave, 1, "IO", 0, 1, 8, t_chan_addr(0x400)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* Two IO_T2H channels and no IO. */ + t_write_desc(ave, 0, "IO_T2H", 1, 3, 8, t_chan_addr(0x200)); + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, t_chan_addr(0x400)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_9003(ave); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); +} + +/* Ring addresses must land inside the channel area, past the descriptors. */ +static void ave_ipc_test_channels_out_of_range(struct kunit *test) +{ + static const u64 bad[] = { + /* Below the window, and far below it (u64 wrap). */ + T_FW_BASE - AVE_RING_SLOT_BYTES, + 0, + /* Not slot aligned. */ + T_FW_BASE + AVE_IPC_CHANNEL_OFF + 0x208, + /* On top of the descriptor table. */ + T_FW_BASE + AVE_IPC_CHANNEL_OFF, + T_FW_BASE + AVE_IPC_CHANNEL_OFF + 2 * AVE_CHAN_DESC_STRIDE - + AVE_RING_SLOT_BYTES, + /* One slot past the end of the channel area. */ + T_FW_BASE + AVE_IPC_CHANNEL_OFF + T_CHAN_BYTES - + 7 * AVE_RING_SLOT_BYTES, + /* Inside the window but past the channel area. */ + T_FW_BASE + AVE_IPC_HANDSHAKE_OFF, + /* Past the window, and at the top of the address space. */ + T_FW_BASE + T_IPC_BYTES, + U64_MAX & ~(u64)(AVE_RING_SLOT_BYTES - 1), + }; + struct ave_dev *ave; + struct t_ipc ti; + + t_channels_init(test, &ti); + ave = ti.ave; + for (unsigned int i = 0; i < ARRAY_SIZE(bad); i++) { + for (unsigned int d = 0; d < 2; d++) { + t_table_9003(ave); + put_unaligned_le64(bad[i], t_desc(ave, d) + AVE_CHAN_DESC_ADDR); + KUNIT_EXPECT_EQ_MSG(test, ave_ipc_parse_channels(ave), -EPROTO, + "descriptor %u at %#llx", d, bad[i]); + } + } + t_canary_intact(test, ave); +} + +/* Rings may touch but not share a slot. */ +static void ave_ipc_test_channels_overlap(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + + t_channels_init(test, &ti); + ave = ti.ave; + /* IO_T2H starting in IO's last slot. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(0x200 + 7 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* Same place. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, t_chan_addr(0x200)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* A one-slot ring inside the other. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 1, + t_chan_addr(0x200 + 3 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* Back to back, either way round. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(0x200 + 8 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + /* IO further up, so that IO_T2H can sit right below it. */ + t_write_desc(ave, 0, "IO", 0, 1, 8, t_chan_addr(0x600)); + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(0x600 - 8 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + /* IO_T2H ending in IO's first slot. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(0x600 - 7 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* IO_T2H starting in IO's last slot. */ + t_write_desc(ave, 1, "IO_T2H", 1, 3, 8, + t_chan_addr(0x600 + 7 * AVE_RING_SLOT_BYTES)); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); +} + +/* The 6070 table: unknown channels are skipped but still bounds checked. */ +static const struct { + const char *name; + u32 dir, doorbell, slots, offset; +} t_6070_desc[] = { + { "TERMINAL", 2, 0, 512, 0x700 }, { "IO", 0, 1, 32, 0x8700 }, + { "DEBUG", 0, 1, 8, 0x8f00 }, { "BUF_H2T", 0, 2, 1, 0x9100 }, + { "BUF_T2H", 1, 3, 1, 0x9140 }, { "SHAREDMALLOC", 1, 3, 8, 0x9180 }, + { "IO_T2H", 1, 3, 32, 0x9380 }, +}; + +static void t_table_6070(struct ave_dev *ave) +{ + for (unsigned int i = 0; i < ARRAY_SIZE(t_6070_desc); i++) + t_write_desc(ave, i, t_6070_desc[i].name, t_6070_desc[i].dir, + t_6070_desc[i].doorbell, t_6070_desc[i].slots, + t_chan_addr(t_6070_desc[i].offset)); +} + +static void ave_ipc_test_channels_6070_unknown(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + u8 *debug; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti.ave; + ave->channel_bytes = ti.t->hello[1]; + t_table_6070(ave); + KUNIT_ASSERT_EQ(test, ave_ipc_parse_channels(ave), 0); + + debug = t_desc(ave, 2); + /* An unused channel pointing past the channel area. */ + put_unaligned_le64(t_chan_addr(ave->channel_bytes), debug + AVE_CHAN_DESC_ADDR); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* Or outside the window altogether. */ + put_unaligned_le64(T_FW_BASE + T_IPC_BYTES, debug + AVE_CHAN_DESC_ADDR); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + /* Or with an unterminated name. */ + t_table_6070(ave); + memset(debug, 'D', AVE_CHAN_DESC_NAME_LEN); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_6070(ave); + /* IO must be exactly where this firmware puts it. */ + put_unaligned_le64(t_chan_addr(0x8700 + AVE_RING_SLOT_BYTES), + t_desc(ave, 1) + AVE_CHAN_DESC_ADDR); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_6070(ave); + put_unaligned_le32(2, t_desc(ave, 6) + AVE_CHAN_DESC_IRQ); + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), -EPROTO); + t_table_6070(ave); + /* With no shared-memory pool, SHAREDMALLOC is an unknown channel. */ + ti.t->smalloc_bytes = 0; + KUNIT_EXPECT_EQ(test, ave_ipc_parse_channels(ave), 0); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_SMALLOC].slots, 0U); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_LOG].slots, 512U); + t_canary_intact(test, ave); +} + +/* Host-to-firmware ring: fill, refuse when full, wrap, drain to empty. */ +static void ave_ipc_test_ring_h2f(struct kunit *test) +{ + struct ave_ring *r; + struct ave_dev *ave; + struct t_ipc ti; + u64 addr; + u32 len; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti.ave; + t_rings(ave); + r = &ave->ring[AVE_RING_IO]; + + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), -EAGAIN); + for (unsigned int n = 0; n < 4; n++) { + KUNIT_ASSERT_EQ(test, ave_ring_send(ave, r, 0x1000 * (n + 1), 0x40 + n), 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, n)[0]), + 0x1000ULL * (n + 1)); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, n)[1]), + 0x40ULL + n); + t_ring_indices_valid(test, r); + } + KUNIT_EXPECT_EQ(test, readl(ave->mbox + AVE_MBOX_DOORBELL), BIT(1)); + /* Full: a fifth command must not overwrite one the firmware owns. */ + KUNIT_EXPECT_EQ(test, r->producer, -1); + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, 0x9000, 0x99), -ENOSPC); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, 0)[0]), 0x1000ULL); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, 0)[1]), 0x40ULL); + + /* Not acked yet. */ + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), -EAGAIN); + /* The ack of slot 0 frees exactly that slot. */ + t_fw_post(ave, AVE_RING_IO, 0, 0x1000, 0); + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), 0); + KUNIT_EXPECT_EQ(test, addr, 0x1000ULL); + KUNIT_EXPECT_EQ(test, len, 0U); + KUNIT_EXPECT_EQ(test, r->producer, 0); + KUNIT_EXPECT_EQ(test, r->consumer, 1); + /* Wrap into slot 0; the ring is full again. */ + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, 0x5000, 0x44), 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, 0)[0]), 0x5000ULL); + KUNIT_EXPECT_EQ(test, r->producer, -1); + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, 0x9000, 0x99), -ENOSPC); + + /* Acks come back in ring order 1, 2, 3, 0. */ + for (unsigned int k = 0; k < 4; k++) { + unsigned int n = (k + 1) % 4; + u64 want = n ? 0x1000ULL * (n + 1) : 0x5000ULL; + + t_fw_post(ave, AVE_RING_IO, n, want, 0); + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), 0); + KUNIT_EXPECT_EQ(test, addr, want); + t_ring_indices_valid(test, r); + } + /* Empty. */ + KUNIT_EXPECT_EQ(test, r->consumer, -1); + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), -EAGAIN); + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, 0x6000, 0x40), 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, 1)[0]), 0x6000ULL); +} + +/* Firmware-to-host ring: the two low bits never reach the address. */ +static void ave_ipc_test_ring_f2h(struct kunit *test) +{ + struct ave_ring *r; + struct ave_dev *ave; + struct t_ipc ti; + u64 addr; + u32 len; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti.ave; + t_rings(ave); + r = &ave->ring[AVE_RING_T2H]; + + /* Every slot still belongs to the firmware. */ + KUNIT_EXPECT_EQ(test, ave_ring_recv(ave, r, &addr, &len), -EAGAIN); + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, 0x1000, 0x40), -ENOSPC); + for (unsigned int k = 0; k < 6; k++) { + unsigned int n = k % 4; + + t_fw_post(ave, AVE_RING_T2H, n, 0x2000 * (k + 1) | 2, 0x40); + KUNIT_ASSERT_EQ(test, ave_ring_recv(ave, r, &addr, &len), 0); + KUNIT_EXPECT_EQ(test, addr, 0x2000ULL * (k + 1)); + KUNIT_EXPECT_EQ(test, len, 0x40U); + /* Next to read is the following slot, next to give back this one. */ + KUNIT_EXPECT_EQ(test, r->consumer, (int)((n + 1) % 4)); + KUNIT_EXPECT_EQ(test, r->producer, (int)n); + /* Give it back: bit 0 set hands the slot to the firmware. */ + KUNIT_ASSERT_EQ(test, ave_ring_send(ave, r, addr, len), 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, n)[0]), addr | 1); + KUNIT_EXPECT_EQ(test, r->consumer, (int)((n + 1) % 4)); + KUNIT_EXPECT_EQ(test, r->producer, -1); + KUNIT_EXPECT_EQ(test, ave_ring_send(ave, r, addr, len), -ENOSPC); + } + KUNIT_EXPECT_EQ(test, readl(ave->mbox + AVE_MBOX_DOORBELL), BIT(3)); +} + +/* Every command buffer maps to its own offset and back; nothing else does. */ +static void ave_ipc_test_buf_of(struct kunit *test) +{ + const struct ave_fw_layout *layouts[] = { + &ave_layout_9003_78_0, &ave_layout_6070_11_1, + }; + + for (unsigned int l = 0; l < ARRAY_SIZE(layouts); l++) { + const struct ave_fw_transport *t; + struct ave_dev *ave; + struct t_ipc ti; + size_t max, prev_end = 0; + int off; + + t_ipc_init(test, &ti, layouts[l], SZ_4K); + ave = ti.ave; + t = ti.t; + for (unsigned int buf = 0; buf < AVE_BUF_COUNT; buf++) { + off = ave_ipc_buf_offset(ave, buf, &max); + KUNIT_EXPECT_GE(test, off, (int)t->command_offset); + KUNIT_EXPECT_GE(test, (size_t)off, prev_end); + KUNIT_EXPECT_LE(test, off + max, ave_ipc_command_end(ave)); + prev_end = off + max; + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, T_FW_BASE + off), + (int)buf); + /* Inside a buffer is not a buffer. */ + KUNIT_EXPECT_EQ(test, + ave_ipc_buf_of(ave, T_FW_BASE + off + 4), + -EPROTO); + } + KUNIT_EXPECT_EQ(test, prev_end, (size_t)ave_ipc_command_end(ave)); + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, 0), -EPROTO); + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, T_FW_BASE - 1), -EPROTO); + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, T_FW_BASE), -EPROTO); + KUNIT_EXPECT_EQ(test, + ave_ipc_buf_of(ave, T_FW_BASE + t->command_offset - 4), + -EPROTO); + KUNIT_EXPECT_EQ(test, + ave_ipc_buf_of(ave, T_FW_BASE + ave_ipc_command_end(ave)), + -EPROTO); + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, U64_MAX), -EPROTO); + /* A buffer offset with no window base under it. */ + KUNIT_EXPECT_EQ(test, ave_ipc_buf_of(ave, t->command_offset), -EPROTO); + } +} + +/* A command buffer is only handed out when it fits the window. */ +static void ave_ipc_test_cmd_bounds(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + size_t max; + int off; + u8 *cmd; + + /* A window that ends half way into the first Process buffer. */ + t_ipc_init(test, &ti, &ave_layout_6070_11_1, + ave_layout_6070_11_1.abi->transport->process_offset + SZ_32K); + ave = ti.ave; + + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_COUNT, 4)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, U32_MAX, 4)); + off = ave_ipc_buf_offset(ave, AVE_BUF_CMD, &max); + memset(ave->ipc.cpu + off, 0x5a, 0x100); + cmd = ave_ipc_cmd(ave, AVE_BUF_CMD, 0x80); + KUNIT_ASSERT_PTR_EQ(test, (void *)cmd, ave->ipc.cpu + off); + KUNIT_EXPECT_NULL(test, memchr_inv(cmd, 0, 0x80)); + KUNIT_EXPECT_EQ(test, cmd[0x80], 0x5a); + KUNIT_EXPECT_NOT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_CMD, max)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_CMD, max + 1)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_SCALAR(0), + AVE_IPC_SCALAR_BYTES + 1)); + KUNIT_EXPECT_NOT_NULL(test, + ave_ipc_cmd(ave, AVE_BUF_SCALAR(AVE_IPC_SCALAR_BUFS - 1), + AVE_IPC_SCALAR_BYTES)); + /* A buffer the firmware still owns is not handed out. */ + ave->unacked = BIT(AVE_BUF_SCALAR(3)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_SCALAR(3), 4)); + ave->unacked = 0; + /* Process buffer 0 fits up to the end of the window, not past it. */ + KUNIT_EXPECT_NOT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_PROC(0), SZ_32K)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_PROC(0), SZ_32K + 4)); + /* Process buffer 1 starts past the window. */ + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_PROC(1), 4)); + KUNIT_EXPECT_NULL(test, ave_ipc_cmd(ave, AVE_BUF_COUNT - 1, 4)); + t_canary_intact(test, ave); + + /* Submit applies the same bounds before it reads the command. */ + mutex_init(&ave->hw_lock); + mutex_lock(&ave->hw_lock); + KUNIT_EXPECT_EQ(test, ave_ipc_submit(ave, AVE_BUF_PROC(0), SZ_32K + 4, 0, false), + -EINVAL); + KUNIT_EXPECT_EQ(test, ave_ipc_submit(ave, AVE_BUF_PROC(1), 0x40, 0, false), + -EINVAL); + KUNIT_EXPECT_EQ(test, ave_ipc_submit(ave, AVE_BUF_COUNT, 0x40, 0, false), + -EINVAL); + mutex_unlock(&ave->hw_lock); + KUNIT_EXPECT_EQ(test, ave->unacked, 0U); + KUNIT_EXPECT_EQ(test, ave->ring[AVE_RING_IO].slots, 0U); +} + +/* Command acks: only the exact address of a buffer the firmware holds. */ +static void ave_ipc_test_poll_acks(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + u64 good; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti.ave; + good = T_FW_BASE + ti.t->scalar_offset + 2 * AVE_IPC_SCALAR_BYTES; + + /* Nothing pending. */ + t_rings(ave); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), 0); + + /* A good ack clears exactly its buffer. */ + ave->unacked = BIT(AVE_BUF_SCALAR(2)) | BIT(AVE_BUF_CMD); + KUNIT_ASSERT_EQ(test, ave_ring_send(ave, &ave->ring[AVE_RING_IO], good, 0x40), 0); + t_fw_post(ave, AVE_RING_IO, 0, good, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), 1); + KUNIT_EXPECT_EQ(test, ave->unacked, (u32)BIT(AVE_BUF_CMD)); + + /* An ack with a payload. */ + t_rings(ave); + ave->unacked = BIT(AVE_BUF_SCALAR(2)); + ave_ring_send(ave, &ave->ring[AVE_RING_IO], good, 0x40); + t_fw_post(ave, AVE_RING_IO, 0, good, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + KUNIT_EXPECT_EQ(test, ave->unacked, (u32)BIT(AVE_BUF_SCALAR(2))); + /* An ack inside a buffer. */ + t_rings(ave); + ave_ring_send(ave, &ave->ring[AVE_RING_IO], good, 0x40); + t_fw_post(ave, AVE_RING_IO, 0, good + 0x40, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + /* An ack outside the window. */ + t_rings(ave); + ave_ring_send(ave, &ave->ring[AVE_RING_IO], good, 0x40); + t_fw_post(ave, AVE_RING_IO, 0, good - T_FW_BASE - 0x1000000, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + /* An ack for a buffer the host never sent. */ + t_rings(ave); + ave_ring_send(ave, &ave->ring[AVE_RING_IO], good, 0x40); + t_fw_post(ave, AVE_RING_IO, 0, + T_FW_BASE + ti.t->scalar_offset + 3 * AVE_IPC_SCALAR_BYTES, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + KUNIT_EXPECT_EQ(test, ave->unacked, (u32)BIT(AVE_BUF_SCALAR(2))); +} + +/* Play the firmware: a 6070 lifecycle reply at window offset @off. */ +static void t_reply(struct t_ipc *ti, u32 off, enum ave_opcode op, u32 client, + u32 subtype, u32 status) +{ + u8 *msg = ti->ave->ipc.cpu + off; + + memset(msg, 0, 0x40); + put_unaligned_le16(ti->abi->reply_id[op], msg); + put_unaligned_le32(client, msg + 0x10); + put_unaligned_le32(subtype, msg + 0x1c); + put_unaligned_le32(status, msg + 0x38); +} + +#define T_MSG_OFF AVE_IPC_SHARED_OFF +#define T_REPLY_OK 0x00ee0000 + +static void t_msg_init(struct kunit *test, struct t_ipc *ti) +{ + struct ave_dev *ave; + + t_ipc_init(test, ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti->ave; + t_rings(ave); + ave->want[AVE_OP_OPEN] = 1; + ave->expected[AVE_OP_OPEN].client = 10; + ave->expected[AVE_OP_OPEN].subtype = ti->abi->semantic[AVE_OP_OPEN]; + t_reply(ti, T_MSG_OFF, AVE_OP_OPEN, 10, ti->abi->semantic[AVE_OP_OPEN], + T_REPLY_OK); + memset(ave->msg, 0x5a, sizeof(ave->msg)); +} + +/* The message is copied only when it lies inside the window, outside the commands. */ +static void ave_ipc_test_poll_msg_bounds(struct kunit *test) +{ + const struct ave_fw_transport *t = ave_layout_6070_11_1.abi->transport; + static const struct { + u64 off; + u64 len; + } bad[] = { + /* Larger than the host's message buffer. */ + { T_MSG_OFF, AVE_MSG_MAX + 1 }, + { T_MSG_OFF, U32_MAX }, + /* Running off the end of the window. */ + { T_IPC_BYTES - 0x20, 0x40 }, + { T_IPC_BYTES, 0x40 }, + /* In, or straddling into or out of, the command buffers. */ + { 0x40000, 0x40 }, + { 0x40000 - 0x20, 0x40 }, + { 0x78000 + AVE_IPC_PROC_BUFS * 0x10000 - 0x20, 0x40 }, + }; + struct t_ipc ti; + + /* The offsets above are the 6070 command area. */ + KUNIT_ASSERT_EQ(test, t->command_offset, 0x40000U); + KUNIT_ASSERT_EQ(test, t->process_offset + AVE_IPC_PROC_BUFS * t->process_bytes, + 0x78000U + AVE_IPC_PROC_BUFS * 0x10000); + for (unsigned int i = 0; i < ARRAY_SIZE(bad); i++) { + t_msg_init(test, &ti); + t_fw_post(ti.ave, AVE_RING_T2H, 0, T_FW_BASE + bad[i].off, bad[i].len); + KUNIT_EXPECT_EQ_MSG(test, ave_ipc_poll_once(ti.ave), -EPROTO, + "message %#llx/%#llx", bad[i].off, bad[i].len); + KUNIT_EXPECT_NULL(test, memchr_inv(ti.ave->msg, 0x5a, sizeof(ti.ave->msg))); + KUNIT_EXPECT_EQ(test, ti.ave->want[AVE_OP_OPEN], 1); + } + /* Below the window, and an address that only wraps into it. */ + t_msg_init(test, &ti); + t_fw_post(ti.ave, AVE_RING_T2H, 0, T_FW_BASE - 0x40, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ti.ave), -EPROTO); + t_msg_init(test, &ti); + t_fw_post(ti.ave, AVE_RING_T2H, 0, T_MSG_OFF - T_FW_BASE, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ti.ave), -EPROTO); + KUNIT_EXPECT_NULL(test, memchr_inv(ti.ave->msg, 0x5a, sizeof(ti.ave->msg))); + + /* Right below the command area is fine. */ + t_msg_init(test, &ti); + t_reply(&ti, 0x40000 - 0x40, AVE_OP_OPEN, 10, + ti.abi->semantic[AVE_OP_OPEN], T_REPLY_OK); + t_fw_post(ti.ave, AVE_RING_T2H, 0, T_FW_BASE + 0x40000 - 0x40, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ti.ave), 1); + KUNIT_EXPECT_EQ(test, ti.ave->want[AVE_OP_OPEN], 0); + /* So is right after it. */ + t_msg_init(test, &ti); + t_reply(&ti, 0x78000 + AVE_IPC_PROC_BUFS * 0x10000, AVE_OP_OPEN, 10, + ti.abi->semantic[AVE_OP_OPEN], T_REPLY_OK); + t_fw_post(ti.ave, AVE_RING_T2H, 0, + T_FW_BASE + 0x78000 + AVE_IPC_PROC_BUFS * 0x10000, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ti.ave), 1); + t_canary_intact(test, ti.ave); +} + +/* Replies are matched to what the host waits for, and the slot handed back. */ +static void ave_ipc_test_poll_dispatch(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + __le64 *slot; + + t_msg_init(test, &ti); + ave = ti.ave; + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), 1); + KUNIT_EXPECT_EQ(test, ave->want[AVE_OP_OPEN], 0); + KUNIT_EXPECT_EQ(test, ave->reply_err, 0); + KUNIT_EXPECT_EQ(test, ave->msg_len, 0x40U); + KUNIT_EXPECT_MEMEQ(test, ave->msg, ave->ipc.cpu + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave->msg[0x40], 0x5a); + slot = t_slot(ave, &ave->ring[AVE_RING_T2H], 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(slot[0]), (T_FW_BASE + T_MSG_OFF) | 1); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), 0); + + /* The same reply again: nobody waits for it. */ + t_fw_post(ave, AVE_RING_T2H, 1, T_FW_BASE + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + + /* A reply for another client. */ + t_msg_init(test, &ti); + ave = ti.ave; + t_reply(&ti, T_MSG_OFF, AVE_OP_OPEN, 11, ti.abi->semantic[AVE_OP_OPEN], + T_REPLY_OK); + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + KUNIT_EXPECT_EQ(test, ave->want[AVE_OP_OPEN], 1); + + /* A reply of the wrong length or with an unknown id. */ + t_msg_init(test, &ti); + ave = ti.ave; + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x3c); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + t_msg_init(test, &ti); + ave = ti.ave; + put_unaligned_le16(0xffff, ave->ipc.cpu + T_MSG_OFF); + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); + KUNIT_EXPECT_EQ(test, ave->want[AVE_OP_OPEN], 1); + + /* A refusal is answered but recorded. */ + t_msg_init(test, &ti); + ave = ti.ave; + t_reply(&ti, T_MSG_OFF, AVE_OP_OPEN, 10, ti.abi->semantic[AVE_OP_OPEN], 1); + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x40); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), 1); + KUNIT_EXPECT_EQ(test, ave->want[AVE_OP_OPEN], 0); + KUNIT_EXPECT_EQ(test, ave->reply_err, -EIO); + + /* A frame result on a firmware build that cannot encode. */ + t_msg_init(test, &ti); + ave = ti.ave; + ti.layout->encode_ready = false; + t_reply(&ti, T_MSG_OFF, AVE_OP_PROCESS, 10, 0, T_REPLY_OK); + t_fw_post(ave, AVE_RING_T2H, 0, T_FW_BASE + T_MSG_OFF, 0x48); + KUNIT_EXPECT_EQ(test, ave_ipc_poll_once(ave), -EPROTO); +} + +/* Log lines: every slot is handed back, wherever the line claims to be. */ +static void ave_ipc_test_drain_log(struct kunit *test) +{ + struct ave_ring *r; + struct ave_dev *ave; + struct t_ipc ti; + + t_ipc_init(test, &ti, &ave_layout_6070_11_1, T_IPC_BYTES); + ave = ti.ave; + memset(ave->ring, 0, sizeof(ave->ring)); + t_ring(ave, AVE_RING_LOG, 0x1000, 4, 0, true); + r = &ave->ring[AVE_RING_LOG]; + memcpy(ave->ipc.cpu + T_MSG_OFF, "line\n", 5); + memset(ave->ipc.cpu + T_IPC_BYTES - AVE_LOG_LINE_MAX, 'x', + AVE_LOG_LINE_MAX); + + /* Nothing written yet. */ + ave_ipc_drain_log(ave); + KUNIT_EXPECT_EQ(test, r->consumer, 0); + + t_fw_post(ave, AVE_RING_LOG, 0, T_FW_BASE + T_MSG_OFF, 5); + /* Running off the end of the window. */ + t_fw_post(ave, AVE_RING_LOG, 1, T_FW_BASE + T_IPC_BYTES - 4, 0x100); + /* An oversized line at the very end: clamped, so it fits. */ + t_fw_post(ave, AVE_RING_LOG, 2, + T_FW_BASE + T_IPC_BYTES - AVE_LOG_LINE_MAX, U32_MAX); + ave_ipc_drain_log(ave); + for (unsigned int n = 0; n < 3; n++) + KUNIT_EXPECT_EQ(test, le64_to_cpu(*t_slot(ave, r, n)), + (u64)AVE_LOG_SLOT_FREE); + KUNIT_EXPECT_EQ(test, le64_to_cpu(*t_slot(ave, r, 3)), 1ULL); + KUNIT_EXPECT_EQ(test, r->consumer, 3); + + /* Below the window, then a NULL line; the index wraps. */ + t_fw_post(ave, AVE_RING_LOG, 3, T_FW_BASE - 0x100, 0x10); + t_fw_post(ave, AVE_RING_LOG, 0, 0, 0x10); + ave_ipc_drain_log(ave); + KUNIT_EXPECT_EQ(test, r->consumer, 1); + KUNIT_EXPECT_EQ(test, le64_to_cpu(*t_slot(ave, r, 3)), + (u64)AVE_LOG_SLOT_FREE); + KUNIT_EXPECT_EQ(test, le64_to_cpu(*t_slot(ave, r, 0)), + (u64)AVE_LOG_SLOT_FREE); + + /* A full ring is read once round, not forever. */ + for (unsigned int n = 0; n < 4; n++) + t_fw_post(ave, AVE_RING_LOG, n, T_FW_BASE + T_MSG_OFF, 5); + ave_ipc_drain_log(ave); + KUNIT_EXPECT_EQ(test, r->consumer, 1); + t_canary_intact(test, ave); + + /* No TERMINAL channel: nothing to read. */ + memset(ave->ring, 0, sizeof(ave->ring)); + ave_ipc_drain_log(ave); +} + +/* A shared-memory pool of 48 granules, sized down for the test. */ +#define T_POOL_OFF 0x20000 +#define T_POOL_BYTES 0x30000 + +static void t_pool_init(struct kunit *test, struct t_ipc *ti) +{ + t_ipc_init(test, ti, &ave_layout_6070_11_1, T_POOL_OFF + T_POOL_BYTES); + ti->t->smalloc_offset = T_POOL_OFF; + ti->t->smalloc_bytes = T_POOL_BYTES; +} + +/* Every block lies inside the pool, and only blocks lent can be returned. */ +static void ave_ipc_test_smalloc_bounds(struct kunit *test) +{ + const u64 start = T_FW_BASE + T_POOL_OFF; + struct ave_dev *ave; + struct t_ipc ti; + u64 addr, a, b; + + t_pool_init(test, &ti); + ave = ti.ave; + memset(ave->ipc.cpu + T_POOL_OFF, 0x77, T_POOL_BYTES); + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, 0, &addr), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, T_POOL_BYTES + 1, &addr), -EINVAL); + /* The whole pool in one block, zeroed, and not a byte more. */ + KUNIT_ASSERT_EQ(test, ave_smalloc_get(ave, T_POOL_BYTES, &addr), 0); + KUNIT_EXPECT_EQ(test, addr, start); + KUNIT_EXPECT_NULL(test, memchr_inv(ave->ipc.cpu + T_POOL_OFF, 0, T_POOL_BYTES)); + t_canary_intact(test, ave); + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, 1, &addr), -ENOMEM); + + /* Returns that are not a lent block. */ + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start - AVE_SMALLOC_GRANULE), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start + T_POOL_BYTES), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, U64_MAX & ~(u64)(SZ_4K - 1)), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, 0), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start + 1), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start + AVE_SMALLOC_GRANULE), -ENOENT); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start), 0); + /* Twice. */ + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, start), -ENOENT); + + /* Partial granules round up; the last block ends at the pool's end. */ + KUNIT_ASSERT_EQ(test, ave_smalloc_get(ave, 1, &a), 0); + KUNIT_ASSERT_EQ(test, ave_smalloc_get(ave, T_POOL_BYTES - AVE_SMALLOC_GRANULE, &b), 0); + KUNIT_EXPECT_EQ(test, a, start); + KUNIT_EXPECT_EQ(test, b, start + AVE_SMALLOC_GRANULE); + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, 1, &addr), -ENOMEM); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, a), 0); + KUNIT_ASSERT_EQ(test, ave_smalloc_get(ave, AVE_SMALLOC_GRANULE, &addr), 0); + KUNIT_EXPECT_EQ(test, addr, start); + t_canary_intact(test, ave); +} + +/* The host tracks at most AVE_SMALLOC_MAX blocks, even with room left. */ +static void ave_ipc_test_smalloc_slots(struct kunit *test) +{ + struct ave_dev *ave; + struct t_ipc ti; + u64 addr, first = 0; + + t_pool_init(test, &ti); + ave = ti.ave; + KUNIT_ASSERT_GT(test, T_POOL_BYTES / AVE_SMALLOC_GRANULE, AVE_SMALLOC_MAX); + for (unsigned int i = 0; i < AVE_SMALLOC_MAX; i++) { + KUNIT_ASSERT_EQ(test, ave_smalloc_get(ave, 1, &addr), 0); + KUNIT_EXPECT_EQ(test, addr, T_FW_BASE + T_POOL_OFF + i * AVE_SMALLOC_GRANULE); + if (!i) + first = addr; + } + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, 1, &addr), -ENOSPC); + KUNIT_EXPECT_EQ(test, ave_smalloc_put(ave, first), 0); + KUNIT_EXPECT_EQ(test, ave_smalloc_get(ave, 1, &addr), 0); + KUNIT_EXPECT_EQ(test, addr, first); +} + +/* The SHAREDMALLOC ring: unknown returns are answered, bad sizes stop serving. */ +static void ave_ipc_test_serve_smalloc(struct kunit *test) +{ + struct ave_ring *r; + struct ave_dev *ave; + struct t_ipc ti; + __le64 *slot; + + t_pool_init(test, &ti); + ave = ti.ave; + memset(ave->ring, 0, sizeof(ave->ring)); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), 0); + t_ring(ave, AVE_RING_SMALLOC, 0x800, 4, 3, true); + r = &ave->ring[AVE_RING_SMALLOC]; + + /* A block the host never lent: answered with no size. */ + t_fw_post(ave, AVE_RING_SMALLOC, 0, T_FW_BASE + T_POOL_OFF + SZ_64K, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), 1); + slot = t_slot(ave, r, 0); + KUNIT_EXPECT_EQ(test, le64_to_cpu(slot[0]), (T_FW_BASE + T_POOL_OFF + SZ_64K) | 1); + KUNIT_EXPECT_EQ(test, le64_to_cpu(slot[1]), 0ULL); + /* An address outside the window is answered the same way. */ + t_fw_post(ave, AVE_RING_SMALLOC, 1, 0x1000, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), 1); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, r, 1)[1]), 0ULL); + /* A request with no size, then one larger than the pool. */ + t_fw_post(ave, AVE_RING_SMALLOC, 2, 0, 0); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), -EINVAL); + t_ring(ave, AVE_RING_SMALLOC, 0x800, 4, 3, true); + t_fw_post(ave, AVE_RING_SMALLOC, 0, 0, T_POOL_BYTES + 1); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), -EINVAL); + t_ring_indices_valid(test, r); + t_canary_intact(test, ave); +} + +/* + * Request sizes near 4 GiB: rounding them up to granules must not wrap to + * zero granules, which would lend nothing while telling the firmware it + * has the whole size, at an address the next request gets again. + */ +static void ave_ipc_test_smalloc_huge(struct kunit *test) +{ + static const u32 huge[] = { + U32_MAX - AVE_SMALLOC_GRANULE + 1, + U32_MAX - AVE_SMALLOC_GRANULE + 2, + U32_MAX, + }; + struct ave_dev *ave; + struct t_ipc ti; + u64 addr; + + t_pool_init(test, &ti); + ave = ti.ave; + for (unsigned int i = 0; i < ARRAY_SIZE(huge); i++) + KUNIT_EXPECT_EQ_MSG(test, ave_smalloc_get(ave, huge[i], &addr), -EINVAL, + "request of %#x bytes", huge[i]); + + /* Through the ring: the request must not be answered with a block. */ + memset(ave->ring, 0, sizeof(ave->ring)); + t_ring(ave, AVE_RING_SMALLOC, 0x800, 4, 3, true); + t_fw_post(ave, AVE_RING_SMALLOC, 0, 0, U32_MAX); + KUNIT_EXPECT_EQ(test, ave_ipc_serve_smalloc(ave), -EINVAL); + KUNIT_EXPECT_EQ(test, le64_to_cpu(t_slot(ave, &ave->ring[AVE_RING_SMALLOC], 0)[0]), + 0ULL); +} + +static struct kunit_case ave_ipc_test_cases[] = { + KUNIT_CASE(ave_ipc_test_hello_9003), + KUNIT_CASE(ave_ipc_test_negotiate_bad_hello), + KUNIT_CASE(ave_ipc_test_negotiate_window), + KUNIT_CASE(ave_ipc_test_channels_9003), + KUNIT_CASE(ave_ipc_test_channels_malformed), + KUNIT_CASE(ave_ipc_test_channels_out_of_range), + KUNIT_CASE(ave_ipc_test_channels_overlap), + KUNIT_CASE(ave_ipc_test_channels_6070_unknown), + KUNIT_CASE(ave_ipc_test_ring_h2f), + KUNIT_CASE(ave_ipc_test_ring_f2h), + KUNIT_CASE(ave_ipc_test_buf_of), + KUNIT_CASE(ave_ipc_test_cmd_bounds), + KUNIT_CASE(ave_ipc_test_poll_acks), + KUNIT_CASE(ave_ipc_test_poll_msg_bounds), + KUNIT_CASE(ave_ipc_test_poll_dispatch), + KUNIT_CASE(ave_ipc_test_drain_log), + KUNIT_CASE(ave_ipc_test_smalloc_bounds), + KUNIT_CASE(ave_ipc_test_smalloc_slots), + KUNIT_CASE(ave_ipc_test_serve_smalloc), + KUNIT_CASE(ave_ipc_test_smalloc_huge), + {} +}; + +static struct kunit_suite ave_ipc_test_suite = { + .name = "apple-ave-ipc", + .test_cases = ave_ipc_test_cases, +}; + +kunit_test_suite(ave_ipc_test_suite); diff --git a/drivers/media/platform/apple/ave/ave-ipc.c b/drivers/media/platform/apple/ave/ave-ipc.c index 60a5b006a7875..e6288a6a86b25 100644 --- a/drivers/media/platform/apple/ave/ave-ipc.c +++ b/drivers/media/platform/apple/ave/ave-ipc.c @@ -1001,3 +1001,7 @@ int ave_ipc_settle(struct ave_dev *ave, unsigned int wait_ms) ave->reply_err = 0; return ret; } + +#if IS_ENABLED(CONFIG_VIDEO_APPLE_AVE_IPC_KUNIT_TEST) +#include "ave-ipc-test.c" +#endif diff --git a/drivers/media/platform/apple/ave/ave-writer-test.c b/drivers/media/platform/apple/ave/ave-writer-test.c new file mode 100644 index 0000000000000..1228eba62da1a --- /dev/null +++ b/drivers/media/platform/apple/ave/ave-writer-test.c @@ -0,0 +1,438 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * KUnit tests for the checks the 6070 Start and Process builders make on + * session parameters and buffers before they write a command: counts that + * index the session arrays, every surface the firmware is told about, and + * the codec state copied into Process. + * + * Copyright The Aurora Silicon Contributors + */ +#include +#include +#include +#include +#include + +#include "ave.h" +#include "ave-layout.h" + +#define T_FILL 0xa5 + +struct t_wr { + struct ave_dev *ave; + struct ave_ctx *ctx; + struct ave_session *sess; + struct ave_fw_layout *fw; + u8 *start, *process; + size_t start_len, process_len; +}; + +/* Synthetic, 16 KiB aligned DMA addresses, one window per buffer. */ +static void t_buf(struct ave_buf *b, unsigned int *index) +{ + b->dma = 0x820000000ULL + (u64)(*index) * 0x2000000; + b->size = SZ_16K * (1 + (*index)++); +} + +static void t_wr_init(struct kunit *test, struct t_wr *t, enum ave_codec codec) +{ + struct ave_session *sess; + struct ave_params *p; + unsigned int index = 0; + + t->ave = kunit_kzalloc(test, sizeof(*t->ave), GFP_KERNEL); + t->ctx = kunit_kzalloc(test, sizeof(*t->ctx), GFP_KERNEL); + t->sess = kunit_kzalloc(test, sizeof(*t->sess), GFP_KERNEL); + t->fw = kunit_kmalloc(test, sizeof(*t->fw), GFP_KERNEL); + KUNIT_ASSERT_TRUE(test, t->ave && t->ctx && t->sess && t->fw); + *t->fw = ave_layout_6070_11_1; + t->fw->encode_ready = true; + t->ave->layout = t->fw; + t->ctx->ave = t->ave; + t->ctx->sess = t->sess; + sess = t->sess; + p = &sess->p; + + *p = (struct ave_params){ + .codec = codec, + .width = 1920, + .height = 1080, + .cw = 1920, + .ch = ALIGN(1080, 16), + .stride = ALIGN(1920, 64), + .fps_num = 30, + .fps_den = 1, + .fps_int = 30, + .bframes = true, + .slots = 5, + .refs = 5, + .gop = 30, + .rc_mode = 3, + .bitrate = 4000000, + .initial_qp = 33, + .min_qp = 0, + .max_qp = 48, + .profile = codec == AVE_CODEC_H264 ? 4 : 1, + .level = codec == AVE_CODEC_H264 ? 13 : 7, + .bit_depth = 8, + }; + p->mbs = p->cw / 16 * (p->ch / 16); + p->coded_cap = ALIGN(3 * p->cw * p->ch, SZ_16K); + sess->token = 400; + sess->client = 10; + t_buf(&sess->hdr, &index); + t_buf(&sess->client_mem, &index); + sess->client_mem.size = AVE_6070_CLIENT_MEM_BYTES; + t_buf(&sess->param_sets, &index); + for (unsigned int i = 0; i < AVE_MAX_REFS; i++) { + t_buf(&sess->ref_a[i], &index); + t_buf(&sess->ref_b[i], &index); + t_buf(&sess->ref_c[i], &index); + t_buf(&sess->ref_d[i], &index); + } + t_buf(&sess->mb, &index); + for (unsigned int set = 0; set < AVE_NEIGHBOUR_SETS; set++) { + t_buf(&sess->row_a[set], &index); + t_buf(&sess->row_b[set], &index); + t_buf(&sess->fixed[set], &index); + t_buf(&sess->neighbour_fw[set], &index); + } + for (unsigned int set = 0; set < AVE_ENTROPY_SETS; set++) + for (unsigned int i = 0; i < AVE_TILE_BUFS; i++) { + t_buf(&sess->tile[set][i], &index); + t_buf(&sess->tile_aux[set][i], &index); + } + for (unsigned int i = 0; i < 2; i++) { + t_buf(&sess->hevc_extra[i], &index); + t_buf(&sess->hevc_transcoded[i], &index); + } + sess->hevc_transcoded[1].size = sess->hevc_transcoded[0].size; + for (unsigned int i = 0; i < AVE_MAX_SLOTS; i++) { + t_buf(&sess->slot[i].coded, &index); + t_buf(&sess->slot[i].meta, &index); + t_buf(&sess->slot[i].aux, &index); + } + sess->codec_state_bytes = t->fw->codec_state_bytes[codec - 1]; + sess->codec_state = kunit_kzalloc(test, sess->codec_state_bytes, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, sess->codec_state); + KUNIT_ASSERT_EQ(test, ave_init_codec_state(sess), 0); + + t->start_len = t->fw->bytes[codec - 1][AVE_IMAGE_START]; + t->process_len = t->fw->bytes[codec - 1][AVE_IMAGE_PROCESS]; + t->start = kunit_kmalloc(test, t->start_len + 1, GFP_KERNEL); + t->process = kunit_kmalloc(test, t->process_len + 1, GFP_KERNEL); + KUNIT_ASSERT_TRUE(test, t->start && t->process); +} + +/* Build Start into a filled buffer; a refusal must leave it untouched. */ +static int t_start(struct kunit *test, struct t_wr *t) +{ + int ret; + + memset(t->start, T_FILL, t->start_len + 1); + ret = ave_build_start(t->ctx, t->start, t->start_len); + if (ret) + KUNIT_EXPECT_NULL(test, memchr_inv(t->start, T_FILL, t->start_len)); + KUNIT_EXPECT_EQ(test, t->start[t->start_len], T_FILL); + return ret; +} + +static int t_process(struct kunit *test, struct t_wr *t, unsigned int slot, + dma_addr_t input) +{ + memset(t->process, T_FILL, t->process_len + 1); + return ave_build_process(t->ctx, t->process, t->process_len, slot, input, + t->sess->p.bitrate, false, false); +} + +#define T_INPUT 0x8f0000000ULL + +/* Counts that index the session's arrays are bounded before any is read. */ +static void ave_writer_test_start_counts(struct kunit *test) +{ + struct ave_params *p; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_H264); + p = &t.sess->p; + KUNIT_ASSERT_EQ(test, t_start(test, &t), 0); + + p->refs = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->refs = AVE_MAX_REFS + 1; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->refs = U32_MAX; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->refs = AVE_MAX_REFS; + p->slots = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->slots = t.fw->max_slots + 1; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->slots = U32_MAX; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + p->slots = t.fw->max_slots; + KUNIT_EXPECT_EQ(test, t_start(test, &t), 0); + + /* A command buffer of any other size. */ + memset(t.start, T_FILL, t.start_len + 1); + KUNIT_EXPECT_EQ(test, ave_build_start(t.ctx, t.start, t.start_len - 4), -EINVAL); + KUNIT_EXPECT_EQ(test, ave_build_start(t.ctx, t.start, t.start_len + 1), -EINVAL); + KUNIT_EXPECT_NULL(test, memchr_inv(t.start, T_FILL, t.start_len + 1)); + /* A layout that cannot encode builds nothing. */ + t.fw->encode_ready = false; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EOPNOTSUPP); +} + +/* + * Each buffer the firmware gets must be mapped and 16 KiB aligned. Flip + * the alignment of one at a time: the last one of each array counts too. + */ +static void ave_writer_test_start_buffers(struct kunit *test) +{ + struct ave_session *s; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_H264); + s = t.sess; +#define T_BAD(field) \ + do { \ + dma_addr_t keep = (field).dma; \ + (field).dma = keep + SZ_4K; \ + KUNIT_EXPECT_EQ_MSG(test, t_start(test, &t), -EINVAL, \ + "misaligned " #field); \ + (field).dma = 0; \ + KUNIT_EXPECT_EQ_MSG(test, t_start(test, &t), -EINVAL, \ + "unmapped " #field); \ + (field).dma = keep; \ + } while (0) + T_BAD(s->hdr); + T_BAD(s->client_mem); + T_BAD(s->param_sets); + T_BAD(s->ref_a[0]); + T_BAD(s->ref_a[AVE_MAX_REFS - 1]); + T_BAD(s->ref_b[AVE_MAX_REFS - 1]); + T_BAD(s->ref_c[AVE_MAX_REFS - 1]); + T_BAD(s->ref_d[AVE_6070_LOWRES_RESULTS - 1]); + T_BAD(s->slot[0].coded); + T_BAD(s->slot[4].coded); + T_BAD(s->slot[4].meta); + T_BAD(s->row_a[AVE_NEIGHBOUR_SETS - 1]); + T_BAD(s->row_b[AVE_NEIGHBOUR_SETS - 1]); + T_BAD(s->fixed[AVE_NEIGHBOUR_SETS - 1]); + T_BAD(s->neighbour_fw[AVE_NEIGHBOUR_SETS - 1]); + T_BAD(s->tile[AVE_ENTROPY_SETS - 1][AVE_6070_AVC_ENTROPY_TILES - 1]); + T_BAD(s->tile_aux[AVE_ENTROPY_SETS - 1][AVE_6070_AVC_ENTROPY_TILES - 1]); +#undef T_BAD + KUNIT_EXPECT_EQ(test, t_start(test, &t), 0); + + /* The client memory has the size the firmware expects, no other. */ + s->client_mem.size = AVE_6070_CLIENT_MEM_BYTES - SZ_16K; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->client_mem.size = AVE_6070_CLIENT_MEM_BYTES; + s->param_sets.size = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->param_sets.size = SZ_16K; + + /* Buffers this session does not use are not looked at. */ + s->slot[5].coded.dma = 0; + s->tile[0][AVE_6070_AVC_ENTROPY_TILES].dma = 1; + s->hevc_extra[1].dma = 1; + s->hevc_transcoded[0].dma = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), 0); +} + +/* HEVC uses four entropy tiles and the transcode buffers too. */ +static void ave_writer_test_start_buffers_hevc(struct kunit *test) +{ + struct ave_session *s; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_HEVC); + s = t.sess; + KUNIT_ASSERT_EQ(test, t_start(test, &t), 0); + s->tile[AVE_ENTROPY_SETS - 1][3].dma += SZ_4K; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->tile[AVE_ENTROPY_SETS - 1][3].dma -= SZ_4K; + s->tile_aux[0][3].dma = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->tile_aux[0][3].dma = 0x8e0000000ULL; + s->hevc_extra[1].dma += SZ_4K; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->hevc_extra[1].dma -= SZ_4K; + s->hevc_transcoded[1].dma = 0; + KUNIT_EXPECT_EQ(test, t_start(test, &t), -EINVAL); + s->hevc_transcoded[1].dma = 0x8e0004000ULL; + /* The fifth tile is not used. */ + s->tile[0][4].dma = 1; + KUNIT_EXPECT_EQ(test, t_start(test, &t), 0); +} + +/* general_level_idc is 30 times the level (H.265 A.4); other levels are 0. */ +static void ave_writer_test_hevc_level_idc(struct kunit *test) +{ + static const u32 idc[] = { 0, 30, 60, 63, 90, 93, 120, 123, 150, 153, 0 }; + const struct ave_start_layout *l; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_HEVC); + l = &t.fw->start[AVE_CODEC_HEVC - 1]; + KUNIT_ASSERT_NE(test, l->hevc_level_a, 0U); + KUNIT_ASSERT_NE(test, l->hevc_level_b, 0U); + KUNIT_ASSERT_LE(test, l->hevc_level_a + 4, (u32)t.start_len); + KUNIT_ASSERT_LE(test, l->hevc_level_b + 4, (u32)t.start_len); + for (unsigned int level = 0; level < ARRAY_SIZE(idc); level++) { + t.sess->p.level = level; + KUNIT_ASSERT_EQ(test, t_start(test, &t), 0); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(t.start + l->hevc_level_a), + idc[level], "level %u", level); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(t.start + l->hevc_level_b), + idc[level], "level %u", level); + } + t.sess->p.level = U32_MAX; + KUNIT_ASSERT_EQ(test, t_start(test, &t), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(t.start + l->hevc_level_a), 0U); +} + +/* H.264 level_idc (Table A-1) for every level the controls can select. */ +static void ave_writer_test_h264_level_idc(struct kunit *test) +{ + static const u32 idc[] = { + 10, 9, 11, 12, 13, 20, 21, 22, 30, 31, 32, 40, 41, 42, 50, 51, 52, + }; + const struct ave_start_layout *l; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_H264); + l = &t.fw->start[AVE_CODEC_H264 - 1]; + KUNIT_ASSERT_NE(test, l->h264_level, 0U); + for (unsigned int i = 0; i < ARRAY_SIZE(idc); i++) { + t.sess->p.level = i + 1; + KUNIT_ASSERT_EQ(test, t_start(test, &t), 0); + KUNIT_EXPECT_EQ_MSG(test, get_unaligned_le32(t.start + l->h264_level), + idc[i], "level %u", i + 1); + } +} + +/* Process: the slot, the input and the slot's buffers are checked first. */ +static void ave_writer_test_process_refusal(struct kunit *test) +{ + struct ave_session *s; + struct ave_params *p; + struct t_wr t; + + t_wr_init(test, &t, AVE_CODEC_H264); + s = t.sess; + p = &s->p; + KUNIT_ASSERT_EQ(test, t_process(test, &t, 0, T_INPUT), 0); + KUNIT_EXPECT_EQ(test, t.process[t.process_len], T_FILL); + KUNIT_ASSERT_EQ(test, t_process(test, &t, p->slots - 1, T_INPUT), 0); + +#define T_REFUSED(expr) \ + do { \ + KUNIT_EXPECT_EQ_MSG(test, (expr), -EINVAL, #expr); \ + KUNIT_EXPECT_NULL_MSG(test, \ + memchr_inv(t.process, T_FILL, t.process_len + 1), \ + #expr " wrote the command"); \ + } while (0) + T_REFUSED(t_process(test, &t, p->slots, T_INPUT)); + T_REFUSED(t_process(test, &t, AVE_MAX_SLOTS, T_INPUT)); + T_REFUSED(t_process(test, &t, U32_MAX, T_INPUT)); + T_REFUSED(t_process(test, &t, 0, T_INPUT + SZ_4K)); + T_REFUSED(t_process(test, &t, 0, T_INPUT + 1)); + p->slots = t.fw->max_slots + 1; + T_REFUSED(t_process(test, &t, 0, T_INPUT)); + p->slots = 5; + s->slot[2].coded.dma += SZ_4K; + T_REFUSED(t_process(test, &t, 2, T_INPUT)); + s->slot[2].coded.dma -= SZ_4K; + s->slot[2].meta.dma = 0; + T_REFUSED(t_process(test, &t, 2, T_INPUT)); + s->slot[2].meta.dma = 0x8e0000000ULL; + s->slot[2].aux.dma += 4; + T_REFUSED(t_process(test, &t, 2, T_INPUT)); + s->slot[2].aux.dma -= 4; + /* No codec state to copy into the command. */ + s->codec_state = NULL; + T_REFUSED(t_process(test, &t, 2, T_INPUT)); +#undef T_REFUSED + memset(t.process, T_FILL, t.process_len + 1); + KUNIT_EXPECT_EQ(test, + ave_build_process(t.ctx, t.process, t.process_len - 4, 0, + T_INPUT, p->bitrate, false, false), + -EINVAL); + KUNIT_EXPECT_NULL(test, memchr_inv(t.process, T_FILL, t.process_len + 1)); +} + +/* The codec state copied into Process may not be read past its end. */ +static void ave_writer_test_process_state_bounds(struct kunit *test) +{ + const enum ave_codec codecs[] = { AVE_CODEC_H264, AVE_CODEC_HEVC }; + + for (unsigned int c = 0; c < ARRAY_SIZE(codecs); c++) { + struct ave_session *s; + struct t_wr t; + size_t full; + + t_wr_init(test, &t, codecs[c]); + s = t.sess; + full = s->codec_state_bytes; + KUNIT_ASSERT_EQ(test, t_process(test, &t, 0, T_INPUT), 0); + /* The same state in a buffer one byte short. */ + s->codec_state_bytes = full - 1; + s->codec_state = kunit_kzalloc(test, full - 1, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, s->codec_state); + KUNIT_EXPECT_EQ(test, t_process(test, &t, 0, T_INPUT), -EINVAL); + s->codec_state_bytes = 1; + KUNIT_EXPECT_EQ(test, t_process(test, &t, 0, T_INPUT), -EINVAL); + s->codec_state_bytes = 0; + KUNIT_EXPECT_EQ(test, t_process(test, &t, 0, T_INPUT), -EINVAL); + } +} + +/* The codec state is only set up at the size this firmware uses. */ +static void ave_writer_test_codec_state(struct kunit *test) +{ + struct ave_session *s; + struct t_wr t; + u8 *state; + + t_wr_init(test, &t, AVE_CODEC_H264); + s = t.sess; + state = s->codec_state; + s->codec_state = NULL; + KUNIT_EXPECT_EQ(test, ave_init_codec_state(s), -EINVAL); + s->codec_state = state; + s->codec_state_bytes = t.fw->codec_state_bytes[0] - 4; + KUNIT_EXPECT_EQ(test, ave_init_codec_state(s), -EINVAL); + /* An H.264 state where HEVC is set up, and the other way round. */ + s->codec_state_bytes = t.fw->codec_state_bytes[0]; + s->p.codec = AVE_CODEC_HEVC; + KUNIT_EXPECT_EQ(test, ave_init_codec_state(s), -EINVAL); + s->p.codec = 0; + KUNIT_EXPECT_EQ(test, ave_init_codec_state(s), -EINVAL); + s->p.codec = AVE_CODEC_H264; + KUNIT_EXPECT_EQ(test, ave_init_codec_state(s), 0); + KUNIT_EXPECT_EQ(test, get_unaligned_le32(state), (u32)s->codec_state_bytes); +} + +static struct kunit_case ave_writer_test_cases[] = { + KUNIT_CASE(ave_writer_test_start_counts), + KUNIT_CASE(ave_writer_test_start_buffers), + KUNIT_CASE(ave_writer_test_start_buffers_hevc), + KUNIT_CASE(ave_writer_test_hevc_level_idc), + KUNIT_CASE(ave_writer_test_h264_level_idc), + KUNIT_CASE(ave_writer_test_process_refusal), + KUNIT_CASE(ave_writer_test_process_state_bounds), + KUNIT_CASE(ave_writer_test_codec_state), + {} +}; + +static struct kunit_suite ave_writer_test_suite = { + .name = "apple-ave-writer", + .test_cases = ave_writer_test_cases, +}; + +kunit_test_suite(ave_writer_test_suite); + +MODULE_DESCRIPTION("KUnit tests for Apple AVE command builder input checks"); +MODULE_LICENSE("GPL"); From 599c10df66c2d37928cf1e3fd15a0aa8ddb65111 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 11:17:09 +1100 Subject: [PATCH 11/13] ASoC: apple: macaudio: add speaker volume unlock tests The "Speaker Volume Unlock" lease (macaudio_vlimit_update(), the slk_* control and the timeout work) has no direct tests. Add the apple-speaker-volume-unlock suite (9 cases) on the card of the pm-volumes tests: the speaker volumes leave the safe ceiling only while one process holds the lock control and every speaker volume, and only while it pings within SPEAKER_LOCK_TIMEOUT while speaker playback runs; a missed ping or a volume with another owner relocks them, and the lease is kept while idle. Mutations caught: mixed volume owners no longer relock, and the timeout work keeping the lease. Signed-off-by: Ryan Murray --- sound/soc/apple/macaudio-vlimit-test.h | 251 +++++++++++++++++++++++++ sound/soc/apple/macaudio.c | 1 + 2 files changed, 252 insertions(+) create mode 100644 sound/soc/apple/macaudio-vlimit-test.h diff --git a/sound/soc/apple/macaudio-vlimit-test.h b/sound/soc/apple/macaudio-vlimit-test.h new file mode 100644 index 0000000000000..26b8764805a65 --- /dev/null +++ b/sound/soc/apple/macaudio-vlimit-test.h @@ -0,0 +1,251 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* + * The "Speaker Volume Unlock" lease: the speaker volumes leave the safe + * ceiling only while one process holds the lock control and every speaker + * volume, and pings within SPEAKER_LOCK_TIMEOUT ms while speaker playback + * runs. Built on the card of macaudio-pm-volumes-test.h. + */ +#include +#include + +static int macaudio_vlt_put(struct kunit *test, struct macaudio_pmt_pm *t, long val) +{ + struct snd_ctl_elem_value *uval = kunit_kzalloc(test, sizeof(*uval), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, uval); + uval->value.integer.value[0] = val; + return macaudio_slk_put(t->slk, uval); +} + +static long macaudio_vlt_get(struct kunit *test, struct macaudio_pmt_pm *t) +{ + struct snd_ctl_elem_value *uval = kunit_kzalloc(test, sizeof(*uval), GFP_KERNEL); + + KUNIT_ASSERT_NOT_NULL(test, uval); + KUNIT_EXPECT_EQ(test, macaudio_slk_get(t->slk, uval), 0); + return uval->value.integer.value[0]; +} + +/* Speaker playback runs (or stops): the ping deadline is armed (or held). */ +static void macaudio_vlt_playing(struct macaudio_pmt_pm *t, bool playing) +{ + if (playing) + macaudio_vlimit_enable_timeout(t->ma); + else + macaudio_vlimit_disable_timeout(t->ma); +} + +/* Saved mixer states hold 0 or 1: restoring one is a no-op, nothing else is. */ +static void macaudio_vlimit_restore_values_are_noops(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_vlt_put(test, &t, 0), 0); + KUNIT_EXPECT_EQ(test, macaudio_vlt_put(test, &t, 1), 0); + KUNIT_EXPECT_EQ(test, macaudio_vlt_put(test, &t, 2), -EINVAL); + KUNIT_EXPECT_EQ(test, macaudio_vlt_put(test, &t, SPEAKER_MAGIC_VALUE + 1), -EINVAL); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, macaudio_vlt_get(test, &t), 0L); + + /* Even for the owner */ + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_vlt_put(test, &t, 1), 0); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); +} + +/* A ping without the lock is refused and unlocks nothing. */ +static void macaudio_vlimit_ping_needs_the_lock(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), -EPERM); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, macaudio_vlt_get(test, &t), 0L); +} + +/* The lock alone is not enough: every speaker volume must be the owner's. */ +static void macaudio_vlimit_needs_every_volume(struct kunit *test) +{ + struct snd_ctl_file *other = kunit_kzalloc(test, sizeof(*other), GFP_KERNEL); + struct macaudio_pmt_pm t; + unsigned int i; + + KUNIT_ASSERT_NOT_NULL(test, other); + for (i = 0; i < MACAUDIO_PMT_NR_VOLS - 1; i++) { + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + t.vols[i]->vd[0].owner = other; + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_FALSE_MSG(test, t.ma->speaker_volume_unlocked, + "%s held by another file", macaudio_pmt_vol_names[i]); + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + t.vols[i]->vd[0].owner = NULL; + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_FALSE_MSG(test, t.ma->speaker_volume_unlocked, + "%s not locked", macaudio_pmt_vol_names[i]); + } + + /* A volume that is not a speaker volume does not count */ + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + t.vols[MACAUDIO_PMT_NR_VOLS - 1]->vd[0].owner = other; + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); +} + +/* Closing the lock relocks at once and clips the speaker volumes only. */ +static void macaudio_vlimit_unlock_clips(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, macaudio_vlt_get(test, &t), 1L); + macaudio_pmt_expect_vols(test, &t, false); + + macaudio_slk_unlock(t.slk); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, macaudio_vlt_get(test, &t), 0L); + macaudio_pmt_expect_vols(test, &t, true); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), -EPERM); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); +} + +/* + * While playback runs the lease ends SPEAKER_LOCK_TIMEOUT ms after the last + * ping. The owner's next ping reports the loss with -ETIMEDOUT and unlocks + * nothing; only the ping after it starts a new lease. + */ +static void macaudio_vlimit_lease_expires_while_playing(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + macaudio_vlt_playing(&t, true); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + + msleep(SPEAKER_LOCK_TIMEOUT * 2); + flush_delayed_work(&t.ma->lock_timeout_work); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + macaudio_pmt_expect_vols(test, &t, true); + + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), -ETIMEDOUT); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + macaudio_vlt_playing(&t, false); +} + +/* + * Each ping moves the deadline to SPEAKER_LOCK_TIMEOUT ms after itself and + * re-arms the expiry. Checked on the deadline, not by racing the clock. + */ +static void macaudio_vlimit_pings_keep_the_lease(struct kunit *test) +{ + struct macaudio_pmt_pm t; + ktime_t before, deadline; + unsigned int i; + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + macaudio_vlt_playing(&t, true); + deadline = t.ma->speaker_lock_timeout; + for (i = 0; i < 3; i++) { + usleep_range(1000, 2000); + before = ktime_get(); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_GT(test, t.ma->speaker_lock_timeout, deadline); + KUNIT_EXPECT_GE(test, t.ma->speaker_lock_timeout, + ktime_add_ms(before, SPEAKER_LOCK_TIMEOUT)); + KUNIT_EXPECT_TRUE(test, delayed_work_pending(&t.ma->lock_timeout_work)); + deadline = t.ma->speaker_lock_timeout; + } + macaudio_vlt_playing(&t, false); +} + +/* + * Without playback the deadline is held: an idle owner keeps its lease, and + * the time it had left runs on when playback starts again. + */ +static void macaudio_vlimit_idle_holds_the_lease(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + msleep(SPEAKER_LOCK_TIMEOUT * 2); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_EQ(test, t.ma->speaker_lock_remain, ms_to_ktime(SPEAKER_LOCK_TIMEOUT)); + KUNIT_EXPECT_FALSE(test, delayed_work_pending(&t.ma->lock_timeout_work)); + + /* The time left runs from the start of playback and then ends */ + macaudio_vlt_playing(&t, true); + KUNIT_EXPECT_TRUE(test, delayed_work_pending(&t.ma->lock_timeout_work)); + msleep(SPEAKER_LOCK_TIMEOUT * 2); + flush_delayed_work(&t.ma->lock_timeout_work); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + macaudio_vlt_playing(&t, false); +} + +/* A new owner never inherits the previous owner's lease. */ +static void macaudio_vlimit_new_owner_pings_first(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); + + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + KUNIT_EXPECT_LE(test, t.ma->speaker_lock_remain, 0); + /* The relock was the switch of owners, not a lost lease */ + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_TRUE(test, t.ma->speaker_volume_unlocked); +} + +/* A card without speaker safety never touches its volumes. */ +static void macaudio_vlimit_without_safety(struct kunit *test) +{ + struct macaudio_pmt_pm t; + + macaudio_pmt_pm_card(test, &t); + t.ma->has_safety = false; + macaudio_pmt_take(test, &t); + KUNIT_EXPECT_EQ(test, macaudio_pmt_ping(test, &t), 0); + KUNIT_EXPECT_FALSE(test, t.ma->speaker_volume_unlocked); + macaudio_slk_unlock(t.slk); + macaudio_pmt_expect_vols(test, &t, false); +} + +static struct kunit_case macaudio_vlimit_cases[] = { + KUNIT_CASE(macaudio_vlimit_restore_values_are_noops), + KUNIT_CASE(macaudio_vlimit_ping_needs_the_lock), + KUNIT_CASE(macaudio_vlimit_needs_every_volume), + KUNIT_CASE(macaudio_vlimit_unlock_clips), + KUNIT_CASE_SLOW(macaudio_vlimit_lease_expires_while_playing), + KUNIT_CASE(macaudio_vlimit_pings_keep_the_lease), + KUNIT_CASE_SLOW(macaudio_vlimit_idle_holds_the_lease), + KUNIT_CASE(macaudio_vlimit_new_owner_pings_first), + KUNIT_CASE(macaudio_vlimit_without_safety), + {} +}; + +static struct kunit_suite macaudio_vlimit_suite = { + .name = "apple-speaker-volume-unlock", + .test_cases = macaudio_vlimit_cases, +}; + +kunit_test_suite(macaudio_vlimit_suite); diff --git a/sound/soc/apple/macaudio.c b/sound/soc/apple/macaudio.c index b05d60bc0451a..790e512f9c75f 100644 --- a/sound/soc/apple/macaudio.c +++ b/sound/soc/apple/macaudio.c @@ -4623,6 +4623,7 @@ MODULE_LICENSE("GPL"); #include "macaudio-protection-test.h" #include "macaudio-hpf-test.h" #include "macaudio-pm-volumes-test.h" +#include "macaudio-vlimit-test.h" #include "macaudio-iface-test.h" #if IS_ENABLED(CONFIG_OF_OVERLAY) #include "macaudio-amp-level-test.h" From 20783b6037135144085d525726ba868b624c8c1e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 12:09:36 +1100 Subject: [PATCH 12/13] drm: apple: cec test: allocate the fakes before the device dcp_cec_test_setup() allocates the fake apple_dcp and AFK endpoint with kunit_kzalloc() after kunit_device_register(). KUnit releases resources in reverse order, so both are freed before the device is unregistered, and the device's devres action dcp_cec_devm_release() then reads them: KASAN reports a use-after-free in dcp_cec_unregister() and UBSAN an invalid bool load in afk_service_retry() for the apple-dcp-cec-adap cases. Allocate the fakes before the device. Fixes: 75773377faae ("drm/apple: add native HDMI-CEC and 2 ms IRQ_HPD pulse tracking") Signed-off-by: Ryan Murray --- drivers/gpu/drm/apple/cec_adap_test.c | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/apple/cec_adap_test.c b/drivers/gpu/drm/apple/cec_adap_test.c index 61a30501b3ef7..d4b560c96fc68 100644 --- a/drivers/gpu/drm/apple/cec_adap_test.c +++ b/drivers/gpu/drm/apple/cec_adap_test.c @@ -159,12 +159,13 @@ static struct dcp_cec_test_ctx *dcp_cec_test_setup(struct kunit *test) KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx); spin_lock_init(&ctx->lock); - ctx->dev = kunit_device_register(test, "apple-dcp-cec-kunit"); - KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); - + /* + * The fakes are allocated before the device: KUnit frees in reverse + * order, and the device's devres (dcp_cec_devm_release()) still uses + * them when the device is unregistered. + */ ctx->dcp = kunit_kzalloc(test, sizeof(*ctx->dcp), GFP_KERNEL); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dcp); - ctx->dcp->dev = ctx->dev; ctx->dcp->fixed_connector_type = DRM_MODE_CONNECTOR_HDMIA; ctx->ep = kunit_kzalloc(test, sizeof(*ctx->ep), GFP_KERNEL); @@ -173,6 +174,10 @@ static struct dcp_cec_test_ctx *dcp_cec_test_setup(struct kunit *test) ctx->ep->endpoint = AV_AUDIO_ENDPOINT_DESKTOP; ctx->ep->compact = true; + ctx->dev = kunit_device_register(test, "apple-dcp-cec-kunit"); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx->dev); + ctx->dcp->dev = ctx->dev; + ctx->port_srv.ep = ctx->ep; ctx->dcp->dptxport[0].service = &ctx->port_srv; From ffc9e90a9513078cf26df958a0bb2eaa3d7496be Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Thu, 26 Nov 2026 00:45:33 +1100 Subject: [PATCH 13/13] soc: apple: rtkit: keep the crashlog host tests buildable The standalone crashlog tests compile the production parser without kernel Kconfig helpers. Guard the included test by its boolean Kconfig symbol directly. Signed-off-by: Ryan Murray --- drivers/soc/apple/rtkit-crashlog.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/soc/apple/rtkit-crashlog.c b/drivers/soc/apple/rtkit-crashlog.c index 47335bf11c493..f12a3f6fda854 100644 --- a/drivers/soc/apple/rtkit-crashlog.c +++ b/drivers/soc/apple/rtkit-crashlog.c @@ -493,6 +493,6 @@ void apple_rtkit_crashlog_dump(struct apple_rtkit *rtk, u8 *bfr, size_t size) "RTKit: End of crashlog reached but no footer present"); } -#if IS_ENABLED(CONFIG_APPLE_RTKIT_KUNIT_TEST) +#ifdef CONFIG_APPLE_RTKIT_KUNIT_TEST #include "rtkit-crashlog-test.c" #endif