Introduce SCMI Telemetry support
Subsystems (6)
Cristian Marussi
reviewerv17 cover Introduce SCMI Telemetry support
Hi all,
[TLDR Summary]
[V17 highlights]
- addressed more Sashiko reports
- added a few more SCMI Core fixes that ease per-protocol logic:
+ added more consistency in the SCMI Core Iterators machinery
+ added centralized check (SCMI Core) for truncated reply
+ Reworked some SCM Clock behaviour to allow for truncated checks
+ SCMI protocol core initialization refactor and fixes
[V18 TODO]
- address any remaining outstanding Sashiko/reviewers issues
- address pending human reviews feedback
The upcoming SCMI v4.0 specification [0] introduces a new SCMI protocol dedicated to System Telemetry.
In a nutshell, the SCMI Telemetry protocol allows an agent to discover at runtime the set of Telemetry Data Events (DEs) available on a specific platform and provides the means to configure the set of DEs that a user is interested into, while reading them back using the collection method that is deeemed more suitable for the usecase at hand. (...amongst the various possible collection methods allowed by SCMI specification)
Without delving into the gory details of the whole SCMI Telemetry protocol let's just say that the SCMI platform/server firmware advertises a number of Telemetry Data Events, each one identified by a 32bit unique ID, and an SCMI agent/client, like Linux, can discover them and read back at will the associated data value in a number of ways.
Data collection is mainly intended to happen on demand via shared memory areas exposed by the platform firmware, discovered dynamically via SCMI Telemetry and accessed by Linux on-demand, but some DE can also be reported via SCMI Notifications asynchronous messages or via direct dedicated FastChannels (another kind of SCMI memory based access): all of this underlying mechanism is anyway hidden to the user since it is mediated by the kernel driver which will return the proper data value when queried.
Anyway, the set of well-known architected DE IDs defined by the spec is limited to a dozen IDs, which means that the vast majority of DE IDs are customizable per-platform: as a consequence, though, the same ID, say '0x1234', could represent completely different things on different systems.
Precise definitions and semantic of such custom Data Event IDs are out of the scope of the SCMI Telemetry specification and of this implementation:
they are supposed to be provided using some kind of JSON-like description file that will have to be consumed by a userspace tool which would be finally in charge of making sense of the set of available DEs.
IOW, in turn, this means that even though the DEs enumerated via SCMI come with some sort of topological and qualitative description provided by the protocol (like unit of measurements, name, topology info etc), kernel-wise we CANNOT be completely sure of "what is what" without being fed-back some sort of information about the DEs by the afore mentioned userspace tool.
For these reasons, currently this series does NOT attempt to register any of these DEs with any of the usual in-kernel subsystems (like HWMON, IIO, PERF etc), simply because we cannot be sure which DE is suitable, or even desirable, for a given subsystem. This also means there are NO in-kernel users of these Telemetry data events as of now.
So, while we do not exclude, for the future, to feed/register some of the discovered DEs to/with some of the above mentioned Kernel subsystems, as of now we have ONLY modeled a custom userspace API to make SCMI Telemetry available to userspace tools.
With V5 we adopted a pure chardev/IOCTL ABI approach, refining the IOCTL based interface already present with the previous FS-based ABI.
INTERFACES
For each discovered SCMI Instance a character device named tlm_<N> is created under /dev/scmi/ subtree.
The IOCTL interface described at 'include/uapi/linux/scmi.h' is made available to enumerate and configure Telemetry resources: Telemetry data can be collected using a few different IOCTls, depending on the required granularity.
Alternatively it is possible to obtain a list of the file descriptors referencing directly the underlying SCMI Telemetry SHMTI memory areas and implement in user space an SCMI Telemetry parser accessing directly the SHMTI, while staying in compliance with the SCMI TDCF format.
NOTE THAT from v3 onwards the firmware interface level NOW supports ONLY the latest SCMI v4.0 specification [0].
Based on V7.4-rc4, tested on an emulated setup and AGI HW.
This series is available also at [1].
If you still reading...any feedback welcome :P
Thanks,
Cristian
---
v15 --> v17
- rebased on v7.4-rc4
- [SYS/TLM]
+ return OPNOTSUPP on un-implemented IOCTLs instead of -ENOTTY
+ use proper IS_GROUP macros to discard GROUP request across IOCTLs
- [TLM]
+ fix leak and NULL deref on exit path
+ fix shmti_oveflow WITH LEN
+ check liveness on de_snapshot
+ remove spurious des_sample and notif structure and logic
+ add a comment on bulk read reporting on failures
+ return ENODATA when TLM off instead of -EINVAL
+ rename update_interval_ms to ename update_interval
+ use NULL not zero for pointers
+ fix liveness blkts_snapshot
+ fix tde_state_set_resp handling of INVALISD SHMTI_ID
+ refactor state_set and reject group state change
+ invalidate TDE cache also on enable
+ allow SHMTI_INVALID as bts_offs when DE does NOT use BLK_TS
+ fix err init in blkts_snapshot
+ add comment on LINE_LENGTH_BYTES upper bound
+ remove spurious return
+ removed unused node_lst
+ check TDE TS type, update from last_rate
+ check if used_qwords > avail_qwords early in tdcf_line_parse
+ add __iomem eplg annotation
+ fix shmti_overflow and make it return the line length
+ remove WARN_ON(fc_support), better dev_
+ log error on malformed line data
+ use %pa for phys_addr
+ skip LIST_SHMTI with num_shmti = 0
+ fix %pa and spell USPECIFIED
+ avoid FIELD_PREP check on size for exp
+ remove unused de.ts_rate
+ enaming discovered to enumerated
+ rework list_add to fcs_des
+ use list_del_init for free_des/fcs_des list removals
+ avoid attaching a drevres tdes_cleanup to enumeration
+ consider expected_size when reset_rx_to_max
+ add an unrelated fix to make SCMI clock attributes deterministic
v15 --> v16
- rebased on v7.4-rc3
- [ALL] removed Telemetry unused features
+ Groups/Notifications/AsyncSingleSample/Reset/Events
- [STLM]
+ handling new ABI Feature bits
- [SYS/TLM]
+ remove unsupported features from ABI features
+ clear out->flags in uapi_info
+ cap ABI INFO usize to PAGE_SIZE
+ sanitize input update interval
+ add missing pad/reserved checks in input
- [UAPI]
+ added GROUPS/SINGLE_SAMPLE abi_features flags definitions
- [TLM]
+ initialize/destroy debugFS around SHMTIs init
+ cleanup protocol dbg root after devres group closure
+ discard DE/FC at enumeration time that were found in SHMTI at boot
+ align DE local/global TS state after enumeration
+ check liveness in de_snapshot
+ add shmti_overflow check on snap
+ check liveness on blkts_snapshot too
+ refatcor blkts_update on DE enable and update de.ts_rate even when BLK_TS line is the same
+ on disable do NOT assume SHMTI_ID_INVALID means disable
+ fix remote_update_needed logic
+ invalidate cache on DE disable
+ invalidate base/offset on disable if NOT FC
+ use new shmti_overflow with eplg directly
+ WARN_ON(BLK_TS_INVALID) but keep active_bts valid
+ invalidate TDE cache on blkts_unlin
+ cleanup stale lines on shmti cleanup
+ add more iterators consistency checks
+ added more checks in the SCMI Core Iterators machinery
+ added centralized check for truncated replies
+ droppepd unused support for non devres protocol acquire/release operations
v14 --> v15
- rebased on v7.4-rc2
- [STLM]
+ add lazy enumeration
+ add des/info cmdline options
+ add missing SIGTERM handling
- [SYS/TLM]
+ harden/simplify batch helpers
+ fix shmti mmap size check to include offset
+ simplify session_unsubscribe cleanup on exit/unbind
+ added missing kref.h include
+ expose TLM EVENTS capabilities ONLY IF CONFIG_EVENTFD
+ mmap: improved check to avoid WRITE/EXEC mapping
+ reject non zero vm_pgoff
+ drop usage of guard(srcu) to avoid races with put_device
- [TLM]
+ avoid genration counter reset on TLM RESET
+ add an overflow check on NOTIF payload lines parsing
+ convert to Linux errno before building notification report
+ use better startm/endm initial markers in tdcf_de_payld_get
+ trigger resource enumeration also on de_data_read
+ skip unitialized FCs on reads and return -EPROTO
+ check FC size on enumeration (big enough to hold TS ?)
+ introduce localized single DE snapshot on single DE data read
+ widen tde->mtx locking in msg_payld_process
+ refactor msg_payld_process
+ unlink BLK_TS on DE disable
+ update linked BLK_TS on enable
+ update TDE location ONLY after successfull linked lines processing
+ trigger resource enumeration on state_get
+ trigger resource enumeration on colletion configure only for groups
+ widen tde->mtx locking section on state_set
+ refactor UUID/BLK_TS lines processing in enable
+ introduce BLK_TS localized snapshot during enable
+ check line type at de_offs
+ sanitize requested mode on collection conf
+ use snapshots to collect UUIDs during full scans
+ stop tracking UUIDs lines singularly (useless overhead)
+ use UUIDs line hashing for lookup
+ use snapshots to track and collect BLK_TS during full scan bulk reads
+ account for tstamped TDE during discovery
+ correct SHMTI overflow off-by-one
+ rework TDE cache hit/miss logic
+ introduce snapshots on full scan reads
+ validate DE location also on SCAN_UPDATE
+ fix TDCF prologue/epilogue endianity struct definitions
+ rework SHMTI initialization and allocation
+ add snapshot suppport data structures
+ added alignment checks on SHMTII length size
+ fixed error string formatting
+ warn if less than expected SHMTIs are enumerated
+ improve memory area sanity checks
+ added missing initialization of intrvs->grp_id
+ bailout from group initialization when NO DEs were found
+ better handling of error path on groups init
+ drop usage of devres for FC iomapping
+ trigger full enumeration of DE lookups
+ new IS_TDE_TS_ macro helpers
+ add a dedicated scmi_telemetry_free_tdes_add helper
+ dropping needless __must_check
+ flag as fully enumerated only when ALL declared des were found
+ reworked error path in scmi_allocate_pending_event_handler
+ hardened core iterator parsing of multi-part reply
[0]: https://developer.arm.com/documentation/den0056/f/?lang=en
[1]: https://git.kernel.org/pub/scm/linux/kernel/git/cris/linux.git/log/?h=scmi_telemetry_ng_V17
Cristian Marussi (33):
firmware: arm_scmi: Harden iterators state parsing
[RFC] firmware: arm_scmi: Additional iterators consistency checks
firmware: arm_scmi: Make Clock attributes size deterministic
firmware: arm_scmi: Add centralized detection of truncated replies
firmware: arm_scmi: Introduce a dedicated SCMI Errors header
firmware: arm_scmi: Add new SCMIv4.0 error codes definitions
firmware: arm_scmi: Allow registration of unknown-size events/reports
firmware: arm_scmi: Refactor __scmi_event_handler_get_ops helper
dt-bindings: firmware: arm,scmi: Add support for telemetry protocol
include: trace: Add Telemetry trace events
firmware: arm_scmi: Add Telemetry basic attributes enumeration
firmware: arm_scmi: Add Telemetry resources enumeration
firmware: arm_scmi: Add Telemetry global update intervals enumeration
firmware: arm_scmi: Add Telemetry SHMTI areas enumeration
firmware: arm_scmi: Add Telemetry TDCF areas parsing support
firmware: arm_scmi: Add Telemetry TDCF parsing for BLK_TS lines
firmware: arm_scmi: Add Telemetry TDCF parsing for UUID lines
firmware: arm_scmi: Add Telemetry DEs configuration support
firmware: arm_scmi: Add Telemetry global configuration support
firmware: arm_scmi: Add Telemetry Single/Bulk DEs reads
firmware: arm_scmi: Add Telemetry boot-on support
firmware: arm_scmi: Invoke proper protocol cleanup on failure
firmware: arm_scmi: Refactor protocol allocation
firmware: arm_scmi: Add common per-protocol debugfs support
firmware: arm_scmi: Add Telemetry debugfs SHMTI dump support
firmware: arm_scmi: Add Telemetry debugfs ABI documentation
firmware: arm_scmi: Expose per-instance identifier
uapi: Add ARM SCMI Telemetry definitions
firmware: arm_scmi: Add System Telemetry driver
firmware: arm_scmi: Enable autoloading for System Telemetry driver
docs: ioctl-number: Add SCMI Ioctls
[RFC] Documentation: Add SCMI System Telemetry documentation [RFC] tools/testing/scmi: Add SCMI Telemetry testing tool
Philip Radford (1):
kselftest/arm64: Add SCMI Telemetry UAPI compliance testcases
Documentation/ABI/testing/debugfs-scmi | 22 + .../bindings/firmware/arm,scmi.yaml | 8 + Documentation/userspace-api/index.rst | 1 + .../userspace-api/ioctl/ioctl-number.rst | 1 + Documentation/userspace-api/stlm.rst | 590 +++ MAINTAINERS | 2 + drivers/firmware/arm_scmi/Kconfig | 24 + drivers/firmware/arm_scmi/Makefile | 3 +- drivers/firmware/arm_scmi/bus.c | 1 + drivers/firmware/arm_scmi/clock.c | 12 +- drivers/firmware/arm_scmi/common.h | 41 +- drivers/firmware/arm_scmi/driver.c | 158 +- drivers/firmware/arm_scmi/errors.h | 56 + drivers/firmware/arm_scmi/notify.c | 102 +- drivers/firmware/arm_scmi/notify.h | 8 +- drivers/firmware/arm_scmi/protocols.h | 22 + drivers/firmware/arm_scmi/raw_mode.c | 1 + .../firmware/arm_scmi/scmi_system_telemetry.c | 1376 ++++++ drivers/firmware/arm_scmi/telemetry.c | 4352 +++++++++++++++++ include/linux/scmi_protocol.h | 200 +- include/trace/events/scmi.h | 45 + include/uapi/linux/scmi.h | 533 ++ tools/testing/scmi/Makefile | 25 + tools/testing/scmi/stlm.c | 1698 +++++++ tools/testing/scmi/stlm_decode.c | 252 + tools/testing/scmi/stlm_decode.h | 7 + tools/testing/selftests/arm64/Makefile | 2 +- tools/testing/selftests/arm64/scmi/Makefile | 12 + tools/testing/selftests/arm64/scmi/config | 2 + .../arm64/scmi/test_scmi_telemetry_uapi.c | 2034 ++++++++ 30 files changed, 11477 insertions(+), 113 deletions(-) create mode 100644 Documentation/userspace-api/stlm.rst create mode 100644 drivers/firmware/arm_scmi/errors.h create mode 100644 drivers/firmware/arm_scmi/scmi_system_telemetry.c create mode 100644 drivers/firmware/arm_scmi/telemetry.c create mode 100644 include/uapi/linux/scmi.h create mode 100644 tools/testing/scmi/Makefile create mode 100644 tools/testing/scmi/stlm.c create mode 100644 tools/testing/scmi/stlm_decode.c create mode 100644 tools/testing/scmi/stlm_decode.h create mode 100644 tools/testing/selftests/arm64/scmi/Makefile create mode 100644 tools/testing/selftests/arm64/scmi/config create mode 100644 tools/testing/selftests/arm64/scmi/test_scmi_telemetry_uapi.c
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 1/34 firmware: arm_scmi: Harden iterators state parsing
Add checks in the core multi-part iterators support to detect generally malformed and inconsistent multi-part replies.
--- drivers/firmware/arm_scmi/driver.c | 10 ++++++++++ drivers/firmware/arm_scmi/protocols.h | 7 +++++++ 2 files changed, 17 insertions(+)
drivers/firmware/arm_scmi/driver.c +10 -0
@@ -1873,11 +1873,21 @@ static int __scmi_iterator_run(void *iter, unsigned int *start, unsigned int *enif (ret)return ret; +if (i->t->rx.len <SCMI_MULTIPART_REPLY_MIN_SZ ) { +dev_err (ph->dev,"Invalid multi-part reply.\n" ); +return -EINVAL ; + } + st->rx_len = i->t->rx.len; ret = iops->update_state (st, i->resp, i->priv);if (ret)return ret; +if (!st->num_returned && st->num_remaining) { +dev_err (ph->dev,"Inconsistent multi-part reply.\n" ); +return -EINVAL ; + } +if (st->num_returned > st->max_resources - st->desc_index) { dev_err(ph->dev, "No. of resources can't exceed %d\n",
drivers/firmware/arm_scmi/protocols.h +7 -0
@@ -33,6 +33,13 @@#define MSG_SUPPORTS_FASTCHANNEL (x) ((x) & BIT(0)) +/* +* Common minimum size required by all the existing standard and vendor +* protocols to hold number of returned and remaining items in a multi-part +* reply. +*/ +#define SCMI_MULTIPART_REPLY_MIN_SZ (sizeof(u32)) +enum scmi_common_cmd {PROTOCOL_VERSION =0x0 ,PROTOCOL_ATTRIBUTES =0x1 ,
Signature · 1 line
2.54.0
Re: [PATCH v17 01/34] firmware: arm_scmi: Harden iterators state parsing
Quoted 5 lines · On Tue, 24 Nov 2026 19:48:07 +0000 Cristian Marussi <[email protected]>…
Add checks in the core multi-part iterators support to detect generally malformed and inconsistent multi-part replies.
Fixes 36b6ea0fc6bc ("firmware: arm_scmi: Add iterators for multi-part commands")Signed-off-by Cristian Marussi <[email protected]>
You answered my question on this some versions back (wrt to where the magic size came from).
Cristian Marussi
reviewerRFC PATCH v17 2/34 firmware: arm_scmi: Additional iterators consistency checks
In reply to Cristian MarussiAdd a few more consistency checks around the number of returned and remaining items during the life of an iteration: this is useful to spot prematurely terminated iterations that would produce shorter than expected results.
Handling these anomalies in the platform multi-part replies within the core SCMI iterators machinery avoids the need to address such issues multiple times at the protocol layer.
---
RFC because this is another fix that is potentially disrupting for any non compliant SCMI platform deployed in the wild.
--- drivers/firmware/arm_scmi/driver.c | 36 ++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-)
drivers/firmware/arm_scmi/driver.c +32 -4
@@ -1852,7 +1852,7 @@ static int __scmi_iterator_run(void *iter, unsigned int *start, unsigned int *enconst struct scmi_protocol_handle *ph;struct scmi_iterator_state *st;struct scmi_iterator *i; -unsigned int n; +unsigned int n, i_start, i_max, i_returned;if (!iter)return -EINVAL ;
@@ -1862,10 +1862,15 @@ static int __scmi_iterator_run(void *iter, unsigned int *start, unsigned int *en ph = i->ph; st = &i->state; +/* Initialize iteration counters used to check consistency */ + i_max =0 ; + i_returned =0 ; + i_start = start ? *start :0 ; +/* Reinitialize state for next run */ st->num_returned =0 ; st->num_remaining =0 ; - st->desc_index = start ? *start :0 ; + st->desc_index = i_start; do { iops->prepare_message(i->msg, st->desc_index, i->priv);
@@ -1883,11 +1888,34 @@ static int __scmi_iterator_run(void *iter, unsigned int *start, unsigned int *enif (ret)return ret; -if (!st->num_returned && st->num_remaining) { -dev_err (ph->dev,"Inconsistent multi-part reply.\n" ); +/* +* Initialize max items expectation for this run based on +* values returned on first message exchange: during the +* following iterations consistency will be validated against +* these parameters, so as to spot FW anomalies like sudden +* termination or unplausible conditions. +*/ +if (!i_max) + i_max = i_start + st->num_returned + st->num_remaining; + +if ((!st->num_returned && st->num_remaining) || + (i_max != i_start + i_returned + st->num_returned + st->num_remaining)) { +dev_err (ph->dev, +"Inconsistent multi-part reply. max:%u i_max:%u i_start:%u i_returned:%u returned:%u remaining:%u desc_index:%u\n" , + st->max_resources, i_max, i_start, i_returned, + st->num_returned, st->num_remaining, + st->desc_index);return -EINVAL ; } +dev_dbg (ph->dev, +"Multi-part - max:%u i_max:%u i_start:%u i_returned:%u returned:%u remaining:%u desc_index:%u\n" , + st->max_resources, i_max, i_start, i_returned, + st->num_returned, st->num_remaining, st->desc_index); + +/* Account for last batch received */ + i_returned += st->num_returned; +if (st->num_returned > st->max_resources - st->desc_index) { dev_err(ph->dev, "No. of resources can't exceed %d\n",
Signature · 1 line
2.54.0
Re: [PATCH v17 02/34] [RFC] firmware: arm_scmi: Additional iterators consistency checks
Quoted 5 lines · On Tue, 24 Nov 2026 19:48:08 +0000 Cristian Marussi <[email protected]>…
Add a few more consistency checks around the number of returned and remaining items during the life of an iteration: this is useful to spot prematurely terminated iterations that would produce shorter than expected results.
Quoted 8 lines
Handling these anomalies in the platform multi-part replies within the core SCMI iterators machinery avoids the need to address such issues multiple times at the protocol layer.
Signed-off-by Cristian Marussi <[email protected]>---
RFC because this is another fix that is potentially disrupting for any non compliant SCMI platform deployed in the wild.
Looks sensible to me and cutting out weirdness as early as possible should make everything more resilient. If there is a broken implementation out there (and to hit these is not definitely not great) then quirk that when it surfaces.
Quoted 71 lines
--- drivers/firmware/arm_scmi/driver.c | 36 ++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-)drivers/firmware/arm_scmi/driver.c +32
-4@@ -1852,7 +1852,7 @@ static int __scmi_iterator_run(void *iter, unsigned int *start, unsigned int *enconst struct scmi_protocol_handle *ph;struct scmi_iterator_state *st;struct scmi_iterator *i; -unsigned int n; +unsigned int n, i_start, i_max, i_returned;if (!iter)return -EINVAL ;@@ -1862,10 +1862,15 @@ static int __scmi_iterator_run(void *iter, unsigned int *start, unsigned int *en ph = i->ph; st = &i->state; +/* Initialize iteration counters used to check consistency */ + i_max =0 ; + i_returned =0 ; + i_start = start ? *start :0 ; +/* Reinitialize state for next run */ st->num_returned =0 ; st->num_remaining =0 ; - st->desc_index = start ? *start :0 ; + st->desc_index = i_start; do { iops->prepare_message(i->msg, st->desc_index, i->priv);@@ -1883,11 +1888,34 @@ static int __scmi_iterator_run(void *iter, unsigned int *start, unsigned int *enif (ret)return ret; -if (!st->num_returned && st->num_remaining) { -dev_err (ph->dev,"Inconsistent multi-part reply.\n" ); +/* +* Initialize max items expectation for this run based on +* values returned on first message exchange: during the +* following iterations consistency will be validated against +* these parameters, so as to spot FW anomalies like sudden +* termination or unplausible conditions. +*/ +if (!i_max) + i_max = i_start + st->num_returned + st->num_remaining; + +if ((!st->num_returned && st->num_remaining) || + (i_max != i_start + i_returned + st->num_returned + st->num_remaining)) { +dev_err (ph->dev, +"Inconsistent multi-part reply. max:%u i_max:%u i_start:%u i_returned:%u returned:%u remaining:%u desc_index:%u\n" , + st->max_resources, i_max, i_start, i_returned, + st->num_returned, st->num_remaining, + st->desc_index);return -EINVAL ; } +dev_dbg (ph->dev, +"Multi-part - max:%u i_max:%u i_start:%u i_returned:%u returned:%u remaining:%u desc_index:%u\n" , + st->max_resources, i_max, i_start, i_returned, + st->num_returned, st->num_remaining, st->desc_index); + +/* Account for last batch received */ + i_returned += st->num_returned; +if (st->num_returned > st->max_resources - st->desc_index) { dev_err(ph->dev, "No. of resources can't exceed %d\n",
Cristian Marussi
reviewerPATCH v17 3/34 firmware: arm_scmi: Make Clock attributes size deterministic
In reply to Cristian MarussiSCMI Clock protocol CLOCK_ATTRIBUTES command varied in its reply payload size together with the specification evolution.
Between Clock version 0x10000 and 0x20000 one trailing field was added. The current implementation used the maximum possible payload size across any protocol version as the rx_size paramenter passed to xfer_get_init:
such solution works fine but inhibits any possible centralized check on the size of the received reply.
Size the requested reply strictly according to the expected protocol version.
--- drivers/firmware/arm_scmi/clock.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-)
drivers/firmware/arm_scmi/clock.c +10 -2
@@ -362,10 +362,14 @@ static int scmi_clock_attributes_get(const struct scmi_protocol_handle *ph,u32 attributes;struct scmi_xfer *t;struct scmi_msg_resp_clock_attributes *attr; +size_t rx_size =sizeof (*attr);struct scmi_clock_info *clk =CLOCK_INFO (cinfo, clk_id); +if (PROTOCOL_REV_MAJOR (ph->version) <0x2 ) + rx_size -=sizeof (attr->clock_enable_latency); + ret = ph->xops->xfer_get_init (ph,CLOCK_ATTRIBUTES , -sizeof (clk_id),sizeof (*attr), &t); +sizeof (clk_id), rx_size, &t);if (ret)return ret;
@@ -1002,12 +1006,16 @@ scmi_clock_config_get(const struct scmi_protocol_handle *ph, u32 clk_id,int ret;struct scmi_xfer *t;struct scmi_msg_resp_clock_attributes *resp; +size_t rx_size =sizeof (*resp);if (!enabled)return -EINVAL ; +if (PROTOCOL_REV_MAJOR (ph->version) <0x2 ) + rx_size -=sizeof (resp->clock_enable_latency); + ret = ph->xops->xfer_get_init (ph,CLOCK_ATTRIBUTES , -sizeof (clk_id),sizeof (*resp), &t); +sizeof (clk_id), rx_size, &t);if (ret)return ret;
Signature · 1 line
2.54.0
Re: [PATCH v17 03/34] firmware: arm_scmi: Make Clock attributes size deterministic
Quoted 9 lines · On Tue, 24 Nov 2026 19:48:09 +0000 Cristian Marussi <[email protected]>…
SCMI Clock protocol
CLOCK_ATTRIBUTEScommand varied in its reply payload size together with the specification evolution.Between Clock version
0x10000and0x20000one trailing field was added. The current implementation used the maximum possible payload size across any protocol version as therx_sizeparamenter passed toxfer_get_init:
such solution works fine but inhibits any possible centralized check on the size of the received reply.
Quoted 4 lines
Size the requested reply strictly according to the expected protocol version.
Signed-off-by Cristian Marussi <[email protected]>
You could use offsetof() so it doesn't matter if yet more fields turn up later. In practice though you'll then have 3 options so this code will change anyway, so meh. This is fine.
Being lazy I didn't check old specs :)
Quoted 42 lines
--- drivers/firmware/arm_scmi/clock.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-)drivers/firmware/arm_scmi/clock.c +10
-2@@ -362,10 +362,14 @@ static int scmi_clock_attributes_get(const struct scmi_protocol_handle *ph,u32 attributes;struct scmi_xfer *t;struct scmi_msg_resp_clock_attributes *attr; +size_t rx_size =sizeof (*attr);struct scmi_clock_info *clk =CLOCK_INFO (cinfo, clk_id); +if (PROTOCOL_REV_MAJOR (ph->version) <0x2 ) + rx_size -=sizeof (attr->clock_enable_latency); + ret = ph->xops->xfer_get_init (ph,CLOCK_ATTRIBUTES , -sizeof (clk_id),sizeof (*attr), &t); +sizeof (clk_id), rx_size, &t);if (ret)return ret;@@ -1002,12 +1006,16 @@ scmi_clock_config_get(const struct scmi_protocol_handle *ph, u32 clk_id,int ret;struct scmi_xfer *t;struct scmi_msg_resp_clock_attributes *resp; +size_t rx_size =sizeof (*resp);if (!enabled)return -EINVAL ; +if (PROTOCOL_REV_MAJOR (ph->version) <0x2 ) + rx_size -=sizeof (resp->clock_enable_latency); + ret = ph->xops->xfer_get_init (ph,CLOCK_ATTRIBUTES , -sizeof (clk_id),sizeof (*resp), &t); +sizeof (clk_id), rx_size, &t);if (ret)return ret;
Cristian Marussi
reviewerPATCH v17 4/34 firmware: arm_scmi: Add centralized detection of truncated replies
In reply to Cristian MarussiWhen an xfer is allocated with a very well known fixed reply size by providing a non-zero rx_size parameter to xfer_get_init(), it becomes possible to verify if the effectively received reply was truncated.
Add the logic to detect and report truncated replies.
---
v16 --> v17
- use %zu
- consider expected_size when reset_rx_to_max
--- drivers/firmware/arm_scmi/driver.c | 14 +++++++++++++- drivers/firmware/arm_scmi/protocols.h | 8 ++++++++ drivers/firmware/arm_scmi/raw_mode.c | 1 + 3 files changed, 22 insertions(+), 1 deletion(-)
drivers/firmware/arm_scmi/driver.c +13 -1
@@ -1356,6 +1356,16 @@ static int scmi_wait_for_reply(struct device *dev, const struct scmi_desc *desc, } } +/* Check for truncated messages..it will be logged by the caller */ +if (!ret && !xfer->hdr.status && xfer->expected_rx_len && + xfer->expected_rx_len != xfer->rx.len) { +dev_dbg (dev, +"Truncated reply - HDR:%08X expected:%zu received:%zu\n" , +pack_scmi_header (&xfer->hdr), xfer->expected_rx_len, + xfer->rx.len); + xfer->hdr.status =SCMI_ERR_COMMS ; + } +return ret; }
@@ -1508,7 +1518,7 @@ static void reset_rx_to_maxsz(const struct scmi_protocol_handle *ph,const struct scmi_protocol_instance *pi =ph_to_pi (ph);struct scmi_info *info =handle_to_scmi_info (pi->handle); - xfer->rx.len = info->desc->max_msg_size; + xfer->rx.len = xfer->expected_rx_len ?: info->desc->max_msg_size; }/**
@@ -1616,6 +1626,8 @@ static int xfer_get_init(const struct scmi_protocol_handle *ph, xfer->tx.len = tx_size; xfer->rx.len = rx_size ? : info->desc->max_msg_size; +/* When a specific rx_size was specified, check for truncation */ + xfer->expected_rx_len = rx_size ? :0 ; xfer->hdr.type =MSG_TYPE_COMMAND ; xfer->hdr.id = msg_id; xfer->hdr.poll_completion = false;
drivers/firmware/arm_scmi/protocols.h +8 -0
@@ -106,6 +106,13 @@ struct scmi_msg_hdr {* @rx: Receive message, the buffer should be pre-allocated to store * message. If request-ACK protocol is used, we can reuse the same * buffer for the rx path as we use for the tx path. +* @expected_rx_len: The expected length of the payload in the reply, excluding +* the status field. When set to a non-zero value this is used +* to evaluate if a reply had been possibly truncated due to a +* misconfigured transport: it is only set to some meaningful +* non-zero value for replies having a very well known fixed +* size, definitely not for variable-sized xfers with an RX +* len initialized to max_msg_size. * @done: command message transmit completion event * @async_done: pointer to delayed response message received event completion, * or NULL when no delayed response is expected. Protected by
@@ -139,6 +146,7 @@ struct scmi_xfer {struct scmi_msg_hdr hdr;struct scmi_msg tx;struct scmi_msg rx; +size_t expected_rx_len;struct completion done;struct completion *async_done;bool pending;
drivers/firmware/arm_scmi/raw_mode.c +1 -0
@@ -574,6 +574,7 @@ static int scmi_xfer_raw_get_init(struct scmi_raw_mode_info *raw, void *buf, xfer->hdr.status =SCMI_SUCCESS ; xfer->tx.len = tx_size; xfer->rx.len = raw->desc->max_msg_size; + xfer->expected_rx_len =0 ;/* Clear the whole TX buffer */ memset (xfer->tx.buf,0x00 , raw->desc->max_msg_size);if (xfer->tx.len)
Signature · 1 line
2.54.0
Re: [PATCH v17 04/34] firmware: arm_scmi: Add centralized detection of truncated replies
Quoted 7 lines · On Tue, 24 Nov 2026 19:48:10 +0000 Cristian Marussi <[email protected]>…
When an xfer is allocated with a very well known fixed reply size by providing a non-zero
rx_sizeparameter toxfer_get_init(), it becomes possible to verify if the effectively received reply was truncated.Add the logic to detect and report truncated replies.
Signed-off-by Cristian Marussi <[email protected]>
A suggestion to perhaps move this to a different layer.
I don't feel that strongly about it though, so whilst that is my preference this is fine if not.
Quoted 17 lines
---
v16 --> v17
- use %zu
- considerexpected_sizewhenreset_rx_to_max--- drivers/firmware/arm_scmi/driver.c | 14 +++++++++++++- drivers/firmware/arm_scmi/protocols.h | 8 ++++++++ drivers/firmware/arm_scmi/raw_mode.c | 1 + 3 files changed, 22 insertions(+), 1 deletion(-)drivers/firmware/arm_scmi/driver.c +0
-0@@ -1356,6 +1356,16 @@ static int scmi_wait_for_reply(struct device *dev, const struct scmi_desc *desc, } }
drivers/firmware/arm_scmi/driver.c static int scmi_wait_for_reply(struct device *dev, const struct scmi_desc *desc, · line 1367
Quoted 10 lines
drivers/firmware/arm_scmi/driver.c +9
-0+/* Check for truncated messages..it will be logged by the caller */ +if (!ret && !xfer->hdr.status && xfer->expected_rx_len && + xfer->expected_rx_len != xfer->rx.len) { +dev_dbg (dev, +"Truncated reply - HDR:%08X expected:%zu received:%zu\n" , +pack_scmi_header (&xfer->hdr), xfer->expected_rx_len, + xfer->rx.len); + xfer->hdr.status =SCMI_ERR_COMMS ; + }
The check is good but it's the only validation done in this function and the naming doesn't suggest any validation would be done in here.
There are only two call chains to this, so maybe it makes more sense to move it up to do_xfer() / scmi_xfer_raw_worker()?
Small amount of duplication but in a place I think feels a little more natural.
Quoted 60 lines
drivers/firmware/arm_scmi/driver.c +4
-1+return ret; }@@ -1508,7 +1518,7 @@ static void reset_rx_to_maxsz(const struct scmi_protocol_handle *ph,const struct scmi_protocol_instance *pi =ph_to_pi (ph);struct scmi_info *info =handle_to_scmi_info (pi->handle); - xfer->rx.len = info->desc->max_msg_size; + xfer->rx.len = xfer->expected_rx_len ?: info->desc->max_msg_size; }/** @@ -1616,6 +1626,8 @@ static int xfer_get_init(const struct scmi_protocol_handle *ph, xfer->tx.len = tx_size; xfer->rx.len = rx_size ? : info->desc->max_msg_size; +/* When a specific rx_size was specified, check for truncation */ + xfer->expected_rx_len = rx_size ? :0 ; xfer->hdr.type =MSG_TYPE_COMMAND ; xfer->hdr.id = msg_id; xfer->hdr.poll_completion = false;drivers/firmware/arm_scmi/protocols.h +8
-0@@ -106,6 +106,13 @@ struct scmi_msg_hdr {* @rx: Receive message, the buffer should be pre-allocated to store * message. If request-ACK protocol is used, we can reuse the same * buffer for the rx path as we use for the tx path. +* @expected_rx_len: The expected length of the payload in the reply, excluding +* the status field. When set to a non-zero value this is used +* to evaluate if a reply had been possibly truncated due to a +* misconfigured transport: it is only set to some meaningful +* non-zero value for replies having a very well known fixed +* size, definitely not for variable-sized xfers with an RX +* len initialized to max_msg_size. * @done: command message transmit completion event * @async_done: pointer to delayed response message received event completion, * or NULL when no delayed response is expected. Protected by @@ -139,6 +146,7 @@ struct scmi_xfer {struct scmi_msg_hdr hdr;struct scmi_msg tx;struct scmi_msg rx; +size_t expected_rx_len;struct completion done;struct completion *async_done;bool pending;drivers/firmware/arm_scmi/raw_mode.c +1
-0@@ -574,6 +574,7 @@ static int scmi_xfer_raw_get_init(struct scmi_raw_mode_info *raw, void *buf, xfer->hdr.status =SCMI_SUCCESS ; xfer->tx.len = tx_size; xfer->rx.len = raw->desc->max_msg_size; + xfer->expected_rx_len =0 ;/* Clear the whole TX buffer */ memset (xfer->tx.buf,0x00 , raw->desc->max_msg_size);if (xfer->tx.len)
Cristian Marussi
reviewerPATCH v17 5/34 firmware: arm_scmi: Introduce a dedicated SCMI Errors header
In reply to Cristian MarussiAdd a new dedicated header and move all of the errors definitions and mapping helpers into it and out of common.h so that SCMI errors definitions alone can be easily included in protocol files without all of the unrelated additional stuff contained in common.h
--- drivers/firmware/arm_scmi/common.h | 39 +--------------------- drivers/firmware/arm_scmi/errors.h | 52 ++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 38 deletions(-) create mode 100644 drivers/firmware/arm_scmi/errors.h
drivers/firmware/arm_scmi/common.h +1 -38
@@ -26,6 +26,7 @@#include <linux/unaligned.h> +#include "errors.h" #include "protocols.h" #include "notify.h"
@@ -37,44 +38,6 @@#define SCMI_TRANSPORT_DEVNAME_PREFIX "__scmi_transport_device" -enum scmi_error_codes { -SCMI_SUCCESS =0 ,/* Success */ -SCMI_ERR_SUPPORT =-1 ,/* Not supported */ -SCMI_ERR_PARAMS =-2 ,/* Invalid Parameters */ -SCMI_ERR_ACCESS =-3 ,/* Invalid access/permission denied */ -SCMI_ERR_ENTRY =-4 ,/* Not found */ -SCMI_ERR_RANGE =-5 ,/* Value out of range */ -SCMI_ERR_BUSY =-6 ,/* Device busy */ -SCMI_ERR_COMMS =-7 ,/* Communication Error */ -SCMI_ERR_GENERIC =-8 ,/* Generic Error */ -SCMI_ERR_HARDWARE =-9 ,/* Hardware Error */ -SCMI_ERR_PROTOCOL =-10 ,/* Protocol Error */ -}; - -static const int scmi_linux_errmap[] = { -/* better than switch case as long as return value is continuous */ -0 ,/* SCMI_SUCCESS */ - -EOPNOTSUPP ,/* SCMI_ERR_SUPPORT */ - -EINVAL ,/* SCMI_ERR_PARAM */ - -EACCES ,/* SCMI_ERR_ACCESS */ - -ENOENT ,/* SCMI_ERR_ENTRY */ - -ERANGE ,/* SCMI_ERR_RANGE */ - -EBUSY ,/* SCMI_ERR_BUSY */ - -ECOMM ,/* SCMI_ERR_COMMS */ - -EIO ,/* SCMI_ERR_GENERIC */ - -EREMOTEIO ,/* SCMI_ERR_HARDWARE */ - -EPROTO ,/* SCMI_ERR_PROTOCOL */ -}; - -static inline int scmi_to_linux_errno (int errno) -{ -int err_idx = -errno; - -if (err_idx >=SCMI_SUCCESS && err_idx <ARRAY_SIZE (scmi_linux_errmap)) -return scmi_linux_errmap[err_idx]; -return -EIO ; -} -#define MSG_ID_MASK GENMASK(7, 0)#define MSG_XTRACT_ID (hdr) FIELD_GET(MSG_ID_MASK, (hdr))#define MSG_TYPE_MASK GENMASK(9, 8)
drivers/firmware/arm_scmi/errors.h new file +52 -0
52 lines not on this page · raw message
Signature · 1 line
2.54.0
Re: [PATCH v17 05/34] firmware: arm_scmi: Introduce a dedicated SCMI Errors header
Quoted 6 lines · On Tue, 24 Nov 2026 19:48:11 +0000 Cristian Marussi <[email protected]>…
Add a new dedicated header and move all of the errors definitions and mapping helpers into it and out of
common.hso that SCMI errors definitions alone can be easily included in protocol files without all of the unrelated additional stuff contained incommon.hSigned-off-by Cristian Marussi <[email protected]>
Cristian Marussi
reviewerPATCH v17 6/34 firmware: arm_scmi: Add new SCMIv4.0 error codes definitions
In reply to Cristian MarussiSCMIv4.0 introduces a couple of new possible protocol error codes: add the needed definitions and mappings to Linux error values.
Note that SCMI_PARTIAL_ERROR has to be handled specially and as such it needs to be distinguishable but, as of now, all of the available sensible error codes are already mapped to some other pre-existent SCMI error condition, so we settled on -EBADMSG which is far from ideal, but at least kind of captures the nature of the underlying issue.
---
v12 --> v13
- use EBADMSG to map SCMI_PARTIAL_ERROR
v4 --> v5
- map SCMI_ERR_IN_USE to EBUSY as natural
--- drivers/firmware/arm_scmi/errors.h | 4 ++++ 1 file changed, 4 insertions(+)
drivers/firmware/arm_scmi/errors.h +4 -0
@@ -23,6 +23,8 @@ enum scmi_error_codes {SCMI_ERR_GENERIC =-8 ,/* Generic Error */ SCMI_ERR_HARDWARE =-9 ,/* Hardware Error */ SCMI_ERR_PROTOCOL =-10 ,/* Protocol Error */ +SCMI_ERR_IN_USE =-11 ,/* In Use Error */ + SCMI_ERR_PARTIAL = -12, /* Partial Error */ }; static const int scmi_linux_errmap[] = {
@@ -38,6 +40,8 @@ static const int scmi_linux_errmap[] = { -EIO ,/* SCMI_ERR_GENERIC */ -EREMOTEIO ,/* SCMI_ERR_HARDWARE */ -EPROTO ,/* SCMI_ERR_PROTOCOL */ + -EBUSY ,/* SCMI_ERR_IN_USE */ + -EBADMSG, /* SCMI_ERR_PARTIAL */ };static inline int scmi_to_linux_errno (int errno)
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 7/34 firmware: arm_scmi: Allow registration of unknown-size events/reports
In reply to Cristian MarussiAllow protocols to register events with build-time unknown sizes: such events can be declared zero-sized and let the core SCMI stack perform the needed safe-net boundary checks based on the configured transport size.
---
v14 --> v15
- better commenting
v12 --> v13
- improve variable naming
v10 --> v11
- account for ktime_t field when checking boundary
v2 --> v3
- split out of previous patch on protocol notifier
- use max() instead of max_t()
--- drivers/firmware/arm_scmi/notify.c | 28 +++++++++++++++++++++++----- drivers/firmware/arm_scmi/notify.h | 8 ++++++-- 2 files changed, 29 insertions(+), 7 deletions(-)
drivers/firmware/arm_scmi/notify.c +23 -5
@@ -595,7 +595,16 @@ int scmi_notify(const struct scmi_handle *handle, u8 proto_id, u8 evt_id,if (!r_evt)return -EINVAL ; -if (len > r_evt->evt->max_payld_sz) { +/* +* Events with a zero max_payld_sz are sized to be of the maximum +* size allowed by the transport: no need to be size-checked here +* since the transport layer would have already dropped such +* over-sized messages. +* Note that, though, while this protects from buffer overruns, it is +* no more possible at this layer of the stack to detect zero-sized +* events corrupted by truncation. +*/ +if (r_evt->evt->max_payld_sz && len > r_evt->evt->max_payld_sz) {dev_err (handle->dev,"discard badly sized message\n" );return -EINVAL ; }
@@ -751,7 +760,7 @@ int scmi_register_protocol_events(const struct scmi_handle *handle, u8 proto_id,const struct scmi_protocol_handle *ph, const struct scmi_protocol_events *ee) { - int i; + int i, max_msg_sz, default_report_sz;unsigned int num_sources;size_t payld_sz =0 ;struct scmi_registered_events_desc *pd;
@@ -766,6 +775,9 @@ int scmi_register_protocol_events(const struct scmi_handle *handle, u8 proto_id,if (!ni)return -ENOMEM ; + max_msg_sz = ph->hops->get_max_msg_size (ph); + default_report_sz = max_msg_sz +sizeof (ktime_t); +/* num_sources cannot be <= 0 */ if (ee->num_sources) { num_sources = ee->num_sources;
@@ -778,8 +790,13 @@ int scmi_register_protocol_events(const struct scmi_handle *handle, u8 proto_id, } evt = ee->evts; -for (i =0 ; i < ee->num_events; i++) - payld_sz =max_t (size_t, payld_sz, evt[i].max_payld_sz); +for (i =0 ; i < ee->num_events; i++) { +if (evt[i].max_payld_sz ==0 ) { + payld_sz = max_msg_sz; +break ; + } + payld_sz =max (payld_sz, evt[i].max_payld_sz); + } payld_sz +=sizeof (struct scmi_event_header ); pd = scmi_allocate_registered_events_desc(ni, proto_id, ee->queue_sz,
@@ -805,7 +822,8 @@ int scmi_register_protocol_events(const struct scmi_handle *handle, u8 proto_id,mutex_init (&r_evt->sources_mtx); r_evt->report =devm_kzalloc (ni->handle->dev, - evt->max_report_sz,GFP_KERNEL ); + evt->max_report_sz ?: default_report_sz, +GFP_KERNEL );if (!r_evt->report)return -ENOMEM ;
drivers/firmware/arm_scmi/notify.h +6 -2
@@ -18,8 +18,12 @@/** * struct scmi_event - Describes an event to be supported * @id: Event ID -* @max_payld_sz: Max possible size for the payload of a notification message -* @max_report_sz: Max possible size for the report of a notification message +* @max_payld_sz: Max possible size for the payload of a notification message. +* Set to zero to use the maximum message size allowed by the +* transport. +* @max_report_sz: Max possible size for the report of a notification message. +* Set to zero to use the maximum message size allowed by the +* transport plus the additional ktime_t timestamp. * * Each SCMI protocol, during its initialization phase, can describe the events * it wishes to support in a few struct scmi_event and pass them to the core
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 8/34 firmware: arm_scmi: Refactor __scmi_event_handler_get_ops helper
In reply to Cristian MarussiRefactor the __scmi_event_handler_get_ops notification helper to simplify its logic and make use of guards for locking.
Event handler allocation is split out of registration in a dedicated helper so as to allow for future reuse.
Mostly no functional change, in the sense that while the functionality remained the same, a richer set of errors is returned where before was always a -EINVAL.
---
v14 --> v15
- reworked error path in scmi_allocate_pending_event_handler
- improve commit message
--- drivers/firmware/arm_scmi/notify.c | 74 +++++++++++++++++++----------- 1 file changed, 47 insertions(+), 27 deletions(-)
drivers/firmware/arm_scmi/notify.c +47 -27
@@ -891,7 +891,6 @@ void scmi_deregister_protocol_events(const struct scmi_handle *handle,/** * scmi_allocate_event_handler() - Allocate Event handler -* @ni: A reference to the notification instance to use * @evt_key: 32bit key uniquely bind to the event identified by the tuple * (proto_id, evt_id, src_id) *
@@ -901,21 +900,33 @@ void scmi_deregister_protocol_events(const struct scmi_handle *handle,* associated to this handler descriptor (hndl->r_evt == NULL), so the handler * is initialized as pending. * -* Context: Assumes to be called with @pending_mtx already acquired. * Return: the freshly allocated structure on Success */ -static struct scmi_event_handler * -scmi_allocate_event_handler (struct scmi_notify_instance *ni,u32 evt_key) +static struct scmi_event_handler *scmi_allocate_event_handler (u32 evt_key) {struct scmi_event_handler *hndl; hndl =kzalloc_obj (*hndl);if (!hndl)return NULL ; + hndl->key = evt_key;BLOCKING_INIT_NOTIFIER_HEAD (&hndl->chain);refcount_set (&hndl->users,1 ); -/* New handlers are created pending */ + +return hndl; +} + +static struct scmi_event_handler * +scmi_allocate_pending_event_handler (struct scmi_notify_instance *ni,u32 evt_key) +{ +struct scmi_event_handler *hndl; + +lockdep_assert_held (&ni->pending_mtx); + hndl =scmi_allocate_event_handler (evt_key); +if (!hndl) +return NULL ; +hash_add (ni->pending_events_handlers, &hndl->hash, hndl->key);return hndl;
@@ -1085,7 +1096,8 @@ __scmi_event_handler_get_ops(struct scmi_notify_instance *ni, u32 evt_key, bool create) {struct scmi_registered_event *r_evt; -struct scmi_event_handler *hndl =NULL ; +struct scmi_event_handler *hndl; +int ret; r_evt =SCMI_GET_REVT (ni,KEY_XTRACT_PROTO_ID (evt_key),KEY_XTRACT_EVT_ID (evt_key));
@@ -1093,39 +1105,47 @@ __scmi_event_handler_get_ops(struct scmi_notify_instance *ni,if (r_evt && r_evt->not_supported_by_platform)return ERR_PTR (-EOPNOTSUPP ); -mutex_lock (&ni->pending_mtx); +guard (mutex)(&ni->pending_mtx);/* Search registered events at first ... if possible at all */ if (r_evt) { -mutex_lock (&r_evt->proto->registered_mtx); +guard (mutex)(&r_evt->proto->registered_mtx); hndl =KEY_FIND (r_evt->proto->registered_events_handlers, hndl, evt_key); -if (hndl) +if (hndl) {refcount_inc (&hndl->users); -mutex_unlock (&r_evt->proto->registered_mtx); +return hndl; + } }/* ...then amongst pending. */ -if (!hndl) { - hndl =KEY_FIND (ni->pending_events_handlers, hndl, evt_key); -if (hndl) -refcount_inc (&hndl->users); + hndl =KEY_FIND (ni->pending_events_handlers, hndl, evt_key); +if (hndl) { +refcount_inc (&hndl->users); +return hndl; } -/* Create if still not found and required */ -if (!hndl && create) { - hndl =scmi_allocate_event_handler (ni, evt_key); -if (hndl &&scmi_register_event_handler (ni, hndl)) { -dev_dbg (ni->handle->dev, -"purging UNKNOWN handler - key:%X\n" , - hndl->key); -/* this hndl can be only a pending one */ -scmi_put_handler_unlocked (ni, hndl); - hndl =ERR_PTR (-EINVAL ); - } +if (!create) +return ERR_PTR (-ENODEV ); + +/* +* Create if still not found and required, new handlers are +* created pending and transitioned to registered when bound to +* an event. +*/ + hndl =scmi_allocate_pending_event_handler (ni, evt_key); +if (!hndl) +return ERR_PTR (-ENOMEM ); + + ret =scmi_register_event_handler (ni, hndl); +if (ret) { +dev_dbg (ni->handle->dev, +"purging UNKNOWN handler - key:%X\n" , hndl->key); +/* this hndl can be only a pending one */ +scmi_put_handler_unlocked (ni, hndl); +return ERR_PTR (ret); } -mutex_unlock (&ni->pending_mtx); -return hndl ?:ERR_PTR (-ENODEV ); +return hndl; } static struct scmi_event_handler *
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 9/34 dt-bindings: firmware: arm,scmi: Add support for telemetry protocol
In reply to Cristian MarussiAdd new SCMI v4.0 Telemetry protocol bindings definitions.
---
v3 --> v4
- changed protocol number to lowercase 1b
- fixed misplaced block for protocol 0x1b
--- Documentation/devicetree/bindings/firmware/arm,scmi.yaml | 8 ++++++++ 1 file changed, 8 insertions(+)
Documentation/devicetree/bindings/firmware/arm,scmi.yaml +8 -0
@@ -324,6 +324,14 @@ properties: required: - reg + protocol@1b: + $ref: '#/$defs/protocol-node' + unevaluatedProperties: false + + properties: + reg: + const: 0x1b + unevaluatedProperties: false $defs:
Signature · 1 line
2.54.0
Re: [PATCH v17 09/34] dt-bindings: firmware: arm,scmi: Add support for telemetry protocol
Quoted 4 lines · On Tue, 24 Nov 2026 19:48:15 +0000 Cristian Marussi <[email protected]>…
Add new SCMI v4.0 Telemetry protocol bindings definitions.
Signed-off-by Cristian Marussi <[email protected]>
Cristian Marussi
reviewerPATCH v17 10/34 include: trace: Add Telemetry trace events
In reply to Cristian MarussiAdd custom traces to report Telemetry accesses and collection events.
---
v12 --> v13
- better commit message
- use const char where required
v7 --> v8
- use proper FTRACE helpers for variable strings
--- include/trace/events/scmi.h | 45 +++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+)
include/trace/events/scmi.h +45 -0
@@ -178,6 +178,51 @@ TRACE_EVENT(scmi_msg_dump,__get_str (tag), __entry->msg_id, __entry->seq, __entry->status, __print_hex_str(__get_dynamic_array(cmd), __entry->len)) ); + +TRACE_EVENT (scmi_tlm_access, + TP_PROTO(u64 de_id, const char *tag, u64 startm, u64 endm), +TP_ARGS (de_id, tag, startm, endm), + +TP_STRUCT__entry ( + __field(u64, de_id) + __string(tag, tag) + __field(u64, startm) +__field (u64, endm) + ), + +TP_fast_assign ( + __entry->de_id = de_id; + __assign_str(tag); + __entry->startm = startm; + __entry->endm = endm; + ), + +TP_printk ("[%s] de_id=0x%llX - startm=%016llX endm=%016llX" , +__get_str (tag), __entry->de_id, __entry->startm, __entry->endm) +); + +TRACE_EVENT (scmi_tlm_collect, + TP_PROTO(u64 ts, u64 de_id, u64 value, const char *tag), +TP_ARGS (ts, de_id, value, tag), + +TP_STRUCT__entry ( + __field(u64, ts) + __field(u64, de_id) + __field(u64, value) +__string (tag, tag) + ), + +TP_fast_assign ( + __entry->ts = ts; + __entry->de_id = de_id; + __entry->value = value; + __assign_str(tag); + ), + +TP_printk ("[%s] ts=%llu de_id=0x%04llX value=%016llu" , +__get_str (tag), __entry->ts, __entry->de_id, __entry->value) +); +#endif /* _TRACE_SCMI_H */ /* This part must be outside protection */
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 11/34 firmware: arm_scmi: Add Telemetry basic attributes enumeration
In reply to Cristian MarussiAdd SCMIv4.0 Telemetry basic support for minimal initialization and protocol attributes enumeration: expose telemetry instance descriptor via a simple information retrieval protocol operation.
---
v15 --> v16
- ignore groups
v14 --> v15
- add include uuid.h into scmi_protocol.h
- dropped needless __must_check
v13 --> v14
- split original basic Telemetry patch, reducing this patch to the basics of protocol attributes enumeration only
- fix group unroll loop on groups_init failure
- remove goto from de_desc_parse
- renamed some fields to more strictly adhere to spec nomenclature
v12 --> v13
- headers includes re-order
- rework cleanup path for instance allocations
- relocate tde->mtx guards higher up and add lockdep assertions
- add more _RAW macros
- rename DE_CONFIGURE defines
- use *alloc_objs
- remove TO_CPU64 and useless READ_ONCEs
v11 --> v12
- dropped counted-by in smhtis
- reworked barriers around res_get
- added smp_store_release on TDE registration
v10 -->v11
- relocated a few parsing macros from another patch
- cleanup exit path on resource enumeration
- remove 'naked' ti->rinfo accesses
- walk xa_des to free DEs on removal
v8 --> v9
- Fixes for some Sashiko issues on v8
- use counted_by_lle where appropriate
- consider header in boudanry check in DE_DESCRIPTION iterators
- bail out if SHMTI areas are NOT 32bit aligned
- warn if SHMTI areas are NOT 64bit aligned
- convert SCMI_TDE_VAR_SZ macro to an inline function
- make some enum definition explicit
v7 --> v8
- Fixes for some Sashiko issues on v7
- add proper msg boundary parsing checks on DE_DESCRIPTION multipart
- add proper cleanup/rollback on groups_init err_path
- update num_des_tstamp ONLY after a DE is successfully initialized
- proper cleanup tde during tde_put (preserving info/mutex bits)
- add membarriers in enumerate resources
- add a check and a warn on SHMTI phys_addr alignment
- reword a few dev_errs
- use tde_free_put on resoucers_free
v6 --> v7
- use uuid_t for proper Telemetry UUID DE_IMPL_VERSION endianity
v5 --> v6
- define uuid_line dwords as BE
- fixed Sashiko reviews where applicable:
https://sashiko.dev/#/message/20260703123601.381275-8-cristian.marussi%40arm.com
- fix missing le32 and bound check in variable payload parsing
- fix TDE duplicatin logic
- fix intervals cleanup - fixes also KMEMLEAK report
- implement proper freeinfg for group resources
- proper SHMTI iterations
- removed useless/stale static in scmi_telemetry_tde_get()
v4 --> v5
- fix de->grp_id initialization for DEs not belonging to a group
- removed UAPI structures dependency
- expose discovered SHMTIs areas in scmi_protocol.h
- fixes sparse warnings
v3 -->v4
- bail-out on FW_BUG errors
- count timestamp capable DE to track enables
v2 --> v3
- split from monolithic Telemetry patch
- fix checkpatch macros complaints
- fix ACCESS_PRIVATE usage
- add a few comments on allocation/enumeration lifetime
- use interval.num_intervals
- removed needless cleanup handler usage
- simply return from scmi_telemetry_de_lookup()
- fixed composing_des name length to 08X
--- drivers/firmware/arm_scmi/Makefile | 2 +- drivers/firmware/arm_scmi/driver.c | 2 + drivers/firmware/arm_scmi/protocols.h | 1 + drivers/firmware/arm_scmi/telemetry.c | 149 ++++++++++++++++++++++++++ include/linux/scmi_protocol.h | 33 +++++- 5 files changed, 185 insertions(+), 2 deletions(-) create mode 100644 drivers/firmware/arm_scmi/telemetry.c
drivers/firmware/arm_scmi/Makefile +1 -1
@@ -8,7 +8,7 @@ scmi-driver-$(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT) += raw_mode.o scmi-transport-$(CONFIG_ARM_SCMI_HAVE_SHMEM) = shmem.o scmi-transport-$(CONFIG_ARM_SCMI_HAVE_MSG) += msg.o scmi-protocols-y := base.o clock.o perf.o power.o reset.o sensors.o system.o voltage.o powercap.o -scmi-protocols-y += pinctrl.o +scmi-protocols-y += pinctrl.o telemetry.o scmi-module-objs := $(scmi-driver-y) $(scmi-protocols-y) $(scmi-transport-y) obj-$(CONFIG_ARM_SCMI_PROTOCOL) += transports/
drivers/firmware/arm_scmi/driver.c +2 -0
@@ -3683,6 +3683,7 @@ static int __init scmi_driver_init(void)scmi_system_register ();scmi_powercap_register ();scmi_pinctrl_register (); +scmi_telemetry_register ();return platform_driver_register (&scmi_driver); }
@@ -3701,6 +3702,7 @@ static void __exit scmi_driver_exit(void)scmi_system_unregister ();scmi_powercap_unregister ();scmi_pinctrl_unregister (); +scmi_telemetry_unregister ();platform_driver_unregister (&scmi_driver);
drivers/firmware/arm_scmi/protocols.h +1 -0
@@ -409,5 +409,6 @@ DECLARE_SCMI_REGISTER_UNREGISTER(sensors);DECLARE_SCMI_REGISTER_UNREGISTER (voltage);DECLARE_SCMI_REGISTER_UNREGISTER (system);DECLARE_SCMI_REGISTER_UNREGISTER (powercap); +DECLARE_SCMI_REGISTER_UNREGISTER (telemetry);#endif /* _SCMI_PROTOCOLS_H */
drivers/firmware/arm_scmi/telemetry.c new file +149 -0
149 lines not on this page · raw message
include/linux/scmi_protocol.h +32 -1
@@ -2,17 +2,19 @@/* * SCMI Message Protocol driver header * -* Copyright (C) 2018-2021 ARM Ltd. +* Copyright (C) 2018-2026 ARM Ltd. */ #ifndef _LINUX_SCMI_PROTOCOL_H#define _LINUX_SCMI_PROTOCOL_H#include <linux/bitfield.h> +#include <linux/bitops.h> #include <linux/device-id/scmi.h> #include <linux/device.h> #include <linux/notifier.h> #include <linux/types.h> +#include <linux/uuid.h> #define SCMI_MAX_STR_SIZE 64#define SCMI_SHORT_NAME_MAX_SIZE 16
@@ -828,6 +830,35 @@ struct scmi_pinctrl_proto_ops {int (*pin_free)(const struct scmi_protocol_handle *ph,u32 pin); }; +struct scmi_telemetry_base_info { +unsigned int version; +uuid_t primary_revision; +unsigned int num_des; +unsigned int num_groups; +unsigned int num_intervals; +unsigned int num_shmtis; +}; + +struct scmi_telemetry_info { +bool single_read_support; +bool continuous_update_support; +bool per_group_config_support; +bool reset_support; +bool fc_support; +struct scmi_telemetry_base_info base; +}; + +/** +* struct scmi_telemetry_proto_ops - represents the various operations provided +* by SCMI Telemetry Protocol +* +* @info_get: get the general Telemetry information. +*/ +struct scmi_telemetry_proto_ops { +const struct scmi_telemetry_info *(*info_get) + (const struct scmi_protocol_handle *ph); +}; +/** * struct scmi_notify_ops - represents notifications' operations provided by * SCMI core
Signature · 1 line
2.54.0
Re: [PATCH v17 11/34] firmware: arm_scmi: Add Telemetry basic attributes enumeration
Quoted 8 lines · On Tue, 24 Nov 2026 19:48:17 +0000 Cristian Marussi <[email protected]>…
Add SCMIv4.0 Telemetry basic support for minimal initialization and protocol attributes enumeration: expose telemetry instance descriptor via a simple information retrieval protocol operation.
Signed-off-by Cristian Marussi <[email protected]>---
v15 --> v16
- ignore groups
Partly... Need to do a lot more ignoring to make this true and consistent. There are a few things in here, but key is we need the whole framework to be as unaware of groups as possible. At least up to the userspace interface layer where we may need to ensure extensibility.
Jonathan
Quoted 26 lines
include/linux/scmi_protocol.h +3
-1@@ -2,17 +2,19 @@/* * SCMI Message Protocol driver header * -* Copyright (C) 2018-2021 ARM Ltd. +* Copyright (C) 2018-2026 ARM Ltd. */ #ifndef _LINUX_SCMI_PROTOCOL_H#define _LINUX_SCMI_PROTOCOL_H#include <linux/bitfield.h> +#include <linux/bitops.h> #include <linux/device-id/scmi.h> #include <linux/device.h> #include <linux/notifier.h> #include <linux/types.h> +#include <linux/uuid.h> #define SCMI_MAX_STR_SIZE 64#define SCMI_SHORT_NAME_MAX_SIZE 16
include/linux/scmi_protocol.h struct scmi_pinctrl_proto_ops { · line 837
Quoted 8 lines
include/linux/scmi_protocol.h +5
-0@@ -828,6 +830,35 @@ struct scmi_pinctrl_proto_ops {int (*pin_free)(const struct scmi_protocol_handle *ph,u32 pin); }; +struct scmi_telemetry_base_info { +unsigned int version; +uuid_t primary_revision; +unsigned int num_des; +unsigned int num_groups;
My gut instinct would be to introduce this only in set 2 that adds groups controls. The best form of no groups is no reference to them at all except in userspace ABI where you stub them out for now.
include/linux/scmi_protocol.h struct scmi_pinctrl_proto_ops { · line 839
Quoted 2 lines
include/linux/scmi_protocol.h +2
-0+unsigned int num_intervals; +unsigned int num_shmtis;
Ideally grow this as you add support for things. num_intervals and num_shmtis aren't used yet.
include/linux/scmi_protocol.h struct scmi_pinctrl_proto_ops { · line 845
Quoted 6 lines
include/linux/scmi_protocol.h +6
-0+}; + +struct scmi_telemetry_info { +bool single_read_support; +bool continuous_update_support; +bool per_group_config_support;
Logically without group support we don't care. I'm less bothered though on whether you rip out a simple support bit but if we are going for clean separation this would go as well.
Quoted 19 lines
include/linux/scmi_protocol.h +16
-0+bool reset_support; +bool fc_support; +struct scmi_telemetry_base_info base; +}; + +/** +* struct scmi_telemetry_proto_ops - represents the various operations provided +* by SCMI Telemetry Protocol +* +* @info_get: get the general Telemetry information. +*/ +struct scmi_telemetry_proto_ops { +const struct scmi_telemetry_info *(*info_get) + (const struct scmi_protocol_handle *ph); +}; +/** * struct scmi_notify_ops - represents notifications' operations provided by * SCMI core
Cristian Marussi
reviewerRe: [PATCH v17 11/34] firmware: arm_scmi: Add Telemetry basic attributes enumeration
Quoted 12 lines · Jonathan Cameron
Quoted 8 lines · On Tue, 24 Nov 2026 19:48:17 +0000 Cristian Marussi <[email protected]>…
Add SCMIv4.0 Telemetry basic support for minimal initialization and protocol attributes enumeration: expose telemetry instance descriptor via a simple information retrieval protocol operation.
Signed-off-by Cristian Marussi <[email protected]>---
v15 --> v16
- ignore groups
Quoted 4 lines
Partly... Need to do a lot more ignoring to make this true and consistent. There are a few things in here, but key is we need the whole framework to be as unaware of groups as possible. At least up to the userspace interface layer where we may need to ensure extensibility.
As of now I removed the logic, but kept the existing data structure and interfaces (like grps params in ops) and inhibited where needed any remaining code path pertaining to groups.
I agree that a more clean but pervasive approach would be to fully obliterate any group reference and then just re-introduce all of this later when the extended series will be re-posted...it would be a lot of churn to remove/refactor and test to just then re-add later all of this support...but yes why not I can do that.
Thanks,
Cristian
Cristian Marussi
reviewerPATCH v17 12/34 firmware: arm_scmi: Add Telemetry resources enumeration
In reply to Cristian MarussiAdd basic Telemetry allocation and initialization routines, introducing and wiring-up the logic needed to enumerate all the SCMI Telemetry resources optionally using a lazy on-demand scheme: this approach factors in the flexibility needed to minimize the amount of initialization work based on the effective access pattern used by the upper layer ABI.
---
v16 --> v17
- remove unused de.ts_rate
- renaming discovered to enumerated
- list_add to fcs_des only after successfull TDE registration
- use list_del_init for free_des/fcs_des list removals
- call tdes_cleanup on free_resources
v15 --> v16
- add tdes_cleanup as devm_action after enumeration
- use phys_addr_t and proper format string
- drop TDE_FC_SIZE and introduce better checks
- unlink FC TDEs from fcs_des list on free
- bailout on unknown TDE types
- reject FCs smaller than 8 bytes
v14 --> v15
- drop usage of devres for FC iomapping
- trigger full enumeration of DE lookups
- new IS_TDE_TS_ macro helpers
- add a dedicated scmi_telemetry_free_tdes_add helper
- better commenting
- dropping needless __must_check
- flag as fully enumerated only when ALL declared des were found
- drop redundant iounmap
- check FC size on enumeration
v13 --> v14
- splitted out of the old Basic Telemetry patch, contains the basic instance allocations and the DEs enumeration process
- renamed some fields to more strictly adhere to spec nomenclature
--- drivers/firmware/arm_scmi/telemetry.c | 753 ++++++++++++++++++++++++++ include/linux/scmi_protocol.h | 37 ++ 2 files changed, 790 insertions(+)
drivers/firmware/arm_scmi/telemetry.c +753 -0
@@ -8,15 +8,19 @@#include <linux/atomic.h> #include <linux/bitfield.h> #include <linux/compiler_types.h> +#include <linux/completion.h> +#include <linux/delay.h> #include <linux/device.h> #include <linux/err.h> #include <linux/io.h> #include <linux/limits.h> #include <linux/module.h> +#include <linux/mutex.h> #include <linux/slab.h> #include <linux/sprintf.h> #include <linux/string.h> #include <linux/uuid.h> +#include <linux/xarray.h> #include "protocols.h" #include "notify.h"
@@ -52,13 +56,216 @@ struct scmi_msg_resp_telemetry_protocol_attributes {__le32 default_blk_ts_rate; }; +struct de_desc_fastchannel { +__le32 addr_low; +__le32 addr_high; +__le32 size; +}; + +struct scmi_de_desc { +__le32 de_id; +__le32 group_id; +__le32 de_data_sz; +__le32 de_attributes_1; +#define IS_NAME_SUPPORTED (d) (le32_get_bits((d)->de_attributes_1, BIT(31))) +#define IS_FC_SUPPORTED (d) (le32_get_bits((d)->de_attributes_1, BIT(30))) +#define GET_DE_TYPE (d) (le32_get_bits((d)->de_attributes_1, GENMASK(29, 22))) +#define IS_PERSISTENT (d) (le32_get_bits((d)->de_attributes_1, BIT(21))) +#define GET_DE_UNIT_EXP (d) \ + ({ \ + __u32 __signed_exp = \ + le32_get_bits((d)->de_attributes_1, GENMASK(20, 13)); \ + \ + sign_extend32(__signed_exp, 7); \ + }) +#define GET_DE_UNIT (d) (le32_get_bits((d)->de_attributes_1, GENMASK(12, 5))) +#define TSTAMP_SUPPORT (d) (le32_get_bits((d)->de_attributes_1, GENMASK(1, 0))) +__le32 de_attributes_2; +#define GET_DE_INSTA_ID (d) (le32_get_bits((d)->de_attributes_2, GENMASK(31, 24))) +#define GET_COMPO_INSTA_ID (d) (le32_get_bits((d)->de_attributes_2, GENMASK(23, 8))) +#define GET_COMPO_TYPE (d) (le32_get_bits((d)->de_attributes_2, GENMASK(7, 0))) +__le32 de_attributes_3; +}; + +struct scmi_msg_resp_telemetry_de_description { +__le32 num_desc;/* This does NOT count desc[] by the spec */ +struct scmi_de_desc desc[]; +}; + +#define IS_TDE_TSTAMP_TYPE (__t, __ttype) ((__t)->ts_type == (__ttype)) +#define IS_TDE_TS_NONE (_t) (IS_TDE_TSTAMP_TYPE((_t), TSTAMP_NONE)) +#define IS_TDE_TS_LINE (_t) (IS_TDE_TSTAMP_TYPE((_t), TSTAMP_LINE)) +#define IS_TDE_TS_BLK (_t) (IS_TDE_TSTAMP_TYPE((_t), TSTAMP_BLK)) + +enum timestamps { +TSTAMP_NONE =0 , +TSTAMP_LINE =1 , +TSTAMP_BLK =2 , +}; + +#define SHMTI_ID_INVALID GENMASK(31, 0) + +struct telemetry_de { +enum timestamps ts_type; +bool enumerated; +void __iomem *base; +u32 sid; +u32 offset; +/* NOTE THAT DE data_sz is registered in scmi_telemetry_de */ +u32 fc_size; +struct list_head item; +struct scmi_telemetry_de de; +/* Protect last_val/ts/magic accesses - MUST BE KEPT LAST */ +struct mutex mtx; +}; + +#define to_tde (d) container_of(d, struct telemetry_de, de) +struct telemetry_info {bool streaming_mode;unsigned int num_shmti;unsigned int num_des_tstamp;unsigned int default_blk_ts_rate;const struct scmi_protocol_handle *ph; +struct telemetry_de *tdes; +struct xarray xa_des; +/* Mutex to protect access to @free_des */ +struct mutex free_mtx; +struct list_head free_des; +struct list_head fcs_des;struct scmi_telemetry_info info; +atomic_t rinfo_initializing; +struct completion rinfo_initdone; +struct scmi_telemetry_res_info *rinfo; +struct scmi_telemetry_res_info *(*res_get)(struct telemetry_info *ti); +}; + +static struct scmi_telemetry_res_info * +__scmi_telemetry_resources_get (struct telemetry_info *ti); + +static struct telemetry_de * +scmi_telemetry_free_tde_get (struct telemetry_info *ti) +{ +struct telemetry_de *tde; + +guard (mutex)(&ti->free_mtx); + + tde = list_first_entry_or_null(&ti->free_des, struct telemetry_de, item); +if (!tde) +return tde; + +list_del_init (&tde->item); + +return tde; +} + +static inline void scmi_telemetry_free_tdes_add (struct telemetry_info *ti, +struct telemetry_de *tde) +{ +guard (mutex)(&ti->free_mtx); +list_add_tail (&tde->item, &ti->free_des); +} + +static void scmi_telemetry_free_tde_put (struct telemetry_info *ti, +struct telemetry_de *tde) +{ +struct scmi_telemetry_de_info *info; + +lockdep_assert_held (&tde->mtx); + +/* Unlink and unmap any valid DE/FC */ +if (tde->de.fc_support) { +/* +* During normal system operation this can be triggered only +* once by the DE description iteraror while enumerating +* resources, so the fcs_des list is not manipulated elsewhere +* when we remove this TDE from that list. +*/ +list_del_init (&tde->item); +if (tde->base) +iounmap (tde->base); + } + +/* Save clear and restore */ + info = tde->de.info; +memset (info,0 ,sizeof (*info)); +memset (tde,0 , offsetof(struct telemetry_de , mtx)); + tde->de.info = info; + +scmi_telemetry_free_tdes_add (ti, tde); +} + +static struct telemetry_de *scmi_telemetry_tde_lookup (struct telemetry_info *ti, +unsigned int de_id) +{ +struct scmi_telemetry_de *de; + + de =xa_load (&ti->xa_des, de_id); +if (!de) +return NULL ; + +return to_tde (de); +} + +static struct telemetry_de *scmi_telemetry_tde_get (struct telemetry_info *ti, +unsigned int de_id) +{ +struct telemetry_de *tde; + + tde =scmi_telemetry_free_tde_get (ti); +if (!tde) { +dev_err (ti->ph->dev,"Cannot get TDE for ID:0x%08X\n" , de_id); +return ERR_PTR (-ENOSPC ); + } + + tde->sid =SHMTI_ID_INVALID ; + +return tde; +} + +static int scmi_telemetry_tde_register (struct telemetry_info *ti, +struct telemetry_de *tde) +{ +struct scmi_telemetry_res_info *rinfo; +int ret; + +lockdep_assert_held (&tde->mtx); + +/* Get rinfo without triggering a recursive enumeration */ + rinfo =__scmi_telemetry_resources_get (ti); + +if (rinfo->num_des >= ti->info.base.num_des) { + ret = -ENOSPC ; + goto err; + } + +/* Store DE pointer by de_id ... */ + ret =xa_insert (&ti->xa_des, tde->de.info->id, &tde->de,GFP_KERNEL ); +if (ret) + goto err; + +/* Add to FastChannels list */ +if (tde->de.fc_support) +list_add (&tde->item, &ti->fcs_des); + +/* ... and in the general array */ + rinfo->des[rinfo->num_des] = &tde->de; +/* Make sure the freshly registered DE is visible before the index update */ +smp_store_release (&rinfo->num_des, rinfo->num_des +1 ); + +return 0 ; + +err: +dev_err (ti->ph->dev,"Cannot register TDE for ID:0x%08X - ret:%d\n" , + tde->de.info->id, ret); + +return ret; +} + +struct scmi_tlm_de_priv { +struct telemetry_info *ti; +void *next; +size_t rx_len; }; static int
@@ -100,6 +307,324 @@ scmi_telemetry_protocol_attributes_get(struct telemetry_info *ti)return ret; } +static void iter_tlm_prepare_message (void *message, +unsigned int desc_index,const void *priv) +{ +put_unaligned_le32 (desc_index, message); +} + +static int iter_de_descr_update_state (struct scmi_iterator_state *st, +const void *response,void *priv) +{ +const struct scmi_msg_resp_telemetry_de_description *r = response; +struct scmi_tlm_de_priv *p = priv; + + st->num_returned =le32_get_bits (r->num_desc,GENMASK (15 ,0 )); + st->num_remaining =le32_get_bits (r->num_desc,GENMASK (31 ,16 )); + +if (st->rx_len < (sizeof (*r) +sizeof (r->desc[0 ]) * st->num_returned)) +return -EINVAL ; + +/* Initialized to first descriptor and initial payload size */ + p->next = (void *)r->desc; + p->rx_len = st->rx_len -sizeof (*r); + +return 0 ; +} + +static inline size_t scmi_telemetry_tde_var_size_calc (struct telemetry_de *tde) +{ +size_t sz =0 ; + + sz +=IS_TDE_TS_LINE (tde) ?sizeof (__le32) :0 ; + sz += tde->de.fc_support ?sizeof (struct de_desc_fastchannel ) :0 ; + sz += tde->de.name_support ?SCMI_SHORT_NAME_MAX_SIZE :0 ; + +return sz; +} + +static inline int +scmi_telemetry_area_check (struct device *dev,const char *tag, +u32 low,u32 high,u32 size, +phys_addr_t *phys_addr,size_t *len) +{ +u64 addr = ((u64 )high <<32 ) | low; +phys_addr_t pa = (phys_addr_t )addr; +phys_addr_t end_phys; + +/* Does the returned pointer fits architetural size ? */ +if ((u64 )pa != addr) { +dev_err (dev,FW_BUG "%s phys_addr (%pa) pointer too big.\n" , + tag, &pa); +return -EOVERFLOW ; + } + +if (!IS_ALIGNED (pa,4 )) { +dev_err (dev,FW_BUG "%s phys_addr (%pa) misaligned.\n" , + tag, &pa); +return -EINVAL ; + } + +if (!IS_ALIGNED (size,4 )) { +dev_err (dev,FW_BUG "%s area length (%u) misaligned\n" , + tag, size); +return -EINVAL ; + } + +if (check_add_overflow (pa, size, &end_phys)) { +dev_err (dev,FW_BUG "%s area (%pa/%u) wrap-around.\n" , + tag, &pa, size); +return -EOVERFLOW ; + } + + *phys_addr = pa; + *len = size; + +return 0 ; +} + +static inline int +scmi_telemetry_fc_size_check (struct telemetry_de *tde,size_t size) +{ +size_t fc_size, fc_base_sz = tde->de.info->data_sz; + +if (fc_base_sz <8 || !size) +return -EINVAL ; + +if (check_add_overflow (fc_base_sz, + tde->de.tstamp_support ?sizeof (u32) *2 :0 , + &fc_size)) +return -EOVERFLOW ; + +if (size < fc_size) +return -ENOSPC ; + +return 0 ; +} + +static int scmi_telemetry_tde_fastchannel_setup (struct device *dev, +struct telemetry_de *tde,void **next) +{ +struct de_desc_fastchannel *dfc; +phys_addr_t phys_addr; +void __iomem *addr; +size_t size; +int ret; + + dfc = *next; + ret =scmi_telemetry_area_check (dev,"FC" , +le32_to_cpu (dfc->addr_low), +le32_to_cpu (dfc->addr_high), +le32_to_cpu (dfc->size), + &phys_addr, &size); +if (ret) +return ret; + +/* Does it fit ? */ +if (scmi_telemetry_fc_size_check (tde, size)) { +dev_err (dev,FW_BUG "TDE FC size inconsistent (%zu)\n" , size); +return -EPROTO ; + } + + addr =ioremap (phys_addr, size); +if (!addr) +return -EADDRNOTAVAIL ; + + tde->base = addr; + tde->offset =0 ; + tde->fc_size = size; + +/* Variably sized depending on FC support */ + *next +=sizeof (*dfc); + +return 0 ; +} + +static int scmi_telemetry_de_descriptor_parse (struct telemetry_info *ti, +struct telemetry_de *tde, +void **next,size_t *rx_len) +{ +const struct scmi_de_desc *desc = *next; +struct device *dev = ti->ph->dev; +size_t payld_sz =sizeof (*desc); +int ret; + +lockdep_assert_held (&tde->mtx); + +if (*rx_len < payld_sz) +return -ENOSPC ; + + tde->de.info->id =le32_to_cpu (desc->de_id); + tde->de.info->grp_id =le32_to_cpu (desc->group_id); + tde->de.info->data_sz =le32_to_cpu (desc->de_data_sz); + tde->de.info->type =GET_DE_TYPE (desc); + tde->de.info->unit =GET_DE_UNIT (desc); + tde->de.info->unit_exp =GET_DE_UNIT_EXP (desc); + tde->de.info->instance_id =GET_DE_INSTA_ID (desc); + tde->de.info->compo_instance_id =GET_COMPO_INSTA_ID (desc); + tde->de.info->compo_type =GET_COMPO_TYPE (desc); + tde->de.info->persistent =IS_PERSISTENT (desc); + tde->ts_type =TSTAMP_SUPPORT (desc); + tde->de.tstamp_support = !!tde->ts_type; + tde->de.fc_support =IS_FC_SUPPORTED (desc); + tde->de.name_support =IS_NAME_SUPPORTED (desc); +/* Update DE_DESCRIPTOR size for the next iteration */ + *next +=sizeof (*desc); + + payld_sz +=scmi_telemetry_tde_var_size_calc (tde); +if (*rx_len < payld_sz) +return -ENOSPC ; + +if (IS_TDE_TS_LINE (tde)) { +__le32 *line_ts_rate = *next; + + tde->de.info->ts_rate =le32_to_cpu ((*line_ts_rate)); + +/* Variably sized depending on TS support */ + *next +=sizeof (*line_ts_rate); + }else if (IS_TDE_TS_BLK (tde)) { +/* Setup default BLK TS value at first */ + tde->de.info->ts_rate = ti->default_blk_ts_rate; + }else if (!IS_TDE_TS_NONE (tde)) { +dev_warn (dev,"Unknown TDE timestamp type %u\n" , tde->ts_type); +return -EPROTO ; + } + +if (tde->de.fc_support) { + ret =scmi_telemetry_tde_fastchannel_setup (dev, tde, next); +if (ret) +return ret; + } + +if (tde->de.name_support) { +const char *de_name = *next; + +strscpy (tde->de.info->name, de_name,SCMI_SHORT_NAME_MAX_SIZE ); +/* Variably sized depending on name support */ + *next +=SCMI_SHORT_NAME_MAX_SIZE ; + } + + *rx_len -= payld_sz; + +return 0 ; +} + +static int iter_de_descr_process_response (const struct scmi_protocol_handle *ph, +const void *response, +struct scmi_iterator_state *st, +void *priv) +{ +struct scmi_tlm_de_priv *p = priv; +struct telemetry_info *ti = p->ti; +const struct scmi_de_desc *desc = p->next; +struct telemetry_de *tde; +bool enumerated = false; +unsigned int de_id; +int ret; + +/* Is at least reading de_id safe */ +if (p->rx_len <sizeof (desc->de_id)) +return -ENOSPC ; + + de_id =le32_to_cpu (desc->de_id); +/* +* Check if this DE was already been discovered by other means, +* such as during boot if Telemetry was detected as already enabled +* and the list of enabled DEs was enumerated separately. +*/ + tde =scmi_telemetry_tde_lookup (ti, de_id); +if (!tde) { +/* Create a new one */ + tde =scmi_telemetry_tde_get (ti, de_id); +if (IS_ERR (tde)) +return PTR_ERR (tde); + + enumerated = true; + } + +guard (mutex)(&tde->mtx); +if (tde->enumerated) { +/* Cannot be a duplicate of a DE already created by enumeration */ +dev_err (ph->dev, +"Discovered INVALID DE with DUPLICATED ID:0x%08X\n" , + de_id); +return -EINVAL ; + } + + ret =scmi_telemetry_de_descriptor_parse (ti, tde, &p->next, &p->rx_len); +if (ret) { +dev_err (ph->dev,"Malformed DE Descriptor - ret:%d\n" , ret); +/* DE not enumerated at this point were created in this call */ +if (enumerated) +scmi_telemetry_free_tde_put (ti, tde); +return ret; + } + +/* Now fully enumerated */ + tde->enumerated = true; + +/* Register if it was not already ... */ +if (enumerated) { + ret =scmi_telemetry_tde_register (ti, tde); +if (ret) { +/* DE not enumerated at this point were created in this call */ +scmi_telemetry_free_tde_put (ti, tde); +return ret; + } + } + +/* Count timestamped DEs */ + ti->num_des_tstamp += !!tde->de.tstamp_support; + +return 0 ; +} + +static void scmi_telemetry_tdes_cleanup (struct telemetry_info *ti) +{ +struct scmi_telemetry_de *de; +unsigned long idx; + +xa_for_each (&ti->xa_des, idx, de) { +struct telemetry_de *tde =to_tde (de); + +guard (mutex)(&tde->mtx); + +scmi_telemetry_free_tde_put (ti, tde); + } +} + +static int scmi_telemetry_de_descriptors_get (struct telemetry_info *ti) +{ +const struct scmi_protocol_handle *ph = ti->ph; + +struct scmi_iterator_ops ops = { + .prepare_message = iter_tlm_prepare_message, + .update_state = iter_de_descr_update_state, + .process_response = iter_de_descr_process_response, + }; +struct scmi_tlm_de_priv tpriv = { + .ti = ti, + .next =NULL , + }; +void *iter; +int ret; + +if (!ti->info.base.num_des) +return 0 ; + + iter = ph->hops->iter_response_init (ph, &ops, ti->info.base.num_des, +TELEMETRY_DE_DESCRIPTION , +sizeof (u32), &tpriv); +if (IS_ERR (iter)) +return PTR_ERR (iter); + + ret = ph->hops->iter_response_run (iter); +if (ret) +return ret; + +return 0 ; +} +static const struct scmi_telemetry_info *scmi_telemetry_info_get (const struct scmi_protocol_handle *ph) {
@@ -108,10 +633,232 @@ scmi_telemetry_info_get(const struct scmi_protocol_handle *ph)return &ti->info; } +static const struct scmi_telemetry_res_info * +scmi_telemetry_resources_get (const struct scmi_protocol_handle *ph) +{ +struct scmi_telemetry_res_info *(*res_get)(struct telemetry_info *ti); +struct telemetry_info *ti = ph->get_priv (ph); + +/* Ensure the latest installed res_get helper is visible */ + res_get =smp_load_acquire (&ti->res_get); + +return res_get (ti); +} + +static const struct scmi_telemetry_de * +scmi_telemetry_de_lookup (const struct scmi_protocol_handle *ph,u32 id) +{ +struct telemetry_info *ti = ph->get_priv (ph); + +/* Trigger a full proper enumeration */ +scmi_telemetry_resources_get (ph); + +return xa_load (&ti->xa_des, id); +} +static const struct scmi_telemetry_proto_ops tlm_proto_ops = { .info_get = scmi_telemetry_info_get, + .de_lookup = scmi_telemetry_de_lookup, + .res_get = scmi_telemetry_resources_get, }; +/** +* scmi_telemetry_resources_alloc - Resources allocation +* @ti: A reference to the telemetry info descriptor for this instance +* +* This allocates and initializes dedicated resources for the maximum possible +* number of needed telemetry resources, based on information gathered from +* the initial enumeration: these allocations represent an upper bound on +* the number of discoverable telemetry resources and they will be later +* populated during late deferred further discovery phases. +* +* Note that some of the allocations down below are designed to keep some +* class of data packed together since it eases retrieval from the ABI layer. +* +* Return: 0 on Success, errno otherwise +*/ +static int scmi_telemetry_resources_alloc (struct telemetry_info *ti) +{ +/* Array to hold pointers to discovered DEs */ + struct scmi_telemetry_de **des __free(kfree) = +kzalloc_objs (*des, ti->info.base.num_des); +if (!des) +return -ENOMEM ; + +/* The allocated DE descriptors */ + struct telemetry_de *tdes __free(kfree) = +kzalloc_objs (*tdes, ti->info.base.num_des); +if (!tdes) +return -ENOMEM ; + +/* Allocate a set of contiguous DE info descriptors. */ + struct scmi_telemetry_de_info *dei_store __free(kfree) = +kzalloc_objs (*dei_store, ti->info.base.num_des); +if (!dei_store) +return -ENOMEM ; + + struct scmi_telemetry_res_info *rinfo __free(kfree) = +kzalloc_obj (*rinfo); +if (!rinfo) +return -ENOMEM ; + +mutex_init (&ti->free_mtx); +INIT_LIST_HEAD (&ti->free_des); +for (int i =0 ; i < ti->info.base.num_des; i++) { +mutex_init (&tdes[i].mtx); +/* Bind contiguous DE info structures */ + tdes[i].de.info = &dei_store[i]; +scmi_telemetry_free_tdes_add (ti, &tdes[i]); + } + +INIT_LIST_HEAD (&ti->fcs_des); + + ti->tdes =no_free_ptr (tdes); +xa_init (&ti->xa_des); + + rinfo->des =no_free_ptr (des); + rinfo->dei_store =no_free_ptr (dei_store); + +/* Ensure all of the above assignments are visible */ +smp_store_release (&ti->rinfo,no_free_ptr (rinfo)); + +return 0 ; +} + +static struct scmi_telemetry_res_info * +__scmi_telemetry_resources_get (struct telemetry_info *ti) +{ +/* Ensure rinfo descriptor is visible */ +return smp_load_acquire (&ti->rinfo); +} + +static void scmi_telemetry_resources_free (struct telemetry_info *ti) +{ +struct scmi_telemetry_res_info *rinfo; + +/* Get rinfo without triggering a recursive enumeration, cannot be NULL */ + rinfo =__scmi_telemetry_resources_get (ti); +/* Ensure rinfo is no more accessible upfront */ +smp_store_release (&ti->rinfo,NULL ); + +scmi_telemetry_tdes_cleanup (ti); +xa_destroy (&ti->xa_des); + +kfree (ti->tdes); + +kfree (rinfo->des); +kfree (rinfo->dei_store); + +kfree (rinfo); + +dev_dbg (ti->ph->dev,"SCMI Telemetry resources freed for instance\n" ); +} + +static void scmi_telemetry_instance_cleanup (void *arg) +{ +struct telemetry_info *ti = arg; + +scmi_telemetry_resources_free (ti); +} + +/** +* scmi_telemetry_resources_enumerate - Enumeration helper +* @ti: A reference to the telemetry info descriptor for this instance +* +* This helper is configured to be called once on the first enumeration +* attempt, when triggered by invoking ti->res_get() from somewhere else. +* +* Once run it substitues itself in ti->res_get() with the simple accessor +* __scmi_telemetry_resources_get, which returns a descriptor to the resources +* that were possibly discovered. +* +* Note that, while it attempts to fully enumerate Data Events, it does NOT +* fail when such enumerations fail, instead it simply gives up with the end +* result that only a partially populated, but consistent, resources descriptor +* will be returned; in such a case the incomplete descriptor will be marked as +* NOT fully_enumerated: this design enables the kernel to deal with badly +* implemented out-of-spec firmware support while keep on providing a minimal +* sane, albeit possibly incomplete, set of telemetry respources. +* +* Return: A reference to a fully or partially populated resources descriptor +*/ +static struct scmi_telemetry_res_info * +scmi_telemetry_resources_enumerate (struct telemetry_info *ti) +{ +struct scmi_telemetry_res_info *rinfo; +struct device *dev = ti->ph->dev; +int ret; + +/* +* Ensure the following initialization can be called only once +* from one thread of execution. +*/ +if (atomic_cmpxchg (&ti->rinfo_initializing,0 ,1 )) { +/* +* When initialization is already ongoing in another thread, +* just wait for its completion and return the fully or partially +* populated rinfo. +*/ +if (!completion_done (&ti->rinfo_initdone)) +wait_for_completion (&ti->rinfo_initdone); + +/* Ensure rinfo descriptor is visible */ +return smp_load_acquire (&ti->rinfo); + } + +/* Note that this code below can be run only once by one thread */ + ret =scmi_telemetry_de_descriptors_get (ti); +if (ret) { +dev_err (dev,FW_BUG "Cannot fully enumerate DEs resources. Degraded system.\n" ); + goto done; + } + +/* Get rinfo without triggering a recursive enumeration */ + rinfo =__scmi_telemetry_resources_get (ti); + rinfo->fully_enumerated = rinfo->num_des == ti->info.base.num_des; +done: +/* Disable initialization permanently */ +smp_store_release (&ti->res_get, __scmi_telemetry_resources_get); + +/* Unblock concurrent threads that have been stalled */ +complete_all (&ti->rinfo_initdone); + +/* Ensure local rinfo is visible before returning it */ +smp_mb (); +return ti->rinfo; +} + +/** +* scmi_telemetry_instance_init - Instance initializer +* @ti: A reference to the telemetry info descriptor for this instance +* +* Note that this allocates and initialize all the resources possibly needed +* and then setups the @scmi_telemetry_resources_enumerate helper as the +* default method for the first call to ti->res_get(): this mechanism enables +* the possibility of optionally implementing deferred enumeration policies +* which optionally delay the discovery phase and related SCMI message exchanges +* to a later point in time. +* +* Return: 0 on Success, errno otherwise +*/ +static int scmi_telemetry_instance_init (struct telemetry_info *ti) +{ +int ret; + + ret =scmi_telemetry_resources_alloc (ti); +if (ret) +return ret; + +/* Setup resources lazy initialization */ +atomic_set (&ti->rinfo_initializing,0 ); +init_completion (&ti->rinfo_initdone); +/* Ensure the new res_get() operation is visible after this point */ +smp_store_mb (ti->res_get, scmi_telemetry_resources_enumerate); + +return devm_add_action_or_reset (ti->ph->dev, + scmi_telemetry_instance_cleanup, ti); +} +static int scmi_telemetry_protocol_init (const struct scmi_protocol_handle *ph) {struct device *dev = ph->dev;
@@ -133,6 +880,12 @@ static int scmi_telemetry_protocol_init(const struct scmi_protocol_handle *ph)return ret; } + ret =scmi_telemetry_instance_init (ti); +if (ret) { +dev_err (dev,"Cannot initialize instance. Abort.\n" ); +return ret; + } + ti->info.base.version = ph->version;return ph->set_priv (ph, ti);
include/linux/scmi_protocol.h +37 -0
@@ -830,6 +830,37 @@ struct scmi_pinctrl_proto_ops {int (*pin_free)(const struct scmi_protocol_handle *ph,u32 pin); }; +struct scmi_telemetry_de_info { +unsigned int id; +unsigned int grp_id; +unsigned int data_sz; +unsigned int type; +unsigned int unit; +int unit_exp; +unsigned int ts_rate; +unsigned int instance_id; +unsigned int compo_instance_id; +unsigned int compo_type; +bool persistent; +char name[16 ]; +}; + +struct scmi_telemetry_de { +bool tstamp_support; +bool fc_support; +bool name_support; +bool enabled; +bool tstamp_enabled; +struct scmi_telemetry_de_info *info; +}; + +struct scmi_telemetry_res_info { +bool fully_enumerated; +unsigned int num_des; +struct scmi_telemetry_de **des; +struct scmi_telemetry_de_info *dei_store; +}; +struct scmi_telemetry_base_info {unsigned int version;uuid_t primary_revision;
@@ -853,10 +884,16 @@ struct scmi_telemetry_info {* by SCMI Telemetry Protocol * * @info_get: get the general Telemetry information. +* @de_lookup: get a specific DE descriptor from the DE id. +* @res_get: get a reference to the Telemetry resources descriptor. */ struct scmi_telemetry_proto_ops {const struct scmi_telemetry_info *(*info_get) (const struct scmi_protocol_handle *ph); +const struct scmi_telemetry_de __must_check *(*de_lookup) + (const struct scmi_protocol_handle *ph,u32 id); +const struct scmi_telemetry_res_info *(*res_get) + (const struct scmi_protocol_handle *ph); };/**
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 13/34 firmware: arm_scmi: Add Telemetry global update intervals enumeration
In reply to Cristian MarussiAdd support to enumerate global available Telemetry update intervals.
---
v16 --> v17
- avoid FIELD_PREP check on size for exp
v15 --> v16
- split out group update interval enumeration
v14 --> v15
- removed unused dev reference in interval parsing
- added missing initialization of intrvs->grp_id
v13 --> v14
- splitted out of the old Basic Telemetry patch, contains the update_intervals enumeration routines
--- drivers/firmware/arm_scmi/telemetry.c | 164 ++++++++++++++++++++++++++ include/linux/scmi_protocol.h | 21 ++++ 2 files changed, 185 insertions(+)
drivers/firmware/arm_scmi/telemetry.c +164 -0
@@ -92,6 +92,21 @@ struct scmi_msg_resp_telemetry_de_description {struct scmi_de_desc desc[]; }; +struct scmi_msg_telemetry_update_intervals { +__le32 index; +__le32 group_identifier; +#define ALL_DES_NO_GROUP 0x0 +#define SPECIFIC_GROUP_DES 0x1 +#define ALL_DES_ANY_GROUP 0x2 +__le32 flags; +}; + +struct scmi_msg_resp_telemetry_update_intervals { +__le32 flags; +#define INTERVALS_DISCRETE (x) (le32_get_bits((x), BIT(12)) == 0) +__le32 intervals[]; +}; +#define IS_TDE_TSTAMP_TYPE (__t, __ttype) ((__t)->ts_type == (__ttype))#define IS_TDE_TS_NONE (_t) (IS_TDE_TSTAMP_TYPE((_t), TSTAMP_NONE))#define IS_TDE_TS_LINE (_t) (IS_TDE_TSTAMP_TYPE((_t), TSTAMP_LINE))
@@ -625,6 +640,149 @@ static int scmi_telemetry_de_descriptors_get(struct telemetry_info *ti)return 0 ; } +struct scmi_tlm_ivl_priv { +struct scmi_telemetry_intervals **intrvs; +unsigned int grp_id; +unsigned int flags; +}; + +static void iter_intervals_prepare_message (void *message, +unsigned int desc_index, +const void *priv) +{ +struct scmi_msg_telemetry_update_intervals *msg = message; +const struct scmi_tlm_ivl_priv *p = priv; + + msg->index =cpu_to_le32 (desc_index); + msg->group_identifier =cpu_to_le32 (p->grp_id); + msg->flags =cpu_to_le32 (FIELD_PREP (GENMASK (3 ,0 ), p->flags)); +} + +static int iter_intervals_update_state (struct scmi_iterator_state *st, +const void *response,void *priv) +{ +const struct scmi_msg_resp_telemetry_update_intervals *r = response; + + st->num_returned =le32_get_bits (r->flags,GENMASK (11 ,0 )); + st->num_remaining =le32_get_bits (r->flags,GENMASK (31 ,16 )); + +if (st->rx_len < (sizeof (*r) +sizeof (r->intervals[0 ]) * st->num_returned)) +return -EINVAL ; + +/* +* total intervals is not declared previously anywhere so we +* assume it's returned+remaining on first call. +*/ +if (!st->max_resources) { +struct scmi_tlm_ivl_priv *p = priv; +struct scmi_telemetry_intervals *intrvs; +bool discrete; +int inum; + + discrete =INTERVALS_DISCRETE (r->flags); +/* Check consistency on first call */ +if (!discrete && (st->num_returned !=3 || st->num_remaining !=0 )) +return -EINVAL ; + + inum = st->num_returned + st->num_remaining; + intrvs =kzalloc_flex (*intrvs, update_intervals, inum); +if (!intrvs) +return -ENOMEM ; + + intrvs->num_intervals = inum; + intrvs->discrete = discrete; + intrvs->grp_id = p->grp_id; + st->max_resources = intrvs->num_intervals; + + *p->intrvs = intrvs; + } + +return 0 ; +} + +static int +iter_intervals_process_response (const struct scmi_protocol_handle *ph, +const void *response, +struct scmi_iterator_state *st,void *priv) +{ +const struct scmi_msg_resp_telemetry_update_intervals *r = response; +struct scmi_tlm_ivl_priv *p = priv; +struct scmi_telemetry_intervals *intrvs = *p->intrvs; +unsigned int idx = st->loop_idx; + + intrvs->update_intervals[st->desc_index + idx] = +le32_to_cpu (r->intervals[idx]); + +return 0 ; +} + +static int +scmi_tlm_enumerate_update_intervals (struct telemetry_info *ti, +struct scmi_telemetry_intervals **intervals, +int grp_id,unsigned int flags) +{ +struct scmi_iterator_ops ops = { + .prepare_message = iter_intervals_prepare_message, + .update_state = iter_intervals_update_state, + .process_response = iter_intervals_process_response, + }; +const struct scmi_protocol_handle *ph = ti->ph; +struct scmi_telemetry_intervals *intrvs =NULL ; +struct scmi_tlm_ivl_priv ipriv = { + .grp_id = grp_id, + .intrvs = &intrvs, + .flags = flags, + }; +void *iter; +int ret; + + iter = ph->hops->iter_response_init (ph, &ops,0 , +TELEMETRY_LIST_UPDATE_INTERVALS , +sizeof (struct scmi_msg_telemetry_update_intervals ), + &ipriv); +if (IS_ERR (iter)) +return PTR_ERR (iter); + +/* Cleanup iterator inner allocations on failure */ + ret = ph->hops->iter_response_run (iter); +if (ret) { +kfree (intrvs); +return ret; + } + + *intervals = intrvs; + +return 0 ; +} + +static void scmi_telemetry_intervals_free (void *interval) +{ +kfree (interval); +} + +static int +scmi_telemetry_enumerate_common_intervals (struct telemetry_info *ti) +{ +unsigned int flags; +int ret; + + flags = !ti->info.per_group_config_support ? +ALL_DES_ANY_GROUP :ALL_DES_NO_GROUP ; + + ret =scmi_tlm_enumerate_update_intervals (ti, &ti->info.intervals, +SCMI_TLM_GRP_INVALID , flags); +if (ret) +return ret; + +/* A copy for UAPI access... */ + ti->info.base.num_intervals = ti->info.intervals->num_intervals; + +/* Delegate freeing of allocated intervals to unbind time */ +return devm_add_action_or_reset (ti->ph->dev, + scmi_telemetry_intervals_free, + ti->info.intervals); +} +static const struct scmi_telemetry_info *scmi_telemetry_info_get (const struct scmi_protocol_handle *ph) {
@@ -886,6 +1044,12 @@ static int scmi_telemetry_protocol_init(const struct scmi_protocol_handle *ph)return ret; } + ret =scmi_telemetry_enumerate_common_intervals (ti); +if (ret) { +dev_err (dev,FW_BUG "Cannot enumerate update intervals. Abort.\n" ); +return ret; + } + ti->info.base.version = ph->version;return ph->set_priv (ph, ti);
include/linux/scmi_protocol.h +21 -0
@@ -830,6 +830,25 @@ struct scmi_pinctrl_proto_ops {int (*pin_free)(const struct scmi_protocol_handle *ph,u32 pin); }; +#define SCMI_TLM_GET_UPDATE_INTERVAL_SECS (x) (FIELD_GET(GENMASK(20, 5), (x))) +#define SCMI_TLM_GET_UPDATE_INTERVAL_EXP (x) (sign_extend32((x), 4)) + +#define SCMI_TLM_GET_UPDATE_INTERVAL (x) (FIELD_GET(GENMASK(20, 0), (x))) +#define SCMI_TLM_BUILD_UPDATE_INTERVAL (s, e) \ + (FIELD_PREP(GENMASK(20, 5), (s)) | FIELD_PREP(GENMASK(4, 0), (e) & GENMASK(4, 0))) + +#define SCMI_TLM_GRP_INVALID 0xFFFFFFFF + +struct scmi_telemetry_intervals { +unsigned int grp_id; +bool discrete; +unsigned int num_intervals; +#define SCMI_TLM_UPDATE_INTVL_SEGMENT_LOW 0 +#define SCMI_TLM_UPDATE_INTVL_SEGMENT_HIGH 1 +#define SCMI_TLM_UPDATE_INTVL_SEGMENT_STEP 2 + unsigned int update_intervals[] __counted_by(num_intervals); +}; +struct scmi_telemetry_de_info {unsigned int id;unsigned int grp_id;
@@ -877,6 +896,8 @@ struct scmi_telemetry_info {bool reset_support;bool fc_support;struct scmi_telemetry_base_info base; +unsigned int active_update_interval; +struct scmi_telemetry_intervals *intervals; };/**
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 14/34 firmware: arm_scmi: Add Telemetry SHMTI areas enumeration
In reply to Cristian MarussiAdd Telemetry support to enumerate SHMTI areas.
---
v16 --> v17
- use %pa for phys_addr
- skip LIST_SHMTI with num_shmti = 0
- fix %pa and spell USPECIFIED
v15 --> v16
- fixed missing \n in dev_err
v14 --> v15
- fix prologue/epilogue endianity fields
- rework SHMTI initialization and allocation
- add snapshot suppport data structures
- added alignment checks on SHMTII length size
- fixed error string formatting
- warn if less than expected SHMTIs are enumerated
- improve memory area sanity checks
v13 --> v14
- splitted out of the old Basic Telemetry patch, contains the SHMTI areas enumeration routines
--- drivers/firmware/arm_scmi/telemetry.c | 312 ++++++++++++++++++++++++++ include/linux/scmi_protocol.h | 59 +++++ 2 files changed, 371 insertions(+)
drivers/firmware/arm_scmi/telemetry.c +312 -0
@@ -16,6 +16,7 @@#include <linux/limits.h> #include <linux/module.h> #include <linux/mutex.h> +#include <linux/sizes.h> #include <linux/slab.h> #include <linux/sprintf.h> #include <linux/string.h>
@@ -56,6 +57,19 @@ struct scmi_msg_resp_telemetry_protocol_attributes {__le32 default_blk_ts_rate; }; +struct scmi_shmti_desc { +__le32 id; +__le32 addr_low; +__le32 addr_high; +__le32 length; +__le32 flags; +}; + +struct scmi_msg_resp_telemetry_shmti_list { +__le32 num_shmti; +struct scmi_shmti_desc desc[]; +}; +struct de_desc_fastchannel {__le32 addr_low;__le32 addr_high;
@@ -107,6 +121,72 @@ struct scmi_msg_resp_telemetry_update_intervals {__le32 intervals[]; }; +/* TDCF */ + +#define _I (__a) (ioread32((void __iomem *)(__a))) + +struct prlg { +__le32 sign_start; +#define SIGNATURE_START 0x5442474E/* TBGN */ +__le32 match_start; +__le32 num_qwords; +__le32 hdr_meta_1; +#define TDCF_REVISION_GET (x) (le32_get_bits((x)->hdr_meta_1, GENMASK(7, 0))) +}; + +struct eplg { +__le32 match_end; +__le32 sign_end; +#define SIGNATURE_END 0x54454E44/* TEND */ +}; + +#define TDCF_EPLG_SZ (sizeof(struct eplg)) + +struct tdcf { +struct prlg prlg; +unsigned char payld[]; +}; + +#define SHMTI_MIN_SIZE (sizeof(struct tdcf) + TDCF_EPLG_SZ) +/* An arbitrary upper bound to avoid crazy allocations driven by buggy FW */ +#define SHMTI_MAX_SIZE SZ_64K + +#define TDCF_START_SIGNATURE (x) (_I(&((x)->prlg.sign_start))) +#define TDCF_END_SIGNATURE (e) (_I(&((e)->sign_end))) + +struct telemetry_shmti ; + +struct shmti_snap { +struct telemetry_shmti *shmti; +u32 magic; +u8 base[]__aligned(8) ; +}; + +struct telemetry_shmti { +u32 flags; +void __iomem *base; +struct scmi_telemetry_shmti_info info; +/* Protect srcu operation */ +struct mutex lock; +struct srcu_struct srcu; +struct shmti_snap *snaps[2 ]; +struct shmti_snap __rcu *cur; +/* Mutex to protect @xa_lines */ +struct mutex lines_mtx; +struct xarray xa_lines; +#define PAYLD_HASH_BITS 4 +struct mutex payld_locks[1 <<PAYLD_HASH_BITS ]; +}; + +#define SHMTI_EPLG (s) \ + ({ \ + struct telemetry_shmti *_s = (s); \ + struct eplg __iomem *_eplg; \ + \ + _eplg = _s->base + _s->info.len - TDCF_EPLG_SZ; \ + (_eplg); \ + }) +#define IS_TDE_TSTAMP_TYPE (__t, __ttype) ((__t)->ts_type == (__ttype))#define IS_TDE_TS_NONE (_t) (IS_TDE_TSTAMP_TYPE((_t), TSTAMP_NONE))#define IS_TDE_TS_LINE (_t) (IS_TDE_TSTAMP_TYPE((_t), TSTAMP_LINE))
@@ -124,6 +204,7 @@ struct telemetry_de {enum timestamps ts_type;bool enumerated;void __iomem *base; +struct eplg __iomem *eplg;u32 sid;u32 offset;/* NOTE THAT DE data_sz is registered in scmi_telemetry_de */
@@ -142,6 +223,7 @@ struct telemetry_info {unsigned int num_des_tstamp;unsigned int default_blk_ts_rate;const struct scmi_protocol_handle *ph; +struct telemetry_shmti *shmti;struct telemetry_de *tdes;struct xarray xa_des;/* Mutex to protect access to @free_des */
@@ -783,6 +865,211 @@ scmi_telemetry_enumerate_common_intervals(struct telemetry_info *ti) ti->info.intervals); } +static int iter_shmti_update_state (struct scmi_iterator_state *st, +const void *response,void *priv) +{ +const struct scmi_msg_resp_telemetry_shmti_list *r = response; + + st->num_returned =le32_get_bits (r->num_shmti,GENMASK (15 ,0 )); + st->num_remaining =le32_get_bits (r->num_shmti,GENMASK (31 ,16 )); + +if (st->rx_len < (sizeof (*r) +sizeof (r->desc[0 ]) * st->num_returned)) +return -EINVAL ; + +return 0 ; +} + +static inline int +scmi_telemetry_shmti_validate (struct device *dev,struct telemetry_shmti *shmti) +{ +struct tdcf __iomem *tdcf = shmti->base; +u32 sign_start, sign_end; + + sign_start =TDCF_START_SIGNATURE (tdcf); + sign_end =TDCF_END_SIGNATURE (SHMTI_EPLG (shmti)); + +if (sign_start !=SIGNATURE_START || sign_end !=SIGNATURE_END ) { +dev_err (dev, +"BAD signature for SHMTI ID:%u @phys:%pa - START:0x%08X END:0x%08X\n" , + shmti->info.sid, &shmti->info.phys, sign_start, sign_end); +return -EINVAL ; + } + +return 0 ; +} + +static int iter_shmti_process_response (const struct scmi_protocol_handle *ph, +const void *response, +struct scmi_iterator_state *st, +void *priv) +{ +const struct scmi_msg_resp_telemetry_shmti_list *r = response; +struct telemetry_info *ti = priv; +struct telemetry_shmti *shmti; +const struct scmi_shmti_desc *desc; +void __iomem *addr; +phys_addr_t phys_addr; +size_t len; +int ret; + + desc = &r->desc[st->loop_idx]; + shmti = &ti->shmti[st->desc_index + st->loop_idx]; + + shmti->info.sid =le32_to_cpu (desc->id); + shmti->flags =le32_to_cpu (desc->flags); + + ret =scmi_telemetry_area_check (ph->dev,"SHMTI" , +le32_to_cpu (desc->addr_low), +le32_to_cpu (desc->addr_high), +le32_to_cpu (desc->length), + &phys_addr, &len); +if (ret) { +dev_err (ph->dev,"Malformed SHMTI ID:%u. Abort.\n" , + shmti->info.sid); +return ret; + } + +if (len <SHMTI_MIN_SIZE || len >SHMTI_MAX_SIZE ) { +dev_err (ph->dev, +FW_BUG "Invalid length for SHMTI ID:%u len:%zu. Abort.\n" , + shmti->info.sid, len); +return -EINVAL ; + } + +/* SHMTI base phys_addr SHOULD be 64bit aligned by the SCMI spec */ +if (!IS_ALIGNED (phys_addr,8 )) +dev_warn (ph->dev, +"SHMTI ID:%u is NOT 64bit aligned (paddr:%pa)\n" , + shmti->info.sid, &phys_addr); + + addr =devm_ioremap (ph->dev, phys_addr, len); +if (!addr) +return -EADDRNOTAVAIL ; + + shmti->base = addr; + shmti->info.len = len; + shmti->info.phys = phys_addr; + shmti->info.offset = shmti->info.phys & ~PAGE_MASK ; + + ret =scmi_telemetry_shmti_validate (ph->dev, shmti); +if (ret) +return ret; + + ti->num_shmti++; + +return 0 ; +} + +static int scmi_telemetry_shmti_list (const struct scmi_protocol_handle *ph, +struct telemetry_info *ti) +{ +struct scmi_iterator_ops ops = { + .prepare_message = iter_tlm_prepare_message, + .update_state = iter_shmti_update_state, + .process_response = iter_shmti_process_response, + }; +int num_shmti; +void *iter; +int ret; + +if (!ti->num_shmti) +return 0 ; + +/* Save and zero...calculate real number of returned */ + num_shmti = ti->num_shmti; + ti->num_shmti =0 ; + iter = ph->hops->iter_response_init (ph, &ops, num_shmti, +TELEMETRY_LIST_SHMTI , +sizeof (u32), ti); +if (IS_ERR (iter)) +return PTR_ERR (iter); + + ret = ph->hops->iter_response_run (iter); +if (ret) +return ret; + +if (num_shmti != ti->num_shmti) +dev_warn (ph->dev, +FW_BUG "SHMTI enumeration returned %u items, expected %u\n" , + ti->num_shmti, num_shmti); + +return 0 ; +} + +static void scmi_telemetry_shmti_cleanup (void *arg) +{ +struct telemetry_shmti *shmti = arg; + +cleanup_srcu_struct (&shmti->srcu); + +kvfree (shmti->snaps[0 ]); +kvfree (shmti->snaps[1 ]); + +xa_destroy (&shmti->xa_lines); +} + +static int scmi_telemetry_shmti_init (struct device *dev, +struct telemetry_shmti *shmti) +{ +int ret; + + struct shmti_snap *s0 __free(kvfree) = +kvzalloc_flex (*s0, base, shmti->info.len); +if (!s0) +return -ENOMEM ; + + struct shmti_snap *s1 __free(kvfree) = +kvzalloc_flex (*s1, base, shmti->info.len); +if (!s1) +return -ENOMEM ; + + ret =init_srcu_struct (&shmti->srcu); +if (ret) +return ret; + +for (int i =0 ; i <1 <<PAYLD_HASH_BITS ; i++) +mutex_init (&shmti->payld_locks[i]); + +mutex_init (&shmti->lock); +RCU_INIT_POINTER (shmti->cur,NULL ); + +mutex_init (&shmti->lines_mtx); +xa_init (&shmti->xa_lines); + + s0->shmti = shmti; + shmti->snaps[0 ] =no_free_ptr (s0); + + s1->shmti = shmti; + shmti->snaps[1 ] =no_free_ptr (s1); + +return devm_add_action_or_reset (dev, scmi_telemetry_shmti_cleanup, shmti); +} + +static int scmi_telemetry_enumerate_shmti (struct telemetry_info *ti) +{ +const struct scmi_protocol_handle *ph = ti->ph; +int ret; + + ret =scmi_telemetry_shmti_list (ph, ti); +if (ret) { +dev_err (ph->dev,"Cannot get SHMTI list descriptors\n" ); +return ret; + } + +for (int i =0 ; i < ti->num_shmti; i++) { + ret =scmi_telemetry_shmti_init (ph->dev, &ti->shmti[i]); +if (ret) +return ret; + + ti->info.shmtis[i] = &ti->shmti[i].info; + } + +/* Expose the fully initialized SHMTI infos */ +smp_store_release (&ti->info.base.num_shmtis, ti->num_shmti); + +return 0 ; +} +static const struct scmi_telemetry_info *scmi_telemetry_info_get (const struct scmi_protocol_handle *ph) {
@@ -836,7 +1123,20 @@ static const struct scmi_telemetry_proto_ops tlm_proto_ops = {* Return: 0 on Success, errno otherwise */ static int scmi_telemetry_resources_alloc (struct telemetry_info *ti) + { +/* Array to hold SHMTIs descriptors */ + struct telemetry_shmti *shmtis __free(kfree) = +kzalloc_objs (*shmtis, ti->num_shmti); +if (!shmtis) +return -ENOMEM ; + +/* Array of initialized SHMTIs references */ + struct scmi_telemetry_shmti_info **shmtis_info __free(kfree) = +kzalloc_objs (*shmtis_info, ti->num_shmti); +if (!shmtis_info) +return -ENOMEM ; +/* Array to hold pointers to discovered DEs */ struct scmi_telemetry_de **des __free(kfree) =kzalloc_objs (*des, ti->info.base.num_des);
@@ -871,6 +1171,9 @@ static int scmi_telemetry_resources_alloc(struct telemetry_info *ti)INIT_LIST_HEAD (&ti->fcs_des); + ti->shmti =no_free_ptr (shmtis); + ti->info.shmtis =no_free_ptr (shmtis_info); + ti->tdes =no_free_ptr (tdes);xa_init (&ti->xa_des);
@@ -902,6 +1205,9 @@ static void scmi_telemetry_resources_free(struct telemetry_info *ti)scmi_telemetry_tdes_cleanup (ti);xa_destroy (&ti->xa_des); +kfree (ti->info.shmtis); +kfree (ti->shmti); +kfree (ti->tdes);kfree (rinfo->des);
@@ -1050,6 +1356,12 @@ static int scmi_telemetry_protocol_init(const struct scmi_protocol_handle *ph)return ret; } + ret =scmi_telemetry_enumerate_shmti (ti); +if (ret) { +dev_err (dev,FW_BUG "Cannot enumerate SHMTIs. Abort.\n" ); +return ret; + } + ti->info.base.version = ph->version;return ph->set_priv (ph, ti);
include/linux/scmi_protocol.h +59 -0
77 lines not on this page · raw message
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 15/34 firmware: arm_scmi: Add Telemetry TDCF areas parsing support
In reply to Cristian MarussiAdd logic to scan the SHMTI areas, parsing the TDCF descriptors and collect DataEvent contained in TDCF DATA lines. Ignore TDCF BLK_TS and UUID lines.
---
v16 --> v17
- check if used_qwords > avail_qwords early in tdcf_line_parse
- add __iomem eplg annotation
- fix shmti_overflow and make it return the line length
- remove WARN_ON(fc_support), better dev_
- log error on malformed line data
v15 --> v16
- fix des_enabled format string
- make magic const in caching helpers
- drop useless __iomem useless cast in de_offs
- improve qwords overflow check on qwords in data_line_parse
- consider cache_stale BAD_START_SEQ(last_magic)
- fix offset_safe_calc helper
- discard and WARN when DE/FC are found on SHMTI
- remove unused SCAN_DISCOVERY
- shmti_oveflow use eplg directly
v14 --> v15
- account for tstamped TDE during discovery
- correct SHMTI overflow off-by-one
- rework TDE cache hit/miss logic
- introduce snapshots on full scan reads
- validate DE location on SCAN_UPDATE
- add custom SNAP eplg and overflow helpers
- moved here definition of scmi_telemetry_payld_offset_safe_calc
v13 --> v14
- fixed AB-BA dealock on blkts_link
- relocate xa_destroy for xa_lines after uuids cleanup
- report errors on scmi_telemetry_line_data_parse()
- moved some common protocol definitions here from previous
patches
- split out of this patch all of the BLK_TS and UUID lines
management, keeping only DATA line processing and delegating
the other line types to following smaller patches
- using a less regular time interval for TDCF scan retries
v12 --> v13
- refactored cleanup resources
- relocate tde->mtx guards higher up and add lockdep assertions
- drop refcount on previous active lines when scanning
- harden freeing path of UUIDs RCU items
- better DATA LINE size-validation while parsing
- reset active lines trackers on scan retries
- validate used_qwords
- redefine startm/endm bad sentinels and error path
- add more BLKTS_INVALID checks on parsing
- unlink stale BTS line when finding a new actibe for the TDE
- retry scans on TDCF sanity failures..could be a torn read
- use *alloc_objs
- remove TO_CPU64
v11 --> v12
- reject zero as MATCHSEQ
- reworked locking around line_get/put
- reworked locking around blkts_read
- a few comments on locking acquisition order
- cleanup active line refs even when bailing out of a scan in error
- added hashed locks for fine grain locking around blkts/uuid line creation
- added RCU protection on UUIDs access
v10 --> v11
- relocated some line handlers from another patch
- reworked TDE and lines locking logic
- fix UUID/BLKTS line refcounting to properly drop unused lines
- add a mutex to protect des cache accesses
v7 --> v9
- avoid referencing a NULL in trace_scmi_tlm_access O_o
- refactor scmi_telemetry_line_put to free its container on release
- convert SHMTI_OVERFLOW macro to an inline function
v7 --> v8
- Fixes for some Sashiko issues on v7
- reword a few dev_errs
- removed a few unused function (moved to next patch)
- add more safeguards and checks to SHMTI_OVERFLOWS
- fix UUIDs copy and allocation
- fix UUID reference store and cleanup
- cleanup all UNBOUND lines and their containers in resources_free
- remove mutex on primary init
v6 --> v7
- add _RAW helpers to manage non MMIO accesses
- sparse fixes
- use uuid_t for UUID lines
- fix proper UUID line parsing and binding
- adding a few traces for TDCF line handling
- add new dynamically sized UUID DB to ease discovered UUIDs lookup
- fix endianity handling in UUID TDCF lines
- handle Primary UUID lines with regular uuid_line
v5 --> v6
- consider UUID line in TDCF as BE when scanning
- use const booleans in scmi_telemetry_de_state_update()
- fix Sashiko review https://sashiko.dev/#/patchset/20260703123601.381275-1-cristian.marussi%40arm.com?part=8
- check SHMTI overflow while parsing
- use proper bytes increment while parsing line_by_type
- use mutex guard when link BLK_TS lines
v4 --> v5
- converted TDE_HAS_TSTAMP to inline scmi_tde_has_tstamp
- fixes sparse warnings
v3 --> v4
- use kzalloc_obj
- track SHMTI-discovered Telemetry DE states
- refactor TDE cache with dedicated helpers
- force tstamp to zero when timestamp is NOT supported or disabled
v2 --> v3
- split from monolithic Telemetry patch
- avoid devres allocation for resources that are added to the xa_lines XArray
- simplify prototype of line parsing helpers to drop unneeded dev
- flip tstmap logic in scmi_telemetry_line_data_parse() to properly emit
a TLM ftrace event
- use ternary ops to simplify quite a few expressions
--- drivers/firmware/arm_scmi/telemetry.c | 756 +++++++++++++++++++++++++- 1 file changed, 755 insertions(+), 1 deletion(-)
drivers/firmware/arm_scmi/telemetry.c +755 -1
@@ -14,21 +14,29 @@#include <linux/err.h> #include <linux/io.h> #include <linux/limits.h> +#include <linux/minmax.h> #include <linux/module.h> #include <linux/mutex.h> +#include <linux/refcount.h> #include <linux/sizes.h> #include <linux/slab.h> #include <linux/sprintf.h> #include <linux/string.h> +#include <linux/time.h> #include <linux/uuid.h> #include <linux/xarray.h> #include "protocols.h" #include "notify.h" +#include <trace/events/scmi.h> +/* Updated only after ALL the mandatory features for that version are merged */ #define SCMI_PROTOCOL_SUPPORTED_VERSION 0x10000 +#define SCMI_TLM_TDCF_MAX_RETRIES 15 +#define SCMI_TLM_TDCF_RETRY_GAP_US 1234 +#define SCMI_TLM_DE_IMPL_NUM_DWORDS 4/* An enum listing the protocol specific commands definitions */
@@ -125,6 +133,157 @@ struct scmi_msg_resp_telemetry_update_intervals {#define _I (__a) (ioread32((void __iomem *)(__a))) +/* +* Define the behaviour of a SHMTI scan defining what information will +* be gathered and which Telemetry items can be updated. +*/ +enum scan_mode { +SCAN_LOOKUP ,/* Update only value/tstamp */ +SCAN_UPDATE ,/* Update also location offset */ +}; + +struct fc_line { +__le32 data_low; +__le32 data_high; +}; + +struct fc_tsline { +__le32 data_low; +__le32 data_high; +__le32 ts_low; +__le32 ts_high; +}; + +struct line { +__le32 data_low; +__le32 data_high; +}; + +struct tsline { +__le32 data_low; +__le32 data_high; +__le32 ts_low; +__le32 ts_high; +}; + +#define LINE_DATA_GET_RAW (f) \ +({ \ + typeof(f) _f = (f); \ + u32 _high = le32_to_cpu(_f->data_high); \ + u32 _low = le32_to_cpu(_f->data_low); \ + u64 _res; \ + \ + _res = (((u64)(_high)) << 32) | (_low); \ + _res; \ +}) + +#define LINE_DATA_GET (f) \ +({ \ + typeof(f) _f = (f); \ + u32 _high = _I(&_f->data_high); \ + u32 _low = _I(&_f->data_low); \ + u64 _res; \ + \ + _res = (((u64)(_high)) << 32) | (_low); \ + _res; \ +}) + +#define LINE_TSTAMP_GET_RAW (f) \ +({ \ + typeof(f) _f = (f); \ + u32 _high = le32_to_cpu(_f->ts_high); \ + u32 _low = le32_to_cpu(_f->ts_low); \ + u64 _res; \ + \ + _res = (((u64)(_high)) << 32) | (_low); \ + _res; \ +}) + +#define LINE_TSTAMP_GET (f) \ +({ \ + typeof(f) _f = (f); \ + u32 _high = _I(&_f->ts_high); \ + u32 _low = _I(&_f->ts_low); \ + u64 _res; \ + \ + _res = (((u64)(_high)) << 32) | (_low); \ + _res; \ +}) + +#define BLK_TS_STAMP (f) LINE_TSTAMP_GET(f) +#define BLK_TS_STAMP_RAW (f) LINE_TSTAMP_GET_RAW(f) +#define BLK_TS_RATE (p) PAYLD_ID(p) +#define BLK_TS_RATE_RAW (p) PAYLD_ID_RAW(p) + +enum tdcf_line_types { +TDCF_DATA_LINE =0 , +TDCF_BLK_TS_LINE =1 , +TDCF_UUID_LINE =2 , +}; + +struct payload { +__le32 meta; +#define PAYLD_META (x) (_I(&((x)->meta))) +#define PAYLD_META_RAW (x) (le32_to_cpu((x)->meta)) +#define LINE_TYPE_RAW (m) (FIELD_GET(GENMASK(7, 4), (m))) +#define LINE_TYPE (x) (LINE_TYPE_RAW(PAYLD_META(x))) +#define IS_DATA_LINE (x) (LINE_TYPE(x) == TDCF_DATA_LINE) +#define IS_DATA_LINE_RAW (x) (LINE_TYPE_RAW(x) == TDCF_DATA_LINE) +#define IS_BLK_TS_LINE (x) (LINE_TYPE(x) == TDCF_BLK_TS_LINE) +#define IS_BLK_TS_LINE_RAW (x) (LINE_TYPE_RAW(x) == TDCF_BLK_TS_LINE) +#define IS_UUID_LINE (x) (LINE_TYPE(x) == TDCF_UUID_LINE) +#define USE_BLK_TS_RAW (m) ((m) & BIT(3)) +#define USE_BLK_TS (x) (USE_BLK_TS_RAW(PAYLD_META(x))) +#define HAS_LINE_EXT_RAW (m) ((m) & BIT(2)) +#define HAS_LINE_EXT (x) (HAS_LINE_EXT_RAW(PAYLD_META(x))) +#define LINE_TS_VALID_RAW (m) ((m) & BIT(1)) +#define LINE_TS_VALID (x) (LINE_TS_VALID_RAW(PAYLD_META(x))) +#define DATA_INVALID_RAW (m) ((m) & BIT(0)) +#define DATA_INVALID (x) (DATA_INVALID_RAW(PAYLD_META(x))) +#define BLK_TS_INVALID_RAW (m) \ +({ \ + bool invalid; \ + \ + invalid = LINE_TS_VALID_RAW(m) || HAS_LINE_EXT_RAW(m) || \ + USE_BLK_TS_RAW(m) || DATA_INVALID_RAW(m); \ + invalid; \ +}) +#define BLK_TS_INVALID (p) BLK_TS_INVALID_RAW(PAYLD_META(p)) + +#define UUID_INVALID_RAW (m) \ +({ \ + bool invalid; \ + \ + invalid = LINE_TS_VALID_RAW(m) || USE_BLK_TS_RAW(m) || \ + DATA_INVALID_RAW(m) || !HAS_LINE_EXT_RAW(m); \ + invalid; \ +}) +#define UUID_INVALID (p) UUID_INVALID_RAW(PAYLD_META(p)) +__le32 id; +union { +struct line l; +struct tsline tsl; + }; +}; + +#define PAYLD_ID (x) (_I(&(((struct payload __iomem *)(x))->id))) +#define PAYLD_ID_RAW (x) (le32_to_cpu((((struct payload *)(x))->id))) + +#define LINE_DATA_PAYLD_WORDS \ + ((sizeof(u32) + sizeof(u32) + sizeof(struct line)) / sizeof(u32)) +#define EXT_LINE_DATA_PAYLD_WORDS \ + ((sizeof(u32) + sizeof(u32) + sizeof(struct tsline)) / sizeof(u32)) + +#define LINE_LENGTH_WORDS_RAW (m) \ + (HAS_LINE_EXT_RAW((m)) ? EXT_LINE_DATA_PAYLD_WORDS : LINE_DATA_PAYLD_WORDS) + +#define LINE_LENGTH_WORDS (x) LINE_LENGTH_WORDS_RAW(PAYLD_META(x)) +#define LINE_LENGTH_QWORDS (x) ((LINE_LENGTH_WORDS(x)) / 2) +#define LINE_LENGTH_QWORDS_RAW (x) ((LINE_LENGTH_WORDS_RAW(x)) / 2) + +#define LINE_LENGTH_BYTES_RAW (m) ((LINE_LENGTH_WORDS_RAW(m)) * sizeof(u32)) +#define LINE_LENGTH_BYTES (x) (LINE_LENGTH_BYTES_RAW(PAYLD_META(x))) +struct prlg {__le32 sign_start;#define SIGNATURE_START 0x5442474E/* TBGN */
@@ -147,12 +306,24 @@ struct tdcf {unsigned char payld[]; }; +#define QWORDS (_t) (_I(&(_t)->prlg.num_qwords)) +#define QWORDS_RAW (_t) (le32_to_cpu((_t)->prlg.num_qwords)) +#define SHMTI_MIN_SIZE (sizeof(struct tdcf) + TDCF_EPLG_SZ)/* An arbitrary upper bound to avoid crazy allocations driven by buggy FW */ #define SHMTI_MAX_SIZE SZ_64K -#define TDCF_START_SIGNATURE (x) (_I(&((x)->prlg.sign_start))) +#define TDCF_START_SIGNATURE (x) (_I(&((x)->prlg.sign_start))) +#define TDCF_START_SEQ_GET (x) (_I(&((x)->prlg.match_start))) +#define TDCF_START_SEQ_GET_RAW (x) (le32_to_cpu((x)->prlg.match_start)) +/* TDCF MatchSequence cannot be zero by the SCMI v4.0 Specification */ +#define TDCF_INVALID_MATCH_SEQ 0 +#define IS_BAD_START_SEQ (s) ((s) & 0x1 || (s) == TDCF_INVALID_MATCH_SEQ) + +#define TDCF_END_SEQ_GET (e) (_I(&((e)->match_end))) +#define TDCF_END_SEQ_GET_RAW (e) (le32_to_cpu((e)->match_end))#define TDCF_END_SIGNATURE (e) (_I(&((e)->sign_end))) +#define TDCF_BAD_END_SEQ GENMASK(31, 0)struct telemetry_shmti ;
@@ -178,6 +349,9 @@ struct telemetry_shmti {struct mutex payld_locks[1 <<PAYLD_HASH_BITS ]; }; +#define TDCF_OFFS (_b, _p) \ + ((unsigned long)((__force void *)(_p) - (__force void *)(_b))) +#define SHMTI_EPLG (s) \ ({ \ struct telemetry_shmti *_s = (s); \
@@ -187,6 +361,44 @@ struct telemetry_shmti { (_eplg); \ }) +#define SNAP_EPLG (s) \ + ({ \ + struct shmti_snap *_s = (s); \ + struct eplg *_eplg; \ + \ + _eplg = (void *)_s->base + _s->shmti->info.len - TDCF_EPLG_SZ; \ + (_eplg); \ + }) + +struct telemetry_info ; + +struct telemetry_line { +enum tdcf_line_types type; +u32 last_magic; +unsigned long offset; +refcount_t users; +struct telemetry_shmti *shmti; +/* Protect line accesses */ +struct mutex mtx; +}; + +struct telemetry_block_ts { +u64 last_ts; +u32 last_rate; +struct telemetry_line line; +}; + +#define to_blkts (l) container_of(l, struct telemetry_block_ts, line) + +struct telemetry_uuid { +u32 key; +struct hlist_node node_ht; +struct hlist_node node_lst; +uuid_t uuid; +}; + +#define to_uuid_from_uuid_t (u) container_of(u, struct telemetry_uuid, uuid) +#define IS_TDE_TSTAMP_TYPE (__t, __ttype) ((__t)->ts_type == (__ttype))#define IS_TDE_TS_NONE (_t) (IS_TDE_TSTAMP_TYPE((_t), TSTAMP_NONE))#define IS_TDE_TS_LINE (_t) (IS_TDE_TSTAMP_TYPE((_t), TSTAMP_LINE))
@@ -209,7 +421,14 @@ struct telemetry_de {u32 offset;/* NOTE THAT DE data_sz is registered in scmi_telemetry_de */ u32 fc_size; +u64 last_val; +u64 last_ts; +u32 last_magic;struct list_head item; +struct telemetry_block_ts *bts; +#define BLK_TS_CHANGED (t, s, o) \ + (!((t)->bts) || (t)->bts->line.shmti != (s) || (t)->bts->line.offset != (o)) +struct telemetry_uuid *uuid;struct scmi_telemetry_de de;/* Protect last_val/ts/magic accesses - MUST BE KEPT LAST */ struct mutex mtx;
@@ -217,10 +436,24 @@ struct telemetry_de {#define to_tde (d) container_of(d, struct telemetry_de, de) +static inline bool scmi_tde_has_tstamp (struct telemetry_de *t) +{ +return t->de.tstamp_support && t->de.tstamp_enabled; +} + +enum de_state { +ENA_STATE , +ENA_TSTAMP , +ENA_MAX +}; +struct telemetry_info {bool streaming_mode;unsigned int num_shmti;unsigned int num_des_tstamp; +/* Mutex to protect des_enabled_mtx */ +struct mutex des_enabled_mtx; +atomic_t des_enabled[ENA_MAX ];unsigned int default_blk_ts_rate;const struct scmi_protocol_handle *ph;struct telemetry_shmti *shmti;
@@ -240,6 +473,27 @@ struct telemetry_info {static struct scmi_telemetry_res_info *__scmi_telemetry_resources_get (struct telemetry_info *ti); +static inline struct tdcf *snap_tdcf (struct shmti_snap *s); + +static int scmi_telemetry_shmti_scan (struct telemetry_info *ti, +unsigned int shmti_id,enum scan_mode mode); + +static inline void +scmi_telemetry_de_state_update (struct telemetry_info *ti,enum de_state state, +bool *current_state,const bool next_state) +{ +guard (mutex)(&ti->des_enabled_mtx); +if (!current_state || *current_state != next_state) +atomic_add (next_state ?1 :-1 , &ti->des_enabled[state]); + +if (current_state) + *current_state = next_state; + +dev_dbg (ti->ph->dev,"Telemetry des_enabled[%s]:%d\n" , + state ==ENA_STATE ?"STATE" :"TSTAMP" , +atomic_read (&ti->des_enabled[state])); +} +static struct telemetry_de *scmi_telemetry_free_tde_get (struct telemetry_info *ti) {
@@ -359,6 +613,36 @@ static int scmi_telemetry_tde_register(struct telemetry_info *ti,return ret; } +static inline bool +scmi_telemetry_tde_cache_stale (struct telemetry_de *tde,const u32 magic) +{ +lockdep_assert_held (&tde->mtx); + +/* last_magic < magic */ +return IS_BAD_START_SEQ (tde->last_magic) || +time_before32 (tde->last_magic, magic); +} + +static void +scmi_telemetry_tde_cache_update (struct telemetry_de *tde,u64 val, +u64 *tstamp,const u32 *magic) +{ +lockdep_assert_held (&tde->mtx); + +/* +* Update the cache only if stale compared to the current +* sample, so bail-out when last_magic >= *magic +*/ +if (magic && !scmi_telemetry_tde_cache_stale (tde, *magic)) +return ; + + tde->last_magic = magic ? *magic :TDCF_BAD_END_SEQ ; + tde->last_val = val; + tde->last_ts = tstamp &&scmi_tde_has_tstamp (tde) ? *tstamp :0 ; +if (tstamp) + *tstamp = tde->last_ts; +} +struct scmi_tlm_de_priv {struct telemetry_info *ti;void *next;
@@ -1101,6 +1385,473 @@ scmi_telemetry_de_lookup(const struct scmi_protocol_handle *ph, u32 id)return xa_load (&ti->xa_des, id); } +static inline struct payload __iomem * +scmi_telemetry_payld_offset_safe_calc (struct telemetry_shmti *shmti,u32 offs) +{ +struct payload __iomem *payld; +unsigned long p; +u32 end; + +if (offs <sizeof (struct tdcf )) +return IOMEM_ERR_PTR (-EPROTO ); + +/* Check if accessing payld->meta is safe. */ +if (check_add_overflow (offs,sizeof (u32), &end) || + end > shmti->info.len) +return IOMEM_ERR_PTR (-EPROTO ); + +if (check_add_overflow ((__force unsigned long )shmti->base, offs, &p)) +return IOMEM_ERR_PTR (-EPROTO ); + + payld = shmti->base + offs; +/* Check line boundary */ +if (check_add_overflow (offs,LINE_LENGTH_BYTES (payld), &end) || + end > shmti->info.len -TDCF_EPLG_SZ ) +return IOMEM_ERR_PTR (-EPROTO ); + +return payld; +} + +static u64 +scmi_telemetry_blkts_read (u32 magic,struct telemetry_de *tde) +{ +lockdep_assert_held (&tde->mtx); + +return 0 ; +} + +static inline int +scmi_telemetry_line_data_parse (struct telemetry_de *tde,struct shmti_snap *snap, +u64 *val,u64 *tstamp,struct payload *payld, +struct payload *bts_payld,u32 magic) +{ +u32 meta =PAYLD_META_RAW (payld); + +lockdep_assert_held (&tde->mtx); + +/* Clear returned values in case of errors */ + *val =0 ; + +if (tstamp) { + *tstamp =0 ; +if (USE_BLK_TS_RAW (meta)) { +/* Read out the actual BLK_TS */ + *tstamp =scmi_telemetry_blkts_read (magic, tde); + }else if (LINE_TS_VALID_RAW (meta)) { +/* +* Note that LINE_TS_VALID implies HAS_LINE_EXT and that +* the per DE line_ts_rate is advertised in the DE +* descriptor, BUT we check anyway against buggy FW. +*/ +if (!HAS_LINE_EXT_RAW (meta)) { +trace_scmi_tlm_access (tde->de.info->id, +"SHMTI_BAD_TS_LINE" ,0 ,0 ); +return -EPROTO ; + } + + *tstamp =LINE_TSTAMP_GET_RAW (&payld->tsl); + } + } + +/* Data is always valid since we are NOT handling BLK TS lines here */ + *val =LINE_DATA_GET_RAW (&payld->l); + +trace_scmi_tlm_collect (tstamp ? *tstamp :0 , tde->de.info->id, + *val,"SHMTI_DE_READ" ); + +scmi_telemetry_tde_cache_update (tde, *val, tstamp, &magic); + +return 0 ; +} + +/** +* scmi_telemetry_tdcf_data_parse - TDCF DataLine parsing +* @ti: A reference to the telemetry info descriptor +* @payld: Line payload to parse +* @snap: A reference to the working SHMTI snapshot that will be processed +* @mode: A flag to determine the behaviour of the scan +* @active_bts: A pointer to keep track and report any found BLK timestamp line +* @active_uuid: A pointer to keep track and report any found UUID line +* +* This routine takes care to: +* - verify line consistency in relation to the used flags and the current +* context: e.g. is there an active preceding BLK_TS line if the DataLine +* sports a USE_BLKTS flag ? +* - verify the related Data Event ID exists OR create a brand new DE +* (depending on the @mode of operation) +* - links any active BLK_TS or UUID line to the current DE +* - read and save value/tstamp for the DE ONLY if anything has changed (by +* tracking the last TDCF magic) and update related magic: this allows to +* minimize future needs of single-DE reads +* +* Modes of operation. +* +* The scan behaviour depends on the chosen @mode: +* - SCAN_LOOKUP: the basic scan which aims to update value associated to +* existing DEs. Any discovered DataLine that could NOT be +* matched to an existing, previously discovered, DE is +* discarded. This is the normal scan behaviour. +* - SCAN_UPDATE: a more advanced scan which provides all the SCAN_LOOKUP +* features plus takes care to update the DEs location +* coordinates inside the SHMTI: note that the related DEs are +* still supposed to have been previously discovered when +* this scan runs. This is used to update location +* coordinates for DEs contained in a Group when such group +* is enabled. +*/ +static void scmi_telemetry_tdcf_data_parse (struct telemetry_info *ti, +struct payload *payld, +struct shmti_snap *snap, +enum scan_mode mode, +struct telemetry_block_ts *active_bts, +struct telemetry_uuid *active_uuid) +{ +struct telemetry_shmti *shmti = snap->shmti; +struct device *dev = ti->ph->dev; +struct telemetry_de *tde; +u64 val, tstamp =0 ; +u32 de_id; + + de_id =PAYLD_ID_RAW (payld); +/* Is this DE ID known ? */ + tde =scmi_telemetry_tde_lookup (ti, de_id); +if (!tde) { +trace_scmi_tlm_access (de_id,"DE_INVALID" ,0 ,0 ); +return ; + } + +guard (mutex)(&tde->mtx); + +if (tde->de.fc_support) { +dev_err (dev,"Found FastChannel DE while parsing a SHMTI.\n" ); +trace_scmi_tlm_access (de_id,"DE_INVALID_FC_ON_SHMTI" ,0 ,0 ); +return ; + } + +/* +* Update DE location refs if requested: normally done only on group +* enable. +* Note that all the DE location information is relative to the +* original SHMTI device-memory area, NOT to the snapshot we are parsing. +*/ +if (mode >=SCAN_UPDATE ) { +u32 de_offs; +void __iomem *p; + +/* Offest is the same in the SHMTI and in the snapshot indeed */ + de_offs = (void *)payld - (void *)snap->base; +/* Validate location before update */ + p =scmi_telemetry_payld_offset_safe_calc (shmti, de_offs); +if (IS_ERR (p)) { +dev_err (dev, +"TDE 0x%08X updated location invalid - shmti:%u offs:%u\n" , + de_id, shmti->info.sid, de_offs); +trace_scmi_tlm_access (de_id,"DE_LOCATION_INVALID" ,0 ,0 ); +return ; + } + + tde->sid = shmti->info.sid; + tde->base = shmti->base; + tde->eplg =SHMTI_EPLG (shmti); + tde->offset = de_offs; + +trace_scmi_tlm_access (de_id,"DE_LOCATION_UPDATED" ,0 ,0 ); + +dev_dbg (dev,"TDCF-updated DE_ID:0x%08X - shmti:%pK offset:%u\n" , + tde->de.info->id, tde->base, tde->offset); + } + +/* +* Has any value/tstamp really changed ? +* Note that, if the magic currently associated with this TDE has +* NOT changed compared to the current SHMTI magic, nothing could have +* been changed across the whole TDCF, including any relation to +* BLK_TS or UUID lines. +*/ +if (!scmi_telemetry_tde_cache_stale (tde, snap->magic)) +return ; + +/* +* Parse data words ... only for the sake of updating TDE cache, +* any error is logged but ignored. +*/ +if (scmi_telemetry_line_data_parse (tde, snap, &val, &tstamp, payld, +NULL , snap->magic)) +dev_err (dev,"Malformed DATA line.\n" ); +} + +/** +* scmi_telemetry_tdcf_line_parse - Line parser +* @ti: A reference to the Telemetry instance +* @avail_qwords: Number of remaining qwords +* @payld: A reference to the payload representing the line to parse +* @snap: A reference to the working SHMTI snapshot that will be processed +* @mode: Specification of the scanning mode +* @active_bts: A reference used to track the last BLK_TS line found +* @active_uuid: A reference used to track the last UUID line found +* +* Note that @active_bts and @active_uuid references are propagated back and +* forth from the line parsers to keep track of the nearest active BLK_TS or +* UUID line found in the SHMTI areas and, while doing that, such descriptors +* are refcounted and tracked in the xa_lines XArray indexed by @payld. +* BLK_TS and UUID descriptors are dropped when no more linked to any DATA line, +* during the normal system operation OR later on when the protocol is +* de-initialized following a driver removal. +* +* Return: Number of QWORDS consumed from @payld by this line parsing; note +* that buggy firmware could return bad, out of range values, so this +* value MUST be carefully checked for SHMTI boundary overflows by the +* caller. +*/ +static int scmi_telemetry_tdcf_line_parse (struct telemetry_info *ti, +unsigned int avail_qwords, +struct payload *payld, +struct shmti_snap *snap, +enum scan_mode mode, +struct telemetry_block_ts **active_bts, +struct telemetry_uuid **active_uuid) +{ +u32 meta =le32_to_cpu (payld->meta); +int used_qwords; + + used_qwords =LINE_LENGTH_QWORDS_RAW (meta); +/* Does they fit in the snapshot (sane) available qwords ? */ +if (used_qwords > avail_qwords) +return -EINVAL ; + +/* Invalid lines are not an error, could simply be disabled DEs */ +if (DATA_INVALID_RAW (meta)) { +trace_scmi_tlm_access (le32_to_cpu (payld->id),"TDCF_INVALID" ,0 ,0 ); +return used_qwords; + } + +/* +* Problematic lines are ignored, their information discarded, and such +* issues are logged, but the scan process continues. +*/ +switch (LINE_TYPE_RAW (meta)) { +case TDCF_DATA_LINE : +scmi_telemetry_tdcf_data_parse (ti, payld, snap, mode, + *active_bts, *active_uuid); +break ; +default : +trace_scmi_tlm_access (PAYLD_ID_RAW (payld),"TDCF_LINE_UNKNOWN" ,0 ,0 ); +break ; + } + +return used_qwords; +} + +static inline ssize_t +scmi_telemetry_shmti_overflow (void __iomem *base,void __iomem *eplg, +void __iomem *next) +{ +ssize_t len; + +/* Is payld->meta accessible and within usable TDCF space ? */ +if (next < base +sizeof (struct tdcf ) || next +sizeof (u32) > eplg) +return -EOVERFLOW ; + + len =LINE_LENGTH_BYTES ((struct payload __iomem *)next); +if (next + len > eplg) +return -EOVERFLOW ; + +return len; +} + +static inline struct tdcf *snap_tdcf (struct shmti_snap *s) +{ +return (struct tdcf *)s->base; +} + +static inline bool +scmi_telemetry_snap_overflow (struct shmti_snap *snap,const void *next) +{ +void *limit =SNAP_EPLG (snap); + +/* Is payld->meta accessible ? */ +if (next >= limit -sizeof (u32)) +return true; + + next +=LINE_LENGTH_BYTES_RAW (PAYLD_META_RAW ((struct payload *)next)); + +return next > limit; +} + +static int scmi_telemetry_shmti_snapshot (struct telemetry_shmti *shmti, +struct shmti_snap *work) +{ +struct tdcf __iomem *tdcf = shmti->base; +int retries =SCMI_TLM_TDCF_MAX_RETRIES ; +struct tdcf *snap =snap_tdcf (work); +u32 startm =0 , endm =0 , live; + +lockdep_assert_held (&shmti->lock); + +do { +/* A bit of exponential backoff between retries */ +fsleep ((SCMI_TLM_TDCF_MAX_RETRIES - retries) *SCMI_TLM_TDCF_RETRY_GAP_US ); + +memcpy_fromio (snap, tdcf, shmti->info.len); +/* Assure the TDCF snapshot has been fully taken before checking seqnum */ +rmb (); +/* Used to detect changes while copying */ + live =TDCF_START_SEQ_GET (tdcf); + + startm =TDCF_START_SEQ_GET_RAW (snap); +if (IS_BAD_START_SEQ (startm)) { +trace_scmi_tlm_access (0 ,"MSEQ_BADSTART" , startm,0 ); +continue ; + } + + endm =TDCF_END_SEQ_GET_RAW (SNAP_EPLG (work)); +if (startm != endm || startm != live) { +trace_scmi_tlm_access (0 ,"MSEQ_MISMATCH" , startm, + startm != endm ? endm : live); +continue ; + } + +trace_scmi_tlm_access (0 ,"TDCF_SNAPSHOT_OK" , startm, endm); + +/* Ensure any snapshot is visible before updating magic */ +smp_store_release (&work->magic, startm); + +return 0 ; + }while (--retries); + +trace_scmi_tlm_access (0 ,"TDCF_SNAPSHOT_FAIL" , startm, endm); + +return -EPROTO ; +} + +/* +* True if neither TDCF marker has moved since the cached snapshot was taken. +* Any platform update must write one marker before touching data (start first +* or end first, depending on the spec's order), so checking both is +* independent of that order. +*/ +static bool scmi_telemetry_shmti_unchanged (struct telemetry_shmti *shmti,u32 magic) +{ +struct tdcf __iomem *tdcf = shmti->base; + +return TDCF_START_SEQ_GET (tdcf) == magic && +TDCF_END_SEQ_GET (SHMTI_EPLG (shmti)) == magic; +} + +/* Returns with the SRCU read lock held (index in *idx) on a snapshot that matched at check time */ +static struct shmti_snap * +scmi_telemetry_shmti_refresh (struct telemetry_shmti *shmti,int *idx) +{ +struct shmti_snap *cur, *work; +int ret; + +guard (mutex)(&shmti->lock); + + cur =rcu_dereference_protected (shmti->cur,lockdep_is_held (&shmti->lock)); +/* Someone else may have refreshed while we waited for the mutex */ +if (cur &&scmi_telemetry_shmti_unchanged (shmti, cur->magic)) { +/* Safe: recycling cur requires shmti->lock, which we hold */ + *idx =srcu_read_lock (&shmti->srcu); +return cur; + } + +/* Pick the spare buffer */ + work = (cur == shmti->snaps[0 ]) ? shmti->snaps[1 ] : shmti->snaps[0 ]; +/* +* Wait for readers that may still be parsing 'work' from its time +* as current +*/ +synchronize_srcu (&shmti->srcu); + + ret =scmi_telemetry_shmti_snapshot (shmti, work); +if (ret) +return ERR_PTR (ret); + +/* +* Take our read lock BEFORE publishing so 'work' cannot be +* recycled under us +*/ + *idx =srcu_read_lock (&shmti->srcu); +rcu_assign_pointer (shmti->cur, work); + +return work; +} + +/** +* scmi_telemetry_shmti_scan - Full SHMTI scan +* @ti: A reference to the telemetry info descriptor +* @shmti_id: ID of the SHMTI area that has to be scanned +* @mode: A flag to determine the behaviour of the scan +* +* Return: 0 on Success +*/ +static int scmi_telemetry_shmti_scan (struct telemetry_info *ti, +unsigned int shmti_id,enum scan_mode mode) +{ +struct telemetry_shmti *shmti = &ti->shmti[shmti_id]; +struct telemetry_block_ts *active_bts =NULL ; +struct telemetry_uuid *active_uuid =NULL ; +unsigned int qwords; +struct shmti_snap *snap; +struct tdcf *tdcf; +int idx, ret =0 ; +void *next; + +if (!shmti->base) +return -ENODEV ; + + idx =srcu_read_lock (&shmti->srcu); + snap =srcu_dereference (shmti->cur, &shmti->srcu); +if (!snap || !scmi_telemetry_shmti_unchanged (shmti, snap->magic)) { +/* MUST drop the read lock: refresh calls synchronize_srcu() */ +srcu_read_unlock (&shmti->srcu, idx); + snap =scmi_telemetry_shmti_refresh (shmti, &idx); +if (IS_ERR (snap)) +return PTR_ERR (snap); + } + + tdcf =snap_tdcf (snap); + next = tdcf->payld; + qwords =QWORDS_RAW (tdcf); +while (qwords) { +int used_qwords; + +/* +* Bailout on any error since we are processing a supposedly +* stable snapshot at this point, so any further error is on +* firmware-side and NOT recoverable: this would mean having to +* drop the remaining part of the scan results after having +* cached the initial good snapshot: log this down below. +*/ +if (scmi_telemetry_snap_overflow (snap, next)) { +trace_scmi_tlm_access (0 ,"SHMTI_OVERFLOW" , snap->magic,0 ); + ret = -EPROTO ; +break ; + } + + used_qwords =scmi_telemetry_tdcf_line_parse (ti, qwords, + next, snap, mode, + &active_bts, &active_uuid); +if (used_qwords <=0 ) { +/* Stop scanning when qwords are inconsistent. */ +trace_scmi_tlm_access (PAYLD_ID_RAW (next),"BAD_QWORDS" , + snap->magic,0 ); + ret = -EPROTO ; +break ; + } + + next += used_qwords *8 ; + qwords -= used_qwords; + } + +srcu_read_unlock (&shmti->srcu, idx); + +if (ret) +dev_err (ti->ph->dev,FW_BUG "Inconsistent TDCF. Scan aborted.\n" ); + +return ret; +} +static const struct scmi_telemetry_proto_ops tlm_proto_ops = { .info_get = scmi_telemetry_info_get, .de_lookup = scmi_telemetry_de_lookup,
@@ -1313,6 +2064,9 @@ static int scmi_telemetry_instance_init(struct telemetry_info *ti)if (ret)return ret; +atomic_set (&ti->des_enabled[ENA_STATE ],0 ); +atomic_set (&ti->des_enabled[ENA_TSTAMP ],0 ); +mutex_init (&ti->des_enabled_mtx);/* Setup resources lazy initialization */ atomic_set (&ti->rinfo_initializing,0 );init_completion (&ti->rinfo_initdone);
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 16/34 firmware: arm_scmi: Add Telemetry TDCF parsing for BLK_TS lines
In reply to Cristian MarussiAdd support to parse, track and link TDCF BLK_TS lines to the related discovered DataEvents.
---
v16 --> v17
- check TDE TS type, update from last_rate
v15 --> v16
- WARN_ON(BLK_TS_INVALID) but keep active_bts valid
- invalidate TDE cache on blkts_unlin
- cleanup stale lines on shmti cleanup
v14 --> v15
- use proper cast on tlm_collect
- use snapshots to track and collect BLK_TS during full scan bulk reads
- fix too early invocation xa_destroy(xa_lines)
v13 --> v14
- split out of previous single patch implementing parse SHMTI routines
--- drivers/firmware/arm_scmi/telemetry.c | 352 +++++++++++++++++++++++++- 1 file changed, 344 insertions(+), 8 deletions(-)
drivers/firmware/arm_scmi/telemetry.c +344 -8
@@ -12,6 +12,7 @@#include <linux/delay.h> #include <linux/device.h> #include <linux/err.h> +#include <linux/hash.h> #include <linux/io.h> #include <linux/limits.h> #include <linux/minmax.h>
@@ -159,6 +160,11 @@ struct line {__le32 data_high; }; +struct blk_tsline { +__le32 ts_low; +__le32 ts_high; +}; +struct tsline {__le32 data_low;__le32 data_high;
@@ -263,6 +269,7 @@ struct payload {union {struct line l;struct tsline tsl; +struct blk_tsline blk_tsl; }; };
@@ -470,6 +477,10 @@ struct telemetry_info {struct scmi_telemetry_res_info *(*res_get)(struct telemetry_info *ti); }; +static void __scmi_telemetry_line_put (struct telemetry_line *line); + +static void scmi_telemetry_de_unlink (struct scmi_telemetry_de *de); +static struct scmi_telemetry_res_info *__scmi_telemetry_resources_get (struct telemetry_info *ti);
@@ -478,6 +489,12 @@ static inline struct tdcf *snap_tdcf(struct shmti_snap *s);static int scmi_telemetry_shmti_scan (struct telemetry_info *ti,unsigned int shmti_id,enum scan_mode mode); +static inline +struct mutex *lock_for_payld (struct mutex *locks,unsigned long offset) +{ +return &locks[hash_long (offset,PAYLD_HASH_BITS )]; +} +static inline void scmi_telemetry_de_state_update (struct telemetry_info *ti,enum de_state state,bool *current_state,const bool next_state)
@@ -613,6 +630,14 @@ static int scmi_telemetry_tde_register(struct telemetry_info *ti,return ret; } +static inline void scmi_telemetry_tde_cache_invalidate (struct telemetry_de *tde) +{ +lockdep_assert_held (&tde->mtx); + +/* Invalidate cache */ + tde->last_magic =TDCF_BAD_END_SEQ ; +} +static inline bool scmi_telemetry_tde_cache_stale (struct telemetry_de *tde,const u32 magic) {
@@ -960,16 +985,24 @@ static int iter_de_descr_process_response(const struct scmi_protocol_handle *ph,return 0 ; } -static void scmi_telemetry_tdes_cleanup (struct telemetry_info *ti) +static void scmi_telemetry_tdes_cleanup (void *arg) { +struct telemetry_info *ti = arg;struct scmi_telemetry_de *de;unsigned long idx; +/* +* Unlinking all the BLK_TS/UUID lines related to a DE triggers also +* the deallocation of such lines when the embedded refcount hits zero. +* Note that the UUID lines are also referenced and refcounted by the +* global UUID RCU array, so they won't be deallocated here. +*/ xa_for_each (&ti->xa_des, idx, de) {struct telemetry_de *tde =to_tde (de);guard (mutex)(&tde->mtx); +scmi_telemetry_de_unlink (&tde->de);scmi_telemetry_free_tde_put (ti, tde); } }
@@ -1280,16 +1313,29 @@ static int scmi_telemetry_shmti_list(const struct scmi_protocol_handle *ph,return 0 ; } +static void scmi_telemetry_shmti_lines_cleanup (struct telemetry_shmti *shmti) +{ +struct telemetry_line *line; +unsigned long idx; + +guard (mutex)(&shmti->lines_mtx); +/* Drop all remaining currently unbound lines and their containers */ +xa_for_each (&shmti->xa_lines, idx, line) +__scmi_telemetry_line_put (line); + +xa_destroy (&shmti->xa_lines); +} +static void scmi_telemetry_shmti_cleanup (void *arg) {struct telemetry_shmti *shmti = arg; +scmi_telemetry_shmti_lines_cleanup (shmti); +cleanup_srcu_struct (&shmti->srcu);kvfree (shmti->snaps[0 ]);kvfree (shmti->snaps[1 ]); - -xa_destroy (&shmti->xa_lines); } static int scmi_telemetry_shmti_init(struct device *dev,
@@ -1351,7 +1397,7 @@ static int scmi_telemetry_enumerate_shmti(struct telemetry_info *ti)/* Expose the fully initialized SHMTI infos */ smp_store_release (&ti->info.base.num_shmtis, ti->num_shmti); -return 0 ; +return devm_add_action_or_reset (ph->dev, scmi_telemetry_tdes_cleanup, ti); } static const struct scmi_telemetry_info *
@@ -1413,11 +1459,242 @@ scmi_telemetry_payld_offset_safe_calc(struct telemetry_shmti *shmti, u32 offs) }static u64 -scmi_telemetry_blkts_read (u32 magic,struct telemetry_de *tde) +scmi_telemetry_blkts_read (u32 magic,struct telemetry_de *tde, +struct payload *bts_payld,struct shmti_snap *snap) { +struct telemetry_block_ts *bts; + +/* Acquiring order is: tde -> line */ lockdep_assert_held (&tde->mtx); +if (WARN_ON (!tde->bts || (!bts_payld && !snap))) +return 0 ; -return 0 ; + bts = tde->bts; +guard (mutex)(&bts->line.mtx); + +if (bts->line.last_magic == magic) +return bts->last_ts; + +/* Unless specified otherwise, use the snapshot BLK_TS paylod */ +if (!bts_payld) { +void *base =snap_tdcf (snap); + + bts_payld = base + bts->line.offset; + } + +/* Note that the bts->last_rate can change ONLY on creation */ + bts->last_ts =BLK_TS_STAMP_RAW (&bts_payld->blk_tsl); + bts->line.last_magic = magic; + +return bts->last_ts; +} + +static void +scmi_telemetry_blkts_update_snap (struct telemetry_info *ti, +struct telemetry_block_ts *bts, +struct payload *bts_payld,u32 magic) +{ +guard (mutex)(&bts->line.mtx); +if (bts->line.last_magic != magic) { + bts->last_ts =BLK_TS_STAMP_RAW (&bts_payld->blk_tsl); + bts->last_rate =BLK_TS_RATE_RAW (bts_payld); +/* BLK_TS clock rate value can change ONLY here on creation */ +if (!bts->last_rate) + bts->last_rate = ti->default_blk_ts_rate; + bts->line.last_magic = magic; + +trace_scmi_tlm_access (0 ,"BLK_TS_UPDATE" , magic,0 ); + } +} + +static inline void scmi_telemetry_line_free (struct telemetry_line *line) +{ +void *blob; + +switch (line->type) { +case TDCF_BLK_TS_LINE : + blob =to_blkts (line); +kfree (blob); +break ; +default : +WARN_ON (1 ); +break ; + } +} + +static void __scmi_telemetry_line_put (struct telemetry_line *line) +{ +lockdep_assert_held (&line->shmti->lines_mtx); + +mutex_lock (&line->mtx); +if (refcount_dec_and_test (&line->users)) { +xa_erase (&line->shmti->xa_lines, line->offset); + +/* Unlock and free the containing structure: blkts or uuid */ +mutex_unlock (&line->mtx); + +trace_scmi_tlm_access (0 ,"DROP_LINE" , line->type, line->last_magic); +scmi_telemetry_line_free (line); + +return ; + } +mutex_unlock (&line->mtx); +} + +static void scmi_telemetry_line_put (struct telemetry_line *line) +{ +/* Acquiring coarse grain first ... */ +guard (mutex)(&line->shmti->lines_mtx); +__scmi_telemetry_line_put (line); +} + +static void scmi_telemetry_blkts_unlink (struct telemetry_de *tde) +{ +/* Acquiring order is: tde -> line */ +lockdep_assert_held (&tde->mtx); +if (!tde->bts) +return ; + +scmi_telemetry_line_put (&tde->bts->line); + +scmi_telemetry_tde_cache_invalidate (tde); + tde->bts =NULL ; + +trace_scmi_tlm_access (tde->de.info->id,"BLKTS_UNLINK" ,0 ,0 ); +} + +static void scmi_telemetry_de_unlink (struct scmi_telemetry_de *de) +{ +struct telemetry_de *tde =to_tde (de); + +lockdep_assert_held (&tde->mtx); + +/* Unlink all related lines triggering their deallocation */ +scmi_telemetry_blkts_unlink (tde); +} + +static struct telemetry_line * +scmi_telemetry_line_get (struct telemetry_shmti *shmti,unsigned long offset) +{ +struct telemetry_line *line; + +/* Acquiring coarse grain first ... */ +guard (mutex)(&shmti->lines_mtx); + line =xa_load (&shmti->xa_lines, offset); +if (!line) +return NULL ; + +guard (mutex)(&line->mtx); +refcount_inc (&line->users); + +return line; +} + +static int +scmi_telemetry_line_init (struct telemetry_shmti *shmti,struct telemetry_line *line, +unsigned long offset,enum tdcf_line_types type) +{ + line->type = type; +refcount_set (&line->users,1 ); + line->offset = offset; + line->shmti = shmti; +mutex_init (&line->mtx); + +guard (mutex)(&shmti->lines_mtx); +return xa_insert (&shmti->xa_lines, offset, line,GFP_KERNEL ); +} + +static struct telemetry_block_ts * +scmi_telemetry_blkts_create (struct telemetry_shmti *shmti,unsigned long offset) +{ +struct telemetry_block_ts *bts; +int ret; + + bts =kzalloc_obj (*bts); +if (!bts) +return NULL ; + + ret =scmi_telemetry_line_init (shmti, &bts->line, offset,TDCF_BLK_TS_LINE ); +if (ret) { +kfree (bts); +return NULL ; + } + +trace_scmi_tlm_collect (0 , shmti->info.sid, offset,"SHMTI_NEW_BLKTS" ); + +return bts; +} + +static struct telemetry_block_ts * +scmi_telemetry_blkts_get_or_create (struct telemetry_shmti *shmti, +unsigned long offset) +{ +struct telemetry_line *line; + +/* Avoid races on line creation for this payld */ +guard (mutex)(lock_for_payld (shmti->payld_locks, offset)); + + line =scmi_telemetry_line_get (shmti, offset); +if (line) +return to_blkts (line); + +return scmi_telemetry_blkts_create (shmti, offset); +} + +/** +* scmi_telemetry_tdcf_blkts_parse - A BLK_TS line parser +* +* @ti: A reference to the telemetry_info descriptor +* @bts_payld: TDCF payld line to process +* @snap: A reference to the working SHMTI snapshot that will be processed +* @active_bts: Input/output reference to keep track of the last blk_ts found +* +* Process a valid TDCF BLK_TS line and, after having looked up or created a +* blk_ts descriptor, update the related data and return it as the currently +* active blk_ts, given that it is effectively the last found during this +* scan. +* +* Note that the current BLK_TS line could be malformed due to garbage in +* the TDCF: in such a case we warn/log and bailout BUT we don't throw away +* the currently active_bts (if any) since the current malformed line could +* be bogus and never intended to be a BLK_TS line. +*/ +static void scmi_telemetry_tdcf_blkts_parse (struct telemetry_info *ti, +struct payload *bts_payld, +struct shmti_snap *snap, +struct telemetry_block_ts **active_bts) +{ +struct telemetry_block_ts *bts, *previous = *active_bts; +struct telemetry_shmti *shmti = snap->shmti; +u32 meta =PAYLD_META_RAW (bts_payld); +unsigned long offset; + +/* Check for spec compliance. */ +if (WARN_ON (BLK_TS_INVALID_RAW (meta))) { +trace_scmi_tlm_access (0 ,"BLK_TS_INVALID" ,0 , meta); +return ; + } + + offset =TDCF_OFFS (snap->base, bts_payld); +/* A BLK_TS descriptor MUST be returned: it is found or it is created */ + bts =scmi_telemetry_blkts_get_or_create (shmti, offset); +/* +* On error processing the new BLK_TS bailout taking care to clear +* the previous last active BLK_TS to avoid mistakenly binding to the +* next data lines. +*/ +if (WARN_ON (!bts)) + goto out; + +/* Update the descriptor with the lastest TS */ +scmi_telemetry_blkts_update_snap (ti, bts, bts_payld, snap->magic); + +out: +/* Drop one refcount on the previous active since we found a new one */ +if (previous) +scmi_telemetry_line_put (&previous->line); + + *active_bts = bts; } static inline int
@@ -1436,7 +1713,8 @@ scmi_telemetry_line_data_parse(struct telemetry_de *tde, struct shmti_snap *snap *tstamp =0 ;if (USE_BLK_TS_RAW (meta)) {/* Read out the actual BLK_TS */ - *tstamp =scmi_telemetry_blkts_read (magic, tde); + *tstamp =scmi_telemetry_blkts_read (magic, tde, + bts_payld, snap); }else if (LINE_TS_VALID_RAW (meta)) {/* * Note that LINE_TS_VALID implies HAS_LINE_EXT and that
@@ -1464,6 +1742,26 @@ scmi_telemetry_line_data_parse(struct telemetry_de *tde, struct shmti_snap *snapreturn 0 ; } +static inline void scmi_telemetry_blkts_link (struct telemetry_de *tde, +struct telemetry_block_ts *bts) +{ +/* Acquiring order is: tde -> line */ +lockdep_assert_held (&tde->mtx); + +/* Unlink old stale BTS if existent */ +scmi_telemetry_blkts_unlink (tde); + +guard (mutex)(&bts->line.mtx); +refcount_inc (&bts->line.users); + +/* Update TS clock rate if provided by the BLK_TS */ +if (bts->last_rate) + tde->de.info->ts_rate = bts->last_rate; + + tde->bts = bts; +trace_scmi_tlm_access (tde->de.info->id,"BLKTS_LINK" ,0 ,0 ); +} +/** * scmi_telemetry_tdcf_data_parse - TDCF DataLine parsing * @ti: A reference to the telemetry info descriptor
@@ -1508,11 +1806,19 @@ static void scmi_telemetry_tdcf_data_parse(struct telemetry_info *ti, {struct telemetry_shmti *shmti = snap->shmti;struct device *dev = ti->ph->dev; +u32 meta =PAYLD_META_RAW (payld); +bool use_blk_ts =USE_BLK_TS_RAW (meta);struct telemetry_de *tde;u64 val, tstamp =0 ;u32 de_id; de_id =PAYLD_ID_RAW (payld); +/* Discard malformed lines...a preceding BLK_TS must exist */ +if (use_blk_ts && !active_bts) { +trace_scmi_tlm_access (de_id,"BAD_USE_BLK_TS" ,0 ,0 ); +return ; + } +/* Is this DE ID known ? */ tde =scmi_telemetry_tde_lookup (ti, de_id);if (!tde) {
@@ -1522,6 +1828,11 @@ static void scmi_telemetry_tdcf_data_parse(struct telemetry_info *ti,guard (mutex)(&tde->mtx); +if (use_blk_ts && !IS_TDE_TS_BLK (tde)) { +trace_scmi_tlm_access (de_id,"BAD_BLK_TS_TYPE" ,0 ,0 ); +return ; + } +if (tde->de.fc_support) {dev_err (dev,"Found FastChannel DE while parsing a SHMTI.\n" );trace_scmi_tlm_access (de_id,"DE_INVALID_FC_ON_SHMTI" ,0 ,0 );
@@ -1571,6 +1882,19 @@ static void scmi_telemetry_tdcf_data_parse(struct telemetry_info *ti,if (!scmi_telemetry_tde_cache_stale (tde, snap->magic))return ; +/* +* Link the related BTS when needed, it's unlinked on disable. +* Note that each DEs timestamp types is statically defined and +* enumerated once for all at init: a Data line cannot suddenly +* 'migrate' to a different timestamp type. +*/ +if (use_blk_ts) { +if (BLK_TS_CHANGED (tde, shmti, active_bts->line.offset)) +scmi_telemetry_blkts_link (tde, active_bts); +else if (tde->bts->last_rate != tde->de.info->ts_rate) + tde->de.info->ts_rate = tde->bts->last_rate; + } +/* * Parse data words ... only for the sake of updating TDE cache, * any error is logged but ignored.
@@ -1634,6 +1958,9 @@ static int scmi_telemetry_tdcf_line_parse(struct telemetry_info *ti,scmi_telemetry_tdcf_data_parse (ti, payld, snap, mode, *active_bts, *active_uuid);break ; +case TDCF_BLK_TS_LINE : +scmi_telemetry_tdcf_blkts_parse (ti, payld, snap, active_bts); +break ;default :trace_scmi_tlm_access (PAYLD_ID_RAW (payld),"TDCF_LINE_UNKNOWN" ,0 ,0 );break ;
@@ -1777,6 +2104,15 @@ scmi_telemetry_shmti_refresh(struct telemetry_shmti *shmti, int *idx)return work; } +static inline void +scmi_telemetry_reset_active_lines (struct telemetry_block_ts **active_bts) +{ +if (*active_bts) { +scmi_telemetry_line_put (&(*active_bts)->line); + *active_bts =NULL ; + } +} +/** * scmi_telemetry_shmti_scan - Full SHMTI scan * @ti: A reference to the telemetry info descriptor
@@ -1844,6 +2180,7 @@ static int scmi_telemetry_shmti_scan(struct telemetry_info *ti, qwords -= used_qwords; } +scmi_telemetry_reset_active_lines (&active_bts);srcu_read_unlock (&shmti->srcu, idx);if (ret)
@@ -1953,7 +2290,6 @@ static void scmi_telemetry_resources_free(struct telemetry_info *ti)/* Ensure rinfo is no more accessible upfront */ smp_store_release (&ti->rinfo,NULL ); -scmi_telemetry_tdes_cleanup (ti);xa_destroy (&ti->xa_des);kfree (ti->info.shmtis);
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 17/34 firmware: arm_scmi: Add Telemetry TDCF parsing for UUID lines
In reply to Cristian MarussiAdd support to parse, track and link TDCF UUID lines to the related discovered DataEvents.
Maintain also a central list of discovered UUID lines.
---
v16 --> v17
- removed unused node+_lst
v15 --> v16
- WARN_ON invalid UUID line
- uuid array drop counted_by
v14 --> v15
- use proper casting in tlm_collect
- use snapshots to collect UUIDs during full scans
- stop tracking UUIDs lines singularly..it's useless
- use UUIDs line hashing for lookup
- clarified UUID/DE binding are permanent
- fixed WARN_ON invocation on missing active_uuid
v13 --> v14
- split out of previous single patch implementing parse SHMTI routines
--- drivers/firmware/arm_scmi/telemetry.c | 281 +++++++++++++++++++++++++- include/linux/scmi_protocol.h | 2 + 2 files changed, 280 insertions(+), 3 deletions(-)
drivers/firmware/arm_scmi/telemetry.c +278 -3
@@ -13,11 +13,14 @@#include <linux/device.h> #include <linux/err.h> #include <linux/hash.h> +#include <linux/hashtable.h> +#include <linux/jhash.h> #include <linux/io.h> #include <linux/limits.h> #include <linux/minmax.h> #include <linux/module.h> #include <linux/mutex.h> +#include <linux/rcupdate.h> #include <linux/refcount.h> #include <linux/sizes.h> #include <linux/slab.h>
@@ -172,6 +175,10 @@ struct tsline {__le32 ts_high; }; +struct uuid_line { +__be32 dwords[SCMI_TLM_DE_IMPL_NUM_DWORDS ]; +}; +#define LINE_DATA_GET_RAW (f) \ ({ \ typeof(f) _f = (f); \
@@ -270,6 +277,7 @@ struct payload {struct line l;struct tsline tsl;struct blk_tsline blk_tsl; +struct uuid_line uuid_l; }; };
@@ -398,9 +406,7 @@ struct telemetry_block_ts {#define to_blkts (l) container_of(l, struct telemetry_block_ts, line)struct telemetry_uuid { -u32 key;struct hlist_node node_ht; -struct hlist_node node_lst;uuid_t uuid; };
@@ -458,6 +464,12 @@ struct telemetry_info {bool streaming_mode;unsigned int num_shmti;unsigned int num_des_tstamp; +#define SCMI_UUID_DB_THRESH 3 +/* Protect uuids_len */ +struct mutex uuids_mtx; +unsigned int uuids_len; +#define SCMI_UUID_HASH_SZ 5 +DECLARE_HASHTABLE (uuids_ht,SCMI_UUID_HASH_SZ );/* Mutex to protect des_enabled_mtx */ struct mutex des_enabled_mtx;atomic_t des_enabled[ENA_MAX ];
@@ -466,6 +478,7 @@ struct telemetry_info {struct telemetry_shmti *shmti;struct telemetry_de *tdes;struct xarray xa_des; +struct telemetry_uuid *primary_uuid;/* Mutex to protect access to @free_des */ struct mutex free_mtx;struct list_head free_des;
@@ -489,6 +502,9 @@ static inline struct tdcf *snap_tdcf(struct shmti_snap *s);static int scmi_telemetry_shmti_scan (struct telemetry_info *ti,unsigned int shmti_id,enum scan_mode mode); +static inline void scmi_telemetry_uuid_link (struct telemetry_de *tde, +struct telemetry_uuid *uuid); +static inline struct mutex *lock_for_payld (struct mutex *locks,unsigned long offset) {
@@ -613,8 +629,10 @@ static int scmi_telemetry_tde_register(struct telemetry_info *ti, goto err;/* Add to FastChannels list */ -if (tde->de.fc_support) +if (tde->de.fc_support) { +scmi_telemetry_uuid_link (tde, ti->primary_uuid);list_add (&tde->item, &ti->fcs_des); + }/* ... and in the general array */ rinfo->des[rinfo->num_des] = &tde->de;
@@ -1563,6 +1581,17 @@ static void scmi_telemetry_blkts_unlink(struct telemetry_de *tde)trace_scmi_tlm_access (tde->de.info->id,"BLKTS_UNLINK" ,0 ,0 ); } +static void scmi_telemetry_uuid_unlink (struct telemetry_de *tde) +{ +/* Acquiring order is: tde -> line */ +lockdep_assert_held (&tde->mtx); +if (!tde->uuid) +return ; + + tde->uuid =NULL ; +trace_scmi_tlm_access (tde->de.info->id,"UUID_UNLINK" ,0 ,0 ); +} +static void scmi_telemetry_de_unlink (struct scmi_telemetry_de *de) {struct telemetry_de *tde =to_tde (de);
@@ -1571,6 +1600,7 @@ static void scmi_telemetry_de_unlink(struct scmi_telemetry_de *de)/* Unlink all related lines triggering their deallocation */ scmi_telemetry_blkts_unlink (tde); +scmi_telemetry_uuid_unlink (tde); } static struct telemetry_line *
@@ -1641,6 +1671,154 @@ scmi_telemetry_blkts_get_or_create(struct telemetry_shmti *shmti,return scmi_telemetry_blkts_create (shmti, offset); } +static int scmi_telemetry_uuids_update (struct telemetry_info *ti, +struct telemetry_uuid *uuid) +{ +uuid_t **cur_uuids; + +/* Resize array if needed ... */ +if (ti->info.num_uuids +SCMI_UUID_DB_THRESH >= ti->uuids_len) { +uuid_t **new_uuids, **old_uuids; +unsigned int new_len = ti->uuids_len *2 ; + + new_uuids =kzalloc_objs (*new_uuids, new_len); +if (!new_uuids) +return -ENOMEM ; + + old_uuids =rcu_dereference_protected (ti->info.uuids, +lockdep_is_held (&ti->uuids_mtx)); +/* Copy/move old allocated UUIDs */ +for (int i =0 ; i < ti->info.num_uuids; i++) + new_uuids[i] = old_uuids[i]; + +/* Expose new UUID pointer */ +rcu_assign_pointer (ti->info.uuids, new_uuids); + ti->uuids_len = new_len; + +kfree_rcu_mightsleep (old_uuids); + } + +/* Store new UUID reference into the globally accessible UUIDS */ + cur_uuids =rcu_dereference_protected (ti->info.uuids, +lockdep_is_held (&ti->uuids_mtx)); + cur_uuids[ti->info.num_uuids] = &uuid->uuid; +rcu_assign_pointer (ti->info.uuids, cur_uuids); +/* Update UUIDs count */ +smp_store_release (&ti->info.num_uuids, ti->info.num_uuids +1 ); + +return 0 ; +} + +static int scmi_telemetry_uuid_register (struct telemetry_info *ti,u32 key, +struct telemetry_uuid *uuid) +{ +int ret; + +lockdep_assert_held (&ti->uuids_mtx); + + ret =scmi_telemetry_uuids_update (ti, uuid); +if (ret) +return ret; + +/* Register by key for easy lookup */ +hash_add (ti->uuids_ht, &uuid->node_ht, key); + +trace_scmi_tlm_collect (0 , key,0 ,"SHMTI_NEW_UUID" ); + +return 0 ; +} + +static struct telemetry_uuid * +scmi_telemetry_uuid_create (struct telemetry_info *ti,__be32 *dwords) +{ +u32 key; +int ret; + +lockdep_assert_held (&ti->uuids_mtx); + + struct telemetry_uuid *uuid __free(kfree) = kzalloc_obj(*uuid); +if (!uuid) +return NULL ; + +/* +* Fetch BigEndian in-memory UUID fields as per SCMIv4.0 +* specification 3.12.2.2 +*/ +import_uuid (&uuid->uuid, (__force const __u8 *)dwords); + key =jhash2 ((__force const u32 *)dwords,SCMI_TLM_DE_IMPL_NUM_DWORDS ,1 ); + ret =scmi_telemetry_uuid_register (ti, key, uuid); +if (ret) +return NULL ; + +return no_free_ptr (uuid); +} + +static struct telemetry_uuid * +scmi_telemetry_uuid_lookup (struct telemetry_info *ti,__be32 *dwords) +{ +struct telemetry_uuid *uuid; +u32 key; + +lockdep_assert_held (&ti->uuids_mtx); + + key =jhash2 ((__force const u32 *)dwords,SCMI_TLM_DE_IMPL_NUM_DWORDS ,1 ); +hash_for_each_possible (ti->uuids_ht, uuid, node_ht, key) +if (!memcmp (&uuid->uuid, dwords,sizeof (uuid->uuid))) +return uuid; + +return NULL ; +} + +static struct telemetry_uuid * +scmi_telemetry_uuid_get_or_create (struct telemetry_info *ti,__be32 *dwords) +{ +struct telemetry_uuid *uuid; + +guard (mutex)(&ti->uuids_mtx); + + uuid =scmi_telemetry_uuid_lookup (ti, dwords); +if (uuid) +return uuid; + +return scmi_telemetry_uuid_create (ti, dwords); +} + +/** +* scmi_telemetry_tdcf_uuid_parse - A UUID line parser +* +* @ti: A reference to the telemetry_info descriptor +* @uuid_payld: UUID payld line to process +* @snap: A reference to the working SHMTI snapshot that will be processed +* @active_uuid: Input/output reference to keep track of the last uuid found +* +* Note that by the SCMI v4.0 Telemetry specification the associations between +* DEs and UUIDs, both primary and secondary, are permanent across the same +* session (boot): once discovered they cannot change. +* +* Moreover, since the current UUID line could be malformed due to garbage in +* the TDCF, in such a case we warn/log and bailout BUT we don't throw away +* the currently active_uuid (if any) since the current malformed line could +* be bogus and never intended to be a UUID line. +*/ +static void scmi_telemetry_tdcf_uuid_parse (struct telemetry_info *ti, +struct payload *uuid_payld, +struct shmti_snap *snap, +struct telemetry_uuid **active_uuid) +{ +__be32 *dwords = uuid_payld->uuid_l.dwords; +u32 meta =PAYLD_META_RAW (uuid_payld); + +if (WARN_ON (UUID_INVALID_RAW (meta))) { +trace_scmi_tlm_access (0 ,"UUID_INVALID" , + snap->magic, snap->magic); +return ; + } + + *active_uuid =scmi_telemetry_uuid_get_or_create (ti, dwords); + +WARN_ON (!*active_uuid); +} +/** * scmi_telemetry_tdcf_blkts_parse - A BLK_TS line parser *
@@ -1762,6 +1940,18 @@ static inline void scmi_telemetry_blkts_link(struct telemetry_de *tde,trace_scmi_tlm_access (tde->de.info->id,"BLKTS_LINK" ,0 ,0 ); } +static inline void scmi_telemetry_uuid_link (struct telemetry_de *tde, +struct telemetry_uuid *uuid) +{ +lockdep_assert_held (&tde->mtx); +if (tde->uuid) +return ; + +/* Update UUID association */ + tde->uuid = uuid; +trace_scmi_tlm_access (tde->de.info->id,"UUID_LINK" ,0 ,0 ); +} +/** * scmi_telemetry_tdcf_data_parse - TDCF DataLine parsing * @ti: A reference to the telemetry info descriptor
@@ -1895,6 +2085,9 @@ static void scmi_telemetry_tdcf_data_parse(struct telemetry_info *ti, tde->de.info->ts_rate = tde->bts->last_rate; } +/* Link the active UUID or the primary, it's unlinked on disable */ +scmi_telemetry_uuid_link (tde, active_uuid ?: ti->primary_uuid); +/* * Parse data words ... only for the sake of updating TDE cache, * any error is logged but ignored.
@@ -1961,6 +2154,9 @@ static int scmi_telemetry_tdcf_line_parse(struct telemetry_info *ti,case TDCF_BLK_TS_LINE :scmi_telemetry_tdcf_blkts_parse (ti, payld, snap, active_bts);break ; +case TDCF_UUID_LINE : +scmi_telemetry_tdcf_uuid_parse (ti, payld, snap, active_uuid); +break ;default :trace_scmi_tlm_access (PAYLD_ID_RAW (payld),"TDCF_LINE_UNKNOWN" ,0 ,0 );break ;
@@ -2258,6 +2454,7 @@ static int scmi_telemetry_resources_alloc(struct telemetry_info *ti) }INIT_LIST_HEAD (&ti->fcs_des); +hash_init (ti->uuids_ht); ti->shmti =no_free_ptr (shmtis); ti->info.shmtis =no_free_ptr (shmtis_info);
@@ -2305,10 +2502,42 @@ static void scmi_telemetry_resources_free(struct telemetry_info *ti)dev_dbg (ti->ph->dev,"SCMI Telemetry resources freed for instance\n" ); } +static void scmi_telemetry_uuids_cleanup (struct telemetry_info *ti) +{ +uuid_t **cur_uuids; + +/* Drop reference to UUID lines kept in the growable array */ + scoped_guard(mutex, &ti->uuids_mtx) { +int num_uuids; + +/* Ensure looking up an updated counter */ + num_uuids =smp_load_acquire (&ti->info.num_uuids); +/* Ensure zeroing is visible */ +smp_store_release (&ti->info.num_uuids,0 ); +/* Inhibit further accesses to cur_uuids */ + cur_uuids =rcu_replace_pointer (ti->info.uuids,NULL , +lockdep_is_held (&ti->uuids_mtx)); +synchronize_rcu (); + +for (int i =0 ; i < num_uuids; i++) { +struct telemetry_uuid *uuid; + + uuid =to_uuid_from_uuid_t (cur_uuids[i]); +hash_del (&uuid->node_ht); +kfree (uuid); + +trace_scmi_tlm_access (0 ,"DROP_LINE" ,TDCF_UUID_LINE ,0 ); + } + } + +kfree_rcu_mightsleep (cur_uuids); +} +static void scmi_telemetry_instance_cleanup (void *arg) {struct telemetry_info *ti = arg; +scmi_telemetry_uuids_cleanup (ti);scmi_telemetry_resources_free (ti); }
@@ -2379,6 +2608,23 @@ scmi_telemetry_resources_enumerate(struct telemetry_info *ti)return ti->rinfo; } +static int scmi_telemetry_primary_uuid_init (struct telemetry_info *ti) +{ +__be32 *dwords = (__be32 *)&ti->info.base.primary_revision.b; +struct telemetry_uuid *uuid; + + uuid =scmi_telemetry_uuid_get_or_create (ti, dwords); +if (!uuid) { +dev_err (ti->ph->dev,"Failed to register Primary UUID\n" ); +return -ENOMEM ; + } + +/* Ensure Primary UUID association is visible */ +smp_store_release (&ti->primary_uuid, uuid); + +return 0 ; +} +/** * scmi_telemetry_instance_init - Instance initializer * @ti: A reference to the telemetry info descriptor for this instance
@@ -2394,12 +2640,41 @@ scmi_telemetry_resources_enumerate(struct telemetry_info *ti)*/ static int scmi_telemetry_instance_init (struct telemetry_info *ti) { +unsigned int uuids_len; +uuid_t **cur_uuids;int ret; ret =scmi_telemetry_resources_alloc (ti);if (ret)return ret; +/* +* Always allocate at least one slot for the primary and anyway at +* least enough to avoid immediate resizing, assuring uuids_len +* always greater or equal to one. +*/ + uuids_len =max (ti->num_shmti *2 ,SCMI_UUID_DB_THRESH +1 ); + cur_uuids =kzalloc_objs (*cur_uuids, uuids_len); +if (!cur_uuids) { +scmi_telemetry_resources_free (ti); +return -ENOMEM ; + } + +mutex_init (&ti->uuids_mtx); +/* Expose new UUID pointer */ + scoped_guard(mutex, &ti->uuids_mtx) { +rcu_assign_pointer (ti->info.uuids, cur_uuids); + ti->uuids_len = uuids_len; + } + +/* Initialize the first UUIDs in the global list with the primary */ + ret =scmi_telemetry_primary_uuid_init (ti); +if (ret) { +scmi_telemetry_uuids_cleanup (ti); +scmi_telemetry_resources_free (ti); +return ret; + } +atomic_set (&ti->des_enabled[ENA_STATE ],0 );atomic_set (&ti->des_enabled[ENA_TSTAMP ],0 );mutex_init (&ti->des_enabled_mtx);
include/linux/scmi_protocol.h +2 -0
@@ -957,6 +957,8 @@ struct scmi_telemetry_info {unsigned int active_update_interval;struct scmi_telemetry_intervals *intervals;struct scmi_telemetry_shmti_info **shmtis; +unsigned int num_uuids; +uuid_t *__rcu *uuids; };/**
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 18/34 firmware: arm_scmi: Add Telemetry DEs configuration support
In reply to Cristian MarussiAdd support for basic Telemetry DEs configuration operations to selectively enable or disable DataEvents monitoring.
---
v16 --> v17
- use NULL not zero for pointers
- fix shmti_oveflow WITH LEN
- fix liveness blkts_snapshot
- fix tde_state_set_resp handling of INVALISD SHMTI_ID
- refactor state_set and reject group state change
- invalidate TDE cache also on enable
- allow SHMTI_INVALID as bts_offs when DE does NOT use BLK_TS
- fix err init in blkts_snapshot
- add comment on LINE_LENGTH_BYTES upper bound
- remove spurious return
v15 --> v16
- split out group config support
- split out global collection configure
- check liveness on blkts_snapshot too
- refatcor blkts_update on DE enable and update de.ts_rate even when BLK_TS line is the same
- on disable do NOT assume SHMTI_ID_INVALID means disable
- fix remote_update_needed logic
- invalidate cache on DE disable
- invalidate base/offset on disable if NOT FC
- use new shmti_overflow with weplg directly
v14 --> v15
- unlink BLK_TS on DE disable
- update linked BLK_TS on enable
- update TDE location ONLY after successfull linked lines processing
- skip tstamp state update when tstamp NOT supported
- fix TDE location returned value on error path
- trigger resource enumeration on state_get
- trigger resource enumeration on colletion configure only for groups
- use rinfo->num_groups to check groups sanity
- fix per-group collection_configure calls
- fix streaming_mode variable handling
- widen tde->mtx locking section on state_set
- refactor UUID/BLK_TS lines processing in enable
- introduce BLK_TS localized snapshot during enable
- check line type at de_offs
- sanitize requested mode on collection conf
- missing err init
- moved away definition of scmi_telemetry_payload_offset_safe_calc
v13 --> v14
- move BLK_ST_CHANGED check when bts_payld is really known
- check lso LINE_TYPE when processing BLK_TS on enable
- grab individual tde->mtx while updating group state
- clear returned sid/offset/uid on error path
- do NOT mutate global config when configuring groups
- call state_update on do_xfer success even if response process fails
- moved some definitions from earlier split patch
- renamed some fields to more strictly adhere to spec nomenclature
v12 --> v13
- refactored cleanup path
- generalize payload_offset_safe_calc
- harden nearest_line_type scanner
- full refactoring of SET/GET helpers: keep DE and group in distinct code path
- relocate tde->mtx guards higher up and add lockdep assertions
- cleanup xa_lines under mutex_lock on cleanup
- unlink stale BTS line when finding a new actibe for the TDE
- use *alloc_objs
v11 --> v12
- added a few locking order acquisition comments
- added more checks on wraparounds and alignment
- added proper locking around TDE access on state_get
- added a config_mtx to serialize configuration accesses between collection configure and state_set
- refactored state_cache_update
- added locking around sid/offset/uuid updates on enable
v10 --> v11
- refactor reply processing code on DE enable/disable
- use the new des_ennabled mutex to protect des cache updates
- clear sid on group disable for each composing DEs
- add dev_warn_once on ZERO blk_ts offset
v8 --> v9
- use new scmi_telemetry_shmti_overflow() inline
- review DE offsets boundary and wraparound checks (Sashiko v8
- update per-DE ts_rate for DE using BLK_TS too
v7 --> v8
- Fixes for some Sashiko issues on v7
- re-add functions unused in previous patch
- add proper barriers to TDE/UUID binding process
- update tde->sid on SCAN_UPDATE too
- check wrap-arounds on shmti_de_offset manipulation
- fix GROUP enable pollutes status update (was polluting global state)
- remove .all_disable telemetry_operation since unused
- add WARN on if a valid SHMTI ID is reported on enabling a FastChannel/DE
v6 --> v7
- expose per-DE tracked sid/offset/UUIDs
- trigger a full SHMTI scan when a SHMTI-based is enabled and it still has NO associated UUID
v5 --> v6
- constify a few booleans used as inpurt in telemetry_operations
- fixes (some) Sashiko reviews
https://sashiko.dev/#/patchset/20260703123601.381275-1-cristian.marussi%40arm.com?part=9
- underflow on de_offs
- SHMTI overflow checks
- bail out on failed group scan
- unlink comprising DEs on group disable
- add boudnary check on message response parsing
v4 --> v5
- use renamed grp_id instead of old id in group descriptors
- remove useless grp_ignore param from collection_configure
- fixes sparse warnings
v3 --> v4
- track configured Telemetry DE states
- add aggregate Telemetry state query
v2 --> v3
- split from monolithic Telemetry patch
- simplify clenaup with scmi_telemetry_de_unlink
--- drivers/firmware/arm_scmi/telemetry.c | 709 +++++++++++++++++++++++++- include/linux/scmi_protocol.h | 11 + 2 files changed, 718 insertions(+), 2 deletions(-)
drivers/firmware/arm_scmi/telemetry.c +707 -2
@@ -133,6 +133,49 @@ struct scmi_msg_resp_telemetry_update_intervals {__le32 intervals[]; }; +struct scmi_msg_telemetry_de_configure { +__le32 identifier; +__le32 flags; +#define CFG_ENABLE_NO_TSTAMP BIT(0) +#define CFG_ENABLE_WTH_TSTAMP BIT(1) +#define CFG_DISABLE_ALL BIT(2) +#define CFG_GROUP_SELECTOR BIT(3) +#define CFG_EVENT_DE 0 +#define CFG_EVENT_GROUP 1 +#define CFG_DISABLE_ONE 0x0 +}; + +struct scmi_msg_resp_telemetry_de_configure { +__le32 shmti_id; +#define SHMTI_ID_INVALID GENMASK(31, 0) +#define IS_SHMTI_ID_VALID (x) ((x) != SHMTI_ID_INVALID) +__le32 shmti_de_offset; +__le32 blk_ts_offset; +}; + +struct scmi_msg_telemetry_config_set { +__le32 group_identifier; +__le32 control; +#define TELEMETRY_ENABLE (BIT(0)) +#define TELEMETRY_MODE GENMASK(4, 1) +#define TELEMETRY_MODE_SET (x) (FIELD_PREP(TELEMETRY_MODE, (x))) +#define TLM_ONDEMAND (0) +#define TLM_NOTIFS (1) +#define TLM_SINGLE (2) +#define TELEMETRY_MODE_ONDEMAND TELEMETRY_MODE_SET(TLM_ONDEMAND) +#define TELEMETRY_MODE_NOTIFS TELEMETRY_MODE_SET(TLM_NOTIFS) +#define TELEMETRY_MODE_SINGLE TELEMETRY_MODE_SET(TLM_SINGLE) + +#define TLM_ORPHANS (0) +#define TLM_GROUP (1) +#define TLM_ALL (2) +#define TELEMETRY_SET_SELECTOR (x) (FIELD_PREP(GENMASK(8, 5), (x))) +#define TELEMETRY_SET_SELECTOR_ORPHANS TELEMETRY_SET_SELECTOR(TLM_ORPHANS) +#define TELEMETRY_SET_SELECTOR_GROUP TELEMETRY_SET_SELECTOR(TLM_GROUP) +#define TELEMETRY_SET_SELECTOR_ALL TELEMETRY_SET_SELECTOR(TLM_ALL) +__le32 sampling_rate; +}; +/* TDCF */ #define _I (__a) (ioread32((void __iomem *)(__a)))
@@ -423,8 +466,6 @@ enum timestamps { TSTAMP_BLK = 2, }; -#define SHMTI_ID_INVALID GENMASK(31, 0) -struct telemetry_de {enum timestamps ts_type;bool enumerated;
@@ -483,6 +524,8 @@ struct telemetry_info {struct mutex free_mtx;struct list_head free_des;struct list_head fcs_des; +/* Protect global and per-group configuration data */ +struct mutex config_mtx;struct scmi_telemetry_info info;atomic_t rinfo_initializing;struct completion rinfo_initdone;
@@ -1819,6 +1862,70 @@ static void scmi_telemetry_tdcf_uuid_parse(struct telemetry_info *ti,WARN_ON (!*active_uuid); } +static struct payload __iomem * +scmi_telemetry_nearest_line_by_type (struct telemetry_shmti *shmti, +void __iomem *last,enum tdcf_line_types ltype) +{ +struct tdcf __iomem *tdcf = shmti->base; +void __iomem *next, *found =NULL ; + +/* Scan from start of the first TDCF payload up to last payld */ + next = tdcf->payld; +while (next < last) { +struct payload __iomem *payld; +enum tdcf_line_types cur_type; +u32 meta, offs; + +if (check_sub_overflow ((__force unsigned long )next, + (__force unsigned long )tdcf, &offs)) { +trace_scmi_tlm_access (ltype,"LINE_OFFSET_OUT_OF_RANGE" ,0 ,0 ); +return NULL ; + } + + payld =scmi_telemetry_payld_offset_safe_calc (shmti, offs); +if (IS_ERR (payld)) { +trace_scmi_tlm_access (ltype,"LINE_PAYLD_MALFORMED" ,0 ,0 ); +return NULL ; + } + + meta =PAYLD_META (payld); + cur_type =LINE_TYPE_RAW (meta); + +/* +* Bail-out on malformed lines, since the whole TDCF scan +* could be affected. +*/ +if ((cur_type ==TDCF_BLK_TS_LINE &&BLK_TS_INVALID_RAW (meta)) || + (cur_type ==TDCF_UUID_LINE &&UUID_INVALID_RAW (meta))) { +trace_scmi_tlm_access (ltype,"LINE_TYPE_MALFORMED" ,0 ,0 ); +return NULL ; + } + +if (cur_type == ltype) + found = next; + + next +=LINE_LENGTH_BYTES_RAW (meta); + } + +return found; +} + +static struct telemetry_block_ts * +scmi_telemetry_blkts_bind (struct telemetry_info *ti, +struct telemetry_shmti *shmti, +struct payload *bts_payld, +unsigned long offset,u32 magic) +{ +struct telemetry_block_ts *bts; + + bts =scmi_telemetry_blkts_get_or_create (shmti, offset); +/* Update the descriptor with the lastest TS */ +if (bts) +scmi_telemetry_blkts_update_snap (ti, bts, bts_payld, magic); + +return bts; +} +/** * scmi_telemetry_tdcf_blkts_parse - A BLK_TS line parser *
@@ -1952,6 +2059,32 @@ static inline void scmi_telemetry_uuid_link(struct telemetry_de *tde,trace_scmi_tlm_access (tde->de.info->id,"UUID_LINK" ,0 ,0 ); } +static struct telemetry_uuid * +scmi_telemetry_uuid_bind (struct telemetry_info *ti, +struct telemetry_shmti *shmti, +struct payload __iomem *payld) +{ +__be32 dwords[SCMI_TLM_DE_IMPL_NUM_DWORDS ]; +struct payload __iomem *uuid_payld; +struct uuid_line __iomem *uuid_l; + + uuid_payld =scmi_telemetry_nearest_line_by_type (shmti, payld, +TDCF_UUID_LINE ); +if (!uuid_payld) +return NULL ; + +/* +* Use proper mem accessors BUT no swapping, maintain UUID +* in memory BE layout. +*/ + uuid_l = &uuid_payld->uuid_l; +for (int i =0 ; i <SCMI_TLM_DE_IMPL_NUM_DWORDS ; i++) + dwords[i] = (__force __be32 )__raw_readl (&uuid_l->dwords[i]); + +/* Here the nearest UUID line just found has been already validated */ +return scmi_telemetry_uuid_get_or_create (ti, dwords); +} +/** * scmi_telemetry_tdcf_data_parse - TDCF DataLine parsing * @ti: A reference to the telemetry info descriptor
@@ -2385,10 +2518,581 @@ static int scmi_telemetry_shmti_scan(struct telemetry_info *ti,return ret; } +static struct payload __iomem * +scmi_telemetry_blkts_payld_locate (struct device *dev, +struct telemetry_shmti *shmti,u32 *bts_offs, +struct payload __iomem *payld,u32 de_id) +{ +struct payload __iomem *bts_payld =NULL ; + +if (!bts_offs) +return IOMEM_ERR_PTR (-EINVAL ); + +if (*bts_offs && +check_add_overflow ((__force unsigned long )shmti->base, *bts_offs, + (__force unsigned long *)&bts_payld)) +return IOMEM_ERR_PTR (-EPROTO ); + +/* Check SHMTI overflow on returned offset */ +if (bts_payld) { +ssize_t ret =scmi_telemetry_shmti_overflow (shmti->base, +SHMTI_EPLG (shmti), + bts_payld); +if (ret <0 ) { +trace_scmi_tlm_access (de_id,"SHMTI_OVERFLOW" ,0 ,0 ); +return IOMEM_ERR_PTR (ret); + } + }else { +dev_warn_once (dev,"Received BLK_TS with zero offset.\n" ); +trace_scmi_tlm_access (de_id,"BLKTS_WITH_ZERO_OFFSET" ,0 ,0 ); + +/* +* Find the BLK_TS immediately preceding this DE payld by +* scanning. +*/ + bts_payld =scmi_telemetry_nearest_line_by_type (shmti, payld, +TDCF_BLK_TS_LINE ); +if (WARN_ON (!bts_payld)) +return IOMEM_ERR_PTR (-EPROTO ); + +/* Calculate offset of found blkts */ + *bts_offs = (void __iomem *)bts_payld - shmti->base; + } + +return bts_payld; +} + +static int +scmi_telemetry_tdcf_bts_payld_check (struct payload *bts_snap,u32 de_id) +{ +u32 meta =PAYLD_META_RAW (bts_snap); + +if (!IS_BLK_TS_LINE_RAW (meta)) { +trace_scmi_tlm_access (de_id,"BAD_BLK_TS_LINE_OFFSET" ,0 , meta); +return -EPROTO ; + } + +/* Check for spec compliance */ +if (BLK_TS_INVALID_RAW (meta)) { +trace_scmi_tlm_access (de_id,"BLK_TS_INVALID" ,0 , meta); +return -EINVAL ; + } + +return 0 ; +} + +static int scmi_telemetry_blkts_snapshot (struct telemetry_shmti *shmti, +struct payload __iomem *bts_payld, +struct payload *bts_snap,u32 *magic, +u32 de_id) +{ +int retries =SCMI_TLM_TDCF_MAX_RETRIES ; +struct tdcf __iomem *tdcf = shmti->base; +u32 startm, endm, live =0 ; +int err; + +do { +/* A bit of exponential backoff between retries */ +fsleep ((SCMI_TLM_TDCF_MAX_RETRIES - retries) *SCMI_TLM_TDCF_RETRY_GAP_US ); + + err =0 ; + startm =TDCF_START_SEQ_GET (tdcf); +/* Build a default endm certainly different from startm */ + endm = startm +1 ; +if (IS_BAD_START_SEQ (startm)) { +trace_scmi_tlm_access (de_id,"MSEQ_BADSTART_BLKTS" , + startm,0 ); +continue ; + } + +/* +* NOTE that while LINE_LENGTH_BYTES depends on firmware +* provided values, the upper bound does NOT depend on +* firmware +*/ +memcpy_fromio (bts_snap, bts_payld,LINE_LENGTH_BYTES (bts_payld)); +/* +* In this context any anomaly detected on the payload could +* due to a torn read, and it is worth retrying a snapshot. +*/ + err =scmi_telemetry_tdcf_bts_payld_check (bts_snap, de_id); +if (err) +continue ; + +/* Assure the snapshot has been fully taken before checking seqnum */ +rmb (); + +/* Used to detect changes while copying */ + live =TDCF_START_SEQ_GET (tdcf); + endm =TDCF_END_SEQ_GET (SHMTI_EPLG (shmti)); +if (startm != endm || startm != live) +trace_scmi_tlm_access (de_id,"MSEQ_MISMATCH_BLKTS" , + startm, startm != endm ? endm : live); + }while ((startm != endm || startm != live || err) && --retries); + +if (startm != endm || startm != live || err) { +trace_scmi_tlm_access (de_id,"TDCF_SNAPSHOT_BLKTS_FAIL" , + startm, startm != endm ? endm : live); +return err ?: -EPROTO ; + } + +/* Ensure any snapshot is visible before updating magic */ +smp_store_release (magic, startm); + +trace_scmi_tlm_access (de_id,"TDCF_SNAPSHOT_BLKTS_OK" , startm, endm); + +return 0 ; +} + +static struct telemetry_block_ts * +scmi_telemetry_blkts_update (struct telemetry_info *ti, +struct telemetry_shmti *shmti, +struct payload __iomem *bts_payld, +u32 bts_offs,u32 de_id) +{ +struct telemetry_block_ts *bts; +struct payload bts_snap = {}; +u32 magic =0 ; +int ret; + + ret =scmi_telemetry_blkts_snapshot (shmti, bts_payld, &bts_snap, + &magic, de_id); +if (ret) +return ERR_PTR (ret); + +/* Look for a viable BLK_TS line */ + bts =scmi_telemetry_blkts_bind (ti, shmti, &bts_snap, bts_offs, magic); +if (WARN_ON (!bts)) { +trace_scmi_tlm_access (de_id,"INVALID_USE_BLK_TS" ,0 ,0 ); +return ERR_PTR (-EPROTO ); + } + +return bts; +} + +static int +scmi_telemetry_tde_linked_lines_process (struct telemetry_info *ti, +struct telemetry_de *tde, +struct telemetry_shmti *shmti, +struct payload __iomem *payld, +u32 bts_offs) +{ +struct payload __iomem *bts_payld; + +lockdep_assert_held (&ti->config_mtx); +lockdep_assert_held (&tde->mtx); + +/* +* On enable, if a UUID was NOT already assigned, scan looking for +* possible Secondary UUID to bind: if NO secondary could be found +* embedded in the preceding SHMTI lines, install the primary UUID +* for this DE. +* NOTE that UUID lines content is immutable once created and no +* concurrent configuration request is possible at this point since +* config_mtx is held, so while the platform can still concurrently +* update all the existing SHMTI lines variable values, existing lines +* CANNOT be shuffled around: as a consequence a full snapshot is NOT +* needed as a pre-requisite to perform a scan when looking for +* UUID lines. +*/ +if (!tde->uuid) { +struct telemetry_uuid *uuid; + + uuid =scmi_telemetry_uuid_bind (ti, shmti, payld); +if (uuid) + tde->uuid = uuid; +else +scmi_telemetry_uuid_link (tde, ti->primary_uuid); + } + +/* Process related BLK_TS lines if any */ +if (!USE_BLK_TS (payld)) { +/* Unlink old stale BTS if existent */ +if (IS_TDE_TS_BLK (tde) && tde->bts) +scmi_telemetry_blkts_unlink (tde); +return 0 ; + } + +if (!IS_TDE_TS_BLK (tde) || bts_offs ==SHMTI_ID_INVALID ) { +trace_scmi_tlm_access (tde->de.info->id,"BAD_DE_TSTAMP_TYPE" ,0 ,0 ); +return -EPROTO ; + } + + bts_payld =scmi_telemetry_blkts_payld_locate (ti->ph->dev, shmti, + &bts_offs, payld, + tde->de.info->id); +if (IS_ERR (bts_payld)) +return PTR_ERR (bts_payld); + +/* Has associated BLK_TS line changed at all ? */ +if (BLK_TS_CHANGED (tde, shmti, bts_offs)) { +struct telemetry_block_ts *bts; + + bts =scmi_telemetry_blkts_update (ti, shmti, bts_payld, + bts_offs, tde->de.info->id); +if (IS_ERR (bts)) +return PTR_ERR (bts); + +/* Unlink old stale BTS if existent */ +scmi_telemetry_blkts_unlink (tde); + +/* Store freshly discovered sane BLK_TS */ + tde->bts = bts; + } + +/* Update per-DE BLK_TS rate if any */ +if (tde->bts->last_rate) + tde->de.info->ts_rate = tde->bts->last_rate; + +return 0 ; +} + +static int +scmi_telemetry_state_set_tde_resp (struct telemetry_info *ti, +struct scmi_telemetry_de *de, +u32 sid,u32 de_offs,u32 bts_offs) +{ +struct telemetry_de *tde =to_tde (de); +struct telemetry_shmti *shmti; +struct payload __iomem *payld; +int ret; + +lockdep_assert_held (&tde->mtx); + +/* A FastChannel DE MUST return an INVALID SHMTI ID on enable */ +if (WARN_ON (de->fc_support)) { +trace_scmi_tlm_access (de->info->id,"INVALID_DE_FC_ON_SHMTI" ,0 ,0 ); +return -EPROTO ; + } + +/* Update SHMTI/offset while skipping non-SHMTI based DES */ + shmti = &ti->shmti[sid]; +/* Check sanity of received location... */ + payld =scmi_telemetry_payld_offset_safe_calc (shmti, de_offs); +if (IS_ERR (payld)) +return PTR_ERR (payld); + +/* +* Note that here we are processing a configuration request on a DE +* while holding @config_mtx: in this scenario platform cannot relocate +* or mutate this line freely, so we can directly access the TDCF and +* lookup the line sitting at @de_offs to check its line type without +* having to worry about consistency or taking snapshots. +*/ +if (!IS_DATA_LINE (payld)) +return -EPROTO ; + + ret =scmi_telemetry_tde_linked_lines_process (ti, tde, shmti, payld, + bts_offs); +if (ret) +return ret; + +/* ...then assign once validated */ + tde->sid = sid; + tde->base = shmti->base; + tde->offset = de_offs; +/* A handy reference to the Epilogue updated */ + tde->eplg =SHMTI_EPLG (shmti); + +/* A relocation due to a TS toggle needs cache invalidation */ +scmi_telemetry_tde_cache_invalidate (tde); + +return 0 ; +} + +static int +scmi_telemetry_tde_state_set_resp_process (struct telemetry_info *ti, +struct scmi_telemetry_de *de, +struct scmi_msg_resp_telemetry_de_configure *r) +{ +u32 sid =le32_to_cpu (r->shmti_id); + +/* +* 3.12.4.8 TELEMETRY_DE_CONFIGURE - SHMTI ID +* This field is optional and is set to 0xFFFFFFFF if any of the +* following are true: +* - no DE or event group is being enabled. +* - No SHMTI is supported. +* - SHMTI is not used for this DE or event group. This could +* be the case for example, if this DE is associated with a +* FastChannel. +* - the platform does not support returning this information. +*/ +if (de->enabled) { +u32 de_offs, bts_offs; + +/* Platform does NOT support returning this information or a +* NON SHMTI based DE was enabled: in any case nothing to do. +*/ +if (!IS_SHMTI_ID_VALID (sid)) +return 0 ; + +if (sid >= ti->num_shmti) +return -EPROTO ; + + de_offs =le32_to_cpu (r->shmti_de_offset); + bts_offs =le32_to_cpu (r->blk_ts_offset); +if (!IS_ALIGNED (de_offs,4 ) || + (bts_offs !=SHMTI_ID_INVALID && !IS_ALIGNED (bts_offs,4 ))) { +dev_err (ti->ph->dev, +"Returned DE/BTS offsets are NOT 32-bit aligned - de_offs:%X bts_offs:%X\n" , + de_offs, bts_offs); +return -EINVAL ; + } + +return scmi_telemetry_state_set_tde_resp (ti, de, sid, + de_offs, bts_offs); + }else { +/* +* Unlink the related BLK_TS lines on disable and update +* sid/offset, unless unsupported by platform or the +* current DE flavour (FCs/Notifs) +* UUID is never unlinked once discovered. +*/ +struct telemetry_de *tde =to_tde (de); + +WARN_ON (IS_SHMTI_ID_VALID (sid)); + +lockdep_assert_held (&tde->mtx); + + tde->sid =SHMTI_ID_INVALID ; +if (!tde->de.fc_support) { + tde->base =NULL ; + tde->offset =0 ; + tde->eplg =NULL ; + +scmi_telemetry_blkts_unlink (tde); + } + +/* Consider that a TDE could be re-located on next re-enable */ +scmi_telemetry_tde_cache_invalidate (tde); + } + +return 0 ; +} + +static void +scmi_telemetry_state_cache_update (struct telemetry_info *ti, +const bool *enable,bool *enabled_state, +const bool *tstamp,bool *tstamp_enabled_state, +struct scmi_telemetry_de *de) +{ +if (!de) +return ; + +if (enable) +scmi_telemetry_de_state_update (ti,ENA_STATE , + enabled_state, *enable); + +if (tstamp && de->tstamp_support) +scmi_telemetry_de_state_update (ti,ENA_TSTAMP , + tstamp_enabled_state, *tstamp); +} + +static inline bool +scmi_telemetry_remote_state_update_needed (struct telemetry_info *ti, +const bool *enable,bool *enabled_state, +const bool *tstamp, +bool *tstamp_enabled_state, +bool is_group,void *obj) +{ +/* Is anything to do at all on this object ? */ +if ((!enable || *enable == *enabled_state) && + (!tstamp || *tstamp == *tstamp_enabled_state)) +return false; + +/* +* When the object is currently disabled AND no enable state change was +* requested, BUT timestamp is being changed, update only local state... +* no need to send a message now, it will be sent later on enable. +*/ +if ((!enable || !*enable) && !*enabled_state) { +scmi_telemetry_state_cache_update (ti, enable, + enabled_state, tstamp, + tstamp_enabled_state, obj); + +return false; + } + +return true; +} + +static inline void +scmi_telemetry_state_message_prepare (struct scmi_msg_telemetry_de_configure *msg, +unsigned int id,bool is_group, +const bool *enable,bool *enabled_state, +const bool *tstamp,bool *tstamp_enabled_state) +{ + msg->identifier =cpu_to_le32 (id); +/* Default to disable mode */ + msg->flags =CFG_DISABLE_ONE ; + msg->flags |=cpu_to_le32 (FIELD_PREP (GENMASK (3 ,3 ), + !is_group ?CFG_EVENT_DE :CFG_EVENT_GROUP )); + +if ((!enable && *enabled_state) || (enable && *enable)) { +/* Already enabled but tstamp_enabled state changed */ +if (tstamp) { +/* Here, tstamp cannot be NULL too */ + msg->flags |=cpu_to_le32 (*tstamp ? +CFG_ENABLE_WTH_TSTAMP :CFG_ENABLE_NO_TSTAMP ); + }else { + msg->flags |=cpu_to_le32 (*tstamp_enabled_state ? +CFG_ENABLE_WTH_TSTAMP :CFG_ENABLE_NO_TSTAMP ); + } + } +} + +static inline void +scmi_telemetry_tde_location_update (struct telemetry_de *tde, +u32 *sid,u32 *offset,uuid_t *uuid) +{ +if (tde) +lockdep_assert_held (&tde->mtx); + +if (sid) + *sid = tde ? tde->sid :SHMTI_ID_INVALID ; +if (offset) + *offset = tde ? tde->offset :0 ; +if (uuid) { +if (tde && tde->uuid) +uuid_copy (uuid, &tde->uuid->uuid); +else +memset (uuid,0x0 ,sizeof (*uuid)); + } +} + +static int scmi_telemetry_tde_state_set (const struct scmi_protocol_handle *ph, +const bool *enable,const bool *tstamp, +struct scmi_telemetry_de *de, +u32 *sid,u32 *offset,uuid_t *uuid) +{ +struct scmi_msg_resp_telemetry_de_configure *resp; +struct scmi_msg_telemetry_de_configure *msg; +struct telemetry_info *ti = ph->get_priv (ph); +struct telemetry_de *tde =to_tde (de); +struct scmi_xfer *t; +int ret; + +/* Stall concurrent configuration request */ +guard (mutex)(&ti->config_mtx); + +/* +* Note that the TDE lock must be taken early on, before the SCMI +* configuration command is even issued to avoid a de-sync between the +* TDE state and the effective HW state enforced by the platform in +* response to our request. +*/ +guard (mutex)(&tde->mtx); + +/* Initialize return values with current TDE in case of error */ +scmi_telemetry_tde_location_update (tde, sid, offset, uuid); + +if (!scmi_telemetry_remote_state_update_needed (ti, enable, &de->enabled, + tstamp, &de->tstamp_enabled, + false, de)) +return 0 ; + + ret = ph->xops->xfer_get_init (ph,TELEMETRY_DE_CONFIGURE , +sizeof (*msg),sizeof (*resp), &t); +if (ret) +return ret; + + msg = t->tx.buf; +scmi_telemetry_state_message_prepare (msg, de->info->id, false, + enable, &de->enabled, + tstamp, &de->tstamp_enabled); + + resp = t->rx.buf; + ret = ph->xops->do_xfer (ph, t); +if (!ret) { +/* +* Update cached state on command success anyway, despite any +* possible later response validation issue: once the command +* has succedeed keep our state in sync with HW. +*/ +scmi_telemetry_state_cache_update (ti, enable, &de->enabled, + tstamp, &de->tstamp_enabled, de); +/* Process response, update DEs location tracking */ + ret =scmi_telemetry_tde_state_set_resp_process (ti, de, resp); +if (!ret) +scmi_telemetry_tde_location_update (tde, sid, offset, uuid); +else +dev_err (ph->dev, +"Could NOT process DE ID 0x%08X state response - ret:%d\n" , + tde->de.info->id, ret); + } + + ph->xops->xfer_put (ph, t); + +return ret; +} + +static int scmi_telemetry_state_get (const struct scmi_protocol_handle *ph, +const u32 *id,bool *enabled,bool *tstamp_enabled, +u32 *sid,u32 *offset,uuid_t *uuid) +{ +struct telemetry_info *ti = ph->get_priv (ph); +struct scmi_telemetry_de *de; +struct telemetry_de *tde; + +if (!enabled || !tstamp_enabled) +return -EINVAL ; + + ti->res_get (ti); +if (!id) { +guard (mutex)(&ti->des_enabled_mtx); +/* Returning the all_des_* state */ + *enabled = + (atomic_read (&ti->des_enabled[ENA_STATE ]) == ti->info.base.num_des); + *tstamp_enabled = + (atomic_read (&ti->des_enabled[ENA_TSTAMP ]) == ti->num_des_tstamp); + +return 0 ; + } + + de =xa_load (&ti->xa_des, *id); +if (!de) +return -ENODEV ; + + tde =to_tde (de); +guard (mutex)(&tde->mtx); + + *enabled = de->enabled; + *tstamp_enabled = de->tstamp_enabled; + +scmi_telemetry_tde_location_update (tde, sid, offset, uuid); + +return 0 ; +} + +static int scmi_telemetry_state_set (const struct scmi_protocol_handle *ph, +bool is_group,u32 id,const bool *enable, +const bool *tstamp,u32 *sid,u32 *offset, +uuid_t *uuid) +{ +struct telemetry_info *ti = ph->get_priv (ph); +struct scmi_telemetry_de *de; + +if (is_group) +return -EOPNOTSUPP ; + + ti->res_get (ti); + de =xa_load (&ti->xa_des, id); +if (!de) +return -ENODEV ; + +/* Filter out unplausible timestamp requests */ +return scmi_telemetry_tde_state_set (ph, enable, + de->tstamp_support ? tstamp :NULL , + de, sid, offset, uuid); +} +static const struct scmi_telemetry_proto_ops tlm_proto_ops = { .info_get = scmi_telemetry_info_get, .de_lookup = scmi_telemetry_de_lookup, .res_get = scmi_telemetry_resources_get, + .state_get = scmi_telemetry_state_get, + .state_set = scmi_telemetry_state_set, };/**
@@ -2461,6 +3165,7 @@ static int scmi_telemetry_resources_alloc(struct telemetry_info *ti) ti->tdes =no_free_ptr (tdes);xa_init (&ti->xa_des); +mutex_init (&ti->config_mtx); rinfo->des =no_free_ptr (des); rinfo->dei_store =no_free_ptr (dei_store);
include/linux/scmi_protocol.h +11 -0
@@ -968,6 +968,10 @@ struct scmi_telemetry_info {* @info_get: get the general Telemetry information. * @de_lookup: get a specific DE descriptor from the DE id. * @res_get: get a reference to the Telemetry resources descriptor. +* @state_get: retrieve the specific DE state, if NULL returns the +* cumulative state of all DEs. Global group state can be looked-up +* directly from @scmi_telemetry_info via @info_get. +* @state_set: enable/disable the specific DE or GROUP with or without timestamps. */ struct scmi_telemetry_proto_ops {const struct scmi_telemetry_info *(*info_get)
@@ -976,6 +980,13 @@ struct scmi_telemetry_proto_ops { (const struct scmi_protocol_handle *ph, u32 id);const struct scmi_telemetry_res_info *(*res_get) (const struct scmi_protocol_handle *ph); +int (*state_get)(const struct scmi_protocol_handle *ph, +const u32 *id,bool *enabled,bool *tstamp_enabled, +u32 *sid,u32 *offset,uuid_t *uuid); +int (*state_set)(const struct scmi_protocol_handle *ph, +bool is_group,u32 id,const bool *enable, +const bool *tstamp,u32 *sid,u32 *offset, +uuid_t *uuid); };/**
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 19/34 firmware: arm_scmi: Add Telemetry global configuration support
In reply to Cristian MarussiAdd support to configure Telemetry globally by setting its enabled state and the requested update interval.
---
v16 --> v17
- avoid collection name clashes
- rename update_interval_ms to ename update_interval
v15 --> v16
- fix mode check logic
--- drivers/firmware/arm_scmi/telemetry.c | 69 +++++++++++++++++++++++++++ include/linux/scmi_protocol.h | 15 ++++++ 2 files changed, 84 insertions(+)
drivers/firmware/arm_scmi/telemetry.c +69 -0
@@ -3087,12 +3087,81 @@ static int scmi_telemetry_state_set(const struct scmi_protocol_handle *ph, de, sid, offset, uuid); } +static int +scmi_telemetry_collection_configure (const struct scmi_protocol_handle *ph, +unsigned int res_id,const bool *enable, +const unsigned int *update_interval, +const enum scmi_telemetry_collection *mode) +{ +enum scmi_telemetry_collection *current_mode, next_mode; +struct telemetry_info *ti = ph->get_priv (ph); +struct scmi_msg_telemetry_config_set *msg; +bool tlm_enable, *current_state, is_group; +unsigned int *active_update_interval; +struct scmi_xfer *t; +__le32 interval; +u32 control; +int ret; + +/* Stall concurrent configuration request */ +guard (mutex)(&ti->config_mtx); + +if (mode && (*mode !=SCMI_TLM_COLLECTION_ONDEMAND )) +return -EOPNOTSUPP ; + + is_group = res_id !=SCMI_TLM_GRP_INVALID ; +if (is_group) +return -EOPNOTSUPP ; + + active_update_interval = &ti->info.active_update_interval; + current_mode = &ti->info.current_mode; + current_state = &ti->info.enabled; + +if (!enable && !update_interval && (!mode || *mode == *current_mode)) +return 0 ; + + ret = ph->xops->xfer_get_init (ph,TELEMETRY_CONFIG_SET , +sizeof (*msg),0 , &t); +if (ret) +return ret; + +if (!update_interval) + interval =cpu_to_le32 (*active_update_interval); +else + interval =cpu_to_le32 (*update_interval); + + tlm_enable = enable ? *enable : *current_state; + next_mode = mode ? *mode : *current_mode; + + msg = t->tx.buf; + msg->group_identifier =cpu_to_le32 (res_id); + control = tlm_enable ?TELEMETRY_ENABLE :0 ; + control |= !is_group ?TELEMETRY_SET_SELECTOR_ALL :TELEMETRY_SET_SELECTOR_GROUP ; + control |=TELEMETRY_MODE_SET (next_mode); + msg->control =cpu_to_le32 (control); + msg->sampling_rate = interval; + ret = ph->xops->do_xfer (ph, t); +if (!ret) { + *current_mode = next_mode; + *current_state = tlm_enable; + ti->streaming_mode = + *current_mode ==SCMI_TLM_COLLECTION_NOTIFICATION ; +if (update_interval) + *active_update_interval =le32_to_cpu (interval); + } + + ph->xops->xfer_put (ph, t); + +return ret; +} +static const struct scmi_telemetry_proto_ops tlm_proto_ops = { .info_get = scmi_telemetry_info_get, .de_lookup = scmi_telemetry_de_lookup, .res_get = scmi_telemetry_resources_get, .state_get = scmi_telemetry_state_get, .state_set = scmi_telemetry_state_set, + .collection_configure = scmi_telemetry_collection_configure, };/**
include/linux/scmi_protocol.h +15 -0
@@ -888,6 +888,12 @@ enum scmi_telemetry_compo_type {#define SCMI_TLM_BUILD_UPDATE_INTERVAL (s, e) \ (FIELD_PREP(GENMASK(20, 5), (s)) | FIELD_PREP(GENMASK(4, 0), (e) & GENMASK(4, 0))) +enum scmi_telemetry_collection { +SCMI_TLM_COLLECTION_ONDEMAND , +SCMI_TLM_COLLECTION_NOTIFICATION , +SCMI_TLM_COLLECTION_SINGLE_READ , +}; +#define SCMI_TLM_GRP_INVALID 0xFFFFFFFFstruct scmi_telemetry_intervals {
@@ -959,6 +965,8 @@ struct scmi_telemetry_info {struct scmi_telemetry_shmti_info **shmtis;unsigned int num_uuids;uuid_t *__rcu *uuids; +bool enabled; +enum scmi_telemetry_collection current_mode; };/**
@@ -972,6 +980,9 @@ struct scmi_telemetry_info {* cumulative state of all DEs. Global group state can be looked-up * directly from @scmi_telemetry_info via @info_get. * @state_set: enable/disable the specific DE or GROUP with or without timestamps. +* @collection_configure: choose a sampling rate and enable SHMTI/FC sampling +* for on demand collection via @de_data_read or async +* notificatioins for all the enabled DEs. */ struct scmi_telemetry_proto_ops {const struct scmi_telemetry_info *(*info_get)
@@ -987,6 +998,10 @@ struct scmi_telemetry_proto_ops { bool is_group, u32 id, const bool *enable, const bool *tstamp, u32 *sid, u32 *offset, uuid_t *uuid); +int (*collection_configure)(const struct scmi_protocol_handle *ph, +unsigned int res_id,const bool *enable, +const unsigned int *update_interval, +const enum scmi_telemetry_collection *mode); };/**
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 20/34 firmware: arm_scmi: Add Telemetry Single/Bulk DEs reads
In reply to Cristian MarussiAdd support for Telemetry operations needed to read DataEvent values and timestamps as single entities or all together in a single bulk buffer. The returned values are effectiely retrieved from the platform only when strictly needed, i.e. when no fresh recent cached value was already available.
The DataEvent values are fetched transparently from the platform origins using the proper synchronization and consistency primitives, directly from the SHMTIs areas or the FastChannels memory depending on the configuration.
---
v16 --> v17
- fix shmti_oveflow WITH LEN
- check liveness on de_snapshot
- remove des_sample and notif structure and logic
- add a comment on bulk read reporting on failures
- return ENODATA when TLM off
v15 --> v16
- removed SINGLE SAMPLE delayed response reads capabilities
- removed groups references
- check liveness in de_snapshot
- add shmti_overflow check on snap
v14 --> v15
- use IS_TDE_TS_LINE macro
- use NOT IS_DATA_LINE in tdcf_de_payld_get
- use better startm/endm initial markers in tdcf_de_payld_get
- retry scmi_telemetry_tdcf_de_parse on error too
- trigger resource enumeration also on de_data_read
- skip unitialized FCs on reads and return -EPROTO
- introduce localized single DE snapshot on single DE data read
- widen tde->mtx locking in msg_payld_process
- use unsigned int samples
- better des_sample_get sanity checks
- refactor msg_payld_process
v13 --> v14
- report scmi_telemetry_line_data_parse errors
- add traces for CACHED_DE_UPDATED
- moved some definitions from earlier patches
- using a less regular time interval for TDCF scan retries
- renamed some fields to more strictly adhere to spec nomenclature
v12 --> v13
- use new RAW macros in line_data_parse and check for line validity
- handle PARTIAL_ERROR by logging and carrying on
- relocate tde->mtx guards higher up and add lockdep assertions
- better tdcf/eplg init within tde->mtx
- do not cache tde->base between DE read retries
- retry scan on payld sanity errors
v11 --> v12
- using new TDCF_INVALID_MATCH_SEQ macro
- reporting transient DATA_INVALID lines as -EINVAL
- added cacheable param to msg_payld_process
v10 --> v11
- split out and relocate unrelated code to previous patches
- add TDE mutex_lock when getting payload address
- check LINE_TYPE while parsing payloads
- check overflows and boundary on single sample replies
v8 -->v9
- Fix Sashiko reports for v8
- check if TS supported on FC line before using it
- check for unexpected shorter reply on sample_get
- use non-LE accessors in msg_payld where appropriate
v7 --> v8
- Fixes for some Sashiko issues on v7
- added CACHED_DE_READ trace
- reworked locking around line handling: blkts/uuid
v6 -->v7
- usse proper le32 accesors, fix sparse warns
v5 --> v6
- fixed some Sashiko review
- add new macros parse TDCF-like content on regular ram (non IO)
https://sashiko.dev/#/patchset/20260703123601.381275-1-cristian.marussi%40arm.com?part=10
- fix retry loop in DE parse to avoid exiting on transient errors
- use proper non-IO accessors for msg payld parsing
- add msg payld boundary check
v4 --> v5
- removed UAPI structures dependency
- cleaned up sample_get logic around groups
- fixes sparse warnings
v3 --> v4
- fix typos in comments
- extend TDE cache helpers with cache lookup routine and use cumulative scmi_telemetry_de_sample param
v2 --> v3
- split from monolithic Telemetry patch
- simplity using a few assignement using ternary ops
- remove useless ts param from scanning function
- use a compound literal to simplify samples init
- add a missing __must_check on telemetry_ops
- changed errno on DE read troubles:
- ENODEV/ENOENT: DE is UNKNOWN
- EINVAL: DE is marked as DATA_INVALID
- ENODATA: TLM susbsystem or the specific DE is OFF
--- drivers/firmware/arm_scmi/telemetry.c | 529 ++++++++++++++++++++++++-- include/linux/scmi_protocol.h | 17 + 2 files changed, 511 insertions(+), 35 deletions(-)
drivers/firmware/arm_scmi/telemetry.c +494 -35
@@ -383,6 +383,12 @@ struct tdcf {#define TDCF_END_SIGNATURE (e) (_I(&((e)->sign_end)))#define TDCF_BAD_END_SEQ GENMASK(31, 0) +struct telemetry_de_snapshot { +u32 magic; +struct payload payld; +struct payload bts_payld; +}; +struct telemetry_shmti ;struct shmti_snap {
@@ -710,8 +716,9 @@ scmi_telemetry_tde_cache_stale(struct telemetry_de *tde, const u32 magic) }static void -scmi_telemetry_tde_cache_update (struct telemetry_de *tde,u64 val, -u64 *tstamp,const u32 *magic) +scmi_telemetry_tde_cache_update (struct telemetry_de *tde, +struct scmi_telemetry_de_sample *sample, +const u32 *magic) {lockdep_assert_held (&tde->mtx);
@@ -723,10 +730,37 @@ scmi_telemetry_tde_cache_update(struct telemetry_de *tde, u64 val,return ; tde->last_magic = magic ? *magic :TDCF_BAD_END_SEQ ; - tde->last_val = val; - tde->last_ts = tstamp &&scmi_tde_has_tstamp (tde) ? *tstamp :0 ; -if (tstamp) - *tstamp = tde->last_ts; + tde->last_val = sample->val; + tde->last_ts =scmi_tde_has_tstamp (tde) ? sample->tstamp :0 ; +/* Update returned value too */ + sample->tstamp = tde->last_ts; + +trace_scmi_tlm_collect (tde->last_ts, tde->de.info->id, + tde->last_val,"CACHED_DE_UPDATED" ); +} + +static int +scmi_telemetry_tde_cache_lookup (struct telemetry_de *tde, +struct scmi_telemetry_de_sample *sample, +u32 *magic) +{ +lockdep_assert_held (&tde->mtx); + +/* +* Bailout without providing any sample when the cache is +* stale, i.e. last_magic < *magic +*/ +if (magic &&scmi_telemetry_tde_cache_stale (tde, *magic)) +return -EAGAIN ; + + sample->id = tde->de.info->id; + sample->val = tde->last_val; + sample->tstamp = tde->last_ts; + +trace_scmi_tlm_collect (sample->tstamp, sample->id, + sample->val,"CACHED_DE_READ" ); + +return 0 ; }struct scmi_tlm_de_priv {
@@ -1984,45 +2018,45 @@ static void scmi_telemetry_tdcf_blkts_parse(struct telemetry_info *ti,static inline int scmi_telemetry_line_data_parse (struct telemetry_de *tde,struct shmti_snap *snap, -u64 *val,u64 *tstamp,struct payload *payld, -struct payload *bts_payld,u32 magic) +struct scmi_telemetry_de_sample *sample, +struct payload *payld,struct payload *bts_payld, +u32 magic) {u32 meta =PAYLD_META_RAW (payld);lockdep_assert_held (&tde->mtx);/* Clear returned values in case of errors */ - *val =0 ; - -if (tstamp) { - *tstamp =0 ; -if (USE_BLK_TS_RAW (meta)) { -/* Read out the actual BLK_TS */ - *tstamp =scmi_telemetry_blkts_read (magic, tde, - bts_payld, snap); - }else if (LINE_TS_VALID_RAW (meta)) { -/* -* Note that LINE_TS_VALID implies HAS_LINE_EXT and that -* the per DE line_ts_rate is advertised in the DE -* descriptor, BUT we check anyway against buggy FW. -*/ -if (!HAS_LINE_EXT_RAW (meta)) { -trace_scmi_tlm_access (tde->de.info->id, -"SHMTI_BAD_TS_LINE" ,0 ,0 ); -return -EPROTO ; - } - - *tstamp =LINE_TSTAMP_GET_RAW (&payld->tsl); + sample->tstamp =0 ; + sample->val =0 ; + +if (USE_BLK_TS_RAW (meta)) { +/* Read out the actual BLK_TS */ + sample->tstamp =scmi_telemetry_blkts_read (magic, tde, + bts_payld, snap); + }else if (LINE_TS_VALID_RAW (meta)) { +/* +* Note that LINE_TS_VALID implies HAS_LINE_EXT and that +* the per DE line_ts_rate is advertised in the DE +* descriptor, BUT we check anyway against buggy FW. +*/ +if (!HAS_LINE_EXT_RAW (meta)) { +trace_scmi_tlm_access (tde->de.info->id, +"SHMTI_BAD_TS_LINE" ,0 ,0 ); +return -EPROTO ; } + + sample->tstamp =LINE_TSTAMP_GET_RAW (&payld->tsl); }/* Data is always valid since we are NOT handling BLK TS lines here */ - *val =LINE_DATA_GET_RAW (&payld->l); + sample->val =LINE_DATA_GET_RAW (&payld->l); -trace_scmi_tlm_collect (tstamp ? *tstamp :0 , tde->de.info->id, - *val,"SHMTI_DE_READ" ); +/* Trace originally read tstamp */ +trace_scmi_tlm_collect (sample->tstamp, tde->de.info->id, + sample->val,"SHMTI_DE_READ" ); -scmi_telemetry_tde_cache_update (tde, *val, tstamp, &magic); +scmi_telemetry_tde_cache_update (tde, sample, &magic);return 0 ; }
@@ -2128,11 +2162,11 @@ static void scmi_telemetry_tdcf_data_parse(struct telemetry_info *ti, struct telemetry_uuid *active_uuid) {struct telemetry_shmti *shmti = snap->shmti; +struct scmi_telemetry_de_sample sample = {};struct device *dev = ti->ph->dev;u32 meta =PAYLD_META_RAW (payld);bool use_blk_ts =USE_BLK_TS_RAW (meta);struct telemetry_de *tde; -u64 val, tstamp =0 ;u32 de_id; de_id =PAYLD_ID_RAW (payld);
@@ -2225,7 +2259,7 @@ static void scmi_telemetry_tdcf_data_parse(struct telemetry_info *ti,* Parse data words ... only for the sake of updating TDE cache, * any error is logged but ignored. */ -if (scmi_telemetry_line_data_parse (tde, snap, &val, &tstamp, payld, +if (scmi_telemetry_line_data_parse (tde, snap, &sample, payld,NULL , snap->magic))dev_err (dev,"Malformed DATA line.\n" ); }
@@ -3155,6 +3189,429 @@ scmi_telemetry_collection_configure(const struct scmi_protocol_handle *ph,return ret; } +static inline int +scmi_telemetry_de_data_fc_read (struct telemetry_de *tde, +struct scmi_telemetry_de_sample *sample) +{ +struct fc_tsline __iomem *fc; + +lockdep_assert_held (&tde->mtx); + +/* +* A FastChannel DE that was discovered as enabled at boot but later +* failed to be enumerated cannot be accessed. +*/ +if (!tde->base) +return -EPROTO ; + + fc = tde->base + tde->offset; + sample->val =LINE_DATA_GET (fc); + sample->tstamp =IS_TDE_TS_LINE (tde) ?LINE_TSTAMP_GET (fc) :0 ; + +/* Trace originally read tstamp */ +trace_scmi_tlm_collect (sample->tstamp, tde->de.info->id, sample->val, +"FC_READ" ); + +/* Cache anyway since TDE caches are on the read path anyway */ +scmi_telemetry_tde_cache_update (tde, sample,NULL ); + +return 0 ; +} + +static void scmi_telemetry_scan_update (struct telemetry_info *ti) +{ +struct telemetry_de *tde; + +/* Scan all SHMTIs ... */ +for (int id =0 ; id < ti->num_shmti; id++) { +int ret; + + ret =scmi_telemetry_shmti_scan (ti, id,SCAN_LOOKUP ); +if (ret) +dev_warn (ti->ph->dev, +"Failed update-scan of SHMTI ID:%d - ret:%d\n" , + id, ret); + } + +if (!ti->info.fc_support) +return ; + +/* Need to enumerate resources to access fastchannels */ + ti->res_get (ti); +list_for_each_entry (tde, &ti->fcs_des, item) { +struct scmi_telemetry_de_sample sample = {}; + +guard (mutex)(&tde->mtx); +if (!tde->de.enabled) +continue ; + +/* +* Only for the sake of updating TDE cache. +* Ignoring errors deriving from malformed FCs. +*/ +scmi_telemetry_de_data_fc_read (tde, &sample); + } +} + +/* +* TDCF and TS Line Management Notes +* --------------------------------- +* +* TDCF Payload Metadata notable bits: +* - Bit[3]: USE BLK Tstamp +* - Bit[2]: Line-Extension Field present (LineTstamp) +* - Bit[1]: Tstamp VALID +* - Bit[0]: Data INVALID +* +* CASE_1: +* ------- +* + A DE is enabled with timestamp disabled, so the TS fields are +* NOT present +* -> BIT[3:0] = 0000b +* +* - 1/A LINE_TSTAMP +* ------------------ +* + that DE is then 're-enabled' with TS: so it was ON, it remains +* ON but using DE_CONFIGURE I now enabled also TS, so the +* platform relocates it at the end of the SHMTI and return the +* new offset +* -> BIT[3:0] = 0110b +* +* - 1/B BLK_TSTAMP +* ------------------ +* + that DE is then 're-enabled' with BLK TS: so it was ON, it +* remains ON but using DE_CONFIGURE, we now also enabled the TS, +* so the platform will: +* - IF a preceding BLK_TS line exist (with same clk rate) +* it relocates the DE at the end of the SHMTI and return the +* new offset (if there is enough room, if not in another SHMTI) +* - IF a preceding BLK_TS line DOES NOT exist (with same clk rate) +* it creates a new BLK_TS line at the end of the SHMTI and then +* relocates the DE after the new BLK_TS and return the +* new offset (if there is enough room, if not in another SHMTI) +* -> BIT[3:1] = 1010b +* +* + the hole left from the relocated DE can be reused by the platform +* to fit another equally sized DE. (i.e. without shuffling around any +* other enabled DE, since that would cause a change of the known offset) +* anyway it will be marked as: +* -> BIT[3:0] = 0101b iff it was a LINE_TSTAMP +* -> BIT[3:0] = 0001b iff it was a BLK_TSTAMP +* +* CASE_2: +* ------- +* + A DE is enabled with LINE timestamp enabled, so the TS_Line is there +* -> BIT[3:0] = 0110b +* + that DE has its timestamp disabled: again, you can do this without +* disabling it fully but just disabling the TS, so now that TS_line +* fields are still physically there but NOT valid +* -> BIT[3:0] = 0100b +* + the hole from the timestamp remain there unused until +* - you enable again the TS so the hole is used again +* -> BIT[3:0] = 0110b +* OR +* - you disable fully the DE and then re-enable it with the TS +* -> potentially CASE_1 the DE is relocated on enable +* + same kind of dynamic applies if the DE had a BLK_TS line +*/ +static int scmi_telemetry_tdcf_de_payld_check (struct telemetry_de *tde, +struct payload *payld) +{ +u32 meta =PAYLD_META_RAW (payld); + +lockdep_assert_held (&tde->mtx); + +if (DATA_INVALID_RAW (meta)) { +trace_scmi_tlm_access (PAYLD_ID_RAW (payld),"DE_DATA_INVALID" ,0 ,0 ); +return -EINVAL ; + } + +if (!IS_DATA_LINE_RAW (meta)) { +trace_scmi_tlm_access (tde->de.info->id,"BAD_DE_LINE_TYPE" ,0 ,0 ); +return -EPROTO ; + } + +if (PAYLD_ID_RAW (payld) != tde->de.info->id) { +trace_scmi_tlm_access (tde->de.info->id,"DE_ID_MISMATCH" ,0 ,0 ); +return -ENODEV ; + } + +/* +* A valid line using BLK_TS should have been initialized with the +* related BLK_TS when enabled, unless is a torn read. +*/ +if ((USE_BLK_TS_RAW (meta) && !tde->bts)) { +trace_scmi_tlm_access (tde->de.info->id,"BAD_USE_BLK_TS" ,0 ,0 ); +return -EPROTO ; + } + +return 0 ; +} + +static int scmi_telemetry_de_snapshot (struct tdcf __iomem *tdcf, +struct telemetry_de *tde, +struct telemetry_de_snapshot *snap) +{ +int retries =SCMI_TLM_TDCF_MAX_RETRIES ; +u32 startm, endm, live =0 ; +int err; + +lockdep_assert_held (&tde->mtx); + +do { +struct payload __iomem *payld, *bts_payld; +ssize_t len; + +/* A bit of exponential backoff between retries */ +fsleep ((SCMI_TLM_TDCF_MAX_RETRIES - retries) *SCMI_TLM_TDCF_RETRY_GAP_US ); + + err =0 ; + startm =TDCF_START_SEQ_GET (tdcf); +/* Build a default endm certainly different from startm */ + endm = startm +1 ; +if (IS_BAD_START_SEQ (startm)) { +trace_scmi_tlm_access (tde->de.info->id,"MSEQ_BADSTART_DE" , + startm,0 ); +continue ; + } + +/* +* In this context any anomaly detected on the payload could +* due to a torn read, and it is worth retrying a snapshot. +* +* Note that TDE base/offset have been sanitized when +* initialized and cannot have changed: accessing them here +* is safe. +*/ + payld = tde->base + tde->offset; +/* Sanitize length before snapshot */ + len =scmi_telemetry_shmti_overflow (tde->base, tde->eplg, payld); +if (len <0 ) +continue ; +memcpy_fromio (&snap->payld, payld, len); + err =scmi_telemetry_tdcf_de_payld_check (tde, &snap->payld); +if (err) +continue ; + +/* +* Here the associated BLK_TS line, if any, has been verified +* as sane when linked/bound: no need of further validation. +*/ +if (tde->bts) { + bts_payld = tde->base + tde->bts->line.offset; +/* Sanitize length before snapshot */ + len =scmi_telemetry_shmti_overflow (tde->base, + tde->eplg, bts_payld); +if (len <0 ) +continue ; +memcpy_fromio (&snap->bts_payld, bts_payld, len); + } + +/* Assure the snapshot has been fully taken before checking seqnum */ +rmb (); + +/* Used to detect changes while copying */ + live =TDCF_START_SEQ_GET (tdcf); + endm =TDCF_END_SEQ_GET (tde->eplg); +if (startm != endm || startm != live) +trace_scmi_tlm_access (tde->de.info->id,"MSEQ_MISMATCH_DE" , + startm, startm != endm ? endm : live); + }while ((startm != endm || startm != live || err) && --retries); + +if (startm != endm || startm != live || err) { +trace_scmi_tlm_access (tde->de.info->id,"TDCF_SNAPSHOT_DE_FAIL" , + startm, startm != endm ? endm : live); +return err ?: -EPROTO ; + } + +/* Ensure any snapshot is visible before updating magic */ +smp_store_release (&snap->magic, startm); + +trace_scmi_tlm_access (tde->de.info->id,"TDCF_SNAPSHOT_DE_OK" , + startm, endm); + +return 0 ; +} + +static int +scmi_telemetry_tdcf_de_sample_cached (struct tdcf __iomem *tdcf, +struct telemetry_de *tde, +struct scmi_telemetry_de_sample *sample) +{ +lockdep_assert_held (&tde->mtx); + +u32 startm; + +/* If updating cannot be cached */ + startm =TDCF_START_SEQ_GET (tdcf); +if (IS_BAD_START_SEQ (startm)) +return -EAGAIN ; + +return scmi_telemetry_tde_cache_lookup (tde, sample, &startm); +} + +/** +* scmi_telemetry_tdcf_de_parse - Helper to read one SHMTI/DE +* @tde: A reference to the DE descriptor to read +* @sample: A reference to the sample used as a container for output +* +* This helper can be used to retrieve the data value of a SHMTI based DE +* and any related BLK_TS line: unless the values are found already available +* and up to date in the TDE cache, a limited snapshot of the involved lines +* is taken at first so that all the subsequent DE parsing and processing can +* happen on a stable in RAM copy. +* +* Taking a limited snapshot does not carry relevant overhead and has the +* benefit of allowing the reuse of the same RAM-baased data accessors used +* during a full scan and related full snapshot, instead of a set of dedicated +* __iomem helpers. +* +* NOTE that since each TDE has its own cache, which is accessed and updated +* both during a single DE read and while performing a bulk read, while +* caching consistency assures to provide always the 'freshest' value +* retrieved, mixing single and bulk reads can lead to the values produced by +* the bulk reads to contain 'fresher' late values derived from concurrent +* single DE reads: IOW mixing single and bulk reads can produce a set of bulk +* DEs values that are NOT all from the same moment in time. +* +* Moreover in general, since no assumption can be made about the TDCF sequence +* numbers across different SHMTIs and related optional DE timestamps, it is NOT +* possible to guarantee anyway that data values retrieved from DEs located in +* distinct SHMTIs areas comes from the same platform update cycle at all. +*/ +static int +scmi_telemetry_tdcf_de_parse (struct telemetry_de *tde, +struct scmi_telemetry_de_sample *sample) +{ +struct telemetry_de_snapshot snap = {}; +struct tdcf __iomem *tdcf; +int ret; + +lockdep_assert_held (&tde->mtx); + +/* +* TDEs can be relocated by platform only during enable phase, +* thing that cannot happen until tde->mtx is released. +*/ + tdcf = tde->base; +if (!tdcf) +return -ENODEV ; + +if (!scmi_telemetry_tdcf_de_sample_cached (tdcf, tde, sample)) +return 0 ; + +/* Attempt a localized DE snapshot: DATA_LINE + optionally BLK_TS */ + ret =scmi_telemetry_de_snapshot (tdcf, tde, &snap); +if (ret) +return ret; + +/* Now parse the stable line snapshot */ +return scmi_telemetry_line_data_parse (tde,NULL , sample, &snap.payld, + &snap.bts_payld, snap.magic); +} + +static int scmi_telemetry_de_access (struct telemetry_de *tde, +struct scmi_telemetry_de_sample *sample) +{ +lockdep_assert_held (&tde->mtx); + +if (!tde->de.fc_support) +return scmi_telemetry_tdcf_de_parse (tde, sample); + +return scmi_telemetry_de_data_fc_read (tde, sample); +} + +static int scmi_telemetry_de_collect (struct telemetry_info *ti, +struct scmi_telemetry_de *de, +struct scmi_telemetry_de_sample *sample) +{ +struct telemetry_de *tde =to_tde (de); + +guard (mutex)(&tde->mtx); + +if (!de->enabled) +return -ENODATA ; + +return scmi_telemetry_de_access (tde, sample); +} + +static int scmi_telemetry_de_data_read (const struct scmi_protocol_handle *ph, +struct scmi_telemetry_de_sample *sample) +{ +struct telemetry_info *ti = ph->get_priv (ph); +struct scmi_telemetry_de *de; + +if (!ti->info.enabled || !sample) +return -ENODATA ; + + ti->res_get (ti); + de =xa_load (&ti->xa_des, sample->id); +if (!de) +return -ENOENT ; + +return scmi_telemetry_de_collect (ti, de, sample); +} + +static int +scmi_telemetry_samples_collect (struct telemetry_info *ti,int grp_id, +unsigned int *num_samples, +struct scmi_telemetry_de_sample *samples) +{ +struct scmi_telemetry_res_info *rinfo; +unsigned int max_samples; + +if (grp_id !=SCMI_TLM_GRP_INVALID ) +return -EOPNOTSUPP ; + + max_samples = *num_samples; + *num_samples =0 ; + + rinfo = ti->res_get (ti); +for (int i =0 ; i < rinfo->num_des; i++) { +struct telemetry_de *tde =to_tde (rinfo->des[i]); + +guard (mutex)(&tde->mtx); + +/* Skip disabled DEs */ +if (!tde->de.enabled) +continue ; + +/* Must be checked here to skip disabled and non selected */ +if (*num_samples == max_samples) +return -ENOSPC ; + +/* Note that this cannot fail when passing a NULL magic */ +scmi_telemetry_tde_cache_lookup (tde, &samples[(*num_samples)++],NULL ); + } + +return 0 ; +} + +static int scmi_telemetry_des_bulk_read (const struct scmi_protocol_handle *ph, +int grp_id,unsigned int *num_samples, +struct scmi_telemetry_de_sample *samples) +{ +struct telemetry_info *ti = ph->get_priv (ph); + +if (!ti->info.enabled) +return -ENODATA ; + +if (!num_samples || !samples) +return -EINVAL ; + +/* Trigger a full SHMTIs & FCs scan */ +scmi_telemetry_scan_update (ti); + +/* +* Collect all last cached values. +* Note that on any read failure this reports the latest successfully +* collected values: timestamp, where available, can be used to spot +* stale values. Single DE reads and related batch requests can be used +* to attain a more fine grained access with detailed error reporting. +*/ +return scmi_telemetry_samples_collect (ti, grp_id, num_samples, samples); +} +static const struct scmi_telemetry_proto_ops tlm_proto_ops = { .info_get = scmi_telemetry_info_get, .de_lookup = scmi_telemetry_de_lookup,
@@ -3162,6 +3619,8 @@ static const struct scmi_telemetry_proto_ops tlm_proto_ops = { .state_get = scmi_telemetry_state_get, .state_set = scmi_telemetry_state_set, .collection_configure = scmi_telemetry_collection_configure, + .de_data_read = scmi_telemetry_de_data_read, + .des_bulk_read = scmi_telemetry_des_bulk_read, };/**
include/linux/scmi_protocol.h +17 -0
@@ -969,6 +969,13 @@ struct scmi_telemetry_info {enum scmi_telemetry_collection current_mode; }; +struct scmi_telemetry_de_sample { +unsigned int id; +unsigned int pad; +unsigned long long tstamp; +unsigned long long val; +}; +/** * struct scmi_telemetry_proto_ops - represents the various operations provided * by SCMI Telemetry Protocol
@@ -983,6 +990,11 @@ struct scmi_telemetry_info {* @collection_configure: choose a sampling rate and enable SHMTI/FC sampling * for on demand collection via @de_data_read or async * notificatioins for all the enabled DEs. +* @de_data_read: on-demand read of a single DE and related optional timestamp: +* the value will be retrieved at the proper SHMTI offset OR +* from the dedicated FC area (if supported by that DE). +* @des_bulk_read: on-demand read of all the currently enabled DEs, or just +* the ones belonging to a specific group when provided. */ struct scmi_telemetry_proto_ops {const struct scmi_telemetry_info *(*info_get)
@@ -1002,6 +1014,11 @@ struct scmi_telemetry_proto_ops { unsigned int res_id, const bool *enable, const unsigned int *update_interval, const enum scmi_telemetry_collection *mode); +int __must_check (*de_data_read)(const struct scmi_protocol_handle *ph, +struct scmi_telemetry_de_sample *sample); +int __must_check (*des_bulk_read)(const struct scmi_protocol_handle *ph, +int grp_id,unsigned int *num_samples, +struct scmi_telemetry_de_sample *samples); };/**
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 21/34 firmware: arm_scmi: Add Telemetry boot-on support
In reply to Cristian MarussiAdd the initialization and discovery logic needed to detect when the platform SCMI server is configured with telemetry enabled at boot and perform all the needed resource enumerations to keep the kernel telemetry subsystem state aligned with the platform boot-on configurations.
---
v16 -->v17
- bailout early on unplausible FC_SUPPORT in DE enumeration
- avoid collection naming clashes
- do NOT use tde_register to finalize pre-discovered (enabled) DE/FC
v15 --> 16
- removed group support at boot-on
- discard DE/FC at enumeration time that were found in SHMTI at boot
- align DE local/global TS state after enumeration
v14 --> v15
- use IS_TDE_TS_ macro
- retrieve collection_mode at boot-on and force ignore groups
- count only successfully initialized groups at boot-on
v13 --> v14
- moved some definitions from earlier split patch
- renamed some fields to more strictly adhere to spec nomenclature
v12 --> v13
- greb tde->mtx on DE_ENABLED_LIST
v11 --> v12
- fixed TS_RATE determination at boot-on
v10 --> v11
- fix non-conformancy on CONFIG_GET when groups NON configurable
- use SCAN_UPDATE also on BOOT-ON initial scan (NO discovery)
- avoid 'naked' ti->rinfo accesses
v8 -- > v9
- remove useless initial state lookup after RESET
- properly set de->tstamp_support on DE_ENABLED_LIST
v5 --> v6
- reporte properly an error on scmi_telemetry_config_lookup() failure (Sashiko)
v4 --> v5
- use renamed grp_id instead of old id in group descriptors
- fixes sparse warnings
v3 --> v4
- bail-out FW_BUG errors
- fix typos in comments
- track boot-on Telemetry DE states
v2 --> v3
- split from monolithic telemetry protocol patch
- swap logic in scmi_telemetry_initial_state_lookup
--- drivers/firmware/arm_scmi/telemetry.c | 295 +++++++++++++++++++++++++- 1 file changed, 284 insertions(+), 11 deletions(-)
drivers/firmware/arm_scmi/telemetry.c +284 -11
@@ -133,6 +133,21 @@ struct scmi_msg_resp_telemetry_update_intervals {__le32 intervals[]; }; +struct scmi_msg_telemetry_de_enabled_list { +__le32 index; +__le32 flags; +}; + +struct scmi_enabled_de_desc { +__le32 id; +__le32 mode; +}; + +struct scmi_msg_resp_telemetry_de_enabled_list { +__le32 flags; +struct scmi_enabled_de_desc array[]; +}; +struct scmi_msg_telemetry_de_configure {__le32 identifier;__le32 flags;
@@ -176,6 +191,20 @@ struct scmi_msg_telemetry_config_set {__le32 sampling_rate; }; +struct scmi_msg_telemetry_config_get { +__le32 group_identifier; +__le32 flags; +#define TELEMETRY_GET_SELECTOR (x) (FIELD_PREP(GENMASK(3, 0), (x))) +#define TELEMETRY_GET_SELECTOR_ORPHANS TELEMETRY_GET_SELECTOR(TLM_ORPHANS) +#define TELEMETRY_GET_SELECTOR_GROUP TELEMETRY_GET_SELECTOR(TLM_GROUP) +#define TELEMETRY_GET_SELECTOR_ALL TELEMETRY_GET_SELECTOR(TLM_ALL) +}; + +struct scmi_msg_resp_telemetry_config_get { +__le32 control; +__le32 sampling_rate; +}; +/* TDCF */ #define _I (__a) (ioread32((void __iomem *)(__a)))
@@ -501,6 +530,8 @@ static inline bool scmi_tde_has_tstamp(struct telemetry_de *t)return t->de.tstamp_support && t->de.tstamp_enabled; } +#define DE_ENABLED_WITH_TSTAMP 2 +enum de_state {ENA_STATE ,ENA_TSTAMP ,
@@ -677,12 +708,6 @@ static int scmi_telemetry_tde_register(struct telemetry_info *ti,if (ret) goto err; -/* Add to FastChannels list */ -if (tde->de.fc_support) { -scmi_telemetry_uuid_link (tde, ti->primary_uuid); -list_add (&tde->item, &ti->fcs_des); - } -/* ... and in the general array */ rinfo->des[rinfo->num_des] = &tde->de;/* Make sure the freshly registered DE is visible before the index update */
@@ -948,6 +973,7 @@ static int scmi_telemetry_de_descriptor_parse(struct telemetry_info *ti,const struct scmi_de_desc *desc = *next;struct device *dev = ti->ph->dev;size_t payld_sz =sizeof (*desc); +bool fc_support;int ret;lockdep_assert_held (&tde->mtx);
@@ -955,6 +981,12 @@ static int scmi_telemetry_de_descriptor_parse(struct telemetry_info *ti,if (*rx_len < payld_sz)return -ENOSPC ; + fc_support =IS_FC_SUPPORTED (desc); +/* Bail-out if already discovered as a SHMTI-based DE */ +if (fc_support && tde->base) +return -EPROTO ; + + tde->de.fc_support = fc_support; tde->de.info->id =le32_to_cpu (desc->de_id); tde->de.info->grp_id =le32_to_cpu (desc->group_id); tde->de.info->data_sz =le32_to_cpu (desc->de_data_sz);
@@ -967,7 +999,6 @@ static int scmi_telemetry_de_descriptor_parse(struct telemetry_info *ti, tde->de.info->persistent =IS_PERSISTENT (desc); tde->ts_type =TSTAMP_SUPPORT (desc); tde->de.tstamp_support = !!tde->ts_type; - tde->de.fc_support =IS_FC_SUPPORTED (desc); tde->de.name_support =IS_NAME_SUPPORTED (desc);/* Update DE_DESCRIPTOR size for the next iteration */ *next +=sizeof (*desc);
@@ -984,8 +1015,13 @@ static int scmi_telemetry_de_descriptor_parse(struct telemetry_info *ti,/* Variably sized depending on TS support */ *next +=sizeof (*line_ts_rate); }else if (IS_TDE_TS_BLK (tde)) { -/* Setup default BLK TS value at first */ - tde->de.info->ts_rate = ti->default_blk_ts_rate; +/* +* Setup default BLK TS rate value at first, if it has NOT +* already been picked from the BLK_TS line by the boot-on +* SCAN_UPDATE. +*/ +if (!tde->de.info->ts_rate) + tde->de.info->ts_rate = ti->default_blk_ts_rate; }else if (!IS_TDE_TS_NONE (tde)) {dev_warn (dev,"Unknown TDE timestamp type %u\n" , tde->ts_type);return -EPROTO ;
@@ -1074,12 +1110,234 @@ static int iter_de_descr_process_response(const struct scmi_protocol_handle *ph, } } +/* Add to FastChannels list */ +if (tde->de.fc_support) { +scmi_telemetry_uuid_link (tde, ti->primary_uuid); +list_add (&tde->item, &ti->fcs_des); + } + +/* TS is NOT supported clear any enabled state possibly at boot-on */ +if (!tde->de.tstamp_support) +scmi_telemetry_de_state_update (ti,ENA_TSTAMP , + &tde->de.tstamp_enabled, false); +/* Count timestamped DEs */ ti->num_des_tstamp += !!tde->de.tstamp_support;return 0 ; } +static int scmi_telemetry_config_lookup (struct telemetry_info *ti, +unsigned int grp_id,bool *enabled, +unsigned int *active_update_interval, +enum scmi_telemetry_collection *mode, +bool ignore_groups) +{ +const struct scmi_protocol_handle *ph = ti->ph; +struct scmi_msg_telemetry_config_get *msg; +struct scmi_msg_resp_telemetry_config_get *resp; +bool is_group = grp_id !=SCMI_TLM_GRP_INVALID ; +struct scmi_xfer *t; +u32 flags; +int ret; + + ret = ph->xops->xfer_get_init (ph,TELEMETRY_CONFIG_GET , +sizeof (*msg),sizeof (*resp), &t); +if (ret) +return ret; + + msg = t->tx.buf; + msg->group_identifier =cpu_to_le32 (grp_id); + +/* Spec mandates the ALL selector when per-group config not available */ +if (!ti->info.per_group_config_support || ignore_groups) + flags =TELEMETRY_GET_SELECTOR_ALL ; +else + flags = !is_group ?TELEMETRY_GET_SELECTOR_ORPHANS : +TELEMETRY_GET_SELECTOR_GROUP ; + + msg->flags =cpu_to_le32 (flags); + + resp = t->rx.buf; + ret = ph->xops->do_xfer (ph, t); +if (!ret) { + *enabled =le32_get_bits (resp->control,TELEMETRY_ENABLE ); + *mode =le32_get_bits (resp->control,TELEMETRY_MODE ); +if (!is_group) + ti->streaming_mode = + *mode ==SCMI_TLM_COLLECTION_NOTIFICATION ; + *active_update_interval = +SCMI_TLM_GET_UPDATE_INTERVAL (le32_to_cpu (resp->sampling_rate)); + } + + ph->xops->xfer_put (ph, t); + +return ret; +} + +static void iter_enabled_list_prepare_message (void *message, +unsigned int desc_index, +const void *priv) +{ +struct scmi_msg_telemetry_de_enabled_list *msg = message; + + msg->index =cpu_to_le32 (desc_index); + msg->flags =0 ; +} + +static int iter_enabled_list_update_state (struct scmi_iterator_state *st, +const void *response,void *priv) +{ +const struct scmi_msg_resp_telemetry_de_enabled_list *r = response; + + st->num_returned =le32_get_bits (r->flags,GENMASK (15 ,0 )); + st->num_remaining =le32_get_bits (r->flags,GENMASK (31 ,16 )); + +if (st->rx_len < (sizeof (*r) +sizeof (r->array[0 ]) * st->num_returned)) +return -EINVAL ; + +/* +* total enabled is not declared previously anywhere so we +* assume it's returned+remaining on first call. +*/ +if (!st->max_resources) + st->max_resources = st->num_returned + st->num_remaining; + +return 0 ; +} + +static int +iter_enabled_list_process_response (const struct scmi_protocol_handle *ph, +const void *response, +struct scmi_iterator_state *st,void *priv) +{ +const struct scmi_msg_resp_telemetry_de_enabled_list *r = response; +const struct scmi_enabled_de_desc *desc; +struct telemetry_info *ti = priv; +struct telemetry_de *tde; +u32 de_id; +int ret; + + desc = &r->array[st->loop_idx]; + de_id =le32_to_cpu (desc->id); +if (scmi_telemetry_tde_lookup (ti, de_id)) { +dev_err (ph->dev, +"Found INVALID DE with DUPLICATED ID:0x%08X\n" , de_id); +return -EINVAL ; + } + + tde =scmi_telemetry_tde_get (ti, de_id); +if (IS_ERR (tde)) +return PTR_ERR (tde); + +guard (mutex)(&tde->mtx); + tde->de.info->id = de_id; + tde->de.enabled = true; + tde->de.tstamp_enabled =le32_to_cpu (desc->mode) ==DE_ENABLED_WITH_TSTAMP ; +/* +* Guessing that, if a DE is reported as enabled with timestamp, it has +* to support timestamp: NOTE THAT the timestamp type (tde->ts_type) can +* ONLY be discovered later by DE_DESCRIPTION. +*/ + tde->de.tstamp_support = tde->de.tstamp_enabled; + + ret =scmi_telemetry_tde_register (ti, tde); +if (ret) { +scmi_telemetry_free_tde_put (ti, tde); +return ret; + } + +scmi_telemetry_de_state_update (ti,ENA_STATE ,NULL , true); +if (tde->de.tstamp_enabled) +scmi_telemetry_de_state_update (ti,ENA_TSTAMP ,NULL , true); + +dev_dbg (ph->dev,"Registered new ENABLED DE with ID:0x%08X\n" , + tde->de.info->id); + +return 0 ; +} + +static int scmi_telemetry_enumerate_des_enabled_list (struct telemetry_info *ti) +{ +const struct scmi_protocol_handle *ph = ti->ph; +struct scmi_telemetry_res_info *rinfo; +struct scmi_iterator_ops ops = { + .prepare_message = iter_enabled_list_prepare_message, + .update_state = iter_enabled_list_update_state, + .process_response = iter_enabled_list_process_response, + }; +void *iter; +int ret; + + iter = ph->hops->iter_response_init (ph, &ops,0 , +TELEMETRY_DE_ENABLED_LIST , +sizeof (u32) *2 , ti); +if (IS_ERR (iter)) +return PTR_ERR (iter); + + ret = ph->hops->iter_response_run (iter); +if (ret) +return ret; + +/* Get rinfo as it is...without triggering an enumeration */ + rinfo =__scmi_telemetry_resources_get (ti); + +dev_info (ti->ph->dev,"Found %u enabled DEs.\n" , rinfo->num_des); + +return 0 ; +} + +static int scmi_telemetry_initial_state_lookup (struct telemetry_info *ti) +{ +struct device *dev = ti->ph->dev; +int ret; + +/* Discover the initial state ONLY for DEs, ignoring groups */ + ret =scmi_telemetry_config_lookup (ti,SCMI_TLM_GRP_INVALID , + &ti->info.enabled, + &ti->info.active_update_interval, + &ti->info.current_mode, true); +if (ret) +return ret; + +if (!ti->info.enabled) +return 0 ; + +/* +* When Telemetry is found already enabled on the platform, proceed with +* passive discovery using DE_ENABLED_LIST and TDCF scanning: note that +* this CAN only discover DEs exposed via SHMTIs. +* FastChannel DEs need a proper DE_DESCRIPTION enumeration, while, even +* though incoming Notifications could be used for passive discovery too, +* it would carry a considerable risk of assimilating trash as DEs. +*/ +dev_info (dev, +"Telemetry found enabled with update interval %lux10^%d mode:%u\n" , +SCMI_TLM_GET_UPDATE_INTERVAL_SECS (ti->info.active_update_interval), +SCMI_TLM_GET_UPDATE_INTERVAL_EXP (ti->info.active_update_interval), + ti->info.current_mode); +/* +* Query enabled DEs list: collect states. It will include DEs from any +* interface. Enabled groups still NOT enumerated. +*/ + ret =scmi_telemetry_enumerate_des_enabled_list (ti); +if (ret) { +dev_err (dev,FW_BUG "Cannot query enabled DE list. Abort.\n" ); +return ret; + } + +/* Discover DEs on SHMTis: collect states/offsets/values */ +for (int id =0 ; id < ti->num_shmti; id++) { + ret =scmi_telemetry_shmti_scan (ti, id,SCAN_UPDATE ); +if (ret) +dev_warn (dev, +"Failed discovery-scan of SHMTI ID:%d - ret:%d\n" , + id, ret); + } + +return 0 ; +} +static void scmi_telemetry_tdes_cleanup (void *arg) {struct telemetry_info *ti = arg;
@@ -2225,8 +2483,17 @@ static void scmi_telemetry_tdcf_data_parse(struct telemetry_info *ti,trace_scmi_tlm_access (de_id,"DE_LOCATION_UPDATED" ,0 ,0 ); -dev_dbg (dev,"TDCF-updated DE_ID:0x%08X - shmti:%pK offset:%u\n" , - tde->de.info->id, tde->base, tde->offset); +/* Just in case it was passively discovered boot-on */ +if (IS_TDE_TS_NONE (tde)) { +if (use_blk_ts) + tde->ts_type =TSTAMP_BLK ; +else if (LINE_TS_VALID_RAW (meta)) + tde->ts_type =TSTAMP_LINE ; + } + +dev_dbg (dev, +"TDCF-updated DE_ID:0x%08X - shmti:%pK offset:%u ts_type:%d\n" , + tde->de.info->id, tde->base, tde->offset, tde->ts_type); }/*
@@ -3960,6 +4227,12 @@ static int scmi_telemetry_protocol_init(const struct scmi_protocol_handle *ph)return ret; } + ret =scmi_telemetry_initial_state_lookup (ti); +if (ret) { +dev_err (dev,FW_BUG "Cannot retrieve initial state. Abort.\n" ); +return ret; + } + ti->info.base.version = ph->version;return ph->set_priv (ph, ti);
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 22/34 firmware: arm_scmi: Invoke proper protocol cleanup on failure
In reply to Cristian MarussiAfter a failure in the protocol initialization phase, invoke if provided the protocol deinitialization routines.
--- drivers/firmware/arm_scmi/driver.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/firmware/arm_scmi/driver.c +4 -1
@@ -2353,7 +2353,7 @@ scmi_alloc_init_protocol_instance(struct scmi_info *info, ret =idr_alloc (&info->protocols, pi, proto->id, proto->id +1 ,GFP_KERNEL );if (ret != proto->id) - goto clean; + goto deinit;/* * Warn but ignore events registration errors since we do not want
@@ -2374,6 +2374,9 @@ scmi_alloc_init_protocol_instance(struct scmi_info *info,return pi; +deinit: +if (pi->proto->instance_deinit) + pi->proto->instance_deinit (&pi->ph); clean:/* Take care to put the protocol module's owner before releasing all */ scmi_protocol_put (proto);
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 23/34 firmware: arm_scmi: Refactor protocol allocation
In reply to Cristian MarussiSimplify protocol initialization and finalization using cleanup handlers. Relocate the protocol put operations out of the setup and cleanup code so as to be executed strictly after the protocol devres groups have been fully released.
--- drivers/firmware/arm_scmi/driver.c | 53 +++++++++++++----------------- 1 file changed, 22 insertions(+), 31 deletions(-)
drivers/firmware/arm_scmi/driver.c +22 -31
@@ -2306,24 +2306,21 @@ static void scmi_protocol_version_initialize(struct device *dev,* * Context: Assumes to be called with @protocols_mtx already acquired. * Return: A reference to a freshly allocated and initialized protocol instance -* or ERR_PTR on failure. On failure the @proto reference is at first -* put using @scmi_protocol_put() before releasing all the devres group. +* or ERR_PTR on failure. */ static struct scmi_protocol_instance *scmi_alloc_init_protocol_instance (struct scmi_info *info,const struct scmi_protocol *proto) { +const struct scmi_handle *handle = &info->handle; +struct scmi_protocol_instance *pi;int ret = -ENOMEM ;void *gid; -struct scmi_protocol_instance *pi; -const struct scmi_handle *handle = &info->handle;/* Protocol specific devres group */ gid =devres_open_group (handle->dev,NULL ,GFP_KERNEL ); -if (!gid) { -scmi_protocol_put (proto); - goto out; - } +if (!gid) +return ERR_PTR (ret); pi =devm_kzalloc_obj (handle->dev, *pi);if (!pi)
@@ -2378,10 +2375,7 @@ scmi_alloc_init_protocol_instance(struct scmi_info *info,if (pi->proto->instance_deinit) pi->proto->instance_deinit (&pi->ph); clean: -/* Take care to put the protocol module's owner before releasing all */ -scmi_protocol_put (proto);devres_release_group (handle->dev, gid); -out:return ERR_PTR (ret); }
@@ -2401,25 +2395,25 @@ scmi_alloc_init_protocol_instance(struct scmi_info *info,static struct scmi_protocol_instance *__must_check scmi_get_protocol_instance (const struct scmi_handle *handle,u8 protocol_id) { -struct scmi_protocol_instance *pi;struct scmi_info *info =handle_to_scmi_info (handle); +struct scmi_protocol_instance *pi; +const struct scmi_protocol *proto; -mutex_lock (&info->protocols_mtx); +guard (mutex)(&info->protocols_mtx); pi =idr_find (&info->protocols, protocol_id); -if (pi) {refcount_inc (&pi->users); - }else { -const struct scmi_protocol *proto; - -/* Fails if protocol not registered on bus */ - proto =scmi_protocol_get (protocol_id, &info->version); -if (proto) - pi =scmi_alloc_init_protocol_instance (info, proto); -else - pi =ERR_PTR (-EPROBE_DEFER ); +return pi; } -mutex_unlock (&info->protocols_mtx); + +/* Fails if protocol not registered on bus */ + proto =scmi_protocol_get (protocol_id, &info->version); +if (!proto) +return ERR_PTR (-EPROBE_DEFER ); + + pi =scmi_alloc_init_protocol_instance (info, proto); +if (IS_ERR (pi)) +scmi_protocol_put (proto);return pi; }
@@ -2452,12 +2446,13 @@ void scmi_protocol_release(const struct scmi_handle *handle, u8 protocol_id)struct scmi_info *info =handle_to_scmi_info (handle);struct scmi_protocol_instance *pi; -mutex_lock (&info->protocols_mtx); +guard (mutex)(&info->protocols_mtx); pi =idr_find (&info->protocols, protocol_id);if (WARN_ON (!pi)) - goto out; +return ;if (refcount_dec_and_test (&pi->users)) { +const struct scmi_protocol *proto = pi->proto;void *gid = pi->gid;if (pi->proto->events)
@@ -2468,15 +2463,11 @@ void scmi_protocol_release(const struct scmi_handle *handle, u8 protocol_id)idr_remove (&info->protocols, protocol_id); -scmi_protocol_put (pi->proto); -devres_release_group (handle->dev, gid); +scmi_protocol_put (proto);dev_dbg (handle->dev,"De-Initialized protocol: 0x%X\n" , protocol_id); } - -out: -mutex_unlock (&info->protocols_mtx); } void scmi_setup_protocol_implemented(const struct scmi_protocol_handle *ph,
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 24/34 firmware: arm_scmi: Add common per-protocol debugfs support
In reply to Cristian MarussiAllow interested SCMI protocols to register their own specific debugfs entries under a common per-instance and per-protocol subtree rooted at /sys/kernel/debug/scmi/<N>/protocols/<PROTO_ID>/
Expose a helper to enable protocol initialization code to get access to such per-protocol/per-instance dentries in order to be able to install their own dedicated debugfs entries.
Per-protocol debugfs support is configurable and default off.
---
v16 --> v17
- fix leak and NULL deref on exit path
v15 --> v16
- cleanup protocol dbg root after devres group closure
v14 --> v15
- fix debugfs_remove_recursive call-site...was too early
v8 --> v9
- avoid NULL deref on DBG cleanup path
v5 --> v6
- bail out of dentry_get helper when SCMI debug susbsytem failed to init
- remove stale SCMI protocol operations
- add a preoper clean up of debugfs when protocol init fails
--- drivers/firmware/arm_scmi/Kconfig | 14 +++++++++ drivers/firmware/arm_scmi/common.h | 2 ++ drivers/firmware/arm_scmi/driver.c | 41 ++++++++++++++++++++++++++- drivers/firmware/arm_scmi/protocols.h | 6 ++++ 4 files changed, 62 insertions(+), 1 deletion(-)
drivers/firmware/arm_scmi/Kconfig +14 -0
@@ -69,6 +69,20 @@ config ARM_SCMI_DEBUG_COUNTERS such useful debug counters. This can be helpful for debugging and SCMI monitoring. +config ARM_SCMI_DEBUG_PROTOCOLS + bool "Enable SCMI protocols debug" + select ARM_SCMI_NEED_DEBUGFS + depends on DEBUG_FS + default n + help + Enables per-protocol specific debug features, where available. + When provided, such per-protocol debugfs entries are grouped + inside a common a subtree named by the protocol number and rooted + under a per-instance 'protocols' directory. + + Such per-protocol entries subtree structure is freely defined + within the related protocol code. + config ARM_SCMI_QUIRKS bool "Enable SCMI Quirks framework" depends on JUMP_LABEL || COMPILE_TEST
drivers/firmware/arm_scmi/common.h +2 -0
@@ -307,6 +307,7 @@ enum debug_counters {/** * struct scmi_debug_info - Debug common info * @top_dentry: A reference to the top debugfs dentry +* @protos: A reference to the top debugfs protocols subdirectory * @name: Name of this SCMI instance * @type: Type of this SCMI instance * @is_atomic: Flag to state if the transport of this instance is atomic
@@ -314,6 +315,7 @@ enum debug_counters {*/ struct scmi_debug_info {struct dentry *top_dentry; +struct dentry *protos;const char *name;const char *type;bool is_atomic;
drivers/firmware/arm_scmi/driver.c +40 -1
109 lines not on this page · raw message
drivers/firmware/arm_scmi/protocols.h +6 -0
@@ -11,6 +11,7 @@#include <linux/bitfield.h> #include <linux/completion.h> +#include <linux/debugfs.h> #include <linux/device.h> #include <linux/errno.h> #include <linux/kernel.h>
@@ -292,6 +293,9 @@ struct scmi_fc_info {* gathering FC descriptions from the SCMI platform server. * @fastchannel_db_ring: A common helper to ring a FC doorbell. * @get_max_msg_size: A common helper to get the maximum message size. +* @debugfs_proto_dentry_get: A common helper to get a per-protocol debugfs top +* directory to use as a root. It will be +* recursively removed on protocol de-initialization. */ struct scmi_proto_helpers_ops { int (*extended_name_get)(const struct scmi_protocol_handle *ph,
@@ -315,6 +319,8 @@ struct scmi_proto_helpers_ops { u32 *rate_limit);void (*fastchannel_db_ring)(struct scmi_fc_db_info *db);int (*get_max_msg_size)(const struct scmi_protocol_handle *ph); +struct dentry *(*debugfs_proto_dentry_get) + (const struct scmi_protocol_handle *ph); };/**
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 25/34 firmware: arm_scmi: Add Telemetry debugfs SHMTI dump support
In reply to Cristian MarussiExpose one debugfs entry for each discovered SHMTI that can be used to dump the related SHMTI in binary form from TBGN up to TEND markers.
No processing is done kernel side, beside using proper accessors for device memory.
---
v15 --> v16
- initialize/destroy debugFS around SHMTIs init
v14 --> v15
- cleanup local debugfs subtree with debugfs_remove_recursive on remove
v12 --> v13
- get inode lock on time update
v11 --> v12
- fix debugfs shmti dump file to use the SID as name
v8 --> v9
- use kvzalloc/kfree
- use file_update_time to update debugfs file ts
v5 --> v6
- added mutex to protect binary dump buffer during reads (Sashiko)
- using debugfs_create_file_size() (Sashiko)
--- drivers/firmware/arm_scmi/telemetry.c | 103 ++++++++++++++++++++++++++ 1 file changed, 103 insertions(+)
drivers/firmware/arm_scmi/telemetry.c +103 -0
@@ -9,9 +9,11 @@#include <linux/bitfield.h> #include <linux/compiler_types.h> #include <linux/completion.h> +#include <linux/debugfs.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/err.h> +#include <linux/fs.h> #include <linux/hash.h> #include <linux/hashtable.h> #include <linux/jhash.h>
@@ -445,6 +447,14 @@ struct telemetry_shmti {#define TDCF_OFFS (_b, _p) \ ((unsigned long)((__force void *)(_p) - (__force void *)(_b))) +struct scmi_telemetry_dbg_shmti { +struct telemetry_shmti *shmti; +size_t buf_sz; +void *buf; +/* Protect this descriptor from concurrent readers using it */ +struct mutex mtx; +}; +#define SHMTI_EPLG (s) \ ({ \ struct telemetry_shmti *_s = (s); \
@@ -554,6 +564,7 @@ struct telemetry_info {unsigned int default_blk_ts_rate;const struct scmi_protocol_handle *ph;struct telemetry_shmti *shmti; +struct dentry *shmti_top;struct telemetry_de *tdes;struct xarray xa_des;struct telemetry_uuid *primary_uuid;
@@ -1358,6 +1369,10 @@ static void scmi_telemetry_tdes_cleanup(void *arg)scmi_telemetry_de_unlink (&tde->de);scmi_telemetry_free_tde_put (ti, tde); } + +/* Safe removal of SHMTI debugfs tree before freeing underlying data */ +if (IS_ENABLED (CONFIG_ARM_SCMI_DEBUG_PROTOCOLS )) +debugfs_remove_recursive (ti->shmti_top); }static int scmi_telemetry_de_descriptors_get (struct telemetry_info *ti)
@@ -1535,6 +1550,91 @@ scmi_telemetry_enumerate_common_intervals(struct telemetry_info *ti) ti->info.intervals); } +static int scmi_telemetry_dbg_shmti_open (struct inode *inode,struct file *filp) +{ +struct scmi_telemetry_dbg_shmti *sblob; +struct telemetry_shmti *shmti; + +if (!inode->i_private) +return -ENODEV ; + + shmti = inode->i_private; + sblob =kzalloc_obj (*sblob); +if (!sblob) +return -ENOMEM ; + + sblob->shmti = shmti; + sblob->buf =kvzalloc (shmti->info.len,GFP_KERNEL ); +if (!sblob->buf) { +kfree (sblob); +return -ENOMEM ; + } + +mutex_init (&sblob->mtx); + + filp->private_data = sblob; + +return 0 ; +} + +static ssize_t scmi_telemetry_dbg_shmti_read (struct file *filp,char __user *buf, +size_t count,loff_t *ppos) +{ +struct scmi_telemetry_dbg_shmti *sblob = filp->private_data; + +/* Dump on first read and again after each rewind to start pos */ +guard (mutex)(&sblob->mtx); +if (!sblob->buf_sz || *ppos ==0 ) { +struct inode *ino =file_inode (filp); + +memcpy_fromio (sblob->buf, sblob->shmti->base, + sblob->shmti->info.len); + sblob->buf_sz = sblob->shmti->info.len; +/* update inode timestamps */ +inode_lock (ino); +file_update_time (filp); +inode_unlock (ino); + } + +return simple_read_from_buffer (buf, count, ppos, sblob->buf, sblob->buf_sz); +} + +static int scmi_telemetry_dbg_shmti_release (struct inode *inode,struct file *filp) +{ +struct scmi_telemetry_dbg_shmti *sblob = filp->private_data; + +kvfree (sblob->buf); +kfree (sblob); + +return 0 ; +} + +static const struct file_operations scmi_telemetry_dbg_shmti_fops = { + .open = scmi_telemetry_dbg_shmti_open, + .release = scmi_telemetry_dbg_shmti_release, + .read = scmi_telemetry_dbg_shmti_read, + .llseek = generic_file_llseek, + .owner =THIS_MODULE , +}; + +static void scmi_telemetry_debugfs_initialize (struct telemetry_info *ti) +{ +const struct scmi_protocol_handle *ph = ti->ph; +struct dentry *top; + + top = ph->hops->debugfs_proto_dentry_get (ph); + ti->shmti_top =debugfs_create_dir ("shmtis" , top); + +for (unsigned int i =0 ; i < ti->num_shmti; i++) { +char id[16 ]; + +snprintf (id,16 ,"%u" , ti->shmti[i].info.sid); +debugfs_create_file_size (id,0444 , ti->shmti_top, &ti->shmti[i], + &scmi_telemetry_dbg_shmti_fops, + ti->shmti[i].info.len); + } +} +static int iter_shmti_update_state (struct scmi_iterator_state *st,const void *response,void *priv) {
@@ -1750,6 +1850,9 @@ static int scmi_telemetry_enumerate_shmti(struct telemetry_info *ti)/* Expose the fully initialized SHMTI infos */ smp_store_release (&ti->info.base.num_shmtis, ti->num_shmti); +if (IS_ENABLED (CONFIG_ARM_SCMI_DEBUG_PROTOCOLS )) +scmi_telemetry_debugfs_initialize (ti); +return devm_add_action_or_reset (ph->dev, scmi_telemetry_tdes_cleanup, ti); }
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 26/34 firmware: arm_scmi: Add Telemetry debugfs ABI documentation
In reply to Cristian MarussiAdd description of the debugfs SCMI Telemetry protocol ABI.
---
v15 --> v16
- fix Kernel version/date
v5 --> v6
- fixed typos
--- Documentation/ABI/testing/debugfs-scmi | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+)
Documentation/ABI/testing/debugfs-scmi +22 -0
@@ -68,3 +68,25 @@ Description: Max number of concurrently allowed in-flight SCMI messages for the currently configured SCMI transport for instance <n> on the RX channels. Users: Debugging, any userspace test suite + +What: /sys/kernel/debug/scmi/<n>/protocols/0x<m>/ +Date: Feb 2027 +KernelVersion: 7.5 +Contact: [email protected] +Description: A subdirectory grouping debug entries related to protocol <m> + for instance <n>. Each protocol owns and defines the subtree + of entries rooted under this directory. +Users: Debugging, any userspace test suite + +What: /sys/kernel/debug/scmi/<n>/protocols/0x1B/shmtis/<m> +Date: Feb 2027 +KernelVersion: 7.5 +Contact: [email protected] +Description: A set of RO files exposed by the Telemetry protocol (0x1B) in + order to dump the latest snapshot of each SHMTI memory area in + binary format: each file is named by its SHMTI id. + File is seekable and a seek to position zero on an open file + causes the SHMTI snapshot to be refreshed; file timestamps are + updated after each snapshot. + This directory reports SHMTIs for instance <n>. +Users: Debugging, any userspace test suite
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 27/34 firmware: arm_scmi: Expose per-instance identifier
In reply to Cristian MarussiWhen multiple SCMI instances are configured, the SCMI stack probes and it is initialized multiple times: one core stack for each defined instance.
Each istance is simply identified internally with a number and such number is already exposed to the user to name the root of the per-instance debugfs subtree, if enabled.
Expose such unique identifier to the SCMI drivers so that they can use that same identifier when in need to name their per-instance resources.
---
v7 --> v8
- fixed Doxygen 'non-negative' integer
--- drivers/firmware/arm_scmi/driver.c | 1 + include/linux/scmi_protocol.h | 5 +++++ 2 files changed, 6 insertions(+)
drivers/firmware/arm_scmi/driver.c +1 -0
@@ -3445,6 +3445,7 @@ static int scmi_probe(struct platform_device *pdev)idr_init (&info->rx_idr); handle = &info->handle; + handle->id = info->id; handle->dev = info->dev; handle->version = &info->version; handle->devm_protocol_acquire = scmi_devm_protocol_acquire;
include/linux/scmi_protocol.h +5 -0
@@ -1081,6 +1081,10 @@ struct scmi_notify_ops {/** * struct scmi_handle - Handle returned to ARM SCMI clients for usage. * +* @id: A unique non-negative natural integer identifying the SCMI Instance +* associated with this handle to be used across all drivers for +* naming purposes: same identifier used internally as the root for +* the debugfs per-instance tree. * @dev: pointer to the SCMI device * @version: pointer to the structure containing SCMI version information * @devm_protocol_acquire: devres managed method to get hold of a protocol,
@@ -1101,6 +1105,7 @@ struct scmi_notify_ops {* @notify_ops: pointer to set of notifications related operations */ struct scmi_handle { +unsigned int id;struct device *dev;struct scmi_base_info *version;
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 28/34 uapi: Add ARM SCMI Telemetry definitions
In reply to Cristian MarussiAdd a number of structures and ioctls definitions used by the ARM SCMI Telemetry protocol.
---
v15 --> v16
- added GROUPS/SINGLE_SAMPLE abi_features flags definitions
v14 --> v15
- a couple of clarification in doxygen
v11 --> v12
- fixed documentation around event lifetime cycle to align with the new implemented logic
v10 --> v11
- typos fixing and comments fixup
- more docs on BATCH IOCTLs and structures
- more docs on SHMTI_LIST
- more docs on EVENT_REGISTER
- more docs on GET_INTRVS upper bounds and zero-query
- more docs on BULK/SINGLE upper bounds and zero-query
v8 --> v9
- Simplified ABI related to _LIST IOCTL, substituting all custom container structures in favour of the usage of scmi_tlm_batch, i.e. dropping:
- scmi_tlm_des_list
- scmi_tlm_uuid_list
- scmi_tlm_grps_list
- scmi_tlm_shmtis_list
- Updated related _LIST documentation
v7 --> v8
- Fixes for some Sashiko issues on v7
- fix typos and wrong struct reference in SCMI_TLM_BATCH_READ
- move a couple of IOCTL to be _IOW
- add a few more comments on usage and behaviour of BATCH ops
v6 --> v7
- added per-DE UUID/SID/OFFS
- IOCTL EVENTS: generation counter
- generic BATCH support (scmi_tlm_batch)
- BATCH READ with perf-DE status
- BATCH DE GET/SET CONFIG
- added reserved fields for grow
- added more ABI features flags
- better Doxygen desciption for IN/OUT params
v5 --> v6
- Fixed interval exp to be __s32 as documented
- Using a more unique name for IOCTL MAGIC define
- Renamed a few IOCTLs to be consistent
- redefine primary UUID as an array of u8
- add GET_ABI_INFO to gather ABI version and instance info
- add RESET support
- fixed typos in kdoc
v4 --> v5
- Added more structure padding
- Removed frowned upon flexible array in favour of u64 pointers to external userspace provided buffer
- Added UAPI support to access SHMTIs from userspace
- Cleaned up Doxygen
v2 --> v3
- Change tstamp_exp tp ts_rate
- renamed num -> num_intervals in scmi_tlm_interval
- added padding in scmi_tlm_de_sample to avoid packing issues on 32bit
v1 --> v2
- Added proper __counted_by marks
- Fixed a few dox comments
- Renamed reserved[] fields to pad[]
--- MAINTAINERS | 1 + include/uapi/linux/scmi.h | 533 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 534 insertions(+) create mode 100644 include/uapi/linux/scmi.h
MAINTAINERS +1 -0
@@ -27338,6 +27338,7 @@ F: drivers/reset/reset-scmi.c F: include/linux/device-id/scmi.h F: include/linux/sc[mp]i_protocol.h F: include/trace/events/scmi.h +F: include/uapi/linux/scmi.h F: include/uapi/linux/virtio_scmi.h SYSTEM CONTROL MANAGEMENT INTERFACE (SCMI) i.MX Extension Message Protocol drivers
include/uapi/linux/scmi.h new file +533 -0
533 lines not on this page · raw message
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 29/34 firmware: arm_scmi: Add System Telemetry driver
In reply to Cristian MarussiAdd an SCMI driver to allow enumeration, configuration and data collection of SCMI Telemetry data.
The driver exposes one character device for each found SCMI instance and a set of related IOCTLs can be used to enumerate, configure and collect Telemetry resources.
---
v16 --> v17
- return OPNOTSUPP on un-implemented IOCTLs instead of -ENOTTY
- use proper IS_GROUP macros to discard GROUP request across IOCTLs
v15 --> v16
- removed group related IOCTLs
- removed single sample read IOCTLs
- removed reset IOCTL suppport
- removed events IOCTL
- remove unsupported features from ABI features
- clear out->flags in uapi_info
- cap ABI INFO usize to PAGE_SIZE
- sanitize input update interval
- add missing pad/reserved checks in input
v14 --> v15
- reject config attempts and intervals query for groups that do not support per-group config
- harden/simplify batch helpers
- fix shmti mmap size check to include offset
- drop usage of sdev->dev in device_release
- simplify session_unsubscribe cleanup on exit/unbind
- added missing kref.h include
- expose TLM EVENTS capabilities ONLY IF CONFIG_EVENTFD
- mmap: check/clear also VM_EXEC VM_MAYWRITE VM_MAYEXEC
- reject non zero vm_pgoff
- drop usage of guard(srcu) to avoid races with put_device
v13 --> v14
- avoid double free on probe err path
- grab ctx and check if dead when mmapping an anon_fd
- move away from dead_mtx in favour of dead_srcu and extend srcu'ed section in ioctl handler
v12 --> v13
- pass back E2BIG from copy_struct_from_user to userspace
- remove a few redundant copy_from_user
- fix filedescriptor lifecycle: drop kref in favour of embedded cdev and use cdev_device_add. Rely on devm_protocol_get for proto_ops
- refactor EVENT session unsubscribe and check for aliveness
- use *alloc_objs
v11 --> v12
- added RCU deref access on UUIDs
- dropped needless copy_from_user on states_batch
- fixed double free on anon ids error path
- reworked eventfd handling using per-session tracking and cleanup on chardev last release
- properly free also ti->tsp on error path
- properly acquire/release sdev->dev via get/put_device
v10 --> v11
- make SCMI tlm_<N> devices 664 by default
- add 0-sized query support for all the NON _LIST remaining BATCH ops
- add 0-sized query support on GET_INTRVS
- add 0-sized query support on BULOK/SINGLE reads
v8 --> v9
- Fix some Sashiko reports on v8
- use kvmalloc/kvcalloc for all buffers with user/FW generated size
- add a proper upper bounds checks on IOCTL requests
- make SET_ALL_CFG carry on after a failure (reporting last error anyway)
- properly initialize some possibly unused stack vars
- refactor SHMTIs list processing and ANON fds allocation to avoid leaking fds by premature installing them into process.
- completely rework cdev and scmi_tlm_instance interactions and lifecycle and drop all devres allocation: reject fops on cdev after driver unbind and delay data structures freeing till the last reference has been dropped.
- reworked BATCH helpers to handle ZERO items requests (for IOCTL query)
- reworked all the _LIST IOCTLs to use scmi_tlm_batch as a container structure instead of custom structs
- add support for 0-items query pattern to all _LIST IOCTLs
v7 --> v8
- Fixes for some Sashiko issues on v7
- refactor batch handling into common batch init/fini routines
- use array_size to check for overflows
- explain cleanup logic of eventfd_ctx (xa_for_each)
- add a mutex to protect events_xa
- introduce per-IOCTL check on batch upper bounds
v6 --> v7
- fixed module_init errors paths
- introduced a check on FMODE to filter-out unprivleged writers
- added UUID list IOCTL
- added UUID/SID/OFFS tp GET/SET config IOCTLs
- added EVENT subscribe IOCTL
- modified BATCH READ with per-DE status
- added BATCHed mode for DE_CFG_SET/GET
- fix setting properly discrete interval flag
- new ABI feats flags\
- new SCMI feats flags
- new reserved checks
v5 --> v6
- drop hunam readable .read capabilities on chardev
- fill-up the new UAPI de_implementation version u8 array
- added compat_ioctl support
- fixed initialization of flags in scmi_tlm_to_uapi_base_info
- fix grp_id bounds check in scmi_tlm_grp_info_get_ioctl
- fix booleans
- fix SHMTI get list to loop on input params
- reworked bounds checks into:
- scmi_tlm_intervals_get_ioctl
- scmi_tlm_des_list_get_ioctl
- scmi_tlm_grp_list_get_ioctl
- scmi_tlm_grp_desc_get_ioctl
- renamed some READ ioctl to be consistent
- reject oversized mmap requests
- support new GET_ABI_INFO IOCTL
- support RESET IOCTL
- add a missing READ_ONCE() to rinfo get
- avoid gaps in the anon fds returned array needed by shmti mmap
- adding missing cdev_del on remove
--- drivers/firmware/arm_scmi/Kconfig | 10 + drivers/firmware/arm_scmi/Makefile | 1 + .../firmware/arm_scmi/scmi_system_telemetry.c | 1376 +++++++++++++++++ 3 files changed, 1387 insertions(+) create mode 100644 drivers/firmware/arm_scmi/scmi_system_telemetry.c
drivers/firmware/arm_scmi/Kconfig +10 -0
@@ -113,4 +113,14 @@ config ARM_SCMI_POWER_CONTROL called scmi_power_control. Note this may be needed early in boot to catch early shutdown/reboot SCMI requests. +config ARM_SCMI_SYSTEM_TELEMETRY + tristate "SCMI System Telemetry driver" + depends on ARM_SCMI_PROTOCOL || (COMPILE_TEST && OF) + help + This enables SCMI Systemn Telemetry support that allows userspace to + retrieve ARM Telemetry data made available via SCMI. + + This driver can also be built as a module. If so, the module will be + called scmi_system_telemetry. + endmenu
drivers/firmware/arm_scmi/Makefile +1 -0
@@ -18,3 +18,4 @@ obj-$(CONFIG_ARM_SCMI_PROTOCOL) += scmi-core.o obj-$(CONFIG_ARM_SCMI_PROTOCOL) += scmi-module.o obj-$(CONFIG_ARM_SCMI_POWER_CONTROL) += scmi_power_control.o +obj-$(CONFIG_ARM_SCMI_SYSTEM_TELEMETRY) += scmi_system_telemetry.o
drivers/firmware/arm_scmi/scmi_system_telemetry.c new file +1376 -0
1,376 lines not on this page · raw message
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 30/34 firmware: arm_scmi: Enable autoloading for System Telemetry driver
In reply to Cristian MarussiAdd the SCMI System Telemetry driver and related protocols to the list of standard protocols whosw devices are created automatically, so enabling module autoloading.
--- drivers/firmware/arm_scmi/bus.c | 1 + 1 file changed, 1 insertion(+)
drivers/firmware/arm_scmi/bus.c +1 -0
@@ -546,6 +546,7 @@ static const struct scmi_device_id scmi_std_id_table[] = { { SCMI_PROTOCOL_POWERCAP, "powercap" }, { SCMI_PROTOCOL_PINCTRL, "pinctrl" }, { SCMI_PROTOCOL_PINCTRL, "pinctrl-imx" }, + { SCMI_PROTOCOL_TELEMETRY, "telemetry" }, { }, };
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 31/34 docs: ioctl-number: Add SCMI Ioctls
In reply to Cristian MarussiAdd SCMI Subsystem IOCTLs numbers
--- Documentation/userspace-api/ioctl/ioctl-number.rst | 1 + 1 file changed, 1 insertion(+)
Documentation/userspace-api/ioctl/ioctl-number.rst +1 -0
@@ -403,6 +403,7 @@ Code Seq# Include File Comments 0xEC 00-01 linux/platform_data/cros_ec_chardev.h ChromeOS EC driver 0xEE 00-09 uapi/linux/pfrut.h Platform Firmware Runtime Update and Telemetry 0xEF 00-0F uapi/linux/ntfs.h NTFS +0xF1 00-FF uapi/linux/scmi.h ARM SCMI Subsystem 0xF3 00-3F drivers/usb/misc/sisusbvga/sisusb.h sisfb (in development) <mailto:[email protected]> 0xF6 all LTTng Linux Trace Toolkit Next Generation
Signature · 1 line
2.54.0
Cristian Marussi
reviewerRFC PATCH v17 32/34 Documentation: Add SCMI System Telemetry documentation
In reply to Cristian MarussiDocument ARM SCMI Telemetry IOCTLs interface.
--- Documentation/userspace-api/index.rst | 1 + Documentation/userspace-api/stlm.rst | 590 ++++++++++++++++++++++++++ 2 files changed, 591 insertions(+) create mode 100644 Documentation/userspace-api/stlm.rst
Documentation/userspace-api/index.rst +1 -0
@@ -54,6 +54,7 @@ Devices and I/O dcdbas vduse isapnp + stlm Everything else ===============
Documentation/userspace-api/stlm.rst new file +590 -0
590 lines not on this page · raw message
Signature · 1 line
2.54.0
Cristian Marussi
reviewerPATCH v17 33/34 kselftest/arm64: Add SCMI Telemetry UAPI compliance testcases
In reply to Cristian MarussiFrom: Philip Radford <[email protected]>
Add support to test SCMI Telemetry UAPI compliance testcases.
--- tools/testing/selftests/arm64/Makefile | 2 +- tools/testing/selftests/arm64/scmi/Makefile | 12 + tools/testing/selftests/arm64/scmi/config | 2 + .../arm64/scmi/test_scmi_telemetry_uapi.c | 2034 +++++++++++++++++ 4 files changed, 2049 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/arm64/scmi/Makefile create mode 100644 tools/testing/selftests/arm64/scmi/config create mode 100644 tools/testing/selftests/arm64/scmi/test_scmi_telemetry_uapi.c
tools/testing/selftests/arm64/Makefile +1 -1
@@ -4,7 +4,7 @@ ARCH ?= $(shell uname -m 2>/dev/null || echo not) ifneq (,$(filter $(ARCH),aarch64 arm64)) -ARM64_SUBTARGETS ?= tags signal pauth fp mte bti abi gcs +ARM64_SUBTARGETS ?= tags signal pauth fp mte bti abi gcs scmi else ARM64_SUBTARGETS := endif
tools/testing/selftests/arm64/scmi/Makefile new file +12 -0
@@ -0,0 +1,12 @@ +# SPDX-License-Identifier: GPL-2.0 +# Copyright (C) 2026 ARM Limited + +# Additional include paths needed by kselftest.h and local headers +CFLAGS += -std=gnu99 -I. +LDFLAGS += -static + +# Generated binaries to be installed by top KSFT script +TEST_GEN_PROGS := test_scmi_telemetry_uapi + +# Include KSFT lib.mk. +include ../../lib.mk
tools/testing/selftests/arm64/scmi/config new file +2 -0
@@ -0,0 +1,2 @@ +CONFIG_ARM_SCMI_SYSTEM_TELEMETRY=y +
tools/testing/selftests/arm64/scmi/test_scmi_telemetry_uapi.c new file +2034 -0
2,034 lines not on this page · raw message
Signature · 1 line
2.54.0
Cristian Marussi
reviewerRFC PATCH v17 34/34 tools/testing/scmi: Add SCMI Telemetry testing tool
In reply to Cristian MarussiAdd a testing tool that exercises the SCMI ioctls UAPI interface: as of now the tool simply queries the initial state of the SCMI Telemetry subsystem, tries to enable all the existent Data Events and dumps all the Telemetry data.
---
v15v --> v16
- handle new abi_features GROUPS/SINGLE_SAMPLE
--- MAINTAINERS | 1 + tools/testing/scmi/Makefile | 25 + tools/testing/scmi/stlm.c | 1698 ++++++++++++++++++++++++++++++ tools/testing/scmi/stlm_decode.c | 252 +++++ tools/testing/scmi/stlm_decode.h | 7 + 5 files changed, 1983 insertions(+) create mode 100644 tools/testing/scmi/Makefile create mode 100644 tools/testing/scmi/stlm.c create mode 100644 tools/testing/scmi/stlm_decode.c create mode 100644 tools/testing/scmi/stlm_decode.h
MAINTAINERS +1 -0
@@ -27340,6 +27340,7 @@ F: include/linux/sc[mp]i_protocol.h F: include/trace/events/scmi.h F: include/uapi/linux/scmi.h F: include/uapi/linux/virtio_scmi.h +F: tools/testing/scmi/ SYSTEM CONTROL MANAGEMENT INTERFACE (SCMI) i.MX Extension Message Protocol drivers M: Peng Fan <[email protected]>
tools/testing/scmi/Makefile new file +25 -0
@@ -0,0 +1,25 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +CC=$(CROSS_COMPILE)gcc +OBJS = stlm.o stlm_decode.o + +CFLAGS=-Wall -static -std=gnu11 -I ../../../include/uapi/ +ifneq ($(DEBUG), ) + CFLAGS+=-O0 -g -ggdb +else + CFLAGS+=-static +endif + +all: stlm + +stlm: $(OBJS) + $(CC) $(CFLAGS) $^ -o $@ + +%.o: %.c + $(CC) $(CFLAGS) -c $< + +clean: + rm -f *.o + rm -f stlm + +.PHONY: clean
tools/testing/scmi/stlm.c new file +1698 -0
1,698 lines not on this page · raw message
tools/testing/scmi/stlm_decode.c new file +252 -0
252 lines not on this page · raw message
tools/testing/scmi/stlm_decode.h new file +7 -0
@@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef __STLM_DECODE_H +#define __STLM_DECODE_H + +int tdcf_decode (const void *buf,size_t len); + +#endif
Signature · 1 line
2.54.0
Quoted 11 lines · On Tue, 24 Nov 2026 19:48:06 +0000 Cristian Marussi <[email protected]>…
Hi all,
[TLDR Summary]
[V17 highlights]
- addressed more Sashiko reports
- added a few more SCMI Core fixes that ease per-protocol logic:
+ added more consistency in the SCMI Core Iterators machinery
+ added centralized check (SCMI Core) for truncated reply
+ Reworked some SCM Clock behaviour to allow for truncated checks
+ SCMI protocol core initialization refactor and fixes
Quoted 3 lines
[V18 TODO]
- address any remaining outstanding Sashiko/reviewers issues
- address pending human reviews feedback
I'm lost.
Does this mean humans should wait for v18? I'll assume not and take a look anyway...
Sashiko is moderately easy to run locally as long as your company isn't too restrictive with tokens (if they are say upstream folk are complaining and ask for more!). Might not be exactly the same as the version here but will reduce the noise and versions on list.
Jonathan
Cristian Marussi
reviewerQuoted 19 lines · Jonathan Cameron
Quoted 11 lines · On Tue, 24 Nov 2026 19:48:06 +0000 Cristian Marussi <[email protected]>…
Hi all,
[TLDR Summary]
[V17 highlights]
- addressed more Sashiko reports
- added a few more SCMI Core fixes that ease per-protocol logic:
+ added more consistency in the SCMI Core Iterators machinery
+ added centralized check (SCMI Core) for truncated reply
+ Reworked some SCM Clock behaviour to allow for truncated checks
+ SCMI protocol core initialization refactor and fixesQuoted 3 lines
[V18 TODO]
- address any remaining outstanding Sashiko/reviewers issues
- address pending human reviews feedbackI'm lost.
Quoted 7 lines
Does this mean humans should wait for v18? I'll assume not and take a look anyway...
Sashiko is moderately easy to run locally as long as your company isn't too restrictive with tokens (if they are say upstream folk are complaining and ask for more!). Might not be exactly the same as the version here but will reduce the noise and versions on list.
Hi,
What I failed to express is that there are still some reports to address both from LLMs generated reviews and human reviewers.
We do run local LLM reviews (multiple versions of them really), that together with the public Sashiko instance and the human reviewers generates a LOT of mostly good and interesting things to look at, BUT such reports most of the time point out different things (depending on the LLM backend or frontend version) which is good but rapidly overwhelming: so in the interest of timely progress I try to address a mix of both upon each posting, but given the load, usually when I post a new series, there could be still be outstanding issues from both sides of the review world, human and not, that I plan to address next...or simply unknown new issue that will be spotted later by human/LLM reviewes even on the same exact codebase.
...so in a nutshell what I was trying to express was simply that, even if some comments are still not addressed/replied, I am NOT ignoring human reviewers (i.e. You mainly) nor LLM generated ones BUT the amount of work for read_reports/fix_it/testing/replies is overwhelming, so in the interest of costant progress I DO sometimes post knowingly less-than-perfect series (maybe focusing more on refining some part than other as an example)
...if NOT there would be probably longer than desired gaps between posting without anyway the guarantee of perfection, given that when I did try to address ALL the outstanding reports in a go a few weeks ago, I got anyway a huge load of brand new issues flagged next...(in these regards LLM do behave like humans...spotting new stuff from version to version :D)
So yes...I gave up on the mirage of complete perfection and instead aiming at addressing issues the best I can to allow me to post week after week a codebase which is increasingly better and improved but still functional and tested...especially since it is apparent from our last discussion on this list that this whol feature wont be merged in one go so what is the point of trying to tidy up to perfection all in one go...
The TDLR summary at the start of the blob was meant to be a heads-up to avoid people thinking I am happily ignoring them :P ...
...but it clearly failed miserably in its mission...so I will drop the useless TLDR next time.
Thanks,
Cristian
Quoted 10 lines · Cristian Marussi
[TLDR Summary]
[V17 highlights]
- addressed more Sashiko reports
- added a few more SCMI Core fixes that ease per-protocol logic:
+ added more consistency in the SCMI Core Iterators machinery
+ added centralized check (SCMI Core) for truncated reply
+ Reworked some SCM Clock behaviour to allow for truncated checks
+ SCMI protocol core initialization refactor and fixes[...]
Applied to first 9 patches sudeep.holla/linux (for-next/arm_fw/updates), thanks!
[01/34] firmware: arm_scmi: Harden iterators state parsing
https://git.kernel.org/sudeep.holla/c/2f230c3714f1 [02/34] firmware: arm_scmi: Additional iterators consistency checks https://git.kernel.org/sudeep.holla/c/b7c4069735cb [03/34] firmware: arm_scmi: Make Clock attributes size deterministic https://git.kernel.org/sudeep.holla/c/d35843464f51 [04/34] firmware: arm_scmi: Add centralized detection of truncated replies https://git.kernel.org/sudeep.holla/c/5b07c36129e7 [05/34] firmware: arm_scmi: Introduce a dedicated SCMI Errors header https://git.kernel.org/sudeep.holla/c/20d136413e0c [06/34] firmware: arm_scmi: Add new SCMIv4.0 error codes definitions https://git.kernel.org/sudeep.holla/c/2dfeafbda2d7 [07/34] firmware: arm_scmi: Allow registration of unknown-size events/reports https://git.kernel.org/sudeep.holla/c/0a8624160377 [08/34] firmware: arm_scmi: Refactor __scmi_event_handler_get_ops helper https://git.kernel.org/sudeep.holla/c/cb96c7c1ed1a [09/34] dt-bindings: firmware: arm,scmi: Add support for telemetry protocol https://git.kernel.org/sudeep.holla/c/00591d75250a
Signature · 2 lines
Regards, Sudeep