Skip to contentSkip to conversation

Intro to Hardware timestamping engine

RFC Superseded Dipen Patel 12 participants 78 messages Jun 25, 2021 – Sep 26, 2021 Page 1 of 2

Subsystems (7)

v1 of 6 Superseded Latest is v6 →

lore
Share & tools
lore

Dipen Patel

author maintainer
#0 lore raw

cover Intro to Hardware timestamping engine

This patch series introduces new subsystem called hardware timestamping engine (HTE). It offers functionality such as timestamping through hardware means in realtime. The HTE subsystem centralizes HTE provider and consumers where providers can register themselves with subsystem and the consumers can request interested entity which could be lines, GPIO, signals or buses. The HTE subsystem provides timestamp in nano seconds, having said that the provider need to convert the timestamp if its not in that unit. There was upstream discussion about the same at
https://lore.kernel.org/lkml/[email protected]/

To summarize upstream discussion:
- It was heavily favoured by Linus and Kent to extend GPIOLIB and supporting GPIO drivers to add HTE functionality and I agreed to experiment with it. This patch series implements and extends GPIOLIB and GPIO tegra driver.
- Discussed possibility to add HTE provider as irqchip instead which was argued against as HTE devices are not necessarily event emitting devices.
- Discussed other possibility if HTE device can be added as posix clock type like PTP clocks. That was also argues against since HTE devices are not necessarily tightly coupled with hardware clock.

Typical HTE provider does following:
- Register itself with HTE subsystem
- Provide *request, *release, *enable, *disable timestamp callbacks and optional get_clk_src_info callback to HTE subsystem.
- Provide optional xlate callback to the subsystem which can translate consumer provided logical ids into actual ids of the entity, where entity here is the provider dependent and could be GPIO, in chip lines or signals, buses etc...This converted id will be used between HTE subsystem and the provider for below bullet point.
- Push timestamps to the subsystem. This happens when HTE provider has timestamp data available and willing to push it to HTE subsystem. The HTE subsystem stores it into software buffer for the consumers.
- Unregister itself

Typical HTE consumer does following:
- Request interested entity it wishes to timestamp in realtime to the subsystem. During this call HTE subsystem allocates software buffer to store timestamps data.
- The subsystem does necessary communications with the provider to complete the request, which includes translating logical id of the entity to provider dependent physical/actual id and enabling hardware timestamping on requested id.
- It can optionally specify callback during registration, this cb will be called when provider pushes timestamps. Once notified through cb, the consumer can call retrieve API to read the data from the software buffer. If cb is not provided, the consumers can elect to call blocking version of retrieve API.
- Manage pre allocated software buffer if needed. It includes changing buffer length and watermark/threshold. The subsystem automatically sets watermark or threshold at 1, consumers can later change it to any other value it wishes. The main purpose for having threshold functionality is to notify consumer either through callback if provided or unblock waiting consumer when threshold is reached.
- Retrieve timestamp using various means provided by subsystem.
- Release entity and its resources.

HTE and GPIOLIB:
- For the HTE provider which can timestamp GPIO lines.
- For the GPIO consumers, either in kernel or userspace, The GPIOLIB and its CDEV framework are extended as frontend to the HTE by introducing new APIs.
- Tegra194 AON GPIO controller has HTE support also known as GTE (Generic Timestamping Engine). The tegra gpio driver is modified to accommodate HTE functionality.

Dipen Patel (11):
Documentation: Add HTE subsystem guide
drivers: Add HTE subsystem
hte: Add tegra194 HTE kernel provider
dt-bindings: Add HTE bindings
hte: Add Tegra194 IRQ HTE test driver
gpiolib: Add HTE support
gpio: tegra186: Add HTE in gpio-tegra186 driver
gpiolib: cdev: Add hardware timestamp clock type
tools: gpio: Add new hardware clock type
hte: Add tegra GPIO HTE test driver
MAINTAINERS: Added HTE Subsystem

 .../bindings/gpio/nvidia,tegra186-gpio.txt    |    7 +
 .../devicetree/bindings/hte/hte-consumer.yaml |   47 +
 .../devicetree/bindings/hte/hte.yaml          |   34 +
 .../bindings/hte/nvidia,tegra194-hte.yaml     |   83 +
 Documentation/hte/hte.rst                     |  198 +++
 Documentation/hte/index.rst                   |   21 +
 Documentation/hte/tegra194-hte.rst            |   65 +
 Documentation/index.rst                       |    1 +
 MAINTAINERS                                   |    8 +
 drivers/Kconfig                               |    2 +
 drivers/Makefile                              |    1 +
 drivers/gpio/gpio-tegra186.c                  |   78 +
 drivers/gpio/gpiolib-cdev.c                   |   65 +-
 drivers/gpio/gpiolib.c                        |   92 ++
 drivers/gpio/gpiolib.h                        |   11 +
 drivers/hte/Kconfig                           |   49 +
 drivers/hte/Makefile                          |    4 +
 drivers/hte/hte-tegra194-gpio-test.c          |  255 +++
 drivers/hte/hte-tegra194-irq-test.c           |  400 +++++
 drivers/hte/hte-tegra194.c                    |  554 +++++++
 drivers/hte/hte.c                             | 1368 +++++++++++++++++
 include/linux/gpio/consumer.h                 |   21 +-
 include/linux/gpio/driver.h                   |   13 +
 include/linux/hte.h                           |  278 ++++
 include/uapi/linux/gpio.h                     |    1 +
 tools/gpio/gpio-event-mon.c                   |    6 +-
 26 files changed, 3657 insertions(+), 5 deletions(-)
 create mode 100644 Documentation/devicetree/bindings/hte/hte-consumer.yaml
 create mode 100644 Documentation/devicetree/bindings/hte/hte.yaml
 create mode 100644 Documentation/devicetree/bindings/hte/nvidia,tegra194-hte.yaml
 create mode 100644 Documentation/hte/hte.rst
 create mode 100644 Documentation/hte/index.rst
 create mode 100644 Documentation/hte/tegra194-hte.rst
 create mode 100644 drivers/hte/Kconfig
 create mode 100644 drivers/hte/Makefile
 create mode 100644 drivers/hte/hte-tegra194-gpio-test.c
 create mode 100644 drivers/hte/hte-tegra194-irq-test.c
 create mode 100644 drivers/hte/hte-tegra194.c
 create mode 100644 drivers/hte/hte.c
 create mode 100644 include/linux/hte.h
Signature · 1 line
2.17.1
author maintainer
#1 lore raw

RFC 1/11 Documentation: Add HTE subsystem guide

Adding hte document which can help understand various APIs implemented in HTE framework for the HTE producers and the consumers.

---
 Documentation/hte/hte.rst | 198 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 198 insertions(+)
 create mode 100644 Documentation/hte/hte.rst
Documentation/hte/hte.rst new file +198 -0
new file mode 100644
index 000000000000..11744dbc6d16
@@ -0,0 +1,198 @@
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+:Author: Dipen Patel
+
+Introduction
+------------
+
+The certain devices have the built in hardware timestamping engine which can
+monitor sets of system signals, lines, buses etc... in realtime for the state
+change; upon detecting the change it can automatically store the timestamp at
+the moment of occurrence. Such functionality may help achieve better accuracy
+in obtaining timestamp than using software counterparts i.e. ktime and friends.
+
+This document describes the API that can be used by hardware timestamping
+engine provider and consumer drivers that want to use the hardware timestamping
+engine (HTE) framework.
+
+The HTE framework APIs for the providers
+----------------------------------------
+Each driver must #include <linux/hte.h>. The ``linux/hte.h`` declares the
+following functions for the provider:
+
+.. c:function:: int hte_register_chip( struct hte_chip *chip )
+		int hte_unregister_chip( struct hte_chip *chip )
+
+	The provider uses these APIs to un/register itself with HTE framework.
+
+.. c:function:: int hte_push_ts_ns_atomic( const struct hte_chip *chip, u32 xlated_id, struct hte_ts_data *data, size_t n )
+
+	The provider pushes timestamp data in nano seconds unit using this API.
+
+The detail about parameters and API usage are described in each functions
+definitions in ``drivers/hte/hte.c`` file.
+
+The HTE framework APIs for the consumers
+----------------------------------------
+The consumers use following APIs to control the line for the timestamp:
+
+.. c:function:: int hte_release_ts( struct hte_ts_desc *desc )
+		int devm_hte_release_ts( struct device *dev, struct hte_ts_desc *desc )
+
+	The consumer uses API to release specified desc from timestamping.
+	The API frees resources associated with the desc and disables the
+	timestamping on it. The later is managed version of the same API.
+
+.. c:function:: struct hte_ts_desc *of_hte_request_ts( struct device *dev, const char *label, void (*cb)(enum hte_notify n) )
+		struct hte_ts_desc *devm_of_hte_request_ts( struct device *dev, const char *label, void (*cb)(enum hte_notify n) )
+
+	The consumers can use above request APIs to request real timestamp
+	capability on specified entity. The later is resource managed version
+	of the of_hte_request_ts API. Both the APIs expect consumer to follow
+	device tree bindings for the HTE consumer. The details about binding
+	is in ``Documentation/devicetree/bindings/hte/hte-consumer.yaml``.
+
+.. c:function:: struct hte_ts_desc *hte_req_ts_by_dt_node( struct device_node *of_node, unsigned int id, void (*cb)(enum hte_notify n) )
+
+	The consumer can request timestamping directly specifying provider
+	device tree node.
+
+.. c:function:: int hte_enable_ts( struct hte_ts_desc *desc )
+.. c:function:: int hte_disable_ts( struct hte_ts_desc *desc )
+
+	The consumer can enable/disable timestamping on given desc.
+
+.. c:function:: int hte_retrieve_ts_ns( const struct hte_ts_desc *desc, struct hte_ts_data *el, size_t n )
+		int hte_retrieve_ts_ns_wait( const struct hte_ts_desc *desc, struct hte_ts_data *el, size_t n )
+
+	The consumer uses above two API versions to get/retrieve timestamp data
+	for the given desc. The later is blocking version.
+
+.. c:function:: hte_get_clk_src_info(const struct hte_line_desc *desc, struct hte_clk_info *ci)
+
+	The consumer retrieves clock source information that provider uses to
+	timestamp entity in the structure hte_clk_info. This information
+	specifies clock rate in HZ and clock.
+
+The details on struct hte_clk_info
+-----------------------------------
+This structure presents detail of the hardware clock that provider uses for
+realtime timestamping purposes. The consumer can use hte_get_clk_src_info API
+to get the information in hte_clk_info structure. It has hz and type parameters
+where hz represents clock rate in HZ and type is clock type of clockid_t and
+of CLOCK_* family (for example, CLOCK_MONOTONIC).
+
+The consumers calling of_hte_request_ts or hte_req_ts_by_dt_node APIs with
+cb parameter set, usually will call hte_retrieve_ts (non blocking
+version) after being notified by the callbacks from HTE subsystem. The
+consumers calling those requests APIs with cb parameter NULL, usually will call
+hte_retrieve_ts_wait API.
+
+The HTE subsystem provides software buffer per requested id/entity to store
+timestamp data (struct hte_ts_data type). The consumers can manage the buffer.
+It also provides buffer watermark which can notify (if cb parameter is provided
+during request API call) consumer or unblock consumers calling
+hte_retrieve_ts_wait API. The following APIs are used to manipulate the
+software buffer:
+
+.. c:function:: int hte_set_buf_len( const struct hte_ts_desc *desc,unsigned int len )
+		int hte_get_buf_len( const struct hte_ts_desc *desc )
+
+	The consumer uses above APIs to set/get software buffer depth.
+
+.. c:function:: int hte_set_buf_watermark( const struct hte_ts_desc *desc, unsigned int val )
+		int hte_get_buf_watermark( const struct hte_ts_desc *desc )
+
+	The consumer uses above APIs to set/get software threshold, threshold
+	can be used to notity or unblock waiting consumer when data becomes
+	available equal or above to threshold value.
+
+.. c:function:: size_t hte_available_ts( const struct hte_ts_desc *desc )
+
+	The consumer uses above API to get available timestamp data stored
+	in the software buffer for the desc.
+
+The detail about parameters and API usage are described in each functions
+definitions in ``drivers/hte/hte.c`` file.
+
+The HTE timestamp element detail
+--------------------------------
+The struct hte_ts_data, declared at ``include/linux/hte.h``, is used to pass
+timestamp details between the consumers and the providers. It expresses
+timestamp data in nano second in u64 data type. For now all the HTE APIs
+using struct hte_ts_data requires tsc to be in nano seconds. The timestamp
+element structure stores below information along with timestamp data::
+
+ struct hte_ts_data {
+	/*
+	 * Timestamp value
+	 */
+	u64 tsc;
+	/*
+	 * The sequence counter, keep track of the number of timestamps.
+	 * It can be used to check if data is dropped in between.
+	 */
+	u64 seq;
+	/* Direction of the event, i.e. falling or rising */
+	int dir;
+ };
+
+The typical hte_ts_data data life cycle::
+In this example the provider provides timestamp in nano seconds and for the
+GPIO line::
+
+ - Monitors GPIO line change.
+ - Detects the state change on GPIO line.
+ - Converts timestamps in nano seconds and stores it in tsc.
+ - Stores GPIO direction in dir variable if the provider has that hardware
+ capability.
+ - Pushes this hte_timestamp_el object to HTE subsystem.
+ - HTE subsystem increments seq counter and stores it in software buffer
+ dedicated to requested GPIO line.
+ - Waiting consumer gets notified.
+ - The consumer calls the retrieve timestamp API.
+
+HTE subsystem debugfs attributes
+--------------------------------
+HTE subsystem creates debugfs attributes at ``/sys/kernel/debug/hte/``.
+It also creates line/signal related debugfs attributes at
+``/sys/kernel/debug/hte/<provider>/<label or line id>/``.
+
+`ts_requested`
+		The total number of entities requested from the given provider,
+		where entity is the provider specific and could represent
+		lines, GPIO, chip signals, buses etc...
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/``.
+
+		Read only value
+
+`total_ts`
+		The total number of entities supported by the provider.
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/``.
+
+		Read only value
+
+`ts_buffer_depth`
+		The software buffer lenth to store timestamp data.
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/<label or id>/``.
+
+		Read only value
+
+`ts_buffer_watermark`
+		The software buffer watermark or threshold.
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/<label or line id>/``.
+
+		Read only value
+
+`dropped_timestamps`
+		The dropped timestamps for a given line.
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/<label or line id>/``.
+
+		Read only value
Signature · 1 line
2.17.1
maintainer
#2 lore raw

Re: [RFC 01/11] Documentation: Add HTE subsystem guide

Quoted 4 lines · On Fri, 25 Jun 2021 16:55:22 -0700 Dipen Patel <[email protected]> wrote:

Adding hte document which can help understand various APIs implemented in HTE framework for the HTE producers and the consumers.

Some editorial stuff inline. (I can't resist even on RFCs)

Certainly interesting. I'm running a bit tight on time today, so not sure how much of the code I'll get a chance to look at. Will try to get to it soon though.

Jonathan

Quoted 11 lines
---
 Documentation/hte/hte.rst | 198 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 198 insertions(+)
 create mode 100644 Documentation/hte/hte.rst
Documentation/hte/hte.rst new file +0 -0
new file mode 100644
index 000000000000..11744dbc6d16

Documentation/hte/hte.rst line 10

Quoted 10 lines
Documentation/hte/hte.rst new file +10 -0
@@ -0,0 +1,198 @@
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+:Author: Dipen Patel
+
+Introduction
+------------
+
+The certain devices have the built in hardware timestamping engine which can

Certain devices have built in hardware timestamping engines which can

Documentation/hte/hte.rst line 11

Quoted 1 line
Documentation/hte/hte.rst new file +1 -0
+monitor sets of system signals, lines, buses etc... in realtime for the state

for state changes;

Documentation/hte/hte.rst line 12

Quoted 1 line
Documentation/hte/hte.rst new file +1 -0
+change; upon detecting the change it can automatically store the timestamp at

they can

Quoted 18 lines
Documentation/hte/hte.rst new file +18 -0
+the moment of occurrence. Such functionality may help achieve better accuracy
+in obtaining timestamp than using software counterparts i.e. ktime and friends.
+
+This document describes the API that can be used by hardware timestamping
+engine provider and consumer drivers that want to use the hardware timestamping
+engine (HTE) framework.
+
+The HTE framework APIs for the providers
+----------------------------------------
+Each driver must #include <linux/hte.h>. The ``linux/hte.h`` declares the
+following functions for the provider:
+
+.. c:function:: int hte_register_chip( struct hte_chip *chip )
+		int hte_unregister_chip( struct hte_chip *chip )
+
+	The provider uses these APIs to un/register itself with HTE framework.
+
+.. c:function:: int hte_push_ts_ns_atomic( const struct hte_chip *chip, u32 xlated_id, struct hte_ts_data *data, size_t n )

Documentation/hte/hte.rst line 40

Quoted 10 lines
Documentation/hte/hte.rst new file +10 -0
+
+	The provider pushes timestamp data in nano seconds unit using this API.
+
+The detail about parameters and API usage are described in each functions
+definitions in ``drivers/hte/hte.c`` file.
+
+The HTE framework APIs for the consumers
+----------------------------------------
+The consumers use following APIs to control the line for the timestamp:
+

When documenting APIs you may well be better including a reference to the files themselves and using kernel doc there. The documentation build can then pull that in when creating the html docs etc (and crucially you don't have to provide the
same docs in two places.). Having them here is very convenient for the RFC however :)

Quoted 10 lines
Documentation/hte/hte.rst new file +10 -0
+.. c:function:: int hte_release_ts( struct hte_ts_desc *desc )
+		int devm_hte_release_ts( struct device *dev, struct hte_ts_desc *desc )
+
+	The consumer uses API to release specified desc from timestamping.
+	The API frees resources associated with the desc and disables the
+	timestamping on it. The later is managed version of the same API.
+
+.. c:function:: struct hte_ts_desc *of_hte_request_ts( struct device *dev, const char *label, void (*cb)(enum hte_notify n) )
+		struct hte_ts_desc *devm_of_hte_request_ts( struct device *dev, const char *label, void (*cb)(enum hte_notify n) )
+

Documentation/hte/hte.rst line 60

Quoted 10 lines
Documentation/hte/hte.rst new file +10 -0
+	The consumers can use above request APIs to request real timestamp
+	capability on specified entity. The later is resource managed version
+	of the of_hte_request_ts API. Both the APIs expect consumer to follow
+	device tree bindings for the HTE consumer. The details about binding
+	is in ``Documentation/devicetree/bindings/hte/hte-consumer.yaml``.
+
+.. c:function:: struct hte_ts_desc *hte_req_ts_by_dt_node( struct device_node *of_node, unsigned int id, void (*cb)(enum hte_notify n) )
+
+	The consumer can request timestamping directly specifying provider
+	device tree node.

When does this make sense?

Quoted 28 lines
Documentation/hte/hte.rst new file +28 -0
+
+.. c:function:: int hte_enable_ts( struct hte_ts_desc *desc )
+.. c:function:: int hte_disable_ts( struct hte_ts_desc *desc )
+
+	The consumer can enable/disable timestamping on given desc.
+
+.. c:function:: int hte_retrieve_ts_ns( const struct hte_ts_desc *desc, struct hte_ts_data *el, size_t n )
+		int hte_retrieve_ts_ns_wait( const struct hte_ts_desc *desc, struct hte_ts_data *el, size_t n )
+
+	The consumer uses above two API versions to get/retrieve timestamp data
+	for the given desc. The later is blocking version.
+
+.. c:function:: hte_get_clk_src_info(const struct hte_line_desc *desc, struct hte_clk_info *ci)
+
+	The consumer retrieves clock source information that provider uses to
+	timestamp entity in the structure hte_clk_info. This information
+	specifies clock rate in HZ and clock.
+
+The details on struct hte_clk_info
+-----------------------------------
+This structure presents detail of the hardware clock that provider uses for
+realtime timestamping purposes. The consumer can use hte_get_clk_src_info API
+to get the information in hte_clk_info structure. It has hz and type parameters
+where hz represents clock rate in HZ and type is clock type of clockid_t and
+of CLOCK_* family (for example, CLOCK_MONOTONIC).
+
+The consumers calling of_hte_request_ts or hte_req_ts_by_dt_node APIs with
+cb parameter set, usually will call hte_retrieve_ts (non blocking

Documentation/hte/hte.rst line 98

Quoted 10 lines
Documentation/hte/hte.rst new file +10 -0
+version) after being notified by the callbacks from HTE subsystem. The
+consumers calling those requests APIs with cb parameter NULL, usually will call
+hte_retrieve_ts_wait API.
+
+The HTE subsystem provides software buffer per requested id/entity to store
+timestamp data (struct hte_ts_data type). The consumers can manage the buffer.
+It also provides buffer watermark which can notify (if cb parameter is provided
+during request API call) consumer or unblock consumers calling
+hte_retrieve_ts_wait API. The following APIs are used to manipulate the
+software buffer:

Have you come across any devices that have a hardware fifo for these timestamps? It's moderately common on sensor hubs to do so, and then you get into a fun question of how to manage the watermark. You don't want to pull from the hardware too early, but conversely you can get out of sync between the software and hardware buffers if someone reasons less than 'watermark' samples from the software buffer.

Anyhow, it can be entertaining. So in those cases it can be simpler to explicitly provide control of two separate watermarks.

Documentation/hte/hte.rst line 103

Quoted 5 lines
Documentation/hte/hte.rst new file +5 -0
+
+.. c:function:: int hte_set_buf_len( const struct hte_ts_desc *desc,unsigned int len )
+		int hte_get_buf_len( const struct hte_ts_desc *desc )
+
+	The consumer uses above APIs to set/get software buffer depth.

What happens if there is content when it is resized?

Quoted 11 lines
Documentation/hte/hte.rst new file +11 -0
+
+.. c:function:: int hte_set_buf_watermark( const struct hte_ts_desc *desc, unsigned int val )
+		int hte_get_buf_watermark( const struct hte_ts_desc *desc )
+
+	The consumer uses above APIs to set/get software threshold, threshold
+	can be used to notity or unblock waiting consumer when data becomes
+	available equal or above to threshold value.
+
+.. c:function:: size_t hte_available_ts( const struct hte_ts_desc *desc )
+
+	The consumer uses above API to get available timestamp data stored

Documentation/hte/hte.rst

Quoted 10 lines
Documentation/hte/hte.rst new file +10 -0
+	in the software buffer for the desc.
+
+The detail about parameters and API usage are described in each functions
+definitions in ``drivers/hte/hte.c`` file.
+
+The HTE timestamp element detail
+--------------------------------
+The struct hte_ts_data, declared at ``include/linux/hte.h``, is used to pass
+timestamp details between the consumers and the providers. It expresses
+timestamp data in nano second in u64 data type.

I'd suggest s64 to match with kernel timestamp format.

Documentation/hte/hte.rst line 136

Quoted 13 lines

For now all the HTE APIs

Documentation/hte/hte.rst new file +12 -0
+using struct hte_ts_data requires tsc to be in nano seconds. The timestamp
+element structure stores below information along with timestamp data::
+
+ struct hte_ts_data {
+	/*
+	 * Timestamp value
+	 */
+	u64 tsc;
+	/*
+	 * The sequence counter, keep track of the number of timestamps.
+	 * It can be used to check if data is dropped in between.
+	 */

Is this a hardware feature? A bit unusual to have this rather than simple overflow flag to indicate we dropped an unknown number of samples.

Documentation/hte/hte.rst line 139

Quoted 3 lines
Documentation/hte/hte.rst new file +3 -0
+	u64 seq;
+	/* Direction of the event, i.e. falling or rising */
+	int dir;

Given an even could do more than that potentially, or indeed not be able to tell if it was rising or falling, I would suggest an enum to which we can add more options as needed.

Documentation/hte/hte.rst line 150

Quoted 11 lines

+ };

Documentation/hte/hte.rst new file +10 -0
+
+The typical hte_ts_data data life cycle::
+In this example the provider provides timestamp in nano seconds and for the
+GPIO line::
+
+ - Monitors GPIO line change.
+ - Detects the state change on GPIO line.
+ - Converts timestamps in nano seconds and stores it in tsc.
+ - Stores GPIO direction in dir variable if the provider has that hardware
+ capability.

We definitely want to know if it does or not. How does an application query that?

Quoted 3 lines

+ - Pushes this hte_timestamp_el object to HTE subsystem.
+ - HTE subsystem increments seq counter and stores it in software buffer
+ dedicated to requested GPIO line.

Ah. So that seq counter is only for software drops if the fifo fills up.

Quoted 45 lines

+ - Waiting consumer gets notified.
+ - The consumer calls the retrieve timestamp API.

Documentation/hte/hte.rst new file +43 -0
+
+HTE subsystem debugfs attributes
+--------------------------------
+HTE subsystem creates debugfs attributes at ``/sys/kernel/debug/hte/``.
+It also creates line/signal related debugfs attributes at
+``/sys/kernel/debug/hte/<provider>/<label or line id>/``.
+
+`ts_requested`
+		The total number of entities requested from the given provider,
+		where entity is the provider specific and could represent
+		lines, GPIO, chip signals, buses etc...
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/``.
+
+		Read only value
+
+`total_ts`
+		The total number of entities supported by the provider.
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/``.
+
+		Read only value
+
+`ts_buffer_depth`
+		The software buffer lenth to store timestamp data.
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/<label or id>/``.
+
+		Read only value
+
+`ts_buffer_watermark`
+		The software buffer watermark or threshold.
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/<label or line id>/``.
+
+		Read only value
+
+`dropped_timestamps`
+		The dropped timestamps for a given line.
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/<label or line id>/``.
+
+		Read only value
author maintainer
#3 lore raw

Re: [RFC 01/11] Documentation: Add HTE subsystem guide

Quoted 6 lines · Jonathan Cameron
Quoted 3 lines · On Fri, 25 Jun 2021 16:55:22 -0700 Dipen Patel <[email protected]> wrote:

Adding hte document which can help understand various APIs implemented in HTE framework for the HTE producers and the consumers.

Quoted 7 lines
Quoted 1 line

Some editorial stuff inline. (I can't resist even on RFCs)

Certainly interesting. I'm running a bit tight on time today, so not sure how much of the code I'll get a chance to look at. Will try to get to it soon though.

Jonathan

Thanks Jonathan for the review comment and time. My answers inline.

Quoted 24 lines
Quoted 12 lines
---
 Documentation/hte/hte.rst | 198 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 198 insertions(+)
 create mode 100644 Documentation/hte/hte.rst
Documentation/hte/hte.rst new file +0 -0
new file mode 100644
index 000000000000..11744dbc6d16

Documentation/hte/hte.rst line 10

Quoted 10 lines
Documentation/hte/hte.rst new file +10 -0
@@ -0,0 +1,198 @@
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+:Author: Dipen Patel
+
+Introduction
+------------
+
+The certain devices have the built in hardware timestamping engine which can

Certain devices have built in hardware timestamping engines which can

Quoted 5 lines

Documentation/hte/hte.rst line 11

Quoted 1 line
Documentation/hte/hte.rst new file +1 -0
+monitor sets of system signals, lines, buses etc... in realtime for the state

for state changes;

Documentation/hte/hte.rst line 12

Quoted 1 line
Documentation/hte/hte.rst new file +1 -0
+change; upon detecting the change it can automatically store the timestamp at

they can

Will add above in next RFC version2.

Quoted 25 lines
Quoted 25 lines
Documentation/hte/hte.rst new file +24 -0
+the moment of occurrence. Such functionality may help achieve better accuracy
+in obtaining timestamp than using software counterparts i.e. ktime and friends.
+
+This document describes the API that can be used by hardware timestamping
+engine provider and consumer drivers that want to use the hardware timestamping
+engine (HTE) framework.
+
+The HTE framework APIs for the providers
+----------------------------------------
+Each driver must #include <linux/hte.h>. The ``linux/hte.h`` declares the
+following functions for the provider:
+
+.. c:function:: int hte_register_chip( struct hte_chip *chip )
+		int hte_unregister_chip( struct hte_chip *chip )
+
+	The provider uses these APIs to un/register itself with HTE framework.
+
+.. c:function:: int hte_push_ts_ns_atomic( const struct hte_chip *chip, u32 xlated_id, struct hte_ts_data *data, size_t n )
+
+	The provider pushes timestamp data in nano seconds unit using this API.
+
+The detail about parameters and API usage are described in each functions
+definitions in ``drivers/hte/hte.c`` file.
+
Quoted 8 lines

Documentation/hte/hte.rst line 40

Quoted 4 lines
Documentation/hte/hte.rst new file +4 -0
+The HTE framework APIs for the consumers
+----------------------------------------
+The consumers use following APIs to control the line for the timestamp:
+

When documenting APIs you may well be better including a reference to the files themselves and using kernel doc there. The documentation build can then pull that in when creating the html docs etc (and crucially you don't have to provide the
same docs in two places.). Having them here is very convenient for the RFC however :)

You mean to omit description here and put reference to file like ``drivers/hte/hte.c``?

Quoted 14 lines
Quoted 14 lines
Documentation/hte/hte.rst new file +13 -0
+.. c:function:: int hte_release_ts( struct hte_ts_desc *desc )
+		int devm_hte_release_ts( struct device *dev, struct hte_ts_desc *desc )
+
+	The consumer uses API to release specified desc from timestamping.
+	The API frees resources associated with the desc and disables the
+	timestamping on it. The later is managed version of the same API.
+
+.. c:function:: struct hte_ts_desc *of_hte_request_ts( struct device *dev, const char *label, void (*cb)(enum hte_notify n) )
+		struct hte_ts_desc *devm_of_hte_request_ts( struct device *dev, const char *label, void (*cb)(enum hte_notify n) )
+
+	The consumers can use above request APIs to request real timestamp
+	capability on specified entity. The later is resource managed version
+	of the of_hte_request_ts API. Both the APIs expect consumer to follow
Quoted 8 lines

Documentation/hte/hte.rst line 60

Quoted 7 lines
Documentation/hte/hte.rst new file +7 -0
+	device tree bindings for the HTE consumer. The details about binding
+	is in ``Documentation/devicetree/bindings/hte/hte-consumer.yaml``.
+
+.. c:function:: struct hte_ts_desc *hte_req_ts_by_dt_node( struct device_node *of_node, unsigned int id, void (*cb)(enum hte_notify n) )
+
+	The consumer can request timestamping directly specifying provider
+	device tree node.

When does this make sense?

This is needed when provider has dependencies on other IP within chip, for example

tegra chip GPIO HTE has to talk to GPIO controller to fully enable HTE functionality.

Quoted 45 lines
Quoted 29 lines
Documentation/hte/hte.rst new file +28 -0
+
+.. c:function:: int hte_enable_ts( struct hte_ts_desc *desc )
+.. c:function:: int hte_disable_ts( struct hte_ts_desc *desc )
+
+	The consumer can enable/disable timestamping on given desc.
+
+.. c:function:: int hte_retrieve_ts_ns( const struct hte_ts_desc *desc, struct hte_ts_data *el, size_t n )
+		int hte_retrieve_ts_ns_wait( const struct hte_ts_desc *desc, struct hte_ts_data *el, size_t n )
+
+	The consumer uses above two API versions to get/retrieve timestamp data
+	for the given desc. The later is blocking version.
+
+.. c:function:: hte_get_clk_src_info(const struct hte_line_desc *desc, struct hte_clk_info *ci)
+
+	The consumer retrieves clock source information that provider uses to
+	timestamp entity in the structure hte_clk_info. This information
+	specifies clock rate in HZ and clock.
+
+The details on struct hte_clk_info
+-----------------------------------
+This structure presents detail of the hardware clock that provider uses for
+realtime timestamping purposes. The consumer can use hte_get_clk_src_info API
+to get the information in hte_clk_info structure. It has hz and type parameters
+where hz represents clock rate in HZ and type is clock type of clockid_t and
+of CLOCK_* family (for example, CLOCK_MONOTONIC).
+
+The consumers calling of_hte_request_ts or hte_req_ts_by_dt_node APIs with
+cb parameter set, usually will call hte_retrieve_ts (non blocking

Documentation/hte/hte.rst line 98

Quoted 10 lines
Documentation/hte/hte.rst new file +10 -0
+version) after being notified by the callbacks from HTE subsystem. The
+consumers calling those requests APIs with cb parameter NULL, usually will call
+hte_retrieve_ts_wait API.
+
+The HTE subsystem provides software buffer per requested id/entity to store
+timestamp data (struct hte_ts_data type). The consumers can manage the buffer.
+It also provides buffer watermark which can notify (if cb parameter is provided
+during request API call) consumer or unblock consumers calling
+hte_retrieve_ts_wait API. The following APIs are used to manipulate the
+software buffer:

Have you come across any devices that have a hardware fifo for these timestamps? It's moderately common on sensor hubs to do so, and then you get into a fun question of how to manage the watermark. You don't want to pull from the hardware too early, but conversely you can get out of sync between the software and hardware buffers if someone reasons less than 'watermark' samples from the software buffer.

Quoted 2 lines

Anyhow, it can be entertaining. So in those cases it can be simpler to explicitly provide control of two separate watermarks.

The provider I have dealt with had single hardware FIFO to store timestamps

indiscriminately. I am sure this will come up in future in which case we can

expand it to separate watermark.

Quoted 7 lines

Documentation/hte/hte.rst line 103

Quoted 6 lines
Documentation/hte/hte.rst new file +5 -0
+
+.. c:function:: int hte_set_buf_len( const struct hte_ts_desc *desc,unsigned int len )
+		int hte_get_buf_len( const struct hte_ts_desc *desc )
+
+	The consumer uses above APIs to set/get software buffer depth.

What happens if there is content when it is resized?

I have described in the hte_set_buf_len API description. To summarize, you can

follow certain sequences to consume old data if you still care. Otherwise this

is a destructive API.

Quoted 15 lines
Quoted 15 lines
Documentation/hte/hte.rst new file +14 -0
+
+.. c:function:: int hte_set_buf_watermark( const struct hte_ts_desc *desc, unsigned int val )
+		int hte_get_buf_watermark( const struct hte_ts_desc *desc )
+
+	The consumer uses above APIs to set/get software threshold, threshold
+	can be used to notity or unblock waiting consumer when data becomes
+	available equal or above to threshold value.
+
+.. c:function:: size_t hte_available_ts( const struct hte_ts_desc *desc )
+
+	The consumer uses above API to get available timestamp data stored
+	in the software buffer for the desc.
+
+The detail about parameters and API usage are described in each functions
Quoted 8 lines

Documentation/hte/hte.rst

Quoted 7 lines
Documentation/hte/hte.rst new file +7 -0
+definitions in ``drivers/hte/hte.c`` file.
+
+The HTE timestamp element detail
+--------------------------------
+The struct hte_ts_data, declared at ``include/linux/hte.h``, is used to pass
+timestamp details between the consumers and the providers. It expresses
+timestamp data in nano second in u64 data type.

I'd suggest s64 to match with kernel timestamp format.

Make sense, I will update in next revision.

Quoted 16 lines
Quoted 4 lines

For now all the HTE APIs

Documentation/hte/hte.rst new file +2 -0
+using struct hte_ts_data requires tsc to be in nano seconds. The timestamp
+element structure stores below information along with timestamp data::

Documentation/hte/hte.rst line 136

Quoted 10 lines
Documentation/hte/hte.rst new file +10 -0
+
+ struct hte_ts_data {
+	/*
+	 * Timestamp value
+	 */
+	u64 tsc;
+	/*
+	 * The sequence counter, keep track of the number of timestamps.
+	 * It can be used to check if data is dropped in between.
+	 */

Is this a hardware feature? A bit unusual to have this rather than simple overflow flag to indicate we dropped an unknown number of samples.

Its software feature. I Believe having seq helps consumer to backtrack.

Quoted 7 lines

Documentation/hte/hte.rst line 139

Quoted 4 lines
Documentation/hte/hte.rst new file +3 -0
+	u64 seq;
+	/* Direction of the event, i.e. falling or rising */
+	int dir;

Given an even could do more than that potentially, or indeed not be able to tell if it was rising or falling, I would suggest an enum to which we can add more options as needed.

I have two defines in hte.h for now. I can convert them into enum type.

Quoted 13 lines

Documentation/hte/hte.rst line 150

Quoted 12 lines

+ };

Documentation/hte/hte.rst new file +10 -0
+
+The typical hte_ts_data data life cycle::
+In this example the provider provides timestamp in nano seconds and for the
+GPIO line::
+
+ - Monitors GPIO line change.
+ - Detects the state change on GPIO line.
+ - Converts timestamps in nano seconds and stores it in tsc.
+ - Stores GPIO direction in dir variable if the provider has that hardware
+ capability.

We definitely want to know if it does or not. How does an application query that?

Its stored in dir field of the hte_ts_data structure.

Quoted 5 lines
Quoted 4 lines

+ - Pushes this hte_timestamp_el object to HTE subsystem.
+ - HTE subsystem increments seq counter and stores it in software buffer
+ dedicated to requested GPIO line.

Ah. So that seq counter is only for software drops if the fifo fills up.

Yes.

Quoted 46 lines
Quoted 46 lines

+ - Waiting consumer gets notified.
+ - The consumer calls the retrieve timestamp API.

Documentation/hte/hte.rst new file +43 -0
+
+HTE subsystem debugfs attributes
+--------------------------------
+HTE subsystem creates debugfs attributes at ``/sys/kernel/debug/hte/``.
+It also creates line/signal related debugfs attributes at
+``/sys/kernel/debug/hte/<provider>/<label or line id>/``.
+
+`ts_requested`
+		The total number of entities requested from the given provider,
+		where entity is the provider specific and could represent
+		lines, GPIO, chip signals, buses etc...
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/``.
+
+		Read only value
+
+`total_ts`
+		The total number of entities supported by the provider.
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/``.
+
+		Read only value
+
+`ts_buffer_depth`
+		The software buffer lenth to store timestamp data.
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/<label or id>/``.
+
+		Read only value
+
+`ts_buffer_watermark`
+		The software buffer watermark or threshold.
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/<label or line id>/``.
+
+		Read only value
+
+`dropped_timestamps`
+		The dropped timestamps for a given line.
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/<label or line id>/``.
+
+		Read only value
maintainer
#4 lore raw

Re: [RFC 01/11] Documentation: Add HTE subsystem guide

Quoted 7 lines · On Tue, 27 Jul 2021 16:44:30 -0700 Dipen Patel <[email protected]> wrote:
Quoted 6 lines · Jonathan Cameron
Quoted 3 lines · On Fri, 25 Jun 2021 16:55:22 -0700 Dipen Patel <[email protected]> wrote:

Adding hte document which can help understand various APIs implemented in HTE framework for the HTE producers and the consumers.

Quoted 8 lines
Quoted 7 lines
Quoted 1 line

Some editorial stuff inline. (I can't resist even on RFCs)

Certainly interesting. I'm running a bit tight on time today, so not sure how much of the code I'll get a chance to look at. Will try to get to it soon though.

Jonathan

Thanks Jonathan for the review comment and time. My answers inline.

Hi Dipen,

A few follow up comments inline.

Quoted 63 lines
Quoted 24 lines
Quoted 12 lines
 
---
 Documentation/hte/hte.rst | 198 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 198 insertions(+)
 create mode 100644 Documentation/hte/hte.rst
Documentation/hte/hte.rst new file +0 -0
new file mode 100644
index 000000000000..11744dbc6d16

Documentation/hte/hte.rst line 10

Quoted 10 lines
Documentation/hte/hte.rst new file +10 -0
@@ -0,0 +1,198 @@
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+:Author: Dipen Patel
+
+Introduction
+------------
+
+The certain devices have the built in hardware timestamping engine which can  

Certain devices have built in hardware timestamping engines which can

Quoted 5 lines

Documentation/hte/hte.rst line 11

Quoted 1 line
Documentation/hte/hte.rst new file +1 -0
+monitor sets of system signals, lines, buses etc... in realtime for the state  

for state changes;

Documentation/hte/hte.rst line 12

Quoted 1 line
Documentation/hte/hte.rst new file +1 -0
+change; upon detecting the change it can automatically store the timestamp at  

they can

Will add above in next RFC version2.

Quoted 25 lines
Quoted 25 lines
Documentation/hte/hte.rst new file +24 -0
+the moment of occurrence. Such functionality may help achieve better accuracy
+in obtaining timestamp than using software counterparts i.e. ktime and friends.
+
+This document describes the API that can be used by hardware timestamping
+engine provider and consumer drivers that want to use the hardware timestamping
+engine (HTE) framework.
+
+The HTE framework APIs for the providers
+----------------------------------------
+Each driver must #include <linux/hte.h>. The ``linux/hte.h`` declares the
+following functions for the provider:
+
+.. c:function:: int hte_register_chip( struct hte_chip *chip )
+		int hte_unregister_chip( struct hte_chip *chip )
+
+	The provider uses these APIs to un/register itself with HTE framework.
+
+.. c:function:: int hte_push_ts_ns_atomic( const struct hte_chip *chip, u32 xlated_id, struct hte_ts_data *data, size_t n )
+
+	The provider pushes timestamp data in nano seconds unit using this API.
+
+The detail about parameters and API usage are described in each functions
+definitions in ``drivers/hte/hte.c`` file.
+
Quoted 8 lines

Documentation/hte/hte.rst line 40

Quoted 4 lines
Documentation/hte/hte.rst new file +4 -0
+The HTE framework APIs for the consumers
+----------------------------------------
+The consumers use following APIs to control the line for the timestamp:
+  

When documenting APIs you may well be better including a reference to the files themselves and using kernel doc there. The documentation build can then pull that in when creating the html docs etc (and crucially you don't have to provide the
same docs in two places.). Having them here is very convenient for the RFC however :)

Quoted 1 line

You mean to omit description here and put reference to file like ``drivers/hte/hte.c``?

Exactly. You can cross reference to kernel-doc from within the rst. That means the documentation will be in the generated html etc and available in the source code, cutting down on duplication and chances of them disagreeing. The disadvantage is it isn't quite as useful to provide an easily reviewable single document when discussing the design.

What can be useful in a docs file though is to describe the 'flow' of how these functions might be used. That can be harder to do inline in comments etc.

Quoted 23 lines
Quoted 14 lines
Quoted 14 lines
Documentation/hte/hte.rst new file +13 -0
+.. c:function:: int hte_release_ts( struct hte_ts_desc *desc )
+		int devm_hte_release_ts( struct device *dev, struct hte_ts_desc *desc )
+
+	The consumer uses API to release specified desc from timestamping.
+	The API frees resources associated with the desc and disables the
+	timestamping on it. The later is managed version of the same API.
+
+.. c:function:: struct hte_ts_desc *of_hte_request_ts( struct device *dev, const char *label, void (*cb)(enum hte_notify n) )
+		struct hte_ts_desc *devm_of_hte_request_ts( struct device *dev, const char *label, void (*cb)(enum hte_notify n) )
+
+	The consumers can use above request APIs to request real timestamp
+	capability on specified entity. The later is resource managed version
+	of the of_hte_request_ts API. Both the APIs expect consumer to follow
Quoted 8 lines

Documentation/hte/hte.rst line 60

Quoted 7 lines
Documentation/hte/hte.rst new file +7 -0
+	device tree bindings for the HTE consumer. The details about binding
+	is in ``Documentation/devicetree/bindings/hte/hte-consumer.yaml``.
+
+.. c:function:: struct hte_ts_desc *hte_req_ts_by_dt_node( struct device_node *of_node, unsigned int id, void (*cb)(enum hte_notify n) )
+
+	The consumer can request timestamping directly specifying provider
+	device tree node.  

When does this make sense?

Quoted 3 lines

This is needed when provider has dependencies on other IP within chip, for example

tegra chip GPIO HTE has to talk to GPIO controller to fully enable HTE functionality.

I'd expect that to be done via a device tree handle at the consumer end. So you'd be requesting based on your own struct device pointer (and the firmware node underneath though that would ideally not be visible in this interface).

Similar to how regulator and other provider / consumer firmware description works.

Whilst it's not immediately clear what this would map to in other firmware types, you should also try to avoid exposing device tree specific interfaces, in favour of generic ones (see include/property.h)

Quoted 46 lines
Quoted 46 lines
Quoted 30 lines
Documentation/hte/hte.rst new file +28 -0
+
+.. c:function:: int hte_enable_ts( struct hte_ts_desc *desc )
+.. c:function:: int hte_disable_ts( struct hte_ts_desc *desc )
+
+	The consumer can enable/disable timestamping on given desc.
+
+.. c:function:: int hte_retrieve_ts_ns( const struct hte_ts_desc *desc, struct hte_ts_data *el, size_t n )
+		int hte_retrieve_ts_ns_wait( const struct hte_ts_desc *desc, struct hte_ts_data *el, size_t n )
+
+	The consumer uses above two API versions to get/retrieve timestamp data
+	for the given desc. The later is blocking version.
+
+.. c:function:: hte_get_clk_src_info(const struct hte_line_desc *desc, struct hte_clk_info *ci)
+
+	The consumer retrieves clock source information that provider uses to
+	timestamp entity in the structure hte_clk_info. This information
+	specifies clock rate in HZ and clock.
+
+The details on struct hte_clk_info
+-----------------------------------
+This structure presents detail of the hardware clock that provider uses for
+realtime timestamping purposes. The consumer can use hte_get_clk_src_info API
+to get the information in hte_clk_info structure. It has hz and type parameters
+where hz represents clock rate in HZ and type is clock type of clockid_t and
+of CLOCK_* family (for example, CLOCK_MONOTONIC).
+
+The consumers calling of_hte_request_ts or hte_req_ts_by_dt_node APIs with
+cb parameter set, usually will call hte_retrieve_ts (non blocking

Documentation/hte/hte.rst line 98

Quoted 10 lines
Documentation/hte/hte.rst new file +10 -0
+version) after being notified by the callbacks from HTE subsystem. The
+consumers calling those requests APIs with cb parameter NULL, usually will call
+hte_retrieve_ts_wait API.
+
+The HTE subsystem provides software buffer per requested id/entity to store
+timestamp data (struct hte_ts_data type). The consumers can manage the buffer.
+It also provides buffer watermark which can notify (if cb parameter is provided
+during request API call) consumer or unblock consumers calling
+hte_retrieve_ts_wait API. The following APIs are used to manipulate the
+software buffer:  

Have you come across any devices that have a hardware fifo for these timestamps? It's moderately common on sensor hubs to do so, and then you get into a fun question of how to manage the watermark. You don't want to pull from the hardware too early, but conversely you can get out of sync between the software and hardware buffers if someone reasons less than 'watermark' samples from the software buffer.

Quoted 8 lines
Quoted 2 lines

Anyhow, it can be entertaining. So in those cases it can be simpler to explicitly provide control of two separate watermarks.

The provider I have dealt with had single hardware FIFO to store timestamps

indiscriminately. I am sure this will come up in future in which case we can

expand it to separate watermark.

Just to check I've understood this correctly.
You do have a hardware fifo and it has a fixed watermark? (perhaps of 1 timestamp?) If so, indeed one for the future.

Quoted 9 lines
Quoted 8 lines

Documentation/hte/hte.rst line 103

Quoted 7 lines
Documentation/hte/hte.rst new file +5 -0
+
+.. c:function:: int hte_set_buf_len( const struct hte_ts_desc *desc,unsigned int len )
+		int hte_get_buf_len( const struct hte_ts_desc *desc )
+
+	The consumer uses above APIs to set/get software buffer depth.  

What happens if there is content when it is resized?

Quoted 5 lines

I have described in the hte_set_buf_len API description. To summarize, you can

follow certain sequences to consume old data if you still care. Otherwise this

is a destructive API.

OK. You might want to think about blocking this from changing if the timestamping is currently enabled (assuming you don't already!) Otherwise you tend to get entertaining race conditions that consumers will need to deal with - probably by doing the locking at their end.

Quoted 41 lines
Quoted 16 lines
Quoted 16 lines
Documentation/hte/hte.rst new file +14 -0
+
+.. c:function:: int hte_set_buf_watermark( const struct hte_ts_desc *desc, unsigned int val )
+		int hte_get_buf_watermark( const struct hte_ts_desc *desc )
+
+	The consumer uses above APIs to set/get software threshold, threshold
+	can be used to notity or unblock waiting consumer when data becomes
+	available equal or above to threshold value.
+
+.. c:function:: size_t hte_available_ts( const struct hte_ts_desc *desc )
+
+	The consumer uses above API to get available timestamp data stored
+	in the software buffer for the desc.
+
+The detail about parameters and API usage are described in each functions
Quoted 8 lines

Documentation/hte/hte.rst

Quoted 7 lines
Documentation/hte/hte.rst new file +7 -0
+definitions in ``drivers/hte/hte.c`` file.
+
+The HTE timestamp element detail
+--------------------------------
+The struct hte_ts_data, declared at ``include/linux/hte.h``, is used to pass
+timestamp details between the consumers and the providers. It expresses
+timestamp data in nano second in u64 data type.  

I'd suggest s64 to match with kernel timestamp format.

Make sense, I will update in next revision.

Quoted 16 lines
Quoted 4 lines

For now all the HTE APIs

Documentation/hte/hte.rst new file +2 -0
+using struct hte_ts_data requires tsc to be in nano seconds. The timestamp
+element structure stores below information along with timestamp data::

Documentation/hte/hte.rst line 136

Quoted 10 lines
Documentation/hte/hte.rst new file +10 -0
+
+ struct hte_ts_data {
+	/*
+	 * Timestamp value
+	 */
+	u64 tsc;
+	/*
+	 * The sequence counter, keep track of the number of timestamps.
+	 * It can be used to check if data is dropped in between.
+	 */  

Is this a hardware feature? A bit unusual to have this rather than simple overflow flag to indicate we dropped an unknown number of samples.

Quoted 1 line

Its software feature. I Believe having seq helps consumer to backtrack.

Will be interesting to see how this works out, particularly as I expect you will get hardware that only tells you it's dropped something, but not how much. That's what all the sensor hardware with timestamps currently does on overflow Often you can control if old or new samples are dropped, but either way you will get a hole of unknown size.

Quoted 8 lines
Quoted 7 lines

Documentation/hte/hte.rst line 139

Quoted 4 lines
Documentation/hte/hte.rst new file +3 -0
+	u64 seq;
+	/* Direction of the event, i.e. falling or rising */
+	int dir;  

Given an even could do more than that potentially, or indeed not be able to tell if it was rising or falling, I would suggest an enum to which we can add more options as needed.

I have two defines in hte.h for now. I can convert them into enum type.

yikes, I should proof read my comments before sending! Glad you figured out what I meant.

Quoted 13 lines
Quoted 13 lines

Documentation/hte/hte.rst line 150

Quoted 12 lines

+ };

Documentation/hte/hte.rst new file +10 -0
+
+The typical hte_ts_data data life cycle::
+In this example the provider provides timestamp in nano seconds and for the
+GPIO line::
+
+ - Monitors GPIO line change.
+ - Detects the state change on GPIO line.
+ - Converts timestamps in nano seconds and stores it in tsc.
+ - Stores GPIO direction in dir variable if the provider has that hardware
+ capability.  

We definitely want to know if it does or not. How does an application query that?

Quoted 1 line

Its stored in dir field of the hte_ts_data structure.

I wasn't clear in this comment. We need a way to know the hardware does not support providing the direction and hence the dir field is not valid. Is there a way to find that out from a consumer driver?

Thanks,

Jonathan

Quoted 52 lines
Quoted 5 lines
Quoted 4 lines

+ - Pushes this hte_timestamp_el object to HTE subsystem.
+ - HTE subsystem increments seq counter and stores it in software buffer
+ dedicated to requested GPIO line.

Ah. So that seq counter is only for software drops if the fifo fills up.

Yes.

Quoted 46 lines
Quoted 46 lines

+ - Waiting consumer gets notified.
+ - The consumer calls the retrieve timestamp API.

Documentation/hte/hte.rst new file +43 -0
+
+HTE subsystem debugfs attributes
+--------------------------------
+HTE subsystem creates debugfs attributes at ``/sys/kernel/debug/hte/``.
+It also creates line/signal related debugfs attributes at
+``/sys/kernel/debug/hte/<provider>/<label or line id>/``.
+
+`ts_requested`
+		The total number of entities requested from the given provider,
+		where entity is the provider specific and could represent
+		lines, GPIO, chip signals, buses etc...
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/``.
+
+		Read only value
+
+`total_ts`
+		The total number of entities supported by the provider.
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/``.
+
+		Read only value
+
+`ts_buffer_depth`
+		The software buffer lenth to store timestamp data.
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/<label or id>/``.
+
+		Read only value
+
+`ts_buffer_watermark`
+		The software buffer watermark or threshold.
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/<label or line id>/``.
+
+		Read only value
+
+`dropped_timestamps`
+		The dropped timestamps for a given line.
+                The attribute will be availble at
+		``/sys/kernel/debug/hte/<provider>/<label or line id>/``.
+
+		Read only value  
author maintainer
#5 lore raw

RFC 2/11 drivers: Add HTE subsystem

In reply to Dipen Patel

Some devices can timestamp system lines/signals/Buses in real-time using the hardware counter or other hardware means which can give finer granularity and help avoid jitter introduced by software means of timestamping. To utilize such functionality there has to be framework where such devices can register themselves as producers or providers so that the consumers or clients devices can request specific line from the providers. This patch introduces such subsystem as hardware timestamping engine (HTE).

It provides below APIs for the provider:
- hte_register_chip() -- To register the HTE chip.
- hte_unregister_chip() -- To unregister the HTE chip.
- hte_push_ts_ns_atomic() -- To push timestamp data into HTE subsystem.

It provides below APIs for the consumer:
- of_hte_request_ts() -- To request timestamp functionality.
- devm_of_hte_request_ts() -- Managed version of the above.
- hte_req_ts_by_dt_node() -- To request timestamp functionality by using HTE provider dt node.
- devm_hte_release_ts() -- The managed version to release timestamp functionality and associated resources.
- hte_retrieve_ts_ns() -- To retrieve timestamps.
- hte_retrieve_ts_ns_wait() -- Same as above but blocking version.
- hte_enable_ts() -- To disable timestamp functionality.
- hte_disable_ts() -- To enable timestamp functionality.
- hte_available_ts() -- To query available timestamp data.
- hte_release_ts() -- To release timestamp functionality and its associated resources.
- hte_get_clk_src_info() -- To query clock source information from the provider

It provides centralized software buffer management per requested id to store the timestamp data for the consumers as below:
- hte_set_buf_len() -- To set the buffer length.
- hte_get_buf_len() -- To get the buffer length.
- hte_set_buf_watermark() -- To set the software threshold/watermark.
- hte_get_buf_watermark() -- To get the software threshold/watermark.

The detail about parameters and API usage are described in each functions definitions in drivers/hte/hte.c file.

The patch adds compilation support in Makefile and menu options in Kconfig.

---
 drivers/Kconfig      |    2 +
 drivers/Makefile     |    1 +
 drivers/hte/Kconfig  |   22 +
 drivers/hte/Makefile |    1 +
 drivers/hte/hte.c    | 1368 ++++++++++++++++++++++++++++++++++++++++++
 include/linux/hte.h  |  278 +++++++++
 6 files changed, 1672 insertions(+)
 create mode 100644 drivers/hte/Kconfig
 create mode 100644 drivers/hte/Makefile
 create mode 100644 drivers/hte/hte.c
 create mode 100644 include/linux/hte.h
drivers/Kconfig +2 -0
index 47980c6b1945..9b078964974b 100644
@@ -238,4 +238,6 @@ source "drivers/interconnect/Kconfig"
 source "drivers/counter/Kconfig"
 
 source "drivers/most/Kconfig"
+
+source "drivers/hte/Kconfig"
 endmenu
drivers/Makefile +1 -0
index 5a6d613e868d..0a996a698e4c 100644
@@ -190,3 +190,4 @@ obj-$(CONFIG_GNSS)		+= gnss/
 obj-$(CONFIG_INTERCONNECT)	+= interconnect/
 obj-$(CONFIG_COUNTER)		+= counter/
 obj-$(CONFIG_MOST)		+= most/
+obj-$(CONFIG_HTE)		+= hte/
drivers/hte/Kconfig new file +22 -0
new file mode 100644
index 000000000000..394e112f7dfb
@@ -0,0 +1,22 @@
+# SPDX-License-Identifier: GPL-2.0-only
+menuconfig HTE
+        bool "Hardware Timestamping Engine (HTE) Support"
+        help
+          Hardware Timestamping Engine (HTE) Support.
+
+          Some devices provide hardware timestamping engine which can timestamp
+	  certain device lines/signals in realtime. This way to provide
+	  hardware assisted timestamp to generic signals like GPIOs, IRQs lines
+	  comes with benefit for the applications like autonomous machines
+	  needing accurate timestamping event with less jitter.
+
+	  This framework provides a generic interface to such HTE devices
+          within the Linux kernel. It provides an API to register and
+	  unregister a HTE provider chip, configurable sw buffer to
+	  store the timestamps, push the timestamp from the HTE providers and
+	  retrieve timestamps for the consumers. It also provides means for the
+	  consumers to request signals it wishes to hardware timestamp and
+	  release them if not required.
+
+          If unsure, say no.
+
drivers/hte/Makefile new file +1 -0
new file mode 100644
index 000000000000..9899dbe516f7
@@ -0,0 +1 @@
+obj-$(CONFIG_HTE)		+= hte.o
drivers/hte/hte.c new file +1368 -0

1,368 lines not on this page · raw message

include/linux/hte.h new file +278 -0

278 lines not on this page · raw message

Signature · 1 line
2.17.1
#6 lore raw

Re: [RFC 02/11] drivers: Add HTE subsystem

[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in https://git-scm.com/docs/git-format-patch]

Hi Dipen,

[FYI, it's a private test report for your RFC patch.]
[auto build test WARNING on robh/for-next]
[also build test WARNING on linux/master linus/master gpio/for-next v5.13-rc7 next-20210625] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch]

url:    https://github.com/0day-ci/linux/commits/Dipen-Patel/Intro-to-Hardware-timestamping-engine/20210626-074917
base:   https://git.kernel.org/pub/scm/linux/kernel/git/robh/linux.git for-next
config: m68k-allmodconfig (attached as .config)
compiler: m68k-linux-gcc (GCC) 9.3.0

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# https://github.com/0day-ci/linux/commit/887b08c0d50d454bf7c9624afa13c28fe522c977
git remote add linux-review https://github.com/0day-ci/linux
git fetch --no-tags linux-review Dipen-Patel/Intro-to-Hardware-timestamping-engine/20210626-074917 git checkout 887b08c0d50d454bf7c9624afa13c28fe522c977
# save the attached .config to linux build tree
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-9.3.0 make.cross ARCH=m68k

If you fix the issue, kindly add following tag as appropriate

All warnings (new ones prefixed by >>):

In file included from include/linux/printk.h:6,
from include/linux/kernel.h:17,
from drivers/hte/hte.c:8:
drivers/hte/hte.c:298:17: error: initialization of 'initcall_t' {aka 'int (*)(void)'} from incompatible pointer type 'void (*)(void)' [-Werror=incompatible-pointer-types]

     298 | subsys_initcall(hte_subsys_dbgfs_init);
         |                 ^~~~~~~~~~~~~~~~~~~~~
   include/linux/init.h:249:41: note: in definition of macro '____define_initcall'
     249 |   __attribute__((__section__(__sec))) = fn;
         |                                         ^~
   include/linux/init.h:259:2: note: in expansion of macro '__unique_initcall'
     259 |  __unique_initcall(fn, id, __sec, __initcall_id(fn))
         |  ^~~~~~~~~~~~~~~~~
   include/linux/init.h:261:35: note: in expansion of macro '___define_initcall'
     261 | #define __define_initcall(fn, id) ___define_initcall(fn, id, .initcall##id)
         |                                   ^~~~~~~~~~~~~~~~~~
   include/linux/init.h:285:30: note: in expansion of macro '__define_initcall'
     285 | #define subsys_initcall(fn)  __define_initcall(fn, 4)
         |                              ^~~~~~~~~~~~~~~~~
   drivers/hte/hte.c:298:1: note: in expansion of macro 'subsys_initcall'
     298 | subsys_initcall(hte_subsys_dbgfs_init);
         | ^~~~~~~~~~~~~~~
   In file included from include/linux/kernel.h:17,
                    from drivers/hte/hte.c:8:
   drivers/hte/hte.c: In function 'hte_para_check':
>> drivers/hte/hte.c:827:12: warning: format '%lu' expects argument of type 'long unsigned int', but argument 5 has type 'size_t' {aka 'unsigned int'} [-Wformat=]
     827 |   pr_debug("%s:%d: val :%lu\n", __func__, __LINE__, val);
         |            ^~~~~~~~~~~~~~~~~~~
   include/linux/printk.h:301:21: note: in definition of macro 'pr_fmt'
     301 | #define pr_fmt(fmt) fmt
         |                     ^~~
   include/linux/dynamic_debug.h:147:2: note: in expansion of macro '__dynamic_func_call'
     147 |  __dynamic_func_call(__UNIQUE_ID(ddebug), fmt, func, ##__VA_ARGS__)
         |  ^~~~~~~~~~~~~~~~~~~
   include/linux/dynamic_debug.h:157:2: note: in expansion of macro '_dynamic_func_call'
     157 |  _dynamic_func_call(fmt, __dynamic_pr_debug,  \
         |  ^~~~~~~~~~~~~~~~~~
   include/linux/printk.h:424:2: note: in expansion of macro 'dynamic_pr_debug'
     424 |  dynamic_pr_debug(fmt, ##__VA_ARGS__)
         |  ^~~~~~~~~~~~~~~~
   drivers/hte/hte.c:827:3: note: in expansion of macro 'pr_debug'
     827 |   pr_debug("%s:%d: val :%lu\n", __func__, __LINE__, val);
         |   ^~~~~~~~
   drivers/hte/hte.c:827:27: note: format string is defined here
     827 |   pr_debug("%s:%d: val :%lu\n", __func__, __LINE__, val);
         |                         ~~^
         |                           |
         |                           long unsigned int
         |                         %u
   drivers/hte/hte.c: In function 'hte_add_to_device_list':
>> drivers/hte/hte.c:1180:21: warning: variable 'prev' set but not used [-Wunused-but-set-variable]
    1180 |  struct hte_device *prev;
         |                     ^~~~

cc1: some warnings being treated as errors

vim +827 drivers/hte/hte.c

820
821 static struct hte_ts_info *hte_para_check(const struct hte_ts_desc *desc,
822 size_t val)
823 {
824 struct hte_ts_info *ei;
825
826 if (!desc || !desc->data_subsys || !val) {

 > 827			pr_debug("%s:%d: val :%lu\n", __func__, __LINE__, val);

828 return NULL;
829 }
830
831 ei = desc->data_subsys;
832 if (!ei || !ei->buf) {
833 pr_debug("%s:%d\n", __func__, __LINE__);
834 return NULL;
835 }
836
837 return ei;
838 }
839

---
0-DAY CI Kernel Test Service, Intel Corporation
https://lists.01.org/hyperkitty/list/kbuild-all(a)lists.01.org

#7 lore raw

Re: [RFC 02/11] drivers: Add HTE subsystem

In reply to Dipen Patel
[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in https://git-scm.com/docs/git-format-patch]

Hi Dipen,

[FYI, it's a private test report for your RFC patch.]
[auto build test ERROR on robh/for-next]
[also build test ERROR on linux/master linus/master gpio/for-next v5.13-rc7 next-20210625] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch]

url:    https://github.com/0day-ci/linux/commits/Dipen-Patel/Intro-to-Hardware-timestamping-engine/20210626-074917
base:   https://git.kernel.org/pub/scm/linux/kernel/git/robh/linux.git for-next
config: m68k-allmodconfig (attached as .config)
compiler: m68k-linux-gcc (GCC) 9.3.0

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# https://github.com/0day-ci/linux/commit/887b08c0d50d454bf7c9624afa13c28fe522c977
git remote add linux-review https://github.com/0day-ci/linux
git fetch --no-tags linux-review Dipen-Patel/Intro-to-Hardware-timestamping-engine/20210626-074917 git checkout 887b08c0d50d454bf7c9624afa13c28fe522c977
# save the attached .config to linux build tree
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=gcc-9.3.0 make.cross ARCH=m68k

If you fix the issue, kindly add following tag as appropriate

All errors (new ones prefixed by >>):

In file included from include/linux/printk.h:6,
from include/linux/kernel.h:17, from drivers/hte/hte.c:8:

>> drivers/hte/hte.c:298:17: error: initialization of 'initcall_t' {aka 'int (*)(void)'} from incompatible pointer type 'void (*)(void)' [-Werror=incompatible-pointer-types]
     298 | subsys_initcall(hte_subsys_dbgfs_init);
         |                 ^~~~~~~~~~~~~~~~~~~~~
   include/linux/init.h:249:41: note: in definition of macro '____define_initcall'
     249 |   __attribute__((__section__(__sec))) = fn;
         |                                         ^~
   include/linux/init.h:259:2: note: in expansion of macro '__unique_initcall'
     259 |  __unique_initcall(fn, id, __sec, __initcall_id(fn))
         |  ^~~~~~~~~~~~~~~~~
   include/linux/init.h:261:35: note: in expansion of macro '___define_initcall'
     261 | #define __define_initcall(fn, id) ___define_initcall(fn, id, .initcall##id)
         |                                   ^~~~~~~~~~~~~~~~~~
   include/linux/init.h:285:30: note: in expansion of macro '__define_initcall'
     285 | #define subsys_initcall(fn)  __define_initcall(fn, 4)
         |                              ^~~~~~~~~~~~~~~~~
   drivers/hte/hte.c:298:1: note: in expansion of macro 'subsys_initcall'
     298 | subsys_initcall(hte_subsys_dbgfs_init);
         | ^~~~~~~~~~~~~~~
   In file included from include/linux/kernel.h:17,
                    from drivers/hte/hte.c:8:
   drivers/hte/hte.c: In function 'hte_para_check':
   drivers/hte/hte.c:827:12: warning: format '%lu' expects argument of type 'long unsigned int', but argument 5 has type 'size_t' {aka 'unsigned int'} [-Wformat=]
     827 |   pr_debug("%s:%d: val :%lu\n", __func__, __LINE__, val);
         |            ^~~~~~~~~~~~~~~~~~~
   include/linux/printk.h:301:21: note: in definition of macro 'pr_fmt'
     301 | #define pr_fmt(fmt) fmt
         |                     ^~~
   include/linux/dynamic_debug.h:147:2: note: in expansion of macro '__dynamic_func_call'
     147 |  __dynamic_func_call(__UNIQUE_ID(ddebug), fmt, func, ##__VA_ARGS__)
         |  ^~~~~~~~~~~~~~~~~~~
   include/linux/dynamic_debug.h:157:2: note: in expansion of macro '_dynamic_func_call'
     157 |  _dynamic_func_call(fmt, __dynamic_pr_debug,  \
         |  ^~~~~~~~~~~~~~~~~~
   include/linux/printk.h:424:2: note: in expansion of macro 'dynamic_pr_debug'
     424 |  dynamic_pr_debug(fmt, ##__VA_ARGS__)
         |  ^~~~~~~~~~~~~~~~
   drivers/hte/hte.c:827:3: note: in expansion of macro 'pr_debug'
     827 |   pr_debug("%s:%d: val :%lu\n", __func__, __LINE__, val);
         |   ^~~~~~~~
   drivers/hte/hte.c:827:27: note: format string is defined here
     827 |   pr_debug("%s:%d: val :%lu\n", __func__, __LINE__, val);
         |                         ~~^
         |                           |
         |                           long unsigned int
         |                         %u
   drivers/hte/hte.c: In function 'hte_add_to_device_list':
   drivers/hte/hte.c:1180:21: warning: variable 'prev' set but not used [-Wunused-but-set-variable]
    1180 |  struct hte_device *prev;
         |                     ^~~~

cc1: some warnings being treated as errors

vim +298 drivers/hte/hte.c

292
293 static void __init hte_subsys_dbgfs_init(void)
294 {
295 /* creates /sys/kernel/debug/hte/ */
296 hte_root = debugfs_create_dir("hte", NULL);
297 }

 > 298	subsys_initcall(hte_subsys_dbgfs_init);

299

---
0-DAY CI Kernel Test Service, Intel Corporation
https://lists.01.org/hyperkitty/list/kbuild-all(a)lists.01.org

reviewer
#8 lore raw

Re: [RFC 02/11] drivers: Add HTE subsystem

In reply to Dipen Patel
Quoted 17 lines · Dipen Patel
drivers/hte/Kconfig new file +11 -0
new file mode 100644
index 000000000000..394e112f7dfb
@@ -0,0 +1,22 @@
+# SPDX-License-Identifier: GPL-2.0-only
+menuconfig HTE
+        bool "Hardware Timestamping Engine (HTE) Support"
+        help
+          Hardware Timestamping Engine (HTE) Support.
+
+          Some devices provide hardware timestamping engine which can timestamp
+	  certain device lines/signals in realtime. This way to provide
+	  hardware assisted timestamp to generic signals like GPIOs, IRQs lines
+	  comes with benefit for the applications like autonomous machines
+	  needing accurate timestamping event with less jitter.

drivers/hte/Kconfig line 21

Quoted 10 lines
drivers/hte/Kconfig new file +10 -0
+
+	  This framework provides a generic interface to such HTE devices
+          within the Linux kernel. It provides an API to register and
+	  unregister a HTE provider chip, configurable sw buffer to
+	  store the timestamps, push the timestamp from the HTE providers and
+	  retrieve timestamps for the consumers. It also provides means for the
+	  consumers to request signals it wishes to hardware timestamp and
+	  release them if not required.
+
+          If unsure, say no.

semi-bot:

Please follow coding-style for Kconfig files:

(from Documentation/process/coding-style.rst, section 10):

For all of the Kconfig* configuration files throughout the source tree, the indentation is somewhat different. Lines under a ``config`` definition are indented with one tab, while help text is indented an additional two spaces.

thanks.

Signature · 1 line
~Randy
maintainer
#9 lore raw

Re: [RFC 02/11] drivers: Add HTE subsystem

In reply to Dipen Patel
Quoted 38 lines · On Fri, 25 Jun 2021 16:55:23 -0700 Dipen Patel <[email protected]> wrote:

Some devices can timestamp system lines/signals/Buses in real-time using the hardware counter or other hardware means which can give finer granularity and help avoid jitter introduced by software means of timestamping. To utilize such functionality there has to be framework where such devices can register themselves as producers or providers so that the consumers or clients devices can request specific line from the providers. This patch introduces such subsystem as hardware timestamping engine (HTE).

It provides below APIs for the provider:
- hte_register_chip() -- To register the HTE chip.
- hte_unregister_chip() -- To unregister the HTE chip.
- hte_push_ts_ns_atomic() -- To push timestamp data into HTE subsystem.

It provides below APIs for the consumer:
- of_hte_request_ts() -- To request timestamp functionality.
- devm_of_hte_request_ts() -- Managed version of the above.
- hte_req_ts_by_dt_node() -- To request timestamp functionality by using HTE provider dt node.
- devm_hte_release_ts() -- The managed version to release timestamp functionality and associated resources.
- hte_retrieve_ts_ns() -- To retrieve timestamps.
- hte_retrieve_ts_ns_wait() -- Same as above but blocking version.
- hte_enable_ts() -- To disable timestamp functionality.
- hte_disable_ts() -- To enable timestamp functionality.
- hte_available_ts() -- To query available timestamp data.
- hte_release_ts() -- To release timestamp functionality and its associated resources.
- hte_get_clk_src_info() -- To query clock source information from the provider

It provides centralized software buffer management per requested id to store the timestamp data for the consumers as below:
- hte_set_buf_len() -- To set the buffer length.
- hte_get_buf_len() -- To get the buffer length.
- hte_set_buf_watermark() -- To set the software threshold/watermark.
- hte_get_buf_watermark() -- To get the software threshold/watermark.

Quoted 7 lines

The detail about parameters and API usage are described in each functions definitions in drivers/hte/hte.c file.

The patch adds compilation support in Makefile and menu options in Kconfig.

Hi Dipen, this isn't a particularly thorough review as I'm still getting my head around what this is doing + it is an RFC :)

Quoted 39 lines
---
 drivers/Kconfig      |    2 +
 drivers/Makefile     |    1 +
 drivers/hte/Kconfig  |   22 +
 drivers/hte/Makefile |    1 +
 drivers/hte/hte.c    | 1368 ++++++++++++++++++++++++++++++++++++++++++
 include/linux/hte.h  |  278 +++++++++
 6 files changed, 1672 insertions(+)
 create mode 100644 drivers/hte/Kconfig
 create mode 100644 drivers/hte/Makefile
 create mode 100644 drivers/hte/hte.c
 create mode 100644 include/linux/hte.h
drivers/Kconfig +2 -0
index 47980c6b1945..9b078964974b 100644
@@ -238,4 +238,6 @@ source "drivers/interconnect/Kconfig"
 source "drivers/counter/Kconfig"
 
 source "drivers/most/Kconfig"
+
+source "drivers/hte/Kconfig"
 endmenu
drivers/Makefile +1 -0
index 5a6d613e868d..0a996a698e4c 100644
@@ -190,3 +190,4 @@ obj-$(CONFIG_GNSS)		+= gnss/
 obj-$(CONFIG_INTERCONNECT)	+= interconnect/
 obj-$(CONFIG_COUNTER)		+= counter/
 obj-$(CONFIG_MOST)		+= most/
+obj-$(CONFIG_HTE)		+= hte/
drivers/hte/Kconfig new file +0 -0
new file mode 100644
index 000000000000..394e112f7dfb

drivers/hte/Kconfig line 5

Quoted 5 lines
drivers/hte/Kconfig new file +5 -0
@@ -0,0 +1,22 @@
+# SPDX-License-Identifier: GPL-2.0-only
+menuconfig HTE
+        bool "Hardware Timestamping Engine (HTE) Support"
+        help
+          Hardware Timestamping Engine (HTE) Support.

Tidy this up, but think that's already been commented on.

Quoted 143 lines
drivers/hte/Kconfig new file +17 -0
+
+          Some devices provide hardware timestamping engine which can timestamp
+	  certain device lines/signals in realtime. This way to provide
+	  hardware assisted timestamp to generic signals like GPIOs, IRQs lines
+	  comes with benefit for the applications like autonomous machines
+	  needing accurate timestamping event with less jitter.
+
+	  This framework provides a generic interface to such HTE devices
+          within the Linux kernel. It provides an API to register and
+	  unregister a HTE provider chip, configurable sw buffer to
+	  store the timestamps, push the timestamp from the HTE providers and
+	  retrieve timestamps for the consumers. It also provides means for the
+	  consumers to request signals it wishes to hardware timestamp and
+	  release them if not required.
+
+          If unsure, say no.
+
drivers/hte/Makefile new file +1 -0
new file mode 100644
index 000000000000..9899dbe516f7
@@ -0,0 +1 @@
+obj-$(CONFIG_HTE)		+= hte.o
drivers/hte/hte.c new file +113 -0
new file mode 100644
index 000000000000..c53260d1e250
@@ -0,0 +1,1368 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2021 NVIDIA Corporation
+ *
+ * Author: Dipen Patel <[email protected]>
+ */
+
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/err.h>
+#include <linux/slab.h>
+#include <linux/of.h>
+#include <linux/of_device.h>
+#include <linux/kfifo.h>
+#include <linux/mutex.h>
+#include <linux/sched.h>
+#include <linux/uaccess.h>
+#include <linux/hte.h>
+#include <linux/delay.h>
+#include <linux/debugfs.h>
+
+/* Global list of the HTE devices */
+static DEFINE_SPINLOCK(hte_lock);
+static LIST_HEAD(hte_devices);
+
+enum {
+	HTE_TS_REGISTERED,
+	HTE_TS_DISABLE,
+};
+
+/* Default FIFO depth */
+#define HTE_EV_FIFO_EL		32
+
+#define HTE_TS_NAME_LEN		10
+
+struct hte_ts_buf;
+
+/**
+ * struct hte_ts_buf_acc_func - Software buffer management functions.
+ * @store: Store timestamp from atomic context as providers most likely
+ * be pushing timestamps from their interrupt handlers.
+ * @read: Read timestamps from the buffer.
+ * @el_available: Available timestamps to retrieve. The client can use this to
+ * query available elements so that it can pre-allocate internal buffer to send
+ * to during hte_retrieve_ts_ns API.
+ * @set_length: Set length/depth of the buffer.
+ * @get_length: Get length/depth of the buffer.
+ * @set_watermark: Set software threshold of the buffer.
+ * @get_watermark: Get software threshold of the buffer.
+ * @release: Release/free buffer.
+ * @reset: Reset the buffer.
+ */
+struct hte_ts_buf_acc_func {
+	unsigned int (*store)(struct hte_ts_buf *buf, void *data, size_t n);
+	int (*read)(struct hte_ts_buf *buf, unsigned char *data, size_t n,
+		    size_t *copied);
+	size_t (*el_available)(struct hte_ts_buf *buf);
+	int (*set_length)(struct hte_ts_buf *buf,
+			  size_t length, size_t bpd);
+	size_t (*get_length)(struct hte_ts_buf *buf);
+	int (*set_watermark)(struct hte_ts_buf *buf,
+			     size_t val);
+	size_t (*get_watermark)(struct hte_ts_buf *buf);
+	void (*release)(struct hte_ts_buf *buf);
+	void (*reset)(struct hte_ts_buf *buf);
+};
+
+/**
+ * struct hte_ts_buf - Software buffer per requested id or entity to store
+ * timestamps.
+ *
+ * @datum_len: Buffer depth or number of elements.
+ * @bytes_per_datum: Element size in bytes.
+ * @watermark: Software threshold at which client will be notified.
+ * @valid: Validity of the buffer.
+ * @pollq: Waitqueue for the blocking clients.
+ * @access: Various buffer management functions.
+ */
+struct hte_ts_buf {
+	size_t datum_len;
+	size_t bytes_per_datum;
+	size_t watermark;
+	bool valid;
+	wait_queue_head_t pollq;
+	const struct hte_ts_buf_acc_func *access;
+};
+
+/**
+ * struct hte_ts_info - Information related to requested timestamp.
+ *
+ * @xlated_id: Timestamp ID as understood between HTE subsys and HTE provider,
+ * See xlate callback API.
+ * @flags: Flags holding state informations.
+ * @seq: Timestamp sequence counter.
+ * @dropped_ts: Dropped timestamps.
+ * @cb: Callback to notify clients.
+ * @mlock: Lock during timestamp request/release APIs.
+ * @ts_dbg_root: Root for the debug fs.
+ * @gdev: HTE abstract device that this timestamp belongs to.
+ * @buf: Per requested timestamp software buffer.
+ * @desc: Timestamp descriptor understood between clients and HTE subsystem.
+ */
+struct hte_ts_info {
+	u32 xlated_id;
+	unsigned long flags;
+	u64 seq;
+	atomic_t dropped_ts;
+	void (*cb)(enum hte_notify n);
+	struct mutex mlock;
+	struct dentry *ts_dbg_root;
+	struct hte_device *gdev;
+	struct hte_ts_buf *buf;
+	struct hte_ts_desc *desc;

drivers/hte/hte.c line 123

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+};
+
+/**
+ * struct hte_device - HTE abstract device
+ * @nlines: Number of entities this device supports.
+ * @ts_req: Total number of entities requested.
+ * @ei: Timestamp information.
+ * @sdev: Device used at various debug prints.
+ * @dbg_root: Root directory for debug fs.
+ * @list: List node for internal use.

Be more specific of what sort of internal use.

Quoted 255 lines
drivers/hte/hte.c new file +255 -0
+ * @chip: HTE chip providing this HTE device.
+ * @owner: helps prevent removal of modules when in use.
+ */
+struct hte_device {
+	u32 nlines;
+	atomic_t ts_req;
+	struct hte_ts_info *ei;
+	struct device *sdev;
+	struct dentry *dbg_root;
+	struct list_head list;
+	struct hte_chip *chip;
+	struct module *owner;
+};
+
+/* Buffer management functions */
+
+/**
+ * struct hte_kfifo - Software buffer wrapper.
+ * @buffer: Abstract buffer device.
+ * @gkf: Actual software buffer type, this case its FIFO.
+ */
+struct hte_kfifo {
+	struct hte_ts_buf buffer;
+	struct kfifo gkf;
+};
+
+#define buf_to_kfifo(r) container_of(r, struct hte_kfifo, buffer)
+
+static unsigned int hte_ts_store_to_buf(struct hte_ts_buf *r, void *data,
+					size_t n)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if (unlikely(!r->valid))
+		return 0;
+
+	return kfifo_in(&kf->gkf, (unsigned char *)data, n);
+}
+
+static inline int hte_ts_buf_read(struct hte_ts_buf *r,
+				  unsigned char *buf, size_t n,
+				  size_t *copied)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if ((!r->valid) || (n < kfifo_esize(&kf->gkf)))
+		return -EINVAL;
+
+	*copied = kfifo_out(&kf->gkf, buf, n);
+
+	return 0;
+}
+
+static size_t hte_ts_buf_el_available(struct hte_ts_buf *r)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if (!r->valid)
+		return 0;
+
+	return (kfifo_len(&kf->gkf) / r->bytes_per_datum);
+}
+
+static int hte_ts_buf_set_length(struct hte_ts_buf *r,
+				 size_t length, size_t bpd)
+{
+	int ret = 0;
+	struct hte_kfifo *buf;
+
+	if ((length == 0) || (bpd == 0) || !r)
+		return -EINVAL;
+
+	buf = buf_to_kfifo(r);
+
+	if (r->datum_len != length) {
+		if (r->valid)
+			kfifo_free(&buf->gkf);
+		r->valid = false;
+		r->datum_len = length;
+		r->bytes_per_datum = bpd;
+		ret = kfifo_alloc(&buf->gkf, length * bpd, GFP_KERNEL);
+		if (!ret)
+			r->valid = true;
+	}
+
+	return ret;
+}
+
+static inline size_t hte_ts_buf_get_length(struct hte_ts_buf *r)
+{
+	if ((!r->valid) || !r->datum_len)
+		return 0;
+
+	return r->datum_len;
+}
+
+static inline int hte_ts_buf_set_watermark(struct hte_ts_buf *r, size_t val)
+{
+	if ((!r->valid) || (val > r->datum_len))
+		return -EINVAL;
+
+	r->watermark = val;
+
+	return 0;
+}
+
+static inline size_t hte_ts_buf_get_watermark(struct hte_ts_buf *r)
+{
+	if (!r->valid)
+		return 0;
+
+	return r->watermark;
+}
+
+static inline void hte_ts_buf_release(struct hte_ts_buf *r)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	r->valid = false;
+	kfifo_free(&kf->gkf);
+	kfree(kf);
+}
+
+static inline void hte_ts_buf_reset(struct hte_ts_buf *r)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if (!r->valid)
+		return;
+
+	kfifo_reset(&kf->gkf);
+}
+
+static const struct hte_ts_buf_acc_func kfifo_access_funcs = {
+	.store = &hte_ts_store_to_buf,
+	.read = &hte_ts_buf_read,
+	.el_available = &hte_ts_buf_el_available,
+	.set_length = &hte_ts_buf_set_length,
+	.get_length = &hte_ts_buf_get_length,
+	.set_watermark = &hte_ts_buf_set_watermark,
+	.get_watermark = &hte_ts_buf_get_watermark,
+	.release = &hte_ts_buf_release,
+	.reset = &hte_ts_buf_reset,
+};
+
+static struct hte_ts_buf *hte_ts_buf_allocate(void)
+{
+	struct hte_kfifo *kf;
+
+	kf = kzalloc(sizeof(*kf), GFP_KERNEL);
+	if (!kf)
+		return ERR_PTR(-ENOMEM);
+
+	init_waitqueue_head(&kf->buffer.pollq);
+	kf->buffer.watermark = 1;
+	kf->buffer.datum_len = 0;
+	kf->buffer.valid = false;
+	kf->buffer.access = &kfifo_access_funcs;
+
+	return &kf->buffer;
+}
+/* End of buffer management */
+
+/* Debugfs management */
+
+#ifdef CONFIG_DEBUG_FS
+
+static struct dentry *hte_root;
+
+static void __init hte_subsys_dbgfs_init(void)
+{
+	/* creates /sys/kernel/debug/hte/ */
+	hte_root = debugfs_create_dir("hte", NULL);
+}
+subsys_initcall(hte_subsys_dbgfs_init);
+
+static void hte_chip_dbgfs_init(struct hte_device *gdev)
+{
+	const struct hte_chip *chip = gdev->chip;
+	const char *name = chip->name ? chip->name : dev_name(chip->dev);
+
+	gdev->dbg_root = debugfs_create_dir(name, hte_root);
+	if (!gdev->dbg_root)
+		return;
+
+	debugfs_create_atomic_t("ts_requested", 0444, gdev->dbg_root,
+				&gdev->ts_req);
+	debugfs_create_u32("total_ts", 0444, gdev->dbg_root,
+			   &gdev->nlines);
+}
+
+static void hte_ts_dbgfs_init(const char *name, struct hte_ts_info *ei)
+{
+	if (!ei->gdev->dbg_root || !name)
+		return;
+
+	ei->ts_dbg_root = debugfs_create_dir(name, ei->gdev->dbg_root);
+	if (!ei->ts_dbg_root)
+		return;
+
+	debugfs_create_size_t("ts_buffer_depth", 0444, ei->ts_dbg_root,
+			      &ei->buf->datum_len);
+	debugfs_create_size_t("ts_buffer_watermark", 0444, ei->ts_dbg_root,
+			      &ei->buf->watermark);
+	debugfs_create_atomic_t("dropped_timestamps", 0444, ei->ts_dbg_root,
+				&ei->dropped_ts);
+}
+
+static inline void hte_dbgfs_deinit(struct dentry *root)
+{
+	if (!root)
+		return;
+
+	debugfs_remove_recursive(root);
+}
+
+#else
+
+static void hte_chip_dbgfs_init(struct hte_device *gdev)
+{
+}
+
+static void hte_ts_dbgfs_init(const char *name, struct hte_ts_info *ei)
+{
+}
+
+static inline void hte_dbgfs_deinit(struct dentry *root)
+{
+}
+
+#endif
+/* end of debugfs management*/
+
+/* Driver APIs */
+
+/**
+ * hte_release_ts() - Consumer calls this API to release the entity, where
+ * entity could be anything providers support, like lines, signals, buses,
+ * etc...
+ *
+ * The correct sequence to call this API is as below:
+ * 1) Call hte_disable_ts, this stops the timestamp push from the provider.
+ * 2) Retrieve timestamps by calling non blocking hte_retrieve_ts_ns API if you
+ * still care about the data.
+ * 3) Call this API.
+ * Above sequence makes sure that entity gets released race free.
+ *
+ * @desc: timestamp descriptor, this is the same as returned by the request API.
+ *
+ * Context: hte_dbgfs_deinit() function call may use sleeping locks,
+ *	    not suitable from atomic context in that case.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_release_ts(struct hte_ts_desc *desc)
+{

drivers/hte/hte.c line 388

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	u32 id;
+	int ret = 0;
+	struct hte_device *gdev;
+	struct hte_ts_info *ei;
+	struct hte_ts_buf *buf;
+
+	if (!desc)
+		return -EINVAL;
+
+	ei = (struct hte_ts_info *)desc->data_subsys;

As data_subsys is void * you don't need to explicitly cast it to another pointer type.

Quoted 40 lines
drivers/hte/hte.c new file +40 -0
+
+	if (!ei || !ei->gdev || !ei->buf)
+		return -EINVAL;
+
+	gdev = ei->gdev;
+	buf = ei->buf;
+	id = desc->con_id;
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags)) {
+		dev_info(gdev->sdev, "id:%d is not registered", id);
+		return -EUSERS;
+	}
+
+	ret = gdev->chip->ops->release(gdev->chip, ei->xlated_id);
+	if (ret) {
+		dev_err(gdev->sdev, "id: %d free failed\n", id);
+		goto out;
+	}
+
+	atomic_dec(&gdev->ts_req);
+	atomic_set(&ei->dropped_ts, 0);
+
+	kfree(desc->name);
+	kfree(desc);
+	ei->desc = NULL;
+	ei->seq = 0;
+	buf->access->release(buf);
+
+	hte_dbgfs_deinit(ei->ts_dbg_root);
+	module_put(gdev->owner);
+
+	clear_bit(HTE_TS_REGISTERED, &ei->flags);
+
+out:
+	dev_dbg(gdev->sdev, "%s: id: %d\n", __func__, id);
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_release_ts);
+
+static int hte_ts_dis_en_common(struct hte_ts_desc *desc, bool en)

drivers/hte/hte.c line 438

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+{
+	u32 ts_id;
+	struct hte_device *gdev;
+	struct hte_ts_info *ei;
+	int ret;
+
+	if (!desc)
+		return -EINVAL;
+
+	ei = (struct hte_ts_info *)desc->data_subsys;

As above, no need to cast - though it rather implies the type of data_subsys should not be void *.

Quoted 19 lines
drivers/hte/hte.c new file +19 -0
+
+	if (!ei || !ei->gdev)
+		return -EINVAL;
+
+	gdev = ei->gdev;
+	ts_id = desc->con_id;
+
+	mutex_lock(&ei->mlock);
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags)) {
+		dev_dbg(gdev->sdev, "id:%d is not registered", ts_id);
+		ret = -EUSERS;
+		goto out;
+	}
+
+	if (en) {
+		if (!test_bit(HTE_TS_DISABLE, &ei->flags)) {
+			ret = 0;
+			goto out;

drivers/hte/hte.c line 467

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		}
+		ret = gdev->chip->ops->enable(gdev->chip, ei->xlated_id);
+		if (ret) {
+			dev_warn(gdev->sdev, "id: %d enable failed\n",
+				 ts_id);
+			goto out;
+		}
+
+		clear_bit(HTE_TS_DISABLE, &ei->flags);
+		ret = 0;

ret is already 0 so no point in setting it again.

Quoted 135 lines
drivers/hte/hte.c new file +135 -0
+	} else {
+		if (test_bit(HTE_TS_DISABLE, &ei->flags)) {
+			ret = 0;
+			goto out;
+		}
+		ret = gdev->chip->ops->disable(gdev->chip, ei->xlated_id);
+		if (ret) {
+			dev_warn(gdev->sdev, "id: %d disable failed\n",
+				 ts_id);
+			goto out;
+		}
+
+		set_bit(HTE_TS_DISABLE, &ei->flags);
+		ret = 0;
+	}
+
+out:
+	mutex_unlock(&ei->mlock);
+	return ret;
+}
+
+/**
+ * hte_disable_ts() - Disable timestamp on given descriptor.
+ *
+ * @desc: ts descriptor, this is the same as returned by the request API.
+ *
+ * Context: Holds mutex lock, not suitable from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_disable_ts(struct hte_ts_desc *desc)
+{
+	return hte_ts_dis_en_common(desc, false);
+}
+EXPORT_SYMBOL_GPL(hte_disable_ts);
+
+/**
+ * hte_enable_ts() - Enable timestamp on given descriptor.
+ *
+ * @desc: ts descriptor, this is the same as returned by the request API.
+ *
+ * Context: Holds mutex lock, not suitable from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_enable_ts(struct hte_ts_desc *desc)
+{
+	return hte_ts_dis_en_common(desc, true);
+}
+EXPORT_SYMBOL_GPL(hte_enable_ts);
+
+static int hte_simple_xlate(struct hte_chip *gc,
+			    const struct of_phandle_args *args,
+			    struct hte_ts_desc *desc,
+			    u32 *id)
+{
+	if (!id || !desc || !gc)
+		return -EINVAL;
+
+	/*
+	 * For the providers which do not have any internal mappings between
+	 * logically exposed ids and actual ids, will set both
+	 * the same.
+	 *
+	 * In case there is a internal mapping needed, providers will need to
+	 * provide its own xlate function where con_id will be sent as
+	 * args[0] and it will return xlated id. Later xlated id will be
+	 * used for any future exchanges between provider and subsystems.
+	 */
+
+	if (args) {
+		if (gc->of_hte_n_cells < 1)
+			return -EINVAL;
+
+		if (args->args_count != gc->of_hte_n_cells)
+			return -EINVAL;
+
+		*id = args->args[0];
+		desc->con_id = *id;
+	} else {
+		*id = desc->con_id;
+	}
+
+	if (desc->con_id > gc->nlines)
+		return -EINVAL;
+
+	desc->data_subsys = NULL;
+
+	return 0;
+}
+
+static struct hte_device *of_node_to_htedevice(struct device_node *np)
+{
+	struct hte_device *gdev;
+
+	spin_lock(&hte_lock);
+
+	list_for_each_entry(gdev, &hte_devices, list)
+		if (gdev->chip && gdev->chip->dev &&
+		    gdev->chip->dev->of_node == np) {
+			spin_unlock(&hte_lock);
+			return gdev;
+		}
+
+	spin_unlock(&hte_lock);
+
+	return ERR_PTR(-ENODEV);
+}
+
+static int ___hte_req_ts(struct hte_device *gdev, struct hte_ts_desc *desc,
+			 u32 xlated_id, void (*cb)(enum hte_notify n))
+{
+	struct hte_ts_info *ei;
+	struct hte_ts_buf *buf;
+	int ret;
+	u32 con_id = desc->con_id;
+
+	if (!try_module_get(gdev->owner))
+		return -ENODEV;
+
+	ei = &gdev->ei[xlated_id];
+	ei->xlated_id = xlated_id;
+
+	/*
+	 * There a chance that multiple consumers requesting same entity,
+	 * lock here.
+	 */
+	mutex_lock(&ei->mlock);
+
+	if (test_bit(HTE_TS_REGISTERED, &ei->flags)) {
+		dev_dbg(gdev->chip->dev, "id:%u is already registered",
+			xlated_id);
+		ret = -EUSERS;
+		goto unlock;
+	}
+
+	buf = hte_ts_buf_allocate();

drivers/hte/hte.c line 612

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	if (IS_ERR(buf)) {
+		dev_err(gdev->chip->dev, "Buffer allocation failed");
+		ret = PTR_ERR(buf);
+		goto unlock;
+	}
+
+	/* Set default here, let consumer decide how much to set later */
+	ret = buf->access->set_length(buf, HTE_EV_FIFO_EL,
+				      sizeof(struct hte_ts_data));
+

It's good to keep to consistent style of no line break between a statement and it's error check.

Quoted 140 lines
drivers/hte/hte.c new file +140 -0
+	if (ret) {
+		dev_err(gdev->chip->dev, "Fifo set length failed");
+		goto buf_rel;
+	}
+
+	buf->access->reset(buf);
+	buf->valid = true;
+
+	ei->buf = buf;
+	ei->cb = cb;
+
+	ret = gdev->chip->ops->request(gdev->chip, xlated_id);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev, "ts request failed\n");
+		goto buf_rel;
+	}
+
+	desc->data_subsys = ei;
+	ei->desc = desc;
+
+	atomic_inc(&gdev->ts_req);
+	set_bit(HTE_TS_REGISTERED, &ei->flags);
+	mutex_unlock(&ei->mlock);
+
+	if (!desc->name) {
+		desc->name = kzalloc(HTE_TS_NAME_LEN, GFP_KERNEL);
+		if (desc->name)
+			scnprintf(desc->name, HTE_TS_NAME_LEN, "ts_%u",
+				  con_id);
+	}
+
+	hte_ts_dbgfs_init(desc->name, ei);
+
+	dev_dbg(gdev->chip->dev, "%s: id: %u, xlated id:%u",
+		__func__, con_id, xlated_id);
+
+	return 0;
+
+buf_rel:
+	buf->access->release(buf);
+unlock:
+	module_put(gdev->owner);
+	mutex_unlock(&ei->mlock);
+
+	return ret;
+}
+
+static struct hte_device *of_hte_dev_get(struct device *dev,
+					 struct device_node *np,
+					 const char *label,
+					 struct of_phandle_args *args)
+{
+	struct hte_device *gdev = NULL;
+	int index = 0;
+	int err;
+
+	if (label) {
+		index = of_property_match_string(np, "hte-names", label);
+		if (index < 0)
+			return ERR_PTR(index);
+	}
+
+	err = of_parse_phandle_with_args(np, "htes", "#hte-cells", index,
+					 args);
+	if (err) {
+		pr_err("%s(): can't parse \"htes\" property\n", __func__);
+		return ERR_PTR(err);
+	}
+
+	gdev = of_node_to_htedevice(args->np);
+	if (IS_ERR(gdev)) {
+		pr_err("%s(): HTE chip not found\n", __func__);
+		of_node_put(args->np);
+		return gdev;
+	}
+
+	return gdev;
+}
+
+static struct hte_ts_desc *__hte_req_ts(struct device *dev,
+					struct device_node *np,
+					const char *label,
+					void (*cb)(enum hte_notify n))
+{
+	struct hte_device *gdev = NULL;
+	struct hte_ts_desc *desc;
+	struct of_phandle_args args;
+	int ret;
+	u32 xlated_id;
+
+	gdev = of_hte_dev_get(dev, np, label, &args);
+	if (IS_ERR(gdev))
+		return ERR_CAST(gdev);
+
+	if (!gdev->chip) {
+		pr_debug("requested id does not have provider\n");
+		return ERR_PTR(-ENODEV);
+	}
+
+	desc = kzalloc(sizeof(*desc), GFP_KERNEL);
+	if (!desc)
+		return ERR_PTR(-ENOMEM);
+
+	ret = gdev->chip->xlate(gdev->chip, &args, desc, &xlated_id);
+	if (ret < 0)
+		goto put;
+
+	desc->name = NULL;
+	if (label)
+		desc->name = kstrdup(label, GFP_KERNEL);
+
+	ret = ___hte_req_ts(gdev, desc, xlated_id, cb);
+	if (ret < 0)
+		goto put;
+
+	return desc;
+
+put:
+	of_node_put(args.np);
+	kfree(desc);
+
+	return ERR_PTR(ret);
+}
+
+/**
+ * of_hte_request_ts() - Consumer calls this API to request the HTE facility
+ * on the specified entity, where entity is provider specific for example,
+ * GPIO lines, signals, buses etc...
+ *
+ * @dev: Consumer device.
+ * @label: Optional label.
+ * @cb: Optional notify callback to consumer when data is pushed by the
+ * provider.
+ *
+ * Context: Holds mutex lock, not suitable from atomic context.
+ * Returns: Timestamp descriptor on success or error ptr on failure.
+ */
+struct hte_ts_desc *of_hte_request_ts(struct device *dev,
+				      const char *label,
+				      void (*cb)(enum hte_notify n))

drivers/hte/hte.c line 762

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+{
+
+	if (dev && dev->of_node)
+		return __hte_req_ts(dev, dev->of_node, label, cb);
+	else
+		return ERR_PTR(-EOPNOTSUPP);
+}
+EXPORT_SYMBOL_GPL(of_hte_request_ts);
+
+static int devm_hte_ts_match_desc(struct device *dev, void *res, void *data)

I'm not seeing what is devm about this.

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+{
+	struct hte_ts_desc **p = res;
+
+	if (WARN_ON(!p || !*p))
+		return 0;
+

drivers/hte/hte.c line 778

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	return *p == data;
+}
+
+static void __devm_hte_release_ts(struct device *dev, void *res)
+{
+	hte_release_ts(*(struct hte_ts_desc **)res);
+}
+
+/**
+ * devm_hte_release_ts() - Resource managed hte_release_ts().

I'd not introduce this until you have a user. It very rarely actually makes sense to call a devm release manually. Not having one makes people think harder about it.

Quoted 9 lines
drivers/hte/hte.c new file +9 -0
+ * @dev: HTE consumer/client device.
+ * @desc: HTE ts descriptor.
+ *
+ * Release timestamp functionality and its resources previously allocated using
+ * of_hte_request_ts(). Calling this function is usually not needed because
+ * devm-allocated resources are automatically released on driver detach.
+ *
+ * Context: Same as hte_release_ts() function.
+ * Returns: 0 on success otherwise negative error code.

drivers/hte/hte.c line 797

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+ */
+int devm_hte_release_ts(struct device *dev, struct hte_ts_desc *desc)
+{
+	return devres_release(dev, __devm_hte_release_ts,
+			      devm_hte_ts_match_desc, desc);
+}
+EXPORT_SYMBOL_GPL(devm_hte_release_ts);
+
+/**
+ * devm_of_hte_request_ts() - Resource managed of_hte_request_ts().

If it's kernel-doc it needs to give no warnings when you point the kernel-doc scripts at it. They insist on full parameter documentation.

drivers/hte/hte.c line 806

Quoted 9 lines
drivers/hte/hte.c new file +9 -0
+ */
+struct hte_ts_desc *devm_of_hte_request_ts(struct device *dev,
+					   const char *label,
+					   void (*cb)(enum hte_notify n))
+{
+
+	struct hte_ts_desc **ptr, *desc;
+
+	ptr = devres_alloc(__devm_hte_release_ts, sizeof(*ptr), GFP_KERNEL);

Superficially looks like you might get way with just calling dev_add_action_or_reset() in here and avoid this boilerplate. A lot of cases that looked like this got cleaned up in the last kernel cycle.

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+	if (!ptr)
+		return ERR_PTR(-ENOMEM);
+
+	desc = of_hte_request_ts(dev, label, cb);
+	if (!IS_ERR(desc)) {
+		*ptr = desc;

drivers/hte/hte.c line 822

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		devres_add(dev, ptr);
+	} else {
+		devres_free(ptr);
+	}
+	return desc;
+}
+EXPORT_SYMBOL_GPL(devm_of_hte_request_ts);
+
+static struct hte_ts_info *hte_para_check(const struct hte_ts_desc *desc,
+					  size_t val)

Not a good name or indeed combination of different things. hte_desc_to_info() and some separate check on val would be better.

Quoted 14 lines
drivers/hte/hte.c new file +14 -0
+{
+	struct hte_ts_info *ei;
+
+	if (!desc || !desc->data_subsys || !val) {
+		pr_debug("%s:%d: val :%lu\n", __func__, __LINE__, val);
+		return NULL;
+	}
+
+	ei = desc->data_subsys;
+	if (!ei || !ei->buf) {
+		pr_debug("%s:%d\n", __func__, __LINE__);
+		return NULL;
+	}
+

drivers/hte/hte.c line 846

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	return ei;
+}
+
+static inline bool hte_ts_buf_wait(struct hte_ts_buf *buffer, size_t to_read)
+{
+	size_t el_avail;
+
+	el_avail = buffer->access->el_available(buffer);
+
+	return (el_avail >= to_read) ? false : true;

return el_avail < to_read;

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+}
+
+static int _hte_retrieve_ts_ns(const struct hte_ts_desc *desc,
+			       struct hte_ts_data *el, size_t n, bool block)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;

drivers/hte/hte.c line 863

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	int ret;
+	size_t to_read, copied;
+
+	ei = hte_para_check(desc, n);
+	if (!ei)
+		return -EINVAL;
+
+	buffer = ei->buf;
+
+	to_read = min_t(size_t, n, buffer->watermark);

Needs a comment as not obvious why you'd read the min of that requested or the watermark if there might be more available.

Quoted 5 lines
drivers/hte/hte.c new file +5 -0
+
+	do {
+		if (hte_ts_buf_wait(buffer, to_read)) {
+			if (!block) {
+				/* Possibly early here to retrieve, try again */

drivers/hte/hte.c line 878

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+				dev_dbg(ei->gdev->chip->dev, "%s: %d\n",
+					__func__, ret);
+				return -EAGAIN;
+			}
+			ret = wait_event_interruptible(buffer->pollq,
+					!hte_ts_buf_wait(buffer, to_read));
+			if (ret)
+				return ret;
+		}
+		ret = buffer->access->read(buffer, (void *)el,

If you have to cast to a void * that usually means something is wrong in your definitions. Why is it needed here? Looks like read has an inappropriate definition.

Quoted 56 lines
drivers/hte/hte.c new file +56 -0
+					   n * buffer->bytes_per_datum,
+					   &copied);
+		if (ret < 0)
+			return ret;
+
+		if (copied > 0)
+			return 0;
+		else if (copied == 0 && !block)
+			return -EAGAIN;
+	} while (copied == 0);
+
+	return 0;
+}
+
+/**
+ * hte_retrieve_ts_ns() - Consumer calls this API to retrieve timestamp in
+ * nano seconds i.e. el->tsc will be in ns.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ * @el: buffer to store the timestamp details.
+ * @n: Number of struct hte_timestamp_el elements.
+ *
+ * Context: Can be called from the atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_retrieve_ts_ns(const struct hte_ts_desc *desc,
+		       struct hte_ts_data *el, size_t n)
+{
+	return _hte_retrieve_ts_ns(desc, el, n, false);
+}
+EXPORT_SYMBOL_GPL(hte_retrieve_ts_ns);
+
+/**
+ * hte_retrieve_ts_ns_wait() - Blocking version of the hte_retrieve_ts_ns.
+ * @desc: ts descriptor, same as returned from request API.
+ * @el: buffer to store the timestamp data.
+ * @n: Number of struct hte_ts_data data.
+ *
+ * Context: Can not be called from the atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_retrieve_ts_ns_wait(const struct hte_ts_desc *desc,
+			    struct hte_ts_data *el, size_t n)
+{
+	return _hte_retrieve_ts_ns(desc, el, n, true);
+}
+EXPORT_SYMBOL_GPL(hte_retrieve_ts_ns_wait);
+
+/**
+ * hte_set_buf_len() - Consumer calls this API to set timestamp software buffer
+ * depth.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ * @len: New length/depth.
+ *
+ * The correct sequence to set buffer length is as below:

drivers/hte/hte.c line 944

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+ * 1) Disable timestamp by calling hte_disable_ts API.
+ * 2) Optionally retrieve all the timestamps by calling non blocking
+ *    hte_retrieve_ts_ns() API. This step only needed if you still care about
+ *    the data.
+ * 3) Call this API.
+ * 4) Enable timestamp by calling hte_enable_ts API.
+ *
+ * This API destroys previously allocated buffer and creates new one, because
+ * of that, it is mandatory to follow above sequence to make sure there is no
+ * race between various other APIs in the subsystem.

Good docs. This is why I mentioned in review of docs patch that it is better to just have that refer to the kernel-doc in these files. Keep all this good information in one place.

Quoted 13 lines
drivers/hte/hte.c new file +13 -0
+ *
+ * By default during the request API call, HTE subsystem allocates software
+ * buffer with predefined length, this API gives flexibility to adjust the
+ * length according to consumer's need.
+ *
+ * Context: Can not be called from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_set_buf_len(const struct hte_ts_desc *desc, size_t len)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+	int ret;

drivers/hte/hte.c line 967

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+
+	ei = hte_para_check(desc, len);
+	if (!ei)
+		return -EINVAL;
+
+	buffer = ei->buf;
+	ret = buffer->access->set_length(buffer, len,
+					 sizeof(struct hte_ts_data));
+	if (ret)
+		dev_err(ei->gdev->chip->dev, "%s: ret:%d\n", __func__, ret);

Not point in printing things line __func__ manually in dev_err() etc. Dynamic debug includes that and gives far more information + control of this.

Quoted 65 lines
drivers/hte/hte.c new file +65 -0
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_set_buf_len);
+
+/**
+ * hte_get_buf_len() - Consumer calls this API to get timestamp software buffer
+ * depth or length.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: Positive length on success or 0 on failure.
+ */
+size_t hte_get_buf_len(const struct hte_ts_desc *desc)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	ei = hte_para_check(desc, 1);
+	if (!ei)
+		return 0;
+
+	buffer = ei->buf;
+
+	return buffer->access->get_length(buffer);
+}
+EXPORT_SYMBOL_GPL(hte_get_buf_len);
+
+/**
+ * hte_available_ts() - Returns total available timestamps.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * The API helps consumers to pre-allocate its internal buffer required
+ * during hte_retrieve_ts_ns call.
+ *
+ * Context: Any context.
+ * Returns: Positive value if elements are available else 0. The value is
+ * number of total available struct hte_timestamp_el elements available not
+ * the size in bytes.
+ */
+size_t hte_available_ts(const struct hte_ts_desc *desc)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	ei = hte_para_check(desc, 1);
+	if (!ei)
+		return 0;
+
+	buffer = ei->buf;
+
+	return buffer->access->el_available(buffer);
+}
+EXPORT_SYMBOL_GPL(hte_available_ts);
+
+/**
+ * hte_set_buf_watermark() - Consumer calls this API to set timestamp software
+ * buffer watermark. The correct sequence to call this API is as below:
+ * 1) Disable timestamp by calling hte_disable_ts API.
+ * 2) Call this API.
+ * 3) Enable timestamp by calling hte_enable_ts API.
+ *
+ * @desc: ts descriptor, same as returned from request API.

drivers/hte/hte.c line 1042

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+ * @val: New watermark.
+ *
+ * By default during the request API call, HTE subsystem sets watermark as 1,
+ * this API gives flexibility to adjust the watermark according to consumer's
+ * need. The consumers will get notification through callback registered during
+ * request API either when timestamp is dropped or watermark is reached or will
+ * wait till watermark is reached. Refer hte_retrieve_ts_ns() and
+ * hte_push_ts_ns_atomic() APIs to understand how watermark is used.
+ *
+ * Context: Any context.

You have no way of knowing that as will depend on the driver - I'd definitely suggest not from atomic context, but then that would be crazy so you are better
off not documenting any specific requirement at all.

Quoted 44 lines
drivers/hte/hte.c new file +44 -0
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_set_buf_watermark(const struct hte_ts_desc *desc, size_t val)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+	int ret;
+
+	ei = hte_para_check(desc, val);
+	if (!ei)
+		return -EINVAL;
+
+	buffer = ei->buf;
+	ret = buffer->access->set_watermark(buffer, val);
+	if (ret)
+		dev_dbg(ei->gdev->chip->dev, "%s: ret:%d\n", __func__, ret);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_set_buf_watermark);
+
+/**
+ * hte_get_buf_watermark() - Consumer calls this API to get software
+ * buffer watermark.
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: Positive current watermark on success or 0 on failure.
+ */
+size_t hte_get_buf_watermark(const struct hte_ts_desc *desc)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	ei = hte_para_check(desc, 1);
+	if (!ei)
+		return 0;
+
+	buffer = ei->buf;
+
+	return buffer->access->get_watermark(buffer);
+}
+EXPORT_SYMBOL_GPL(hte_get_buf_watermark);
+

drivers/hte/hte.c line 1096

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+/**
+ * hte_req_ts_by_dt_node() - Request entity to monitor by passing HTE device
+ * node directly, where meaning of the entity is provider specific, for example
+ * lines, signals, GPIOs, buses etc...
+ *
+ * @of_node: HTE provider device node.
+ * @id: entity id to monitor, this id belongs to HTE provider of_node.
+ * @cb: Optional callback to notify.
+ *
+ * Context: Holds mutex lock, can not be called from atomic context.

What mutex and why? If it is one you can check is held even better.

Quoted 13 lines
drivers/hte/hte.c new file +13 -0
+ * Returns: ts descriptor on success or error pointers.
+ */
+struct hte_ts_desc *hte_req_ts_by_dt_node(struct device_node *of_node,
+					  unsigned int id,
+					  void (*cb)(enum hte_notify n))
+{
+	struct hte_device *gdev;
+	struct hte_ts_desc *desc;
+	int ret;
+	u32 xlated_id;
+
+	gdev = of_node_to_htedevice(of_node);
+	if (IS_ERR(gdev))

drivers/hte/hte.c line 1119

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		return ERR_PTR(-ENOTSUPP);
+
+	if (!gdev->chip || !gdev->chip->ops)
+		return ERR_PTR(-ENOTSUPP);
+
+	desc = kzalloc(sizeof(*desc), GFP_KERNEL);
+	if (!desc) {
+		ret = -ENOMEM;
+		goto out_put_device;
+	}

Pass a desc pointer into this function rather than allocating the structure in here. That lets the caller embed that structure inside one of it's own structures if it wants to, resulting in fewer small allocations which is always good.

It's far from obvious that the caller needs to free desc.

Quoted 51 lines
drivers/hte/hte.c new file +51 -0
+
+	desc->con_id = id;
+	ret = gdev->chip->xlate(gdev->chip, NULL, desc, &xlated_id);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev,
+			"failed to xlate id: %d\n", id);
+		goto out_free_desc;
+	}
+
+	ret = ___hte_req_ts(gdev, desc, xlated_id, cb);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev,
+			"failed to request id: %d\n", id);
+		goto out_free_desc;
+	}
+
+	return desc;
+
+out_free_desc:
+	kfree(desc);
+
+out_put_device:
+	return ERR_PTR(ret);
+}
+EXPORT_SYMBOL_GPL(hte_req_ts_by_dt_node);
+
+/**
+ * hte_get_clk_src_info() - Consumer calls this API to query clock source
+ * information of the desc.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: 0 on success else negative error code on failure.
+ */
+int hte_get_clk_src_info(const struct hte_ts_desc *desc,
+			 struct hte_clk_info *ci)
+{
+	struct hte_chip *chip;
+	struct hte_ts_info *ei;
+
+	if (!desc || !desc->data_subsys || !ci) {
+		pr_debug("%s:%d\n", __func__, __LINE__);
+		return -EINVAL;
+	}
+
+	ei = desc->data_subsys;
+	if (!ei || !ei->gdev || !ei->gdev->chip)
+		return -EINVAL;
+
+	chip = ei->gdev->chip;

drivers/hte/hte.c line 1180

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	if (!chip->ops->get_clk_src_info)
+		return -ENOTSUPP;
+
+	return chip->ops->get_clk_src_info(chip, ci);
+}
+EXPORT_SYMBOL_GPL(hte_get_clk_src_info);
+
+static inline void hte_add_to_device_list(struct hte_device *gdev)
+{
+	struct hte_device *prev;

Needs to take an appropriate lock as you may have concurrent calls.

drivers/hte/hte.c line 1183

Quoted 3 lines
drivers/hte/hte.c new file +3 -0
+
+	if (list_empty(&hte_devices)) {
+		list_add_tail(&gdev->list, &hte_devices);

Needs a comment. I've no idea why you might want to only add it if there were no other hte_devices already there.

drivers/hte/hte.c line 1187

Quoted 4 lines
drivers/hte/hte.c new file +4 -0
+		return;
+	}
+
+	prev = list_last_entry(&hte_devices, struct hte_device, list);

Why woud you do this?

Quoted 37 lines
drivers/hte/hte.c new file +37 -0
+	list_add_tail(&gdev->list, &hte_devices);
+}
+
+/**
+ * hte_push_ts_ns_atomic() - Used by the provider to push timestamp in nano
+ * seconds i.e data->tsc will be in ns, it is assumed that provider will be
+ * using this API from its ISR or atomic context.
+ *
+ * @chip: The HTE chip, used during the registration.
+ * @xlated_id: entity id understood by both subsystem and provider, usually this
+ * is obtained from xlate callback during request API.
+ * @data: timestamp data.
+ * @n: Size of the data.
+ *
+ * Context: Atomic.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_push_ts_ns_atomic(const struct hte_chip *chip, u32 xlated_id,
+			  struct hte_ts_data *data, size_t n)
+{
+	unsigned int ret;
+	bool notify;
+	size_t el_avail;
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	if (!chip || !data || !chip->gdev)
+		return -EINVAL;
+
+	if (xlated_id > chip->nlines)
+		return -EINVAL;
+
+	ei = &chip->gdev->ei[xlated_id];
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags) ||
+	    test_bit(HTE_TS_DISABLE, &ei->flags)) {
+		dev_dbg(chip->dev, "Unknown timestamp push\n");

drivers/hte/hte.c line 1233

Quoted 10 lines
drivers/hte/hte.c new file +9 -0
+		return -EINVAL;
+	}
+
+	/* timestamp sequence counter, start from 0 */
+	data->seq = ei->seq++;
+
+	buffer = ei->buf;
+	el_avail = buffer->access->el_available(buffer);
 
+	ret = buffer->access->store(buffer, data, n);

If we are doing this from the hte core, why is buffer definition in the scope of the drivers rather than the core? That seems backwards to me.

drivers/hte/hte.c line 1241

Quoted 8 lines
drivers/hte/hte.c new file +8 -0
+	if (ret != n) {
+		atomic_inc(&ei->dropped_ts);
+		if (ei->cb)
+			ei->cb(HTE_TS_DROPPED);
+		return -ENOMEM;
+	}
+
+	notify = ((el_avail + 1) >= buffer->watermark) ? true : false;

You push n but only check on el_avail + 1 here.
Also, this is the same as

	notify = ((el_avail + 1) >= buffer->watermark;

drivers/hte/hte.c line 1249

Quoted 8 lines
drivers/hte/hte.c new file +8 -0
+
+	/*
+	 * If there is a callback, its consumer's job to retrieve the timestamp.
+	 * For the rest, wake up the process.
+	 */
+	if (notify && ei->cb) {
+		ei->cb(HTE_TS_AVAIL);
+		return 0;

Given you return 0 anyway, might as well not have this line.

drivers/hte/hte.c line 1262

Quoted 13 lines
drivers/hte/hte.c new file +13 -0
+	} else if (notify) {
+		wake_up_interruptible(&buffer->pollq);
+	}
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(hte_push_ts_ns_atomic);
+
+/**
+ * hte_register_chip() - Used by provider to register a HTE chip.
+ * @chip: the HTE chip to add to subsystem.
+ *
+ * Context: Can not be called from atomic context.

Whilst true, I'd think that was common sense as it would be insane to register something like this from atomic context. So I'd say no need to comment on it! Keep those comments for things that might be used like that.

Quoted 25 lines

+ * Returns: 0 on success or a negative error code on failure.
+ */

drivers/hte/hte.c new file +23 -0
+int hte_register_chip(struct hte_chip *chip)
+{
+	struct hte_device *gdev;
+	int ret;
+	u32 i;
+
+	if (!chip || !chip->dev || !chip->dev->of_node)
+		return -EINVAL;
+
+	if (!chip->ops || !chip->ops->request || !chip->ops->release) {
+		dev_err(chip->dev, "Driver needs to provide ops\n");
+		return -EINVAL;
+	}
+
+	gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
+	if (!gdev)
+		return -ENOMEM;
+
+	gdev->chip = chip;
+	chip->gdev = gdev;
+	gdev->nlines = chip->nlines;
+	gdev->sdev = chip->dev;
+

drivers/hte/hte.c line 1297

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	/*
+	 * Allocate all the supported entities here at once, this will have
+	 * following advantages:
+	 * When provider pushes timestamp, it can then just send the
+	 * xlated_id, subsystem will use it as an index which
+	 * gives us the constant time access; this is important as mostly
+	 * providers will be pushing the timestamps from their ISR.
+	 */
+	gdev->ei = kcalloc(chip->nlines, sizeof(struct hte_ts_info),
+			   GFP_KERNEL);

I'd be tempted to do this as a 0 length element at the end of gdev then do the allocation in one go use struct_size() etc to work out how long it is. Cuts down on allocations + error paths to deal with for no obvious disadvantage.

drivers/hte/hte.c line 1304

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+	if (!gdev->ei) {
+		ret = -ENOMEM;
+		goto err_free_gdev;
+	}
+
+	for (i = 0; i < chip->nlines; i++) {
+		gdev->ei[i].flags = 0;

zero allocated, so don't bother setting things to 0 where it's a fairly obvious base state. If you set something to 0 to act as some form of documentation then that's fine, but I don't think that's true here.

Quoted 54 lines
drivers/hte/hte.c new file +54 -0
+		gdev->ei[i].gdev = gdev;
+		gdev->ei[i].seq = 0;
+		mutex_init(&gdev->ei[i].mlock);
+	}
+
+	if (chip->dev->driver)
+		gdev->owner = chip->dev->driver->owner;
+	else
+		gdev->owner = THIS_MODULE;
+
+	if (!chip->xlate) {
+		chip->xlate = hte_simple_xlate;
+		/* Just a id number to monitor */
+		chip->of_hte_n_cells = 1;
+	}
+
+	of_node_get(chip->dev->of_node);
+
+	INIT_LIST_HEAD(&gdev->list);
+
+	spin_lock(&hte_lock);
+	hte_add_to_device_list(gdev);
+	spin_unlock(&hte_lock);
+
+	hte_chip_dbgfs_init(gdev);
+
+	dev_dbg(chip->dev, "Added hte chip\n");
+	return 0;
+
+err_free_gdev:
+	kfree(gdev);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_register_chip);
+
+/**
+ * hte_unregister_chip() - Used by the provider to remove a HTE chip.
+ * @chip: the HTE chip to remove.
+ *
+ * Context: Can not be called from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_unregister_chip(struct hte_chip *chip)
+{
+	struct hte_device *gdev = chip->gdev;
+
+	spin_lock(&hte_lock);
+	list_del(&gdev->list);
+	spin_unlock(&hte_lock);
+
+	gdev->chip = NULL;
+
+	of_node_put(chip->dev->of_node);

drivers/hte/hte.c line 1368

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	hte_dbgfs_deinit(gdev->dbg_root);
+	kfree(gdev->ei);
+	kfree(gdev);
+
+	dev_dbg(chip->dev, "Removed hte chip\n");
+	return 0;
+}
+EXPORT_SYMBOL_GPL(hte_unregister_chip);
+
+/* Driver APIs ends */

Don't bother with file layout type comments. They don't add that much and tend to rot horribly over time as people move code around in files.

Quoted 15 lines
include/linux/hte.h new file +9 -0
new file mode 100644
index 000000000000..e1737579d4c4
@@ -0,0 +1,278 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2021 NVIDIA Corporation
+ *
+ * Author: Dipen Patel <[email protected]>
+ */
+
+#ifndef __LINUX_HTE_H
+#define __LINUX_HTE_H

include/linux/hte.h line 19

Quoted 10 lines
include/linux/hte.h new file +10 -0
+
+struct hte_chip;
+struct hte_device;
+struct of_phandle_args;
+
+/**
+ * Used by providers to indicate the direction of the timestamp.
+ */
+#define HTE_EVENT_RISING_EDGE          0x1
+#define HTE_EVENT_FALLING_EDGE         0x2

Use an enum rather than a define for this as it's a value that can take a set of distinct values. Also, provide a name for 'I've no idea' which I'm guessing is 0 currently.

Quoted 13 lines
include/linux/hte.h new file +13 -0
+
+/**
+ * struct hte_ts_data - HTE timestamp data.
+ * The provider uses and fills timestamp related details during push_timestamp
+ * API call. The consumer uses during retrieve_timestamp API call.
+ *
+ * @tsc: Timestamp value.
+ * @seq: Sequence counter of the timestamps.
+ * @dir: Direction of the event at the time of timestamp.
+ */
+struct hte_ts_data {
+	u64 tsc;
+	u64 seq;

include/linux/hte.h line 42

Quoted 10 lines
include/linux/hte.h new file +10 -0
+	int dir;
+};
+
+/**
+ * struct hte_clk_info - Clock source info that HTE provider uses.
+ * The provider uses hardware clock as a source to timestamp real time. This
+ * structure presents the clock information to consumers. 
+ *
+ * @hz: Clock rate in HZ, for example 1KHz clock = 1000.
+ * @type: Clock type. CLOCK_* types.

So this is something we got a it wrong in IIO. It's much better to define a subset of clocks that can be potentially used. There are some that make absolutely no sense and consumers really don't want to have to deal with them.

include/linux/hte.h line 53

Quoted 11 lines
include/linux/hte.h new file +11 -0
+ */
+struct hte_clk_info {
+	u64 hz;
+	clockid_t type;
+};
+
+/**
+ * HTE subsystem notifications for the consumers.
+ *
+ * @HTE_TS_AVAIL: Timestamps available notification.
+ * @HTE_TS_DROPPED: Timestamps dropped notification.

Something I've missed so far is whether drops are in a kfifo or a ring fashion. I'm guess that's stated somewhere, but it might be useful to have it here.

Quoted 27 lines
include/linux/hte.h new file +27 -0
+ */
+enum hte_notify {
+	HTE_TS_AVAIL = 1,
+	HTE_TS_DROPPED,
+	HTE_NUM_NOTIFIER,
+};
+
+/**
+ * struct hte_ts_desc - HTE timestamp descriptor, this structure will be
+ * communication token between consumers to subsystem and subsystem to
+ * providers.
+ *
+ * @con_id: This is the same id sent in request APIs.
+ * @name: Descriptive name of the entity that is being monitored for the
+ * realtime timestamping.
+ * @data_subsys: Subsystem's private data relate to requested con_id.
+ */
+struct hte_ts_desc {
+	u32 con_id;
+	char *name;
+	void *data_subsys;
+};
+
+/**
+ * struct hte_ops - HTE operations set by providers.
+ *
+ * @request: Hook for requesting a HTE timestamp. Returns 0 on success,

include/linux/hte.h line 90

Quoted 10 lines
include/linux/hte.h new file +10 -0
+ * non-zero for failures.
+ * @release: Hook for releasing a HTE timestamp. Returns 0 on success,
+ * non-zero for failures.
+ * @enable: Hook to enable the specified timestamp. Returns 0 on success,
+ * non-zero for failures.
+ * @disable: Hook to disable specified timestamp. Returns 0 on success,
+ * non-zero for failures.
+ * @get_clk_src_info: Optional hook to get the clock information provider uses
+ * to timestamp. Returns 0 for success and negative error code for failure. On
+ * success HTE subsystem fills up provided struct hte_clk_info.

Why optional? Consumers will probably need that information.

Quoted 10 lines
include/linux/hte.h new file +10 -0
+ *
+ * xlated_id parameter is used to communicate between HTE subsystem and the
+ * providers. It is the same id returned during xlate API call and translated
+ * by the provider. This may be helpful as both subsystem and provider locate
+ * the requested entity in constant time, where entity could be anything from
+ * lines, signals, events, buses etc.. that providers support.
+ */
+struct hte_ops {
+	int (*request)(struct hte_chip *chip, u32 xlated_id);
+	int (*release)(struct hte_chip *chip, u32 xlated_id);

include/linux/hte.h line 110

Quoted 10 lines
include/linux/hte.h new file +10 -0
+	int (*enable)(struct hte_chip *chip, u32 xlated_id);
+	int (*disable)(struct hte_chip *chip, u32 xlated_id);
+	int (*get_clk_src_info)(struct hte_chip *chip,
+				struct hte_clk_info *ci);
+};
+
+/**
+ * struct hte_chip - Abstract HTE chip structure.
+ * @name: functional name of the HTE IP block.
+ * @dev: device providing the HTE.

Unclear naming. Is this the parent device, or one associated with the HTE itself? I'm guessing today you don't have one associated with the HTE, but it is plausible you might gain on in future to make it fit nicely in the device model as a function of another device.

Quoted 59 lines
include/linux/hte.h new file +58 -0
+ * @ops: callbacks for this HTE.
+ * @nlines: number of lines/signals supported by this chip.
+ * @xlate: Callback which translates consumer supplied logical ids to
+ * physical ids, return from 0 for the success and negative for the
+ * failures. It stores (0 to @nlines) in xlated_id parameter for the success.
+ * @of_hte_n_cells: Number of cells used to form the HTE specifier.
+ * @gdev: HTE subsystem abstract device, internal to the HTE subsystem.
+ * @data: chip specific private data.
+ */
+struct hte_chip {
+	const char *name;
+	struct device *dev;
+	const struct hte_ops *ops;
+	u32 nlines;
+	int (*xlate)(struct hte_chip *gc,
+		     const struct of_phandle_args *args,
+		     struct hte_ts_desc *desc, u32 *xlated_id);
+	u8 of_hte_n_cells;
+
+	/* only used internally by the HTE framework */
+	struct hte_device *gdev;
+	void *data;
+};
+
+#if IS_ENABLED(CONFIG_HTE)
+/* HTE APIs for the providers */
+int hte_register_chip(struct hte_chip *chip);
+int hte_unregister_chip(struct hte_chip *chip);
+int hte_push_ts_ns_atomic(const struct hte_chip *chip, u32 xlated_id,
+			  struct hte_ts_data *data, size_t n);
+
+/* HTE APIs for the consumers */
+
+int hte_release_ts(struct hte_ts_desc *desc);
+struct hte_ts_desc *of_hte_request_ts(struct device *dev, const char *label,
+				      void (*cb)(enum hte_notify n));
+
+struct hte_ts_desc *devm_of_hte_request_ts(struct device *dev,
+					   const char *label,
+					   void (*cb)(enum hte_notify n));
+struct hte_ts_desc *hte_req_ts_by_dt_node(struct device_node *of_node,
+					  unsigned int id,
+					  void (*cb)(enum hte_notify n));
+int devm_hte_release_ts(struct device *dev, struct hte_ts_desc *desc);
+int hte_retrieve_ts_ns(const struct hte_ts_desc *desc, struct hte_ts_data *el,
+		       size_t n);
+int hte_retrieve_ts_ns_wait(const struct hte_ts_desc *desc,
+			    struct hte_ts_data *el, size_t n);
+int hte_set_buf_len(const struct hte_ts_desc *desc, size_t len);
+size_t hte_get_buf_len(const struct hte_ts_desc *desc);
+int hte_set_buf_watermark(const struct hte_ts_desc *desc, size_t val);
+size_t hte_get_buf_watermark(const struct hte_ts_desc *desc);
+size_t hte_available_ts(const struct hte_ts_desc *desc);
+int hte_enable_ts(struct hte_ts_desc *desc);
+int hte_disable_ts(struct hte_ts_desc *desc);
+int hte_get_clk_src_info(const struct hte_ts_desc *desc,
+			 struct hte_clk_info *ci);
+
maintainer
#10 lore raw

Re: [RFC 02/11] drivers: Add HTE subsystem

Quoted 44 lines · On Sun, 4 Jul 2021 21:15:25 +0100 Jonathan Cameron <[email protected]> wrote:
Quoted 41 lines · On Fri, 25 Jun 2021 16:55:23 -0700 Dipen Patel <[email protected]> wrote:

Some devices can timestamp system lines/signals/Buses in real-time using the hardware counter or other hardware means which can give finer granularity and help avoid jitter introduced by software means of timestamping. To utilize such functionality there has to be framework where such devices can register themselves as producers or providers so that the consumers or clients devices can request specific line from the providers. This patch introduces such subsystem as hardware timestamping engine (HTE).

It provides below APIs for the provider:
- hte_register_chip() -- To register the HTE chip.
- hte_unregister_chip() -- To unregister the HTE chip.
- hte_push_ts_ns_atomic() -- To push timestamp data into HTE subsystem.

It provides below APIs for the consumer:
- of_hte_request_ts() -- To request timestamp functionality.
- devm_of_hte_request_ts() -- Managed version of the above.
- hte_req_ts_by_dt_node() -- To request timestamp functionality by using HTE provider dt node.
- devm_hte_release_ts() -- The managed version to release timestamp functionality and associated resources.
- hte_retrieve_ts_ns() -- To retrieve timestamps.
- hte_retrieve_ts_ns_wait() -- Same as above but blocking version.
- hte_enable_ts() -- To disable timestamp functionality.
- hte_disable_ts() -- To enable timestamp functionality.
- hte_available_ts() -- To query available timestamp data.
- hte_release_ts() -- To release timestamp functionality and its associated resources.
- hte_get_clk_src_info() -- To query clock source information from the provider

It provides centralized software buffer management per requested id to store the timestamp data for the consumers as below:
- hte_set_buf_len() -- To set the buffer length.
- hte_get_buf_len() -- To get the buffer length.
- hte_set_buf_watermark() -- To set the software threshold/watermark.
- hte_get_buf_watermark() -- To get the software threshold/watermark.

The detail about parameters and API usage are described in each functions definitions in drivers/hte/hte.c file.

Quoted 7 lines
Quoted 4 lines

The patch adds compilation support in Makefile and menu options in Kconfig.

Hi Dipen, this isn't a particularly thorough review as I'm still getting my head around what this is doing + it is an RFC :)

Having read on through the rest of the series, one of the biggest things that became clear is you have more layers of abstraction in here than make sense. Squash things together so you have fewer allocations (and hence fewer error paths etc). Don't introduce ops functions unless you have more than one answer to what they
are (and a clear justification for those). It's easy to add layers of indirection
later, but for now they just make your code harder to read. Reality is that the buffer is a kfifo, make it so everywhere, rather than pretending otherwise.

I thought for a while that you were allowing a different buffer implementation for each of the your hte chips and was very confused as to why that would make sense.

Anyhow, it's interesting. I'm not sure yet if the way it all fits together makes sense and you will almost certainly want to support hardware FIFOs and those tend to want to be partly exposed through to the consumer.

As to similar devices. Lots of sensorhubs have timestamping facilities but it is tightly coupled to the data streams, so probably doesn't make sense to map to a generic subsystem like this. You'll hit some of the same issues as those though when you try to align these timestamps with system ones etc.

otherwise, some of the counter devices are closer to this. Perhaps the ti ecap?
https://www.ti.com/lit/ug/spru807b/spru807b.pdf?ts=1625431159791&ref_url=https%253A%252F%252Fwww.google.com%252F

That has a short hardware buffer and can be used for absolute timestamp grabbing on rising triggers etc.

Jonathan

Quoted 182 lines
Quoted 40 lines
---
 drivers/Kconfig      |    2 +
 drivers/Makefile     |    1 +
 drivers/hte/Kconfig  |   22 +
 drivers/hte/Makefile |    1 +
 drivers/hte/hte.c    | 1368 ++++++++++++++++++++++++++++++++++++++++++
 include/linux/hte.h  |  278 +++++++++
 6 files changed, 1672 insertions(+)
 create mode 100644 drivers/hte/Kconfig
 create mode 100644 drivers/hte/Makefile
 create mode 100644 drivers/hte/hte.c
 create mode 100644 include/linux/hte.h
drivers/Kconfig +2 -0
index 47980c6b1945..9b078964974b 100644
@@ -238,4 +238,6 @@ source "drivers/interconnect/Kconfig"
 source "drivers/counter/Kconfig"
 
 source "drivers/most/Kconfig"
+
+source "drivers/hte/Kconfig"
 endmenu
drivers/Makefile +1 -0
index 5a6d613e868d..0a996a698e4c 100644
@@ -190,3 +190,4 @@ obj-$(CONFIG_GNSS)		+= gnss/
 obj-$(CONFIG_INTERCONNECT)	+= interconnect/
 obj-$(CONFIG_COUNTER)		+= counter/
 obj-$(CONFIG_MOST)		+= most/
+obj-$(CONFIG_HTE)		+= hte/
drivers/hte/Kconfig new file +0 -0
new file mode 100644
index 000000000000..394e112f7dfb

drivers/hte/Kconfig line 5

Quoted 5 lines
drivers/hte/Kconfig new file +5 -0
@@ -0,0 +1,22 @@
+# SPDX-License-Identifier: GPL-2.0-only
+menuconfig HTE
+        bool "Hardware Timestamping Engine (HTE) Support"
+        help
+          Hardware Timestamping Engine (HTE) Support.  

Tidy this up, but think that's already been commented on.

Quoted 134 lines
drivers/hte/Kconfig new file +17 -0
+
+          Some devices provide hardware timestamping engine which can timestamp
+	  certain device lines/signals in realtime. This way to provide
+	  hardware assisted timestamp to generic signals like GPIOs, IRQs lines
+	  comes with benefit for the applications like autonomous machines
+	  needing accurate timestamping event with less jitter.
+
+	  This framework provides a generic interface to such HTE devices
+          within the Linux kernel. It provides an API to register and
+	  unregister a HTE provider chip, configurable sw buffer to
+	  store the timestamps, push the timestamp from the HTE providers and
+	  retrieve timestamps for the consumers. It also provides means for the
+	  consumers to request signals it wishes to hardware timestamp and
+	  release them if not required.
+
+          If unsure, say no.
+
drivers/hte/Makefile new file +1 -0
new file mode 100644
index 000000000000..9899dbe516f7
@@ -0,0 +1 @@
+obj-$(CONFIG_HTE)		+= hte.o
drivers/hte/hte.c new file +104 -0
new file mode 100644
index 000000000000..c53260d1e250
@@ -0,0 +1,1368 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2021 NVIDIA Corporation
+ *
+ * Author: Dipen Patel <[email protected]>
+ */
+
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/err.h>
+#include <linux/slab.h>
+#include <linux/of.h>
+#include <linux/of_device.h>
+#include <linux/kfifo.h>
+#include <linux/mutex.h>
+#include <linux/sched.h>
+#include <linux/uaccess.h>
+#include <linux/hte.h>
+#include <linux/delay.h>
+#include <linux/debugfs.h>
+
+/* Global list of the HTE devices */
+static DEFINE_SPINLOCK(hte_lock);
+static LIST_HEAD(hte_devices);
+
+enum {
+	HTE_TS_REGISTERED,
+	HTE_TS_DISABLE,
+};
+
+/* Default FIFO depth */
+#define HTE_EV_FIFO_EL		32
+
+#define HTE_TS_NAME_LEN		10
+
+struct hte_ts_buf;
+
+/**
+ * struct hte_ts_buf_acc_func - Software buffer management functions.
+ * @store: Store timestamp from atomic context as providers most likely
+ * be pushing timestamps from their interrupt handlers.
+ * @read: Read timestamps from the buffer.
+ * @el_available: Available timestamps to retrieve. The client can use this to
+ * query available elements so that it can pre-allocate internal buffer to send
+ * to during hte_retrieve_ts_ns API.
+ * @set_length: Set length/depth of the buffer.
+ * @get_length: Get length/depth of the buffer.
+ * @set_watermark: Set software threshold of the buffer.
+ * @get_watermark: Get software threshold of the buffer.
+ * @release: Release/free buffer.
+ * @reset: Reset the buffer.
+ */
+struct hte_ts_buf_acc_func {
+	unsigned int (*store)(struct hte_ts_buf *buf, void *data, size_t n);
+	int (*read)(struct hte_ts_buf *buf, unsigned char *data, size_t n,
+		    size_t *copied);
+	size_t (*el_available)(struct hte_ts_buf *buf);
+	int (*set_length)(struct hte_ts_buf *buf,
+			  size_t length, size_t bpd);
+	size_t (*get_length)(struct hte_ts_buf *buf);
+	int (*set_watermark)(struct hte_ts_buf *buf,
+			     size_t val);
+	size_t (*get_watermark)(struct hte_ts_buf *buf);
+	void (*release)(struct hte_ts_buf *buf);
+	void (*reset)(struct hte_ts_buf *buf);
+};
+
+/**
+ * struct hte_ts_buf - Software buffer per requested id or entity to store
+ * timestamps.
+ *
+ * @datum_len: Buffer depth or number of elements.
+ * @bytes_per_datum: Element size in bytes.
+ * @watermark: Software threshold at which client will be notified.
+ * @valid: Validity of the buffer.
+ * @pollq: Waitqueue for the blocking clients.
+ * @access: Various buffer management functions.
+ */
+struct hte_ts_buf {
+	size_t datum_len;
+	size_t bytes_per_datum;
+	size_t watermark;
+	bool valid;
+	wait_queue_head_t pollq;
+	const struct hte_ts_buf_acc_func *access;
+};
+
+/**
+ * struct hte_ts_info - Information related to requested timestamp.
+ *
+ * @xlated_id: Timestamp ID as understood between HTE subsys and HTE provider,
+ * See xlate callback API.
+ * @flags: Flags holding state informations.
+ * @seq: Timestamp sequence counter.
+ * @dropped_ts: Dropped timestamps.
+ * @cb: Callback to notify clients.
+ * @mlock: Lock during timestamp request/release APIs.
+ * @ts_dbg_root: Root for the debug fs.
+ * @gdev: HTE abstract device that this timestamp belongs to.
+ * @buf: Per requested timestamp software buffer.
+ * @desc: Timestamp descriptor understood between clients and HTE subsystem.
+ */
+struct hte_ts_info {
+	u32 xlated_id;
Quoted 8 lines

drivers/hte/hte.c line 112

Quoted 8 lines
drivers/hte/hte.c new file +8 -0
+	unsigned long flags;
+	u64 seq;
+	atomic_t dropped_ts;
+	void (*cb)(enum hte_notify n);
+	struct mutex mlock;
+	struct dentry *ts_dbg_root;
+	struct hte_device *gdev;
+	struct hte_ts_buf *buf;

Where there is one instance, just embed it. Lots of small allocations just make for less readable code.

Quoted 164 lines

drivers/hte/hte.c line 123

Quoted 11 lines
drivers/hte/hte.c new file +11 -0
+	struct hte_ts_desc *desc;
+};
+
+/**
+ * struct hte_device - HTE abstract device
+ * @nlines: Number of entities this device supports.
+ * @ts_req: Total number of entities requested.
+ * @ei: Timestamp information.
+ * @sdev: Device used at various debug prints.
+ * @dbg_root: Root directory for debug fs.
+ * @list: List node for internal use.  

Be more specific of what sort of internal use.

Quoted 150 lines
drivers/hte/hte.c new file +150 -0
+ * @chip: HTE chip providing this HTE device.
+ * @owner: helps prevent removal of modules when in use.
+ */
+struct hte_device {
+	u32 nlines;
+	atomic_t ts_req;
+	struct hte_ts_info *ei;
+	struct device *sdev;
+	struct dentry *dbg_root;
+	struct list_head list;
+	struct hte_chip *chip;
+	struct module *owner;
+};
+
+/* Buffer management functions */
+
+/**
+ * struct hte_kfifo - Software buffer wrapper.
+ * @buffer: Abstract buffer device.
+ * @gkf: Actual software buffer type, this case its FIFO.
+ */
+struct hte_kfifo {
+	struct hte_ts_buf buffer;
+	struct kfifo gkf;
+};
+
+#define buf_to_kfifo(r) container_of(r, struct hte_kfifo, buffer)
+
+static unsigned int hte_ts_store_to_buf(struct hte_ts_buf *r, void *data,
+					size_t n)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if (unlikely(!r->valid))
+		return 0;
+
+	return kfifo_in(&kf->gkf, (unsigned char *)data, n);
+}
+
+static inline int hte_ts_buf_read(struct hte_ts_buf *r,
+				  unsigned char *buf, size_t n,
+				  size_t *copied)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if ((!r->valid) || (n < kfifo_esize(&kf->gkf)))
+		return -EINVAL;
+
+	*copied = kfifo_out(&kf->gkf, buf, n);
+
+	return 0;
+}
+
+static size_t hte_ts_buf_el_available(struct hte_ts_buf *r)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if (!r->valid)
+		return 0;
+
+	return (kfifo_len(&kf->gkf) / r->bytes_per_datum);
+}
+
+static int hte_ts_buf_set_length(struct hte_ts_buf *r,
+				 size_t length, size_t bpd)
+{
+	int ret = 0;
+	struct hte_kfifo *buf;
+
+	if ((length == 0) || (bpd == 0) || !r)
+		return -EINVAL;
+
+	buf = buf_to_kfifo(r);
+
+	if (r->datum_len != length) {
+		if (r->valid)
+			kfifo_free(&buf->gkf);
+		r->valid = false;
+		r->datum_len = length;
+		r->bytes_per_datum = bpd;
+		ret = kfifo_alloc(&buf->gkf, length * bpd, GFP_KERNEL);
+		if (!ret)
+			r->valid = true;
+	}
+
+	return ret;
+}
+
+static inline size_t hte_ts_buf_get_length(struct hte_ts_buf *r)
+{
+	if ((!r->valid) || !r->datum_len)
+		return 0;
+
+	return r->datum_len;
+}
+
+static inline int hte_ts_buf_set_watermark(struct hte_ts_buf *r, size_t val)
+{
+	if ((!r->valid) || (val > r->datum_len))
+		return -EINVAL;
+
+	r->watermark = val;
+
+	return 0;
+}
+
+static inline size_t hte_ts_buf_get_watermark(struct hte_ts_buf *r)
+{
+	if (!r->valid)
+		return 0;
+
+	return r->watermark;
+}
+
+static inline void hte_ts_buf_release(struct hte_ts_buf *r)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	r->valid = false;
+	kfifo_free(&kf->gkf);
+	kfree(kf);
+}
+
+static inline void hte_ts_buf_reset(struct hte_ts_buf *r)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if (!r->valid)
+		return;
+
+	kfifo_reset(&kf->gkf);
+}
+
+static const struct hte_ts_buf_acc_func kfifo_access_funcs = {
+	.store = &hte_ts_store_to_buf,
+	.read = &hte_ts_buf_read,
+	.el_available = &hte_ts_buf_el_available,
+	.set_length = &hte_ts_buf_set_length,
+	.get_length = &hte_ts_buf_get_length,
+	.set_watermark = &hte_ts_buf_set_watermark,
+	.get_watermark = &hte_ts_buf_get_watermark,
+	.release = &hte_ts_buf_release,
+	.reset = &hte_ts_buf_reset,
+};
+
+static struct hte_ts_buf *hte_ts_buf_allocate(void)
+{
+	struct hte_kfifo *kf;
+
+	kf = kzalloc(sizeof(*kf), GFP_KERNEL);
Quoted 8 lines

drivers/hte/hte.c line 281

Quoted 8 lines
drivers/hte/hte.c new file +8 -0
+	if (!kf)
+		return ERR_PTR(-ENOMEM);
+
+	init_waitqueue_head(&kf->buffer.pollq);
+	kf->buffer.watermark = 1;
+	kf->buffer.datum_len = 0;
+	kf->buffer.valid = false;
+	kf->buffer.access = &kfifo_access_funcs;

Why do you have this level abstraction? I would suggest you flatten all this into direct calls until you have some clear need for multiple buffer types.

A long long time ago (10 years or more) we had similar abstractions in IIO because we though it would be helpful to support ring buffers and kfifos. It wasn't, we ended up ripping them all out because all they resulted in was a more complex code base when in reality everyone was happy with a kfifo.

Jonathan

Quoted 1,403 lines
Quoted 97 lines
drivers/hte/hte.c new file +97 -0
+
+	return &kf->buffer;
+}
+/* End of buffer management */
+
+/* Debugfs management */
+
+#ifdef CONFIG_DEBUG_FS
+
+static struct dentry *hte_root;
+
+static void __init hte_subsys_dbgfs_init(void)
+{
+	/* creates /sys/kernel/debug/hte/ */
+	hte_root = debugfs_create_dir("hte", NULL);
+}
+subsys_initcall(hte_subsys_dbgfs_init);
+
+static void hte_chip_dbgfs_init(struct hte_device *gdev)
+{
+	const struct hte_chip *chip = gdev->chip;
+	const char *name = chip->name ? chip->name : dev_name(chip->dev);
+
+	gdev->dbg_root = debugfs_create_dir(name, hte_root);
+	if (!gdev->dbg_root)
+		return;
+
+	debugfs_create_atomic_t("ts_requested", 0444, gdev->dbg_root,
+				&gdev->ts_req);
+	debugfs_create_u32("total_ts", 0444, gdev->dbg_root,
+			   &gdev->nlines);
+}
+
+static void hte_ts_dbgfs_init(const char *name, struct hte_ts_info *ei)
+{
+	if (!ei->gdev->dbg_root || !name)
+		return;
+
+	ei->ts_dbg_root = debugfs_create_dir(name, ei->gdev->dbg_root);
+	if (!ei->ts_dbg_root)
+		return;
+
+	debugfs_create_size_t("ts_buffer_depth", 0444, ei->ts_dbg_root,
+			      &ei->buf->datum_len);
+	debugfs_create_size_t("ts_buffer_watermark", 0444, ei->ts_dbg_root,
+			      &ei->buf->watermark);
+	debugfs_create_atomic_t("dropped_timestamps", 0444, ei->ts_dbg_root,
+				&ei->dropped_ts);
+}
+
+static inline void hte_dbgfs_deinit(struct dentry *root)
+{
+	if (!root)
+		return;
+
+	debugfs_remove_recursive(root);
+}
+
+#else
+
+static void hte_chip_dbgfs_init(struct hte_device *gdev)
+{
+}
+
+static void hte_ts_dbgfs_init(const char *name, struct hte_ts_info *ei)
+{
+}
+
+static inline void hte_dbgfs_deinit(struct dentry *root)
+{
+}
+
+#endif
+/* end of debugfs management*/
+
+/* Driver APIs */
+
+/**
+ * hte_release_ts() - Consumer calls this API to release the entity, where
+ * entity could be anything providers support, like lines, signals, buses,
+ * etc...
+ *
+ * The correct sequence to call this API is as below:
+ * 1) Call hte_disable_ts, this stops the timestamp push from the provider.
+ * 2) Retrieve timestamps by calling non blocking hte_retrieve_ts_ns API if you
+ * still care about the data.
+ * 3) Call this API.
+ * Above sequence makes sure that entity gets released race free.
+ *
+ * @desc: timestamp descriptor, this is the same as returned by the request API.
+ *
+ * Context: hte_dbgfs_deinit() function call may use sleeping locks,
+ *	    not suitable from atomic context in that case.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_release_ts(struct hte_ts_desc *desc)
+{

drivers/hte/hte.c line 388

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	u32 id;
+	int ret = 0;
+	struct hte_device *gdev;
+	struct hte_ts_info *ei;
+	struct hte_ts_buf *buf;
+
+	if (!desc)
+		return -EINVAL;
+
+	ei = (struct hte_ts_info *)desc->data_subsys;  

As data_subsys is void * you don't need to explicitly cast it to another pointer type.

Quoted 40 lines
drivers/hte/hte.c new file +40 -0
+
+	if (!ei || !ei->gdev || !ei->buf)
+		return -EINVAL;
+
+	gdev = ei->gdev;
+	buf = ei->buf;
+	id = desc->con_id;
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags)) {
+		dev_info(gdev->sdev, "id:%d is not registered", id);
+		return -EUSERS;
+	}
+
+	ret = gdev->chip->ops->release(gdev->chip, ei->xlated_id);
+	if (ret) {
+		dev_err(gdev->sdev, "id: %d free failed\n", id);
+		goto out;
+	}
+
+	atomic_dec(&gdev->ts_req);
+	atomic_set(&ei->dropped_ts, 0);
+
+	kfree(desc->name);
+	kfree(desc);
+	ei->desc = NULL;
+	ei->seq = 0;
+	buf->access->release(buf);
+
+	hte_dbgfs_deinit(ei->ts_dbg_root);
+	module_put(gdev->owner);
+
+	clear_bit(HTE_TS_REGISTERED, &ei->flags);
+
+out:
+	dev_dbg(gdev->sdev, "%s: id: %d\n", __func__, id);
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_release_ts);
+
+static int hte_ts_dis_en_common(struct hte_ts_desc *desc, bool en)

drivers/hte/hte.c line 438

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+{
+	u32 ts_id;
+	struct hte_device *gdev;
+	struct hte_ts_info *ei;
+	int ret;
+
+	if (!desc)
+		return -EINVAL;
+
+	ei = (struct hte_ts_info *)desc->data_subsys;  

As above, no need to cast - though it rather implies the type of data_subsys should not be void *.

Quoted 19 lines
drivers/hte/hte.c new file +19 -0
+
+	if (!ei || !ei->gdev)
+		return -EINVAL;
+
+	gdev = ei->gdev;
+	ts_id = desc->con_id;
+
+	mutex_lock(&ei->mlock);
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags)) {
+		dev_dbg(gdev->sdev, "id:%d is not registered", ts_id);
+		ret = -EUSERS;
+		goto out;
+	}
+
+	if (en) {
+		if (!test_bit(HTE_TS_DISABLE, &ei->flags)) {
+			ret = 0;
+			goto out;

drivers/hte/hte.c line 467

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		}
+		ret = gdev->chip->ops->enable(gdev->chip, ei->xlated_id);
+		if (ret) {
+			dev_warn(gdev->sdev, "id: %d enable failed\n",
+				 ts_id);
+			goto out;
+		}
+
+		clear_bit(HTE_TS_DISABLE, &ei->flags);
+		ret = 0;  

ret is already 0 so no point in setting it again.

Quoted 135 lines
drivers/hte/hte.c new file +135 -0
+	} else {
+		if (test_bit(HTE_TS_DISABLE, &ei->flags)) {
+			ret = 0;
+			goto out;
+		}
+		ret = gdev->chip->ops->disable(gdev->chip, ei->xlated_id);
+		if (ret) {
+			dev_warn(gdev->sdev, "id: %d disable failed\n",
+				 ts_id);
+			goto out;
+		}
+
+		set_bit(HTE_TS_DISABLE, &ei->flags);
+		ret = 0;
+	}
+
+out:
+	mutex_unlock(&ei->mlock);
+	return ret;
+}
+
+/**
+ * hte_disable_ts() - Disable timestamp on given descriptor.
+ *
+ * @desc: ts descriptor, this is the same as returned by the request API.
+ *
+ * Context: Holds mutex lock, not suitable from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_disable_ts(struct hte_ts_desc *desc)
+{
+	return hte_ts_dis_en_common(desc, false);
+}
+EXPORT_SYMBOL_GPL(hte_disable_ts);
+
+/**
+ * hte_enable_ts() - Enable timestamp on given descriptor.
+ *
+ * @desc: ts descriptor, this is the same as returned by the request API.
+ *
+ * Context: Holds mutex lock, not suitable from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_enable_ts(struct hte_ts_desc *desc)
+{
+	return hte_ts_dis_en_common(desc, true);
+}
+EXPORT_SYMBOL_GPL(hte_enable_ts);
+
+static int hte_simple_xlate(struct hte_chip *gc,
+			    const struct of_phandle_args *args,
+			    struct hte_ts_desc *desc,
+			    u32 *id)
+{
+	if (!id || !desc || !gc)
+		return -EINVAL;
+
+	/*
+	 * For the providers which do not have any internal mappings between
+	 * logically exposed ids and actual ids, will set both
+	 * the same.
+	 *
+	 * In case there is a internal mapping needed, providers will need to
+	 * provide its own xlate function where con_id will be sent as
+	 * args[0] and it will return xlated id. Later xlated id will be
+	 * used for any future exchanges between provider and subsystems.
+	 */
+
+	if (args) {
+		if (gc->of_hte_n_cells < 1)
+			return -EINVAL;
+
+		if (args->args_count != gc->of_hte_n_cells)
+			return -EINVAL;
+
+		*id = args->args[0];
+		desc->con_id = *id;
+	} else {
+		*id = desc->con_id;
+	}
+
+	if (desc->con_id > gc->nlines)
+		return -EINVAL;
+
+	desc->data_subsys = NULL;
+
+	return 0;
+}
+
+static struct hte_device *of_node_to_htedevice(struct device_node *np)
+{
+	struct hte_device *gdev;
+
+	spin_lock(&hte_lock);
+
+	list_for_each_entry(gdev, &hte_devices, list)
+		if (gdev->chip && gdev->chip->dev &&
+		    gdev->chip->dev->of_node == np) {
+			spin_unlock(&hte_lock);
+			return gdev;
+		}
+
+	spin_unlock(&hte_lock);
+
+	return ERR_PTR(-ENODEV);
+}
+
+static int ___hte_req_ts(struct hte_device *gdev, struct hte_ts_desc *desc,
+			 u32 xlated_id, void (*cb)(enum hte_notify n))
+{
+	struct hte_ts_info *ei;
+	struct hte_ts_buf *buf;
+	int ret;
+	u32 con_id = desc->con_id;
+
+	if (!try_module_get(gdev->owner))
+		return -ENODEV;
+
+	ei = &gdev->ei[xlated_id];
+	ei->xlated_id = xlated_id;
+
+	/*
+	 * There a chance that multiple consumers requesting same entity,
+	 * lock here.
+	 */
+	mutex_lock(&ei->mlock);
+
+	if (test_bit(HTE_TS_REGISTERED, &ei->flags)) {
+		dev_dbg(gdev->chip->dev, "id:%u is already registered",
+			xlated_id);
+		ret = -EUSERS;
+		goto unlock;
+	}
+
+	buf = hte_ts_buf_allocate();

drivers/hte/hte.c line 612

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	if (IS_ERR(buf)) {
+		dev_err(gdev->chip->dev, "Buffer allocation failed");
+		ret = PTR_ERR(buf);
+		goto unlock;
+	}
+
+	/* Set default here, let consumer decide how much to set later */
+	ret = buf->access->set_length(buf, HTE_EV_FIFO_EL,
+				      sizeof(struct hte_ts_data));
+  

It's good to keep to consistent style of no line break between a statement and it's error check.

Quoted 140 lines
drivers/hte/hte.c new file +140 -0
+	if (ret) {
+		dev_err(gdev->chip->dev, "Fifo set length failed");
+		goto buf_rel;
+	}
+
+	buf->access->reset(buf);
+	buf->valid = true;
+
+	ei->buf = buf;
+	ei->cb = cb;
+
+	ret = gdev->chip->ops->request(gdev->chip, xlated_id);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev, "ts request failed\n");
+		goto buf_rel;
+	}
+
+	desc->data_subsys = ei;
+	ei->desc = desc;
+
+	atomic_inc(&gdev->ts_req);
+	set_bit(HTE_TS_REGISTERED, &ei->flags);
+	mutex_unlock(&ei->mlock);
+
+	if (!desc->name) {
+		desc->name = kzalloc(HTE_TS_NAME_LEN, GFP_KERNEL);
+		if (desc->name)
+			scnprintf(desc->name, HTE_TS_NAME_LEN, "ts_%u",
+				  con_id);
+	}
+
+	hte_ts_dbgfs_init(desc->name, ei);
+
+	dev_dbg(gdev->chip->dev, "%s: id: %u, xlated id:%u",
+		__func__, con_id, xlated_id);
+
+	return 0;
+
+buf_rel:
+	buf->access->release(buf);
+unlock:
+	module_put(gdev->owner);
+	mutex_unlock(&ei->mlock);
+
+	return ret;
+}
+
+static struct hte_device *of_hte_dev_get(struct device *dev,
+					 struct device_node *np,
+					 const char *label,
+					 struct of_phandle_args *args)
+{
+	struct hte_device *gdev = NULL;
+	int index = 0;
+	int err;
+
+	if (label) {
+		index = of_property_match_string(np, "hte-names", label);
+		if (index < 0)
+			return ERR_PTR(index);
+	}
+
+	err = of_parse_phandle_with_args(np, "htes", "#hte-cells", index,
+					 args);
+	if (err) {
+		pr_err("%s(): can't parse \"htes\" property\n", __func__);
+		return ERR_PTR(err);
+	}
+
+	gdev = of_node_to_htedevice(args->np);
+	if (IS_ERR(gdev)) {
+		pr_err("%s(): HTE chip not found\n", __func__);
+		of_node_put(args->np);
+		return gdev;
+	}
+
+	return gdev;
+}
+
+static struct hte_ts_desc *__hte_req_ts(struct device *dev,
+					struct device_node *np,
+					const char *label,
+					void (*cb)(enum hte_notify n))
+{
+	struct hte_device *gdev = NULL;
+	struct hte_ts_desc *desc;
+	struct of_phandle_args args;
+	int ret;
+	u32 xlated_id;
+
+	gdev = of_hte_dev_get(dev, np, label, &args);
+	if (IS_ERR(gdev))
+		return ERR_CAST(gdev);
+
+	if (!gdev->chip) {
+		pr_debug("requested id does not have provider\n");
+		return ERR_PTR(-ENODEV);
+	}
+
+	desc = kzalloc(sizeof(*desc), GFP_KERNEL);
+	if (!desc)
+		return ERR_PTR(-ENOMEM);
+
+	ret = gdev->chip->xlate(gdev->chip, &args, desc, &xlated_id);
+	if (ret < 0)
+		goto put;
+
+	desc->name = NULL;
+	if (label)
+		desc->name = kstrdup(label, GFP_KERNEL);
+
+	ret = ___hte_req_ts(gdev, desc, xlated_id, cb);
+	if (ret < 0)
+		goto put;
+
+	return desc;
+
+put:
+	of_node_put(args.np);
+	kfree(desc);
+
+	return ERR_PTR(ret);
+}
+
+/**
+ * of_hte_request_ts() - Consumer calls this API to request the HTE facility
+ * on the specified entity, where entity is provider specific for example,
+ * GPIO lines, signals, buses etc...
+ *
+ * @dev: Consumer device.
+ * @label: Optional label.
+ * @cb: Optional notify callback to consumer when data is pushed by the
+ * provider.
+ *
+ * Context: Holds mutex lock, not suitable from atomic context.
+ * Returns: Timestamp descriptor on success or error ptr on failure.
+ */
+struct hte_ts_desc *of_hte_request_ts(struct device *dev,
+				      const char *label,
+				      void (*cb)(enum hte_notify n))

drivers/hte/hte.c line 762

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+{
+
+	if (dev && dev->of_node)
+		return __hte_req_ts(dev, dev->of_node, label, cb);
+	else
+		return ERR_PTR(-EOPNOTSUPP);
+}
+EXPORT_SYMBOL_GPL(of_hte_request_ts);
+
+static int devm_hte_ts_match_desc(struct device *dev, void *res, void *data)  

I'm not seeing what is devm about this.

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+{
+	struct hte_ts_desc **p = res;
+
+	if (WARN_ON(!p || !*p))
+		return 0;
+

drivers/hte/hte.c line 778

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	return *p == data;
+}
+
+static void __devm_hte_release_ts(struct device *dev, void *res)
+{
+	hte_release_ts(*(struct hte_ts_desc **)res);
+}
+
+/**
+ * devm_hte_release_ts() - Resource managed hte_release_ts().  

I'd not introduce this until you have a user. It very rarely actually makes sense to call a devm release manually. Not having one makes people think harder about it.

Quoted 9 lines
drivers/hte/hte.c new file +9 -0
+ * @dev: HTE consumer/client device.
+ * @desc: HTE ts descriptor.
+ *
+ * Release timestamp functionality and its resources previously allocated using
+ * of_hte_request_ts(). Calling this function is usually not needed because
+ * devm-allocated resources are automatically released on driver detach.
+ *
+ * Context: Same as hte_release_ts() function.
+ * Returns: 0 on success otherwise negative error code.

drivers/hte/hte.c line 797

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+ */
+int devm_hte_release_ts(struct device *dev, struct hte_ts_desc *desc)
+{
+	return devres_release(dev, __devm_hte_release_ts,
+			      devm_hte_ts_match_desc, desc);
+}
+EXPORT_SYMBOL_GPL(devm_hte_release_ts);
+
+/**
+ * devm_of_hte_request_ts() - Resource managed of_hte_request_ts().  

If it's kernel-doc it needs to give no warnings when you point the kernel-doc scripts at it. They insist on full parameter documentation.

drivers/hte/hte.c line 806

Quoted 9 lines
drivers/hte/hte.c new file +9 -0
+ */
+struct hte_ts_desc *devm_of_hte_request_ts(struct device *dev,
+					   const char *label,
+					   void (*cb)(enum hte_notify n))
+{
+
+	struct hte_ts_desc **ptr, *desc;
+
+	ptr = devres_alloc(__devm_hte_release_ts, sizeof(*ptr), GFP_KERNEL);  

Superficially looks like you might get way with just calling dev_add_action_or_reset() in here and avoid this boilerplate. A lot of cases that looked like this got cleaned up in the last kernel cycle.

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+	if (!ptr)
+		return ERR_PTR(-ENOMEM);
+
+	desc = of_hte_request_ts(dev, label, cb);
+	if (!IS_ERR(desc)) {
+		*ptr = desc;

drivers/hte/hte.c line 822

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		devres_add(dev, ptr);
+	} else {
+		devres_free(ptr);
+	}
+	return desc;
+}
+EXPORT_SYMBOL_GPL(devm_of_hte_request_ts);
+
+static struct hte_ts_info *hte_para_check(const struct hte_ts_desc *desc,
+					  size_t val)  

Not a good name or indeed combination of different things. hte_desc_to_info() and some separate check on val would be better.

Quoted 14 lines
drivers/hte/hte.c new file +14 -0
+{
+	struct hte_ts_info *ei;
+
+	if (!desc || !desc->data_subsys || !val) {
+		pr_debug("%s:%d: val :%lu\n", __func__, __LINE__, val);
+		return NULL;
+	}
+
+	ei = desc->data_subsys;
+	if (!ei || !ei->buf) {
+		pr_debug("%s:%d\n", __func__, __LINE__);
+		return NULL;
+	}
+

drivers/hte/hte.c line 846

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	return ei;
+}
+
+static inline bool hte_ts_buf_wait(struct hte_ts_buf *buffer, size_t to_read)
+{
+	size_t el_avail;
+
+	el_avail = buffer->access->el_available(buffer);
+
+	return (el_avail >= to_read) ? false : true;  

return el_avail < to_read;

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+}
+
+static int _hte_retrieve_ts_ns(const struct hte_ts_desc *desc,
+			       struct hte_ts_data *el, size_t n, bool block)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;

drivers/hte/hte.c line 863

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	int ret;
+	size_t to_read, copied;
+
+	ei = hte_para_check(desc, n);
+	if (!ei)
+		return -EINVAL;
+
+	buffer = ei->buf;
+
+	to_read = min_t(size_t, n, buffer->watermark);  

Needs a comment as not obvious why you'd read the min of that requested or the watermark if there might be more available.

Quoted 5 lines
drivers/hte/hte.c new file +5 -0
+
+	do {
+		if (hte_ts_buf_wait(buffer, to_read)) {
+			if (!block) {
+				/* Possibly early here to retrieve, try again */

drivers/hte/hte.c line 878

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+				dev_dbg(ei->gdev->chip->dev, "%s: %d\n",
+					__func__, ret);
+				return -EAGAIN;
+			}
+			ret = wait_event_interruptible(buffer->pollq,
+					!hte_ts_buf_wait(buffer, to_read));
+			if (ret)
+				return ret;
+		}
+		ret = buffer->access->read(buffer, (void *)el,  

If you have to cast to a void * that usually means something is wrong in your definitions. Why is it needed here? Looks like read has an inappropriate definition.

Quoted 56 lines
drivers/hte/hte.c new file +56 -0
+					   n * buffer->bytes_per_datum,
+					   &copied);
+		if (ret < 0)
+			return ret;
+
+		if (copied > 0)
+			return 0;
+		else if (copied == 0 && !block)
+			return -EAGAIN;
+	} while (copied == 0);
+
+	return 0;
+}
+
+/**
+ * hte_retrieve_ts_ns() - Consumer calls this API to retrieve timestamp in
+ * nano seconds i.e. el->tsc will be in ns.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ * @el: buffer to store the timestamp details.
+ * @n: Number of struct hte_timestamp_el elements.
+ *
+ * Context: Can be called from the atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_retrieve_ts_ns(const struct hte_ts_desc *desc,
+		       struct hte_ts_data *el, size_t n)
+{
+	return _hte_retrieve_ts_ns(desc, el, n, false);
+}
+EXPORT_SYMBOL_GPL(hte_retrieve_ts_ns);
+
+/**
+ * hte_retrieve_ts_ns_wait() - Blocking version of the hte_retrieve_ts_ns.
+ * @desc: ts descriptor, same as returned from request API.
+ * @el: buffer to store the timestamp data.
+ * @n: Number of struct hte_ts_data data.
+ *
+ * Context: Can not be called from the atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_retrieve_ts_ns_wait(const struct hte_ts_desc *desc,
+			    struct hte_ts_data *el, size_t n)
+{
+	return _hte_retrieve_ts_ns(desc, el, n, true);
+}
+EXPORT_SYMBOL_GPL(hte_retrieve_ts_ns_wait);
+
+/**
+ * hte_set_buf_len() - Consumer calls this API to set timestamp software buffer
+ * depth.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ * @len: New length/depth.
+ *
+ * The correct sequence to set buffer length is as below:

drivers/hte/hte.c line 944

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+ * 1) Disable timestamp by calling hte_disable_ts API.
+ * 2) Optionally retrieve all the timestamps by calling non blocking
+ *    hte_retrieve_ts_ns() API. This step only needed if you still care about
+ *    the data.
+ * 3) Call this API.
+ * 4) Enable timestamp by calling hte_enable_ts API.
+ *
+ * This API destroys previously allocated buffer and creates new one, because
+ * of that, it is mandatory to follow above sequence to make sure there is no
+ * race between various other APIs in the subsystem.  

Good docs. This is why I mentioned in review of docs patch that it is better to just have that refer to the kernel-doc in these files. Keep all this good information in one place.

Quoted 13 lines
drivers/hte/hte.c new file +13 -0
+ *
+ * By default during the request API call, HTE subsystem allocates software
+ * buffer with predefined length, this API gives flexibility to adjust the
+ * length according to consumer's need.
+ *
+ * Context: Can not be called from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_set_buf_len(const struct hte_ts_desc *desc, size_t len)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+	int ret;

drivers/hte/hte.c line 967

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+
+	ei = hte_para_check(desc, len);
+	if (!ei)
+		return -EINVAL;
+
+	buffer = ei->buf;
+	ret = buffer->access->set_length(buffer, len,
+					 sizeof(struct hte_ts_data));
+	if (ret)
+		dev_err(ei->gdev->chip->dev, "%s: ret:%d\n", __func__, ret);  

Not point in printing things line __func__ manually in dev_err() etc. Dynamic debug includes that and gives far more information + control of this.

Quoted 65 lines
drivers/hte/hte.c new file +65 -0
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_set_buf_len);
+
+/**
+ * hte_get_buf_len() - Consumer calls this API to get timestamp software buffer
+ * depth or length.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: Positive length on success or 0 on failure.
+ */
+size_t hte_get_buf_len(const struct hte_ts_desc *desc)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	ei = hte_para_check(desc, 1);
+	if (!ei)
+		return 0;
+
+	buffer = ei->buf;
+
+	return buffer->access->get_length(buffer);
+}
+EXPORT_SYMBOL_GPL(hte_get_buf_len);
+
+/**
+ * hte_available_ts() - Returns total available timestamps.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * The API helps consumers to pre-allocate its internal buffer required
+ * during hte_retrieve_ts_ns call.
+ *
+ * Context: Any context.
+ * Returns: Positive value if elements are available else 0. The value is
+ * number of total available struct hte_timestamp_el elements available not
+ * the size in bytes.
+ */
+size_t hte_available_ts(const struct hte_ts_desc *desc)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	ei = hte_para_check(desc, 1);
+	if (!ei)
+		return 0;
+
+	buffer = ei->buf;
+
+	return buffer->access->el_available(buffer);
+}
+EXPORT_SYMBOL_GPL(hte_available_ts);
+
+/**
+ * hte_set_buf_watermark() - Consumer calls this API to set timestamp software
+ * buffer watermark. The correct sequence to call this API is as below:
+ * 1) Disable timestamp by calling hte_disable_ts API.
+ * 2) Call this API.
+ * 3) Enable timestamp by calling hte_enable_ts API.
+ *
+ * @desc: ts descriptor, same as returned from request API.

drivers/hte/hte.c line 1042

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+ * @val: New watermark.
+ *
+ * By default during the request API call, HTE subsystem sets watermark as 1,
+ * this API gives flexibility to adjust the watermark according to consumer's
+ * need. The consumers will get notification through callback registered during
+ * request API either when timestamp is dropped or watermark is reached or will
+ * wait till watermark is reached. Refer hte_retrieve_ts_ns() and
+ * hte_push_ts_ns_atomic() APIs to understand how watermark is used.
+ *
+ * Context: Any context.  

You have no way of knowing that as will depend on the driver - I'd definitely suggest not from atomic context, but then that would be crazy so you are better
off not documenting any specific requirement at all.

Quoted 44 lines
drivers/hte/hte.c new file +44 -0
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_set_buf_watermark(const struct hte_ts_desc *desc, size_t val)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+	int ret;
+
+	ei = hte_para_check(desc, val);
+	if (!ei)
+		return -EINVAL;
+
+	buffer = ei->buf;
+	ret = buffer->access->set_watermark(buffer, val);
+	if (ret)
+		dev_dbg(ei->gdev->chip->dev, "%s: ret:%d\n", __func__, ret);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_set_buf_watermark);
+
+/**
+ * hte_get_buf_watermark() - Consumer calls this API to get software
+ * buffer watermark.
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: Positive current watermark on success or 0 on failure.
+ */
+size_t hte_get_buf_watermark(const struct hte_ts_desc *desc)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	ei = hte_para_check(desc, 1);
+	if (!ei)
+		return 0;
+
+	buffer = ei->buf;
+
+	return buffer->access->get_watermark(buffer);
+}
+EXPORT_SYMBOL_GPL(hte_get_buf_watermark);
+

drivers/hte/hte.c line 1096

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+/**
+ * hte_req_ts_by_dt_node() - Request entity to monitor by passing HTE device
+ * node directly, where meaning of the entity is provider specific, for example
+ * lines, signals, GPIOs, buses etc...
+ *
+ * @of_node: HTE provider device node.
+ * @id: entity id to monitor, this id belongs to HTE provider of_node.
+ * @cb: Optional callback to notify.
+ *
+ * Context: Holds mutex lock, can not be called from atomic context.  

What mutex and why? If it is one you can check is held even better.

Quoted 13 lines
drivers/hte/hte.c new file +13 -0
+ * Returns: ts descriptor on success or error pointers.
+ */
+struct hte_ts_desc *hte_req_ts_by_dt_node(struct device_node *of_node,
+					  unsigned int id,
+					  void (*cb)(enum hte_notify n))
+{
+	struct hte_device *gdev;
+	struct hte_ts_desc *desc;
+	int ret;
+	u32 xlated_id;
+
+	gdev = of_node_to_htedevice(of_node);
+	if (IS_ERR(gdev))

drivers/hte/hte.c line 1119

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		return ERR_PTR(-ENOTSUPP);
+
+	if (!gdev->chip || !gdev->chip->ops)
+		return ERR_PTR(-ENOTSUPP);
+
+	desc = kzalloc(sizeof(*desc), GFP_KERNEL);
+	if (!desc) {
+		ret = -ENOMEM;
+		goto out_put_device;
+	}  

Pass a desc pointer into this function rather than allocating the structure in here. That lets the caller embed that structure inside one of it's own structures if it wants to, resulting in fewer small allocations which is always good.

It's far from obvious that the caller needs to free desc.

Quoted 51 lines
drivers/hte/hte.c new file +51 -0
+
+	desc->con_id = id;
+	ret = gdev->chip->xlate(gdev->chip, NULL, desc, &xlated_id);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev,
+			"failed to xlate id: %d\n", id);
+		goto out_free_desc;
+	}
+
+	ret = ___hte_req_ts(gdev, desc, xlated_id, cb);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev,
+			"failed to request id: %d\n", id);
+		goto out_free_desc;
+	}
+
+	return desc;
+
+out_free_desc:
+	kfree(desc);
+
+out_put_device:
+	return ERR_PTR(ret);
+}
+EXPORT_SYMBOL_GPL(hte_req_ts_by_dt_node);
+
+/**
+ * hte_get_clk_src_info() - Consumer calls this API to query clock source
+ * information of the desc.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: 0 on success else negative error code on failure.
+ */
+int hte_get_clk_src_info(const struct hte_ts_desc *desc,
+			 struct hte_clk_info *ci)
+{
+	struct hte_chip *chip;
+	struct hte_ts_info *ei;
+
+	if (!desc || !desc->data_subsys || !ci) {
+		pr_debug("%s:%d\n", __func__, __LINE__);
+		return -EINVAL;
+	}
+
+	ei = desc->data_subsys;
+	if (!ei || !ei->gdev || !ei->gdev->chip)
+		return -EINVAL;
+
+	chip = ei->gdev->chip;

drivers/hte/hte.c line 1180

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	if (!chip->ops->get_clk_src_info)
+		return -ENOTSUPP;
+
+	return chip->ops->get_clk_src_info(chip, ci);
+}
+EXPORT_SYMBOL_GPL(hte_get_clk_src_info);
+
+static inline void hte_add_to_device_list(struct hte_device *gdev)
+{
+	struct hte_device *prev;  

Needs to take an appropriate lock as you may have concurrent calls.

drivers/hte/hte.c line 1183

Quoted 3 lines
drivers/hte/hte.c new file +3 -0
+
+	if (list_empty(&hte_devices)) {
+		list_add_tail(&gdev->list, &hte_devices);  

Needs a comment. I've no idea why you might want to only add it if there were no other hte_devices already there.

drivers/hte/hte.c line 1187

Quoted 4 lines
drivers/hte/hte.c new file +4 -0
+		return;
+	}
+
+	prev = list_last_entry(&hte_devices, struct hte_device, list);  

Why woud you do this?

Quoted 37 lines
drivers/hte/hte.c new file +37 -0
+	list_add_tail(&gdev->list, &hte_devices);
+}
+
+/**
+ * hte_push_ts_ns_atomic() - Used by the provider to push timestamp in nano
+ * seconds i.e data->tsc will be in ns, it is assumed that provider will be
+ * using this API from its ISR or atomic context.
+ *
+ * @chip: The HTE chip, used during the registration.
+ * @xlated_id: entity id understood by both subsystem and provider, usually this
+ * is obtained from xlate callback during request API.
+ * @data: timestamp data.
+ * @n: Size of the data.
+ *
+ * Context: Atomic.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_push_ts_ns_atomic(const struct hte_chip *chip, u32 xlated_id,
+			  struct hte_ts_data *data, size_t n)
+{
+	unsigned int ret;
+	bool notify;
+	size_t el_avail;
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	if (!chip || !data || !chip->gdev)
+		return -EINVAL;
+
+	if (xlated_id > chip->nlines)
+		return -EINVAL;
+
+	ei = &chip->gdev->ei[xlated_id];
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags) ||
+	    test_bit(HTE_TS_DISABLE, &ei->flags)) {
+		dev_dbg(chip->dev, "Unknown timestamp push\n");

drivers/hte/hte.c line 1233

Quoted 10 lines
drivers/hte/hte.c new file +9 -0
+		return -EINVAL;
+	}
+
+	/* timestamp sequence counter, start from 0 */
+	data->seq = ei->seq++;
+
+	buffer = ei->buf;
+	el_avail = buffer->access->el_available(buffer);  
 
+	ret = buffer->access->store(buffer, data, n);  

If we are doing this from the hte core, why is buffer definition in the scope of the drivers rather than the core? That seems backwards to me.

drivers/hte/hte.c line 1241

Quoted 8 lines
drivers/hte/hte.c new file +8 -0
+	if (ret != n) {
+		atomic_inc(&ei->dropped_ts);
+		if (ei->cb)
+			ei->cb(HTE_TS_DROPPED);
+		return -ENOMEM;
+	}
+
+	notify = ((el_avail + 1) >= buffer->watermark) ? true : false;  

You push n but only check on el_avail + 1 here.
Also, this is the same as

	notify = ((el_avail + 1) >= buffer->watermark;

drivers/hte/hte.c line 1249

Quoted 8 lines
drivers/hte/hte.c new file +8 -0
+
+	/*
+	 * If there is a callback, its consumer's job to retrieve the timestamp.
+	 * For the rest, wake up the process.
+	 */
+	if (notify && ei->cb) {
+		ei->cb(HTE_TS_AVAIL);
+		return 0;  

Given you return 0 anyway, might as well not have this line.

drivers/hte/hte.c line 1262

Quoted 13 lines
drivers/hte/hte.c new file +13 -0
+	} else if (notify) {
+		wake_up_interruptible(&buffer->pollq);
+	}
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(hte_push_ts_ns_atomic);
+
+/**
+ * hte_register_chip() - Used by provider to register a HTE chip.
+ * @chip: the HTE chip to add to subsystem.
+ *
+ * Context: Can not be called from atomic context.  

Whilst true, I'd think that was common sense as it would be insane to register something like this from atomic context. So I'd say no need to comment on it! Keep those comments for things that might be used like that.

Quoted 25 lines

+ * Returns: 0 on success or a negative error code on failure.
+ */

drivers/hte/hte.c new file +23 -0
+int hte_register_chip(struct hte_chip *chip)
+{
+	struct hte_device *gdev;
+	int ret;
+	u32 i;
+
+	if (!chip || !chip->dev || !chip->dev->of_node)
+		return -EINVAL;
+
+	if (!chip->ops || !chip->ops->request || !chip->ops->release) {
+		dev_err(chip->dev, "Driver needs to provide ops\n");
+		return -EINVAL;
+	}
+
+	gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
+	if (!gdev)
+		return -ENOMEM;
+
+	gdev->chip = chip;
+	chip->gdev = gdev;
+	gdev->nlines = chip->nlines;
+	gdev->sdev = chip->dev;
+

drivers/hte/hte.c line 1297

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	/*
+	 * Allocate all the supported entities here at once, this will have
+	 * following advantages:
+	 * When provider pushes timestamp, it can then just send the
+	 * xlated_id, subsystem will use it as an index which
+	 * gives us the constant time access; this is important as mostly
+	 * providers will be pushing the timestamps from their ISR.
+	 */
+	gdev->ei = kcalloc(chip->nlines, sizeof(struct hte_ts_info),
+			   GFP_KERNEL);  

I'd be tempted to do this as a 0 length element at the end of gdev then do the allocation in one go use struct_size() etc to work out how long it is. Cuts down on allocations + error paths to deal with for no obvious disadvantage.

drivers/hte/hte.c line 1304

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+	if (!gdev->ei) {
+		ret = -ENOMEM;
+		goto err_free_gdev;
+	}
+
+	for (i = 0; i < chip->nlines; i++) {
+		gdev->ei[i].flags = 0;  

zero allocated, so don't bother setting things to 0 where it's a fairly obvious base state. If you set something to 0 to act as some form of documentation then that's fine, but I don't think that's true here.

Quoted 54 lines
drivers/hte/hte.c new file +54 -0
+		gdev->ei[i].gdev = gdev;
+		gdev->ei[i].seq = 0;
+		mutex_init(&gdev->ei[i].mlock);
+	}
+
+	if (chip->dev->driver)
+		gdev->owner = chip->dev->driver->owner;
+	else
+		gdev->owner = THIS_MODULE;
+
+	if (!chip->xlate) {
+		chip->xlate = hte_simple_xlate;
+		/* Just a id number to monitor */
+		chip->of_hte_n_cells = 1;
+	}
+
+	of_node_get(chip->dev->of_node);
+
+	INIT_LIST_HEAD(&gdev->list);
+
+	spin_lock(&hte_lock);
+	hte_add_to_device_list(gdev);
+	spin_unlock(&hte_lock);
+
+	hte_chip_dbgfs_init(gdev);
+
+	dev_dbg(chip->dev, "Added hte chip\n");
+	return 0;
+
+err_free_gdev:
+	kfree(gdev);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_register_chip);
+
+/**
+ * hte_unregister_chip() - Used by the provider to remove a HTE chip.
+ * @chip: the HTE chip to remove.
+ *
+ * Context: Can not be called from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_unregister_chip(struct hte_chip *chip)
+{
+	struct hte_device *gdev = chip->gdev;
+
+	spin_lock(&hte_lock);
+	list_del(&gdev->list);
+	spin_unlock(&hte_lock);
+
+	gdev->chip = NULL;
+
+	of_node_put(chip->dev->of_node);

drivers/hte/hte.c line 1368

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	hte_dbgfs_deinit(gdev->dbg_root);
+	kfree(gdev->ei);
+	kfree(gdev);
+
+	dev_dbg(chip->dev, "Removed hte chip\n");
+	return 0;
+}
+EXPORT_SYMBOL_GPL(hte_unregister_chip);
+
+/* Driver APIs ends */  

Don't bother with file layout type comments. They don't add that much and tend to rot horribly over time as people move code around in files.

Quoted 15 lines
include/linux/hte.h new file +9 -0
new file mode 100644
index 000000000000..e1737579d4c4
@@ -0,0 +1,278 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2021 NVIDIA Corporation
+ *
+ * Author: Dipen Patel <[email protected]>
+ */
+
+#ifndef __LINUX_HTE_H
+#define __LINUX_HTE_H

include/linux/hte.h line 19

Quoted 10 lines
include/linux/hte.h new file +10 -0
+
+struct hte_chip;
+struct hte_device;
+struct of_phandle_args;
+
+/**
+ * Used by providers to indicate the direction of the timestamp.
+ */
+#define HTE_EVENT_RISING_EDGE          0x1
+#define HTE_EVENT_FALLING_EDGE         0x2  

Use an enum rather than a define for this as it's a value that can take a set of distinct values. Also, provide a name for 'I've no idea' which I'm guessing is 0 currently.

Quoted 13 lines
include/linux/hte.h new file +13 -0
+
+/**
+ * struct hte_ts_data - HTE timestamp data.
+ * The provider uses and fills timestamp related details during push_timestamp
+ * API call. The consumer uses during retrieve_timestamp API call.
+ *
+ * @tsc: Timestamp value.
+ * @seq: Sequence counter of the timestamps.
+ * @dir: Direction of the event at the time of timestamp.
+ */
+struct hte_ts_data {
+	u64 tsc;
+	u64 seq;

include/linux/hte.h line 42

Quoted 10 lines
include/linux/hte.h new file +10 -0
+	int dir;
+};
+
+/**
+ * struct hte_clk_info - Clock source info that HTE provider uses.
+ * The provider uses hardware clock as a source to timestamp real time. This
+ * structure presents the clock information to consumers. 
+ *
+ * @hz: Clock rate in HZ, for example 1KHz clock = 1000.
+ * @type: Clock type. CLOCK_* types.  

So this is something we got a it wrong in IIO. It's much better to define a subset of clocks that can be potentially used. There are some that make absolutely no sense and consumers really don't want to have to deal with them.

include/linux/hte.h line 53

Quoted 11 lines
include/linux/hte.h new file +11 -0
+ */
+struct hte_clk_info {
+	u64 hz;
+	clockid_t type;
+};
+
+/**
+ * HTE subsystem notifications for the consumers.
+ *
+ * @HTE_TS_AVAIL: Timestamps available notification.
+ * @HTE_TS_DROPPED: Timestamps dropped notification.  

Something I've missed so far is whether drops are in a kfifo or a ring fashion. I'm guess that's stated somewhere, but it might be useful to have it here.

Quoted 27 lines
include/linux/hte.h new file +27 -0
+ */
+enum hte_notify {
+	HTE_TS_AVAIL = 1,
+	HTE_TS_DROPPED,
+	HTE_NUM_NOTIFIER,
+};
+
+/**
+ * struct hte_ts_desc - HTE timestamp descriptor, this structure will be
+ * communication token between consumers to subsystem and subsystem to
+ * providers.
+ *
+ * @con_id: This is the same id sent in request APIs.
+ * @name: Descriptive name of the entity that is being monitored for the
+ * realtime timestamping.
+ * @data_subsys: Subsystem's private data relate to requested con_id.
+ */
+struct hte_ts_desc {
+	u32 con_id;
+	char *name;
+	void *data_subsys;
+};
+
+/**
+ * struct hte_ops - HTE operations set by providers.
+ *
+ * @request: Hook for requesting a HTE timestamp. Returns 0 on success,

include/linux/hte.h line 90

Quoted 10 lines
include/linux/hte.h new file +10 -0
+ * non-zero for failures.
+ * @release: Hook for releasing a HTE timestamp. Returns 0 on success,
+ * non-zero for failures.
+ * @enable: Hook to enable the specified timestamp. Returns 0 on success,
+ * non-zero for failures.
+ * @disable: Hook to disable specified timestamp. Returns 0 on success,
+ * non-zero for failures.
+ * @get_clk_src_info: Optional hook to get the clock information provider uses
+ * to timestamp. Returns 0 for success and negative error code for failure. On
+ * success HTE subsystem fills up provided struct hte_clk_info.  

Why optional? Consumers will probably need that information.

Quoted 10 lines
include/linux/hte.h new file +10 -0
+ *
+ * xlated_id parameter is used to communicate between HTE subsystem and the
+ * providers. It is the same id returned during xlate API call and translated
+ * by the provider. This may be helpful as both subsystem and provider locate
+ * the requested entity in constant time, where entity could be anything from
+ * lines, signals, events, buses etc.. that providers support.
+ */
+struct hte_ops {
+	int (*request)(struct hte_chip *chip, u32 xlated_id);
+	int (*release)(struct hte_chip *chip, u32 xlated_id);

include/linux/hte.h line 110

Quoted 10 lines
include/linux/hte.h new file +10 -0
+	int (*enable)(struct hte_chip *chip, u32 xlated_id);
+	int (*disable)(struct hte_chip *chip, u32 xlated_id);
+	int (*get_clk_src_info)(struct hte_chip *chip,
+				struct hte_clk_info *ci);
+};
+
+/**
+ * struct hte_chip - Abstract HTE chip structure.
+ * @name: functional name of the HTE IP block.
+ * @dev: device providing the HTE.  

Unclear naming. Is this the parent device, or one associated with the HTE itself? I'm guessing today you don't have one associated with the HTE, but it is plausible you might gain on in future to make it fit nicely in the device model as a function of another device.

Quoted 59 lines
include/linux/hte.h new file +58 -0
+ * @ops: callbacks for this HTE.
+ * @nlines: number of lines/signals supported by this chip.
+ * @xlate: Callback which translates consumer supplied logical ids to
+ * physical ids, return from 0 for the success and negative for the
+ * failures. It stores (0 to @nlines) in xlated_id parameter for the success.
+ * @of_hte_n_cells: Number of cells used to form the HTE specifier.
+ * @gdev: HTE subsystem abstract device, internal to the HTE subsystem.
+ * @data: chip specific private data.
+ */
+struct hte_chip {
+	const char *name;
+	struct device *dev;
+	const struct hte_ops *ops;
+	u32 nlines;
+	int (*xlate)(struct hte_chip *gc,
+		     const struct of_phandle_args *args,
+		     struct hte_ts_desc *desc, u32 *xlated_id);
+	u8 of_hte_n_cells;
+
+	/* only used internally by the HTE framework */
+	struct hte_device *gdev;
+	void *data;
+};
+
+#if IS_ENABLED(CONFIG_HTE)
+/* HTE APIs for the providers */
+int hte_register_chip(struct hte_chip *chip);
+int hte_unregister_chip(struct hte_chip *chip);
+int hte_push_ts_ns_atomic(const struct hte_chip *chip, u32 xlated_id,
+			  struct hte_ts_data *data, size_t n);
+
+/* HTE APIs for the consumers */
+
+int hte_release_ts(struct hte_ts_desc *desc);
+struct hte_ts_desc *of_hte_request_ts(struct device *dev, const char *label,
+				      void (*cb)(enum hte_notify n));
+
+struct hte_ts_desc *devm_of_hte_request_ts(struct device *dev,
+					   const char *label,
+					   void (*cb)(enum hte_notify n));
+struct hte_ts_desc *hte_req_ts_by_dt_node(struct device_node *of_node,
+					  unsigned int id,
+					  void (*cb)(enum hte_notify n));
+int devm_hte_release_ts(struct device *dev, struct hte_ts_desc *desc);
+int hte_retrieve_ts_ns(const struct hte_ts_desc *desc, struct hte_ts_data *el,
+		       size_t n);
+int hte_retrieve_ts_ns_wait(const struct hte_ts_desc *desc,
+			    struct hte_ts_data *el, size_t n);
+int hte_set_buf_len(const struct hte_ts_desc *desc, size_t len);
+size_t hte_get_buf_len(const struct hte_ts_desc *desc);
+int hte_set_buf_watermark(const struct hte_ts_desc *desc, size_t val);
+size_t hte_get_buf_watermark(const struct hte_ts_desc *desc);
+size_t hte_available_ts(const struct hte_ts_desc *desc);
+int hte_enable_ts(struct hte_ts_desc *desc);
+int hte_disable_ts(struct hte_ts_desc *desc);
+int hte_get_clk_src_info(const struct hte_ts_desc *desc,
+			 struct hte_clk_info *ci);
+
author maintainer
#11 lore raw

Re: [RFC 02/11] drivers: Add HTE subsystem

Quoted 53 lines · Jonathan Cameron
Quoted 44 lines · On Sun, 4 Jul 2021 21:15:25 +0100 Jonathan Cameron <[email protected]> wrote:
Quoted 41 lines · On Fri, 25 Jun 2021 16:55:23 -0700 Dipen Patel <[email protected]> wrote:

Some devices can timestamp system lines/signals/Buses in real-time using the hardware counter or other hardware means which can give finer granularity and help avoid jitter introduced by software means of timestamping. To utilize such functionality there has to be framework where such devices can register themselves as producers or providers so that the consumers or clients devices can request specific line from the providers. This patch introduces such subsystem as hardware timestamping engine (HTE).

It provides below APIs for the provider:
- hte_register_chip() -- To register the HTE chip.
- hte_unregister_chip() -- To unregister the HTE chip.
- hte_push_ts_ns_atomic() -- To push timestamp data into HTE subsystem.

It provides below APIs for the consumer:
- of_hte_request_ts() -- To request timestamp functionality.
- devm_of_hte_request_ts() -- Managed version of the above.
- hte_req_ts_by_dt_node() -- To request timestamp functionality by using HTE provider dt node.
- devm_hte_release_ts() -- The managed version to release timestamp functionality and associated resources.
- hte_retrieve_ts_ns() -- To retrieve timestamps.
- hte_retrieve_ts_ns_wait() -- Same as above but blocking version.
- hte_enable_ts() -- To disable timestamp functionality.
- hte_disable_ts() -- To enable timestamp functionality.
- hte_available_ts() -- To query available timestamp data.
- hte_release_ts() -- To release timestamp functionality and its associated resources.
- hte_get_clk_src_info() -- To query clock source information from the provider

It provides centralized software buffer management per requested id to store the timestamp data for the consumers as below:
- hte_set_buf_len() -- To set the buffer length.
- hte_get_buf_len() -- To get the buffer length.
- hte_set_buf_watermark() -- To set the software threshold/watermark.
- hte_get_buf_watermark() -- To get the software threshold/watermark.

The detail about parameters and API usage are described in each functions definitions in drivers/hte/hte.c file.

Quoted 6 lines
Quoted 4 lines

The patch adds compilation support in Makefile and menu options in Kconfig.

Hi Dipen, this isn't a particularly thorough review as I'm still getting my head around what this is doing + it is an RFC :)

Quoted 7 lines

Having read on through the rest of the series, one of the biggest things that became clear is you have more layers of abstraction in here than make sense. Squash things together so you have fewer allocations (and hence fewer error paths etc). Don't introduce ops functions unless you have more than one answer to what they
are (and a clear justification for those). It's easy to add layers of indirection
later, but for now they just make your code harder to read. Reality is that the buffer is a kfifo, make it so everywhere, rather than pretending otherwise.

I can remove buffer abstraction for sure. Do you find any other not needed

abstractions that I can rethink of?

Quoted 7 lines

I thought for a while that you were allowing a different buffer implementation for each of the your hte chips and was very confused as to why that would make sense.

Anyhow, it's interesting. I'm not sure yet if the way it all fits together makes sense and you will almost certainly want to support hardware FIFOs and those tend to want to be partly exposed through to the consumer.

For now I am dealing with the providers which has hardware fifo but it is

not per event/entity i.e. it stores timestamps from all the enabled entities.

For such providers it is not feasible to expose hardware fifo. Can you point

to some references where it is exposed so that if needed I can accommodate

similar changes for any future providers.

Quoted 5 lines

As to similar devices. Lots of sensorhubs have timestamping facilities but it is tightly coupled to the data streams, so probably doesn't make sense to map to a generic subsystem like this. You'll hit some of the same issues as those though when you try to align these timestamps with system ones etc.

What mechanism does sensorhub/iio now have to retrieve timestamp?

Quoted 6 lines

otherwise, some of the counter devices are closer to this. Perhaps the ti ecap?
https://www.ti.com/lit/ug/spru807b/spru807b.pdf?ts=1625431159791&ref_url=https%253A%252F%252Fwww.google.com%252F

That has a short hardware buffer and can be used for absolute timestamp grabbing on rising triggers etc.

I certainly have to read about this device. Initial target was to address in chip

HTEs and see (based on upstream comments) how can it be expanded to other

devices.

Quoted 186 lines

Jonathan

Quoted 182 lines
Quoted 39 lines
---
 drivers/Kconfig      |    2 +
 drivers/Makefile     |    1 +
 drivers/hte/Kconfig  |   22 +
 drivers/hte/Makefile |    1 +
 drivers/hte/hte.c    | 1368 ++++++++++++++++++++++++++++++++++++++++++
 include/linux/hte.h  |  278 +++++++++
 6 files changed, 1672 insertions(+)
 create mode 100644 drivers/hte/Kconfig
 create mode 100644 drivers/hte/Makefile
 create mode 100644 drivers/hte/hte.c
 create mode 100644 include/linux/hte.h
drivers/Kconfig +2 -0
index 47980c6b1945..9b078964974b 100644
@@ -238,4 +238,6 @@ source "drivers/interconnect/Kconfig"
 source "drivers/counter/Kconfig"
 
 source "drivers/most/Kconfig"
+
+source "drivers/hte/Kconfig"
 endmenu
drivers/Makefile +1 -0
index 5a6d613e868d..0a996a698e4c 100644
@@ -190,3 +190,4 @@ obj-$(CONFIG_GNSS)		+= gnss/
 obj-$(CONFIG_INTERCONNECT)	+= interconnect/
 obj-$(CONFIG_COUNTER)		+= counter/
 obj-$(CONFIG_MOST)		+= most/
+obj-$(CONFIG_HTE)		+= hte/
drivers/hte/Kconfig new file +0 -0
new file mode 100644
index 000000000000..394e112f7dfb

drivers/hte/Kconfig line 5

Quoted 5 lines
drivers/hte/Kconfig new file +5 -0
@@ -0,0 +1,22 @@
+# SPDX-License-Identifier: GPL-2.0-only
+menuconfig HTE
+        bool "Hardware Timestamping Engine (HTE) Support"
+        help
+          Hardware Timestamping Engine (HTE) Support.  

Tidy this up, but think that's already been commented on.

Quoted 136 lines
drivers/hte/Kconfig new file +17 -0
+
+          Some devices provide hardware timestamping engine which can timestamp
+	  certain device lines/signals in realtime. This way to provide
+	  hardware assisted timestamp to generic signals like GPIOs, IRQs lines
+	  comes with benefit for the applications like autonomous machines
+	  needing accurate timestamping event with less jitter.
+
+	  This framework provides a generic interface to such HTE devices
+          within the Linux kernel. It provides an API to register and
+	  unregister a HTE provider chip, configurable sw buffer to
+	  store the timestamps, push the timestamp from the HTE providers and
+	  retrieve timestamps for the consumers. It also provides means for the
+	  consumers to request signals it wishes to hardware timestamp and
+	  release them if not required.
+
+          If unsure, say no.
+
drivers/hte/Makefile new file +1 -0
new file mode 100644
index 000000000000..9899dbe516f7
@@ -0,0 +1 @@
+obj-$(CONFIG_HTE)		+= hte.o
drivers/hte/hte.c new file +106 -0
new file mode 100644
index 000000000000..c53260d1e250
@@ -0,0 +1,1368 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2021 NVIDIA Corporation
+ *
+ * Author: Dipen Patel <[email protected]>
+ */
+
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/err.h>
+#include <linux/slab.h>
+#include <linux/of.h>
+#include <linux/of_device.h>
+#include <linux/kfifo.h>
+#include <linux/mutex.h>
+#include <linux/sched.h>
+#include <linux/uaccess.h>
+#include <linux/hte.h>
+#include <linux/delay.h>
+#include <linux/debugfs.h>
+
+/* Global list of the HTE devices */
+static DEFINE_SPINLOCK(hte_lock);
+static LIST_HEAD(hte_devices);
+
+enum {
+	HTE_TS_REGISTERED,
+	HTE_TS_DISABLE,
+};
+
+/* Default FIFO depth */
+#define HTE_EV_FIFO_EL		32
+
+#define HTE_TS_NAME_LEN		10
+
+struct hte_ts_buf;
+
+/**
+ * struct hte_ts_buf_acc_func - Software buffer management functions.
+ * @store: Store timestamp from atomic context as providers most likely
+ * be pushing timestamps from their interrupt handlers.
+ * @read: Read timestamps from the buffer.
+ * @el_available: Available timestamps to retrieve. The client can use this to
+ * query available elements so that it can pre-allocate internal buffer to send
+ * to during hte_retrieve_ts_ns API.
+ * @set_length: Set length/depth of the buffer.
+ * @get_length: Get length/depth of the buffer.
+ * @set_watermark: Set software threshold of the buffer.
+ * @get_watermark: Get software threshold of the buffer.
+ * @release: Release/free buffer.
+ * @reset: Reset the buffer.
+ */
+struct hte_ts_buf_acc_func {
+	unsigned int (*store)(struct hte_ts_buf *buf, void *data, size_t n);
+	int (*read)(struct hte_ts_buf *buf, unsigned char *data, size_t n,
+		    size_t *copied);
+	size_t (*el_available)(struct hte_ts_buf *buf);
+	int (*set_length)(struct hte_ts_buf *buf,
+			  size_t length, size_t bpd);
+	size_t (*get_length)(struct hte_ts_buf *buf);
+	int (*set_watermark)(struct hte_ts_buf *buf,
+			     size_t val);
+	size_t (*get_watermark)(struct hte_ts_buf *buf);
+	void (*release)(struct hte_ts_buf *buf);
+	void (*reset)(struct hte_ts_buf *buf);
+};
+
+/**
+ * struct hte_ts_buf - Software buffer per requested id or entity to store
+ * timestamps.
+ *
+ * @datum_len: Buffer depth or number of elements.
+ * @bytes_per_datum: Element size in bytes.
+ * @watermark: Software threshold at which client will be notified.
+ * @valid: Validity of the buffer.
+ * @pollq: Waitqueue for the blocking clients.
+ * @access: Various buffer management functions.
+ */
+struct hte_ts_buf {
+	size_t datum_len;
+	size_t bytes_per_datum;
+	size_t watermark;
+	bool valid;
+	wait_queue_head_t pollq;
+	const struct hte_ts_buf_acc_func *access;
+};
+
+/**
+ * struct hte_ts_info - Information related to requested timestamp.
+ *
+ * @xlated_id: Timestamp ID as understood between HTE subsys and HTE provider,
+ * See xlate callback API.
+ * @flags: Flags holding state informations.
+ * @seq: Timestamp sequence counter.
+ * @dropped_ts: Dropped timestamps.
+ * @cb: Callback to notify clients.
+ * @mlock: Lock during timestamp request/release APIs.
+ * @ts_dbg_root: Root for the debug fs.
+ * @gdev: HTE abstract device that this timestamp belongs to.
+ * @buf: Per requested timestamp software buffer.
+ * @desc: Timestamp descriptor understood between clients and HTE subsystem.
+ */
+struct hte_ts_info {
+	u32 xlated_id;
+	unsigned long flags;
+	u64 seq;
Quoted 8 lines
Quoted 6 lines

drivers/hte/hte.c line 112

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+	atomic_t dropped_ts;
+	void (*cb)(enum hte_notify n);
+	struct mutex mlock;
+	struct dentry *ts_dbg_root;
+	struct hte_device *gdev;
+	struct hte_ts_buf *buf;

Where there is one instance, just embed it. Lots of small allocations just make for less readable code.

Which specific instance you are alluding to desc and buf types?

Quoted 175 lines
Quoted 164 lines

drivers/hte/hte.c line 123

Quoted 12 lines
drivers/hte/hte.c new file +11 -0
+	struct hte_ts_desc *desc;
+};
+
+/**
+ * struct hte_device - HTE abstract device
+ * @nlines: Number of entities this device supports.
+ * @ts_req: Total number of entities requested.
+ * @ei: Timestamp information.
+ * @sdev: Device used at various debug prints.
+ * @dbg_root: Root directory for debug fs.
+ * @list: List node for internal use.  

Be more specific of what sort of internal use.

Quoted 150 lines
drivers/hte/hte.c new file +150 -0
+ * @chip: HTE chip providing this HTE device.
+ * @owner: helps prevent removal of modules when in use.
+ */
+struct hte_device {
+	u32 nlines;
+	atomic_t ts_req;
+	struct hte_ts_info *ei;
+	struct device *sdev;
+	struct dentry *dbg_root;
+	struct list_head list;
+	struct hte_chip *chip;
+	struct module *owner;
+};
+
+/* Buffer management functions */
+
+/**
+ * struct hte_kfifo - Software buffer wrapper.
+ * @buffer: Abstract buffer device.
+ * @gkf: Actual software buffer type, this case its FIFO.
+ */
+struct hte_kfifo {
+	struct hte_ts_buf buffer;
+	struct kfifo gkf;
+};
+
+#define buf_to_kfifo(r) container_of(r, struct hte_kfifo, buffer)
+
+static unsigned int hte_ts_store_to_buf(struct hte_ts_buf *r, void *data,
+					size_t n)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if (unlikely(!r->valid))
+		return 0;
+
+	return kfifo_in(&kf->gkf, (unsigned char *)data, n);
+}
+
+static inline int hte_ts_buf_read(struct hte_ts_buf *r,
+				  unsigned char *buf, size_t n,
+				  size_t *copied)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if ((!r->valid) || (n < kfifo_esize(&kf->gkf)))
+		return -EINVAL;
+
+	*copied = kfifo_out(&kf->gkf, buf, n);
+
+	return 0;
+}
+
+static size_t hte_ts_buf_el_available(struct hte_ts_buf *r)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if (!r->valid)
+		return 0;
+
+	return (kfifo_len(&kf->gkf) / r->bytes_per_datum);
+}
+
+static int hte_ts_buf_set_length(struct hte_ts_buf *r,
+				 size_t length, size_t bpd)
+{
+	int ret = 0;
+	struct hte_kfifo *buf;
+
+	if ((length == 0) || (bpd == 0) || !r)
+		return -EINVAL;
+
+	buf = buf_to_kfifo(r);
+
+	if (r->datum_len != length) {
+		if (r->valid)
+			kfifo_free(&buf->gkf);
+		r->valid = false;
+		r->datum_len = length;
+		r->bytes_per_datum = bpd;
+		ret = kfifo_alloc(&buf->gkf, length * bpd, GFP_KERNEL);
+		if (!ret)
+			r->valid = true;
+	}
+
+	return ret;
+}
+
+static inline size_t hte_ts_buf_get_length(struct hte_ts_buf *r)
+{
+	if ((!r->valid) || !r->datum_len)
+		return 0;
+
+	return r->datum_len;
+}
+
+static inline int hte_ts_buf_set_watermark(struct hte_ts_buf *r, size_t val)
+{
+	if ((!r->valid) || (val > r->datum_len))
+		return -EINVAL;
+
+	r->watermark = val;
+
+	return 0;
+}
+
+static inline size_t hte_ts_buf_get_watermark(struct hte_ts_buf *r)
+{
+	if (!r->valid)
+		return 0;
+
+	return r->watermark;
+}
+
+static inline void hte_ts_buf_release(struct hte_ts_buf *r)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	r->valid = false;
+	kfifo_free(&kf->gkf);
+	kfree(kf);
+}
+
+static inline void hte_ts_buf_reset(struct hte_ts_buf *r)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if (!r->valid)
+		return;
+
+	kfifo_reset(&kf->gkf);
+}
+
+static const struct hte_ts_buf_acc_func kfifo_access_funcs = {
+	.store = &hte_ts_store_to_buf,
+	.read = &hte_ts_buf_read,
+	.el_available = &hte_ts_buf_el_available,
+	.set_length = &hte_ts_buf_set_length,
+	.get_length = &hte_ts_buf_get_length,
+	.set_watermark = &hte_ts_buf_set_watermark,
+	.get_watermark = &hte_ts_buf_get_watermark,
+	.release = &hte_ts_buf_release,
+	.reset = &hte_ts_buf_reset,
+};
+
+static struct hte_ts_buf *hte_ts_buf_allocate(void)
+{
+	struct hte_kfifo *kf;
+
+	kf = kzalloc(sizeof(*kf), GFP_KERNEL);
Quoted 8 lines

drivers/hte/hte.c line 281

Quoted 8 lines
drivers/hte/hte.c new file +8 -0
+	if (!kf)
+		return ERR_PTR(-ENOMEM);
+
+	init_waitqueue_head(&kf->buffer.pollq);
+	kf->buffer.watermark = 1;
+	kf->buffer.datum_len = 0;
+	kf->buffer.valid = false;
+	kf->buffer.access = &kfifo_access_funcs;

Why do you have this level abstraction? I would suggest you flatten all this into direct calls until you have some clear need for multiple buffer types.

Quoted 4 lines

A long long time ago (10 years or more) we had similar abstractions in IIO because we though it would be helpful to support ring buffers and kfifos. It wasn't, we ended up ripping them all out because all they resulted in was a more complex code base when in reality everyone was happy with a kfifo.

I agree. Initially I thought future providers may need different type of buffers so had

abstraction layer. But I guess its ok to not worry about that for now. I will remove this

in next RFC version.

Quoted 1,374 lines

Jonathan

Quoted 1,370 lines
Quoted 97 lines
drivers/hte/hte.c new file +97 -0
+
+	return &kf->buffer;
+}
+/* End of buffer management */
+
+/* Debugfs management */
+
+#ifdef CONFIG_DEBUG_FS
+
+static struct dentry *hte_root;
+
+static void __init hte_subsys_dbgfs_init(void)
+{
+	/* creates /sys/kernel/debug/hte/ */
+	hte_root = debugfs_create_dir("hte", NULL);
+}
+subsys_initcall(hte_subsys_dbgfs_init);
+
+static void hte_chip_dbgfs_init(struct hte_device *gdev)
+{
+	const struct hte_chip *chip = gdev->chip;
+	const char *name = chip->name ? chip->name : dev_name(chip->dev);
+
+	gdev->dbg_root = debugfs_create_dir(name, hte_root);
+	if (!gdev->dbg_root)
+		return;
+
+	debugfs_create_atomic_t("ts_requested", 0444, gdev->dbg_root,
+				&gdev->ts_req);
+	debugfs_create_u32("total_ts", 0444, gdev->dbg_root,
+			   &gdev->nlines);
+}
+
+static void hte_ts_dbgfs_init(const char *name, struct hte_ts_info *ei)
+{
+	if (!ei->gdev->dbg_root || !name)
+		return;
+
+	ei->ts_dbg_root = debugfs_create_dir(name, ei->gdev->dbg_root);
+	if (!ei->ts_dbg_root)
+		return;
+
+	debugfs_create_size_t("ts_buffer_depth", 0444, ei->ts_dbg_root,
+			      &ei->buf->datum_len);
+	debugfs_create_size_t("ts_buffer_watermark", 0444, ei->ts_dbg_root,
+			      &ei->buf->watermark);
+	debugfs_create_atomic_t("dropped_timestamps", 0444, ei->ts_dbg_root,
+				&ei->dropped_ts);
+}
+
+static inline void hte_dbgfs_deinit(struct dentry *root)
+{
+	if (!root)
+		return;
+
+	debugfs_remove_recursive(root);
+}
+
+#else
+
+static void hte_chip_dbgfs_init(struct hte_device *gdev)
+{
+}
+
+static void hte_ts_dbgfs_init(const char *name, struct hte_ts_info *ei)
+{
+}
+
+static inline void hte_dbgfs_deinit(struct dentry *root)
+{
+}
+
+#endif
+/* end of debugfs management*/
+
+/* Driver APIs */
+
+/**
+ * hte_release_ts() - Consumer calls this API to release the entity, where
+ * entity could be anything providers support, like lines, signals, buses,
+ * etc...
+ *
+ * The correct sequence to call this API is as below:
+ * 1) Call hte_disable_ts, this stops the timestamp push from the provider.
+ * 2) Retrieve timestamps by calling non blocking hte_retrieve_ts_ns API if you
+ * still care about the data.
+ * 3) Call this API.
+ * Above sequence makes sure that entity gets released race free.
+ *
+ * @desc: timestamp descriptor, this is the same as returned by the request API.
+ *
+ * Context: hte_dbgfs_deinit() function call may use sleeping locks,
+ *	    not suitable from atomic context in that case.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_release_ts(struct hte_ts_desc *desc)
+{

drivers/hte/hte.c line 388

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	u32 id;
+	int ret = 0;
+	struct hte_device *gdev;
+	struct hte_ts_info *ei;
+	struct hte_ts_buf *buf;
+
+	if (!desc)
+		return -EINVAL;
+
+	ei = (struct hte_ts_info *)desc->data_subsys;  

As data_subsys is void * you don't need to explicitly cast it to another pointer type.

Quoted 40 lines
drivers/hte/hte.c new file +40 -0
+
+	if (!ei || !ei->gdev || !ei->buf)
+		return -EINVAL;
+
+	gdev = ei->gdev;
+	buf = ei->buf;
+	id = desc->con_id;
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags)) {
+		dev_info(gdev->sdev, "id:%d is not registered", id);
+		return -EUSERS;
+	}
+
+	ret = gdev->chip->ops->release(gdev->chip, ei->xlated_id);
+	if (ret) {
+		dev_err(gdev->sdev, "id: %d free failed\n", id);
+		goto out;
+	}
+
+	atomic_dec(&gdev->ts_req);
+	atomic_set(&ei->dropped_ts, 0);
+
+	kfree(desc->name);
+	kfree(desc);
+	ei->desc = NULL;
+	ei->seq = 0;
+	buf->access->release(buf);
+
+	hte_dbgfs_deinit(ei->ts_dbg_root);
+	module_put(gdev->owner);
+
+	clear_bit(HTE_TS_REGISTERED, &ei->flags);
+
+out:
+	dev_dbg(gdev->sdev, "%s: id: %d\n", __func__, id);
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_release_ts);
+
+static int hte_ts_dis_en_common(struct hte_ts_desc *desc, bool en)

drivers/hte/hte.c line 438

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+{
+	u32 ts_id;
+	struct hte_device *gdev;
+	struct hte_ts_info *ei;
+	int ret;
+
+	if (!desc)
+		return -EINVAL;
+
+	ei = (struct hte_ts_info *)desc->data_subsys;  

As above, no need to cast - though it rather implies the type of data_subsys should not be void *.

Quoted 19 lines
drivers/hte/hte.c new file +19 -0
+
+	if (!ei || !ei->gdev)
+		return -EINVAL;
+
+	gdev = ei->gdev;
+	ts_id = desc->con_id;
+
+	mutex_lock(&ei->mlock);
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags)) {
+		dev_dbg(gdev->sdev, "id:%d is not registered", ts_id);
+		ret = -EUSERS;
+		goto out;
+	}
+
+	if (en) {
+		if (!test_bit(HTE_TS_DISABLE, &ei->flags)) {
+			ret = 0;
+			goto out;

drivers/hte/hte.c line 467

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		}
+		ret = gdev->chip->ops->enable(gdev->chip, ei->xlated_id);
+		if (ret) {
+			dev_warn(gdev->sdev, "id: %d enable failed\n",
+				 ts_id);
+			goto out;
+		}
+
+		clear_bit(HTE_TS_DISABLE, &ei->flags);
+		ret = 0;  

ret is already 0 so no point in setting it again.

Quoted 135 lines
drivers/hte/hte.c new file +135 -0
+	} else {
+		if (test_bit(HTE_TS_DISABLE, &ei->flags)) {
+			ret = 0;
+			goto out;
+		}
+		ret = gdev->chip->ops->disable(gdev->chip, ei->xlated_id);
+		if (ret) {
+			dev_warn(gdev->sdev, "id: %d disable failed\n",
+				 ts_id);
+			goto out;
+		}
+
+		set_bit(HTE_TS_DISABLE, &ei->flags);
+		ret = 0;
+	}
+
+out:
+	mutex_unlock(&ei->mlock);
+	return ret;
+}
+
+/**
+ * hte_disable_ts() - Disable timestamp on given descriptor.
+ *
+ * @desc: ts descriptor, this is the same as returned by the request API.
+ *
+ * Context: Holds mutex lock, not suitable from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_disable_ts(struct hte_ts_desc *desc)
+{
+	return hte_ts_dis_en_common(desc, false);
+}
+EXPORT_SYMBOL_GPL(hte_disable_ts);
+
+/**
+ * hte_enable_ts() - Enable timestamp on given descriptor.
+ *
+ * @desc: ts descriptor, this is the same as returned by the request API.
+ *
+ * Context: Holds mutex lock, not suitable from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_enable_ts(struct hte_ts_desc *desc)
+{
+	return hte_ts_dis_en_common(desc, true);
+}
+EXPORT_SYMBOL_GPL(hte_enable_ts);
+
+static int hte_simple_xlate(struct hte_chip *gc,
+			    const struct of_phandle_args *args,
+			    struct hte_ts_desc *desc,
+			    u32 *id)
+{
+	if (!id || !desc || !gc)
+		return -EINVAL;
+
+	/*
+	 * For the providers which do not have any internal mappings between
+	 * logically exposed ids and actual ids, will set both
+	 * the same.
+	 *
+	 * In case there is a internal mapping needed, providers will need to
+	 * provide its own xlate function where con_id will be sent as
+	 * args[0] and it will return xlated id. Later xlated id will be
+	 * used for any future exchanges between provider and subsystems.
+	 */
+
+	if (args) {
+		if (gc->of_hte_n_cells < 1)
+			return -EINVAL;
+
+		if (args->args_count != gc->of_hte_n_cells)
+			return -EINVAL;
+
+		*id = args->args[0];
+		desc->con_id = *id;
+	} else {
+		*id = desc->con_id;
+	}
+
+	if (desc->con_id > gc->nlines)
+		return -EINVAL;
+
+	desc->data_subsys = NULL;
+
+	return 0;
+}
+
+static struct hte_device *of_node_to_htedevice(struct device_node *np)
+{
+	struct hte_device *gdev;
+
+	spin_lock(&hte_lock);
+
+	list_for_each_entry(gdev, &hte_devices, list)
+		if (gdev->chip && gdev->chip->dev &&
+		    gdev->chip->dev->of_node == np) {
+			spin_unlock(&hte_lock);
+			return gdev;
+		}
+
+	spin_unlock(&hte_lock);
+
+	return ERR_PTR(-ENODEV);
+}
+
+static int ___hte_req_ts(struct hte_device *gdev, struct hte_ts_desc *desc,
+			 u32 xlated_id, void (*cb)(enum hte_notify n))
+{
+	struct hte_ts_info *ei;
+	struct hte_ts_buf *buf;
+	int ret;
+	u32 con_id = desc->con_id;
+
+	if (!try_module_get(gdev->owner))
+		return -ENODEV;
+
+	ei = &gdev->ei[xlated_id];
+	ei->xlated_id = xlated_id;
+
+	/*
+	 * There a chance that multiple consumers requesting same entity,
+	 * lock here.
+	 */
+	mutex_lock(&ei->mlock);
+
+	if (test_bit(HTE_TS_REGISTERED, &ei->flags)) {
+		dev_dbg(gdev->chip->dev, "id:%u is already registered",
+			xlated_id);
+		ret = -EUSERS;
+		goto unlock;
+	}
+
+	buf = hte_ts_buf_allocate();

drivers/hte/hte.c line 612

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	if (IS_ERR(buf)) {
+		dev_err(gdev->chip->dev, "Buffer allocation failed");
+		ret = PTR_ERR(buf);
+		goto unlock;
+	}
+
+	/* Set default here, let consumer decide how much to set later */
+	ret = buf->access->set_length(buf, HTE_EV_FIFO_EL,
+				      sizeof(struct hte_ts_data));
+  

It's good to keep to consistent style of no line break between a statement and it's error check.

Quoted 140 lines
drivers/hte/hte.c new file +140 -0
+	if (ret) {
+		dev_err(gdev->chip->dev, "Fifo set length failed");
+		goto buf_rel;
+	}
+
+	buf->access->reset(buf);
+	buf->valid = true;
+
+	ei->buf = buf;
+	ei->cb = cb;
+
+	ret = gdev->chip->ops->request(gdev->chip, xlated_id);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev, "ts request failed\n");
+		goto buf_rel;
+	}
+
+	desc->data_subsys = ei;
+	ei->desc = desc;
+
+	atomic_inc(&gdev->ts_req);
+	set_bit(HTE_TS_REGISTERED, &ei->flags);
+	mutex_unlock(&ei->mlock);
+
+	if (!desc->name) {
+		desc->name = kzalloc(HTE_TS_NAME_LEN, GFP_KERNEL);
+		if (desc->name)
+			scnprintf(desc->name, HTE_TS_NAME_LEN, "ts_%u",
+				  con_id);
+	}
+
+	hte_ts_dbgfs_init(desc->name, ei);
+
+	dev_dbg(gdev->chip->dev, "%s: id: %u, xlated id:%u",
+		__func__, con_id, xlated_id);
+
+	return 0;
+
+buf_rel:
+	buf->access->release(buf);
+unlock:
+	module_put(gdev->owner);
+	mutex_unlock(&ei->mlock);
+
+	return ret;
+}
+
+static struct hte_device *of_hte_dev_get(struct device *dev,
+					 struct device_node *np,
+					 const char *label,
+					 struct of_phandle_args *args)
+{
+	struct hte_device *gdev = NULL;
+	int index = 0;
+	int err;
+
+	if (label) {
+		index = of_property_match_string(np, "hte-names", label);
+		if (index < 0)
+			return ERR_PTR(index);
+	}
+
+	err = of_parse_phandle_with_args(np, "htes", "#hte-cells", index,
+					 args);
+	if (err) {
+		pr_err("%s(): can't parse \"htes\" property\n", __func__);
+		return ERR_PTR(err);
+	}
+
+	gdev = of_node_to_htedevice(args->np);
+	if (IS_ERR(gdev)) {
+		pr_err("%s(): HTE chip not found\n", __func__);
+		of_node_put(args->np);
+		return gdev;
+	}
+
+	return gdev;
+}
+
+static struct hte_ts_desc *__hte_req_ts(struct device *dev,
+					struct device_node *np,
+					const char *label,
+					void (*cb)(enum hte_notify n))
+{
+	struct hte_device *gdev = NULL;
+	struct hte_ts_desc *desc;
+	struct of_phandle_args args;
+	int ret;
+	u32 xlated_id;
+
+	gdev = of_hte_dev_get(dev, np, label, &args);
+	if (IS_ERR(gdev))
+		return ERR_CAST(gdev);
+
+	if (!gdev->chip) {
+		pr_debug("requested id does not have provider\n");
+		return ERR_PTR(-ENODEV);
+	}
+
+	desc = kzalloc(sizeof(*desc), GFP_KERNEL);
+	if (!desc)
+		return ERR_PTR(-ENOMEM);
+
+	ret = gdev->chip->xlate(gdev->chip, &args, desc, &xlated_id);
+	if (ret < 0)
+		goto put;
+
+	desc->name = NULL;
+	if (label)
+		desc->name = kstrdup(label, GFP_KERNEL);
+
+	ret = ___hte_req_ts(gdev, desc, xlated_id, cb);
+	if (ret < 0)
+		goto put;
+
+	return desc;
+
+put:
+	of_node_put(args.np);
+	kfree(desc);
+
+	return ERR_PTR(ret);
+}
+
+/**
+ * of_hte_request_ts() - Consumer calls this API to request the HTE facility
+ * on the specified entity, where entity is provider specific for example,
+ * GPIO lines, signals, buses etc...
+ *
+ * @dev: Consumer device.
+ * @label: Optional label.
+ * @cb: Optional notify callback to consumer when data is pushed by the
+ * provider.
+ *
+ * Context: Holds mutex lock, not suitable from atomic context.
+ * Returns: Timestamp descriptor on success or error ptr on failure.
+ */
+struct hte_ts_desc *of_hte_request_ts(struct device *dev,
+				      const char *label,
+				      void (*cb)(enum hte_notify n))

drivers/hte/hte.c line 762

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+{
+
+	if (dev && dev->of_node)
+		return __hte_req_ts(dev, dev->of_node, label, cb);
+	else
+		return ERR_PTR(-EOPNOTSUPP);
+}
+EXPORT_SYMBOL_GPL(of_hte_request_ts);
+
+static int devm_hte_ts_match_desc(struct device *dev, void *res, void *data)  

I'm not seeing what is devm about this.

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+{
+	struct hte_ts_desc **p = res;
+
+	if (WARN_ON(!p || !*p))
+		return 0;
+

drivers/hte/hte.c line 778

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	return *p == data;
+}
+
+static void __devm_hte_release_ts(struct device *dev, void *res)
+{
+	hte_release_ts(*(struct hte_ts_desc **)res);
+}
+
+/**
+ * devm_hte_release_ts() - Resource managed hte_release_ts().  

I'd not introduce this until you have a user. It very rarely actually makes sense to call a devm release manually. Not having one makes people think harder about it.

Quoted 9 lines
drivers/hte/hte.c new file +9 -0
+ * @dev: HTE consumer/client device.
+ * @desc: HTE ts descriptor.
+ *
+ * Release timestamp functionality and its resources previously allocated using
+ * of_hte_request_ts(). Calling this function is usually not needed because
+ * devm-allocated resources are automatically released on driver detach.
+ *
+ * Context: Same as hte_release_ts() function.
+ * Returns: 0 on success otherwise negative error code.

drivers/hte/hte.c line 797

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+ */
+int devm_hte_release_ts(struct device *dev, struct hte_ts_desc *desc)
+{
+	return devres_release(dev, __devm_hte_release_ts,
+			      devm_hte_ts_match_desc, desc);
+}
+EXPORT_SYMBOL_GPL(devm_hte_release_ts);
+
+/**
+ * devm_of_hte_request_ts() - Resource managed of_hte_request_ts().  

If it's kernel-doc it needs to give no warnings when you point the kernel-doc scripts at it. They insist on full parameter documentation.

drivers/hte/hte.c line 806

Quoted 9 lines
drivers/hte/hte.c new file +9 -0
+ */
+struct hte_ts_desc *devm_of_hte_request_ts(struct device *dev,
+					   const char *label,
+					   void (*cb)(enum hte_notify n))
+{
+
+	struct hte_ts_desc **ptr, *desc;
+
+	ptr = devres_alloc(__devm_hte_release_ts, sizeof(*ptr), GFP_KERNEL);  

Superficially looks like you might get way with just calling dev_add_action_or_reset() in here and avoid this boilerplate. A lot of cases that looked like this got cleaned up in the last kernel cycle.

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+	if (!ptr)
+		return ERR_PTR(-ENOMEM);
+
+	desc = of_hte_request_ts(dev, label, cb);
+	if (!IS_ERR(desc)) {
+		*ptr = desc;

drivers/hte/hte.c line 822

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		devres_add(dev, ptr);
+	} else {
+		devres_free(ptr);
+	}
+	return desc;
+}
+EXPORT_SYMBOL_GPL(devm_of_hte_request_ts);
+
+static struct hte_ts_info *hte_para_check(const struct hte_ts_desc *desc,
+					  size_t val)  

Not a good name or indeed combination of different things. hte_desc_to_info() and some separate check on val would be better.

Quoted 14 lines
drivers/hte/hte.c new file +14 -0
+{
+	struct hte_ts_info *ei;
+
+	if (!desc || !desc->data_subsys || !val) {
+		pr_debug("%s:%d: val :%lu\n", __func__, __LINE__, val);
+		return NULL;
+	}
+
+	ei = desc->data_subsys;
+	if (!ei || !ei->buf) {
+		pr_debug("%s:%d\n", __func__, __LINE__);
+		return NULL;
+	}
+

drivers/hte/hte.c line 846

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	return ei;
+}
+
+static inline bool hte_ts_buf_wait(struct hte_ts_buf *buffer, size_t to_read)
+{
+	size_t el_avail;
+
+	el_avail = buffer->access->el_available(buffer);
+
+	return (el_avail >= to_read) ? false : true;  

return el_avail < to_read;

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+}
+
+static int _hte_retrieve_ts_ns(const struct hte_ts_desc *desc,
+			       struct hte_ts_data *el, size_t n, bool block)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;

drivers/hte/hte.c line 863

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	int ret;
+	size_t to_read, copied;
+
+	ei = hte_para_check(desc, n);
+	if (!ei)
+		return -EINVAL;
+
+	buffer = ei->buf;
+
+	to_read = min_t(size_t, n, buffer->watermark);  

Needs a comment as not obvious why you'd read the min of that requested or the watermark if there might be more available.

Quoted 5 lines
drivers/hte/hte.c new file +5 -0
+
+	do {
+		if (hte_ts_buf_wait(buffer, to_read)) {
+			if (!block) {
+				/* Possibly early here to retrieve, try again */

drivers/hte/hte.c line 878

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+				dev_dbg(ei->gdev->chip->dev, "%s: %d\n",
+					__func__, ret);
+				return -EAGAIN;
+			}
+			ret = wait_event_interruptible(buffer->pollq,
+					!hte_ts_buf_wait(buffer, to_read));
+			if (ret)
+				return ret;
+		}
+		ret = buffer->access->read(buffer, (void *)el,  

If you have to cast to a void * that usually means something is wrong in your definitions. Why is it needed here? Looks like read has an inappropriate definition.

Quoted 56 lines
drivers/hte/hte.c new file +56 -0
+					   n * buffer->bytes_per_datum,
+					   &copied);
+		if (ret < 0)
+			return ret;
+
+		if (copied > 0)
+			return 0;
+		else if (copied == 0 && !block)
+			return -EAGAIN;
+	} while (copied == 0);
+
+	return 0;
+}
+
+/**
+ * hte_retrieve_ts_ns() - Consumer calls this API to retrieve timestamp in
+ * nano seconds i.e. el->tsc will be in ns.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ * @el: buffer to store the timestamp details.
+ * @n: Number of struct hte_timestamp_el elements.
+ *
+ * Context: Can be called from the atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_retrieve_ts_ns(const struct hte_ts_desc *desc,
+		       struct hte_ts_data *el, size_t n)
+{
+	return _hte_retrieve_ts_ns(desc, el, n, false);
+}
+EXPORT_SYMBOL_GPL(hte_retrieve_ts_ns);
+
+/**
+ * hte_retrieve_ts_ns_wait() - Blocking version of the hte_retrieve_ts_ns.
+ * @desc: ts descriptor, same as returned from request API.
+ * @el: buffer to store the timestamp data.
+ * @n: Number of struct hte_ts_data data.
+ *
+ * Context: Can not be called from the atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_retrieve_ts_ns_wait(const struct hte_ts_desc *desc,
+			    struct hte_ts_data *el, size_t n)
+{
+	return _hte_retrieve_ts_ns(desc, el, n, true);
+}
+EXPORT_SYMBOL_GPL(hte_retrieve_ts_ns_wait);
+
+/**
+ * hte_set_buf_len() - Consumer calls this API to set timestamp software buffer
+ * depth.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ * @len: New length/depth.
+ *
+ * The correct sequence to set buffer length is as below:

drivers/hte/hte.c line 944

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+ * 1) Disable timestamp by calling hte_disable_ts API.
+ * 2) Optionally retrieve all the timestamps by calling non blocking
+ *    hte_retrieve_ts_ns() API. This step only needed if you still care about
+ *    the data.
+ * 3) Call this API.
+ * 4) Enable timestamp by calling hte_enable_ts API.
+ *
+ * This API destroys previously allocated buffer and creates new one, because
+ * of that, it is mandatory to follow above sequence to make sure there is no
+ * race between various other APIs in the subsystem.  

Good docs. This is why I mentioned in review of docs patch that it is better to just have that refer to the kernel-doc in these files. Keep all this good information in one place.

Quoted 13 lines
drivers/hte/hte.c new file +13 -0
+ *
+ * By default during the request API call, HTE subsystem allocates software
+ * buffer with predefined length, this API gives flexibility to adjust the
+ * length according to consumer's need.
+ *
+ * Context: Can not be called from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_set_buf_len(const struct hte_ts_desc *desc, size_t len)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+	int ret;

drivers/hte/hte.c line 967

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+
+	ei = hte_para_check(desc, len);
+	if (!ei)
+		return -EINVAL;
+
+	buffer = ei->buf;
+	ret = buffer->access->set_length(buffer, len,
+					 sizeof(struct hte_ts_data));
+	if (ret)
+		dev_err(ei->gdev->chip->dev, "%s: ret:%d\n", __func__, ret);  

Not point in printing things line __func__ manually in dev_err() etc. Dynamic debug includes that and gives far more information + control of this.

Quoted 65 lines
drivers/hte/hte.c new file +65 -0
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_set_buf_len);
+
+/**
+ * hte_get_buf_len() - Consumer calls this API to get timestamp software buffer
+ * depth or length.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: Positive length on success or 0 on failure.
+ */
+size_t hte_get_buf_len(const struct hte_ts_desc *desc)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	ei = hte_para_check(desc, 1);
+	if (!ei)
+		return 0;
+
+	buffer = ei->buf;
+
+	return buffer->access->get_length(buffer);
+}
+EXPORT_SYMBOL_GPL(hte_get_buf_len);
+
+/**
+ * hte_available_ts() - Returns total available timestamps.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * The API helps consumers to pre-allocate its internal buffer required
+ * during hte_retrieve_ts_ns call.
+ *
+ * Context: Any context.
+ * Returns: Positive value if elements are available else 0. The value is
+ * number of total available struct hte_timestamp_el elements available not
+ * the size in bytes.
+ */
+size_t hte_available_ts(const struct hte_ts_desc *desc)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	ei = hte_para_check(desc, 1);
+	if (!ei)
+		return 0;
+
+	buffer = ei->buf;
+
+	return buffer->access->el_available(buffer);
+}
+EXPORT_SYMBOL_GPL(hte_available_ts);
+
+/**
+ * hte_set_buf_watermark() - Consumer calls this API to set timestamp software
+ * buffer watermark. The correct sequence to call this API is as below:
+ * 1) Disable timestamp by calling hte_disable_ts API.
+ * 2) Call this API.
+ * 3) Enable timestamp by calling hte_enable_ts API.
+ *
+ * @desc: ts descriptor, same as returned from request API.

drivers/hte/hte.c line 1042

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+ * @val: New watermark.
+ *
+ * By default during the request API call, HTE subsystem sets watermark as 1,
+ * this API gives flexibility to adjust the watermark according to consumer's
+ * need. The consumers will get notification through callback registered during
+ * request API either when timestamp is dropped or watermark is reached or will
+ * wait till watermark is reached. Refer hte_retrieve_ts_ns() and
+ * hte_push_ts_ns_atomic() APIs to understand how watermark is used.
+ *
+ * Context: Any context.  

You have no way of knowing that as will depend on the driver - I'd definitely suggest not from atomic context, but then that would be crazy so you are better
off not documenting any specific requirement at all.

Quoted 44 lines
drivers/hte/hte.c new file +44 -0
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_set_buf_watermark(const struct hte_ts_desc *desc, size_t val)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+	int ret;
+
+	ei = hte_para_check(desc, val);
+	if (!ei)
+		return -EINVAL;
+
+	buffer = ei->buf;
+	ret = buffer->access->set_watermark(buffer, val);
+	if (ret)
+		dev_dbg(ei->gdev->chip->dev, "%s: ret:%d\n", __func__, ret);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_set_buf_watermark);
+
+/**
+ * hte_get_buf_watermark() - Consumer calls this API to get software
+ * buffer watermark.
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: Positive current watermark on success or 0 on failure.
+ */
+size_t hte_get_buf_watermark(const struct hte_ts_desc *desc)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	ei = hte_para_check(desc, 1);
+	if (!ei)
+		return 0;
+
+	buffer = ei->buf;
+
+	return buffer->access->get_watermark(buffer);
+}
+EXPORT_SYMBOL_GPL(hte_get_buf_watermark);
+

drivers/hte/hte.c line 1096

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+/**
+ * hte_req_ts_by_dt_node() - Request entity to monitor by passing HTE device
+ * node directly, where meaning of the entity is provider specific, for example
+ * lines, signals, GPIOs, buses etc...
+ *
+ * @of_node: HTE provider device node.
+ * @id: entity id to monitor, this id belongs to HTE provider of_node.
+ * @cb: Optional callback to notify.
+ *
+ * Context: Holds mutex lock, can not be called from atomic context.  

What mutex and why? If it is one you can check is held even better.

Quoted 13 lines
drivers/hte/hte.c new file +13 -0
+ * Returns: ts descriptor on success or error pointers.
+ */
+struct hte_ts_desc *hte_req_ts_by_dt_node(struct device_node *of_node,
+					  unsigned int id,
+					  void (*cb)(enum hte_notify n))
+{
+	struct hte_device *gdev;
+	struct hte_ts_desc *desc;
+	int ret;
+	u32 xlated_id;
+
+	gdev = of_node_to_htedevice(of_node);
+	if (IS_ERR(gdev))

drivers/hte/hte.c line 1119

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		return ERR_PTR(-ENOTSUPP);
+
+	if (!gdev->chip || !gdev->chip->ops)
+		return ERR_PTR(-ENOTSUPP);
+
+	desc = kzalloc(sizeof(*desc), GFP_KERNEL);
+	if (!desc) {
+		ret = -ENOMEM;
+		goto out_put_device;
+	}  

Pass a desc pointer into this function rather than allocating the structure in here. That lets the caller embed that structure inside one of it's own structures if it wants to, resulting in fewer small allocations which is always good.

It's far from obvious that the caller needs to free desc.

Quoted 51 lines
drivers/hte/hte.c new file +51 -0
+
+	desc->con_id = id;
+	ret = gdev->chip->xlate(gdev->chip, NULL, desc, &xlated_id);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev,
+			"failed to xlate id: %d\n", id);
+		goto out_free_desc;
+	}
+
+	ret = ___hte_req_ts(gdev, desc, xlated_id, cb);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev,
+			"failed to request id: %d\n", id);
+		goto out_free_desc;
+	}
+
+	return desc;
+
+out_free_desc:
+	kfree(desc);
+
+out_put_device:
+	return ERR_PTR(ret);
+}
+EXPORT_SYMBOL_GPL(hte_req_ts_by_dt_node);
+
+/**
+ * hte_get_clk_src_info() - Consumer calls this API to query clock source
+ * information of the desc.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: 0 on success else negative error code on failure.
+ */
+int hte_get_clk_src_info(const struct hte_ts_desc *desc,
+			 struct hte_clk_info *ci)
+{
+	struct hte_chip *chip;
+	struct hte_ts_info *ei;
+
+	if (!desc || !desc->data_subsys || !ci) {
+		pr_debug("%s:%d\n", __func__, __LINE__);
+		return -EINVAL;
+	}
+
+	ei = desc->data_subsys;
+	if (!ei || !ei->gdev || !ei->gdev->chip)
+		return -EINVAL;
+
+	chip = ei->gdev->chip;

drivers/hte/hte.c line 1180

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	if (!chip->ops->get_clk_src_info)
+		return -ENOTSUPP;
+
+	return chip->ops->get_clk_src_info(chip, ci);
+}
+EXPORT_SYMBOL_GPL(hte_get_clk_src_info);
+
+static inline void hte_add_to_device_list(struct hte_device *gdev)
+{
+	struct hte_device *prev;  

Needs to take an appropriate lock as you may have concurrent calls.

drivers/hte/hte.c line 1183

Quoted 3 lines
drivers/hte/hte.c new file +3 -0
+
+	if (list_empty(&hte_devices)) {
+		list_add_tail(&gdev->list, &hte_devices);  

Needs a comment. I've no idea why you might want to only add it if there were no other hte_devices already there.

drivers/hte/hte.c line 1187

Quoted 4 lines
drivers/hte/hte.c new file +4 -0
+		return;
+	}
+
+	prev = list_last_entry(&hte_devices, struct hte_device, list);  

Why woud you do this?

Quoted 36 lines
drivers/hte/hte.c new file +36 -0
+	list_add_tail(&gdev->list, &hte_devices);
+}
+
+/**
+ * hte_push_ts_ns_atomic() - Used by the provider to push timestamp in nano
+ * seconds i.e data->tsc will be in ns, it is assumed that provider will be
+ * using this API from its ISR or atomic context.
+ *
+ * @chip: The HTE chip, used during the registration.
+ * @xlated_id: entity id understood by both subsystem and provider, usually this
+ * is obtained from xlate callback during request API.
+ * @data: timestamp data.
+ * @n: Size of the data.
+ *
+ * Context: Atomic.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_push_ts_ns_atomic(const struct hte_chip *chip, u32 xlated_id,
+			  struct hte_ts_data *data, size_t n)
+{
+	unsigned int ret;
+	bool notify;
+	size_t el_avail;
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	if (!chip || !data || !chip->gdev)
+		return -EINVAL;
+
+	if (xlated_id > chip->nlines)
+		return -EINVAL;
+
+	ei = &chip->gdev->ei[xlated_id];
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags) ||
+	    test_bit(HTE_TS_DISABLE, &ei->flags)) {

drivers/hte/hte.c line 1233

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		dev_dbg(chip->dev, "Unknown timestamp push\n");
+		return -EINVAL;
+	}
+
+	/* timestamp sequence counter, start from 0 */
+	data->seq = ei->seq++;
+
+	buffer = ei->buf;
+	el_avail = buffer->access->el_available(buffer);  
+	ret = buffer->access->store(buffer, data, n);  

If we are doing this from the hte core, why is buffer definition in the scope of the drivers rather than the core? That seems backwards to me.

drivers/hte/hte.c line 1241

Quoted 8 lines
drivers/hte/hte.c new file +8 -0
+	if (ret != n) {
+		atomic_inc(&ei->dropped_ts);
+		if (ei->cb)
+			ei->cb(HTE_TS_DROPPED);
+		return -ENOMEM;
+	}
+
+	notify = ((el_avail + 1) >= buffer->watermark) ? true : false;  

You push n but only check on el_avail + 1 here.
Also, this is the same as

	notify = ((el_avail + 1) >= buffer->watermark;

drivers/hte/hte.c line 1249

Quoted 8 lines
drivers/hte/hte.c new file +8 -0
+
+	/*
+	 * If there is a callback, its consumer's job to retrieve the timestamp.
+	 * For the rest, wake up the process.
+	 */
+	if (notify && ei->cb) {
+		ei->cb(HTE_TS_AVAIL);
+		return 0;  

Given you return 0 anyway, might as well not have this line.

drivers/hte/hte.c line 1262

Quoted 13 lines
drivers/hte/hte.c new file +13 -0
+	} else if (notify) {
+		wake_up_interruptible(&buffer->pollq);
+	}
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(hte_push_ts_ns_atomic);
+
+/**
+ * hte_register_chip() - Used by provider to register a HTE chip.
+ * @chip: the HTE chip to add to subsystem.
+ *
+ * Context: Can not be called from atomic context.  

Whilst true, I'd think that was common sense as it would be insane to register something like this from atomic context. So I'd say no need to comment on it! Keep those comments for things that might be used like that.

Quoted 25 lines
drivers/hte/hte.c new file +25 -0
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_register_chip(struct hte_chip *chip)
+{
+	struct hte_device *gdev;
+	int ret;
+	u32 i;
+
+	if (!chip || !chip->dev || !chip->dev->of_node)
+		return -EINVAL;
+
+	if (!chip->ops || !chip->ops->request || !chip->ops->release) {
+		dev_err(chip->dev, "Driver needs to provide ops\n");
+		return -EINVAL;
+	}
+
+	gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
+	if (!gdev)
+		return -ENOMEM;
+
+	gdev->chip = chip;
+	chip->gdev = gdev;
+	gdev->nlines = chip->nlines;
+	gdev->sdev = chip->dev;
+

drivers/hte/hte.c line 1297

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	/*
+	 * Allocate all the supported entities here at once, this will have
+	 * following advantages:
+	 * When provider pushes timestamp, it can then just send the
+	 * xlated_id, subsystem will use it as an index which
+	 * gives us the constant time access; this is important as mostly
+	 * providers will be pushing the timestamps from their ISR.
+	 */
+	gdev->ei = kcalloc(chip->nlines, sizeof(struct hte_ts_info),
+			   GFP_KERNEL);  

I'd be tempted to do this as a 0 length element at the end of gdev then do the allocation in one go use struct_size() etc to work out how long it is. Cuts down on allocations + error paths to deal with for no obvious disadvantage.

drivers/hte/hte.c line 1304

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+	if (!gdev->ei) {
+		ret = -ENOMEM;
+		goto err_free_gdev;
+	}
+
+	for (i = 0; i < chip->nlines; i++) {
+		gdev->ei[i].flags = 0;  

zero allocated, so don't bother setting things to 0 where it's a fairly obvious base state. If you set something to 0 to act as some form of documentation then that's fine, but I don't think that's true here.

Quoted 54 lines
drivers/hte/hte.c new file +54 -0
+		gdev->ei[i].gdev = gdev;
+		gdev->ei[i].seq = 0;
+		mutex_init(&gdev->ei[i].mlock);
+	}
+
+	if (chip->dev->driver)
+		gdev->owner = chip->dev->driver->owner;
+	else
+		gdev->owner = THIS_MODULE;
+
+	if (!chip->xlate) {
+		chip->xlate = hte_simple_xlate;
+		/* Just a id number to monitor */
+		chip->of_hte_n_cells = 1;
+	}
+
+	of_node_get(chip->dev->of_node);
+
+	INIT_LIST_HEAD(&gdev->list);
+
+	spin_lock(&hte_lock);
+	hte_add_to_device_list(gdev);
+	spin_unlock(&hte_lock);
+
+	hte_chip_dbgfs_init(gdev);
+
+	dev_dbg(chip->dev, "Added hte chip\n");
+	return 0;
+
+err_free_gdev:
+	kfree(gdev);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_register_chip);
+
+/**
+ * hte_unregister_chip() - Used by the provider to remove a HTE chip.
+ * @chip: the HTE chip to remove.
+ *
+ * Context: Can not be called from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_unregister_chip(struct hte_chip *chip)
+{
+	struct hte_device *gdev = chip->gdev;
+
+	spin_lock(&hte_lock);
+	list_del(&gdev->list);
+	spin_unlock(&hte_lock);
+
+	gdev->chip = NULL;
+
+	of_node_put(chip->dev->of_node);

drivers/hte/hte.c line 1368

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	hte_dbgfs_deinit(gdev->dbg_root);
+	kfree(gdev->ei);
+	kfree(gdev);
+
+	dev_dbg(chip->dev, "Removed hte chip\n");
+	return 0;
+}
+EXPORT_SYMBOL_GPL(hte_unregister_chip);
+
+/* Driver APIs ends */  

Don't bother with file layout type comments. They don't add that much and tend to rot horribly over time as people move code around in files.

Quoted 15 lines
include/linux/hte.h new file +9 -0
new file mode 100644
index 000000000000..e1737579d4c4
@@ -0,0 +1,278 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2021 NVIDIA Corporation
+ *
+ * Author: Dipen Patel <[email protected]>
+ */
+
+#ifndef __LINUX_HTE_H
+#define __LINUX_HTE_H

include/linux/hte.h line 19

Quoted 10 lines
include/linux/hte.h new file +10 -0
+
+struct hte_chip;
+struct hte_device;
+struct of_phandle_args;
+
+/**
+ * Used by providers to indicate the direction of the timestamp.
+ */
+#define HTE_EVENT_RISING_EDGE          0x1
+#define HTE_EVENT_FALLING_EDGE         0x2  

Use an enum rather than a define for this as it's a value that can take a set of distinct values. Also, provide a name for 'I've no idea' which I'm guessing is 0 currently.

Quoted 13 lines
include/linux/hte.h new file +13 -0
+
+/**
+ * struct hte_ts_data - HTE timestamp data.
+ * The provider uses and fills timestamp related details during push_timestamp
+ * API call. The consumer uses during retrieve_timestamp API call.
+ *
+ * @tsc: Timestamp value.
+ * @seq: Sequence counter of the timestamps.
+ * @dir: Direction of the event at the time of timestamp.
+ */
+struct hte_ts_data {
+	u64 tsc;
+	u64 seq;

include/linux/hte.h line 42

Quoted 10 lines
include/linux/hte.h new file +10 -0
+	int dir;
+};
+
+/**
+ * struct hte_clk_info - Clock source info that HTE provider uses.
+ * The provider uses hardware clock as a source to timestamp real time. This
+ * structure presents the clock information to consumers. 
+ *
+ * @hz: Clock rate in HZ, for example 1KHz clock = 1000.
+ * @type: Clock type. CLOCK_* types.  

So this is something we got a it wrong in IIO. It's much better to define a subset of clocks that can be potentially used. There are some that make absolutely no sense and consumers really don't want to have to deal with them.

include/linux/hte.h line 53

Quoted 11 lines
include/linux/hte.h new file +11 -0
+ */
+struct hte_clk_info {
+	u64 hz;
+	clockid_t type;
+};
+
+/**
+ * HTE subsystem notifications for the consumers.
+ *
+ * @HTE_TS_AVAIL: Timestamps available notification.
+ * @HTE_TS_DROPPED: Timestamps dropped notification.  

Something I've missed so far is whether drops are in a kfifo or a ring fashion. I'm guess that's stated somewhere, but it might be useful to have it here.

Quoted 27 lines
include/linux/hte.h new file +27 -0
+ */
+enum hte_notify {
+	HTE_TS_AVAIL = 1,
+	HTE_TS_DROPPED,
+	HTE_NUM_NOTIFIER,
+};
+
+/**
+ * struct hte_ts_desc - HTE timestamp descriptor, this structure will be
+ * communication token between consumers to subsystem and subsystem to
+ * providers.
+ *
+ * @con_id: This is the same id sent in request APIs.
+ * @name: Descriptive name of the entity that is being monitored for the
+ * realtime timestamping.
+ * @data_subsys: Subsystem's private data relate to requested con_id.
+ */
+struct hte_ts_desc {
+	u32 con_id;
+	char *name;
+	void *data_subsys;
+};
+
+/**
+ * struct hte_ops - HTE operations set by providers.
+ *
+ * @request: Hook for requesting a HTE timestamp. Returns 0 on success,

include/linux/hte.h line 90

Quoted 10 lines
include/linux/hte.h new file +10 -0
+ * non-zero for failures.
+ * @release: Hook for releasing a HTE timestamp. Returns 0 on success,
+ * non-zero for failures.
+ * @enable: Hook to enable the specified timestamp. Returns 0 on success,
+ * non-zero for failures.
+ * @disable: Hook to disable specified timestamp. Returns 0 on success,
+ * non-zero for failures.
+ * @get_clk_src_info: Optional hook to get the clock information provider uses
+ * to timestamp. Returns 0 for success and negative error code for failure. On
+ * success HTE subsystem fills up provided struct hte_clk_info.  

Why optional? Consumers will probably need that information.

Quoted 10 lines
include/linux/hte.h new file +10 -0
+ *
+ * xlated_id parameter is used to communicate between HTE subsystem and the
+ * providers. It is the same id returned during xlate API call and translated
+ * by the provider. This may be helpful as both subsystem and provider locate
+ * the requested entity in constant time, where entity could be anything from
+ * lines, signals, events, buses etc.. that providers support.
+ */
+struct hte_ops {
+	int (*request)(struct hte_chip *chip, u32 xlated_id);
+	int (*release)(struct hte_chip *chip, u32 xlated_id);

include/linux/hte.h line 110

Quoted 10 lines
include/linux/hte.h new file +10 -0
+	int (*enable)(struct hte_chip *chip, u32 xlated_id);
+	int (*disable)(struct hte_chip *chip, u32 xlated_id);
+	int (*get_clk_src_info)(struct hte_chip *chip,
+				struct hte_clk_info *ci);
+};
+
+/**
+ * struct hte_chip - Abstract HTE chip structure.
+ * @name: functional name of the HTE IP block.
+ * @dev: device providing the HTE.  

Unclear naming. Is this the parent device, or one associated with the HTE itself? I'm guessing today you don't have one associated with the HTE, but it is plausible you might gain on in future to make it fit nicely in the device model as a function of another device.

Quoted 59 lines
include/linux/hte.h new file +58 -0
+ * @ops: callbacks for this HTE.
+ * @nlines: number of lines/signals supported by this chip.
+ * @xlate: Callback which translates consumer supplied logical ids to
+ * physical ids, return from 0 for the success and negative for the
+ * failures. It stores (0 to @nlines) in xlated_id parameter for the success.
+ * @of_hte_n_cells: Number of cells used to form the HTE specifier.
+ * @gdev: HTE subsystem abstract device, internal to the HTE subsystem.
+ * @data: chip specific private data.
+ */
+struct hte_chip {
+	const char *name;
+	struct device *dev;
+	const struct hte_ops *ops;
+	u32 nlines;
+	int (*xlate)(struct hte_chip *gc,
+		     const struct of_phandle_args *args,
+		     struct hte_ts_desc *desc, u32 *xlated_id);
+	u8 of_hte_n_cells;
+
+	/* only used internally by the HTE framework */
+	struct hte_device *gdev;
+	void *data;
+};
+
+#if IS_ENABLED(CONFIG_HTE)
+/* HTE APIs for the providers */
+int hte_register_chip(struct hte_chip *chip);
+int hte_unregister_chip(struct hte_chip *chip);
+int hte_push_ts_ns_atomic(const struct hte_chip *chip, u32 xlated_id,
+			  struct hte_ts_data *data, size_t n);
+
+/* HTE APIs for the consumers */
+
+int hte_release_ts(struct hte_ts_desc *desc);
+struct hte_ts_desc *of_hte_request_ts(struct device *dev, const char *label,
+				      void (*cb)(enum hte_notify n));
+
+struct hte_ts_desc *devm_of_hte_request_ts(struct device *dev,
+					   const char *label,
+					   void (*cb)(enum hte_notify n));
+struct hte_ts_desc *hte_req_ts_by_dt_node(struct device_node *of_node,
+					  unsigned int id,
+					  void (*cb)(enum hte_notify n));
+int devm_hte_release_ts(struct device *dev, struct hte_ts_desc *desc);
+int hte_retrieve_ts_ns(const struct hte_ts_desc *desc, struct hte_ts_data *el,
+		       size_t n);
+int hte_retrieve_ts_ns_wait(const struct hte_ts_desc *desc,
+			    struct hte_ts_data *el, size_t n);
+int hte_set_buf_len(const struct hte_ts_desc *desc, size_t len);
+size_t hte_get_buf_len(const struct hte_ts_desc *desc);
+int hte_set_buf_watermark(const struct hte_ts_desc *desc, size_t val);
+size_t hte_get_buf_watermark(const struct hte_ts_desc *desc);
+size_t hte_available_ts(const struct hte_ts_desc *desc);
+int hte_enable_ts(struct hte_ts_desc *desc);
+int hte_disable_ts(struct hte_ts_desc *desc);
+int hte_get_clk_src_info(const struct hte_ts_desc *desc,
+			 struct hte_clk_info *ci);
+
maintainer
#12 lore raw

Re: [RFC 02/11] drivers: Add HTE subsystem

Quoted 62 lines · On Tue, 27 Jul 2021 22:12:18 -0700 Dipen Patel <[email protected]> wrote:
Quoted 53 lines · Jonathan Cameron
Quoted 44 lines · On Sun, 4 Jul 2021 21:15:25 +0100 Jonathan Cameron <[email protected]> wrote:
Quoted 41 lines · On Fri, 25 Jun 2021 16:55:23 -0700 Dipen Patel <[email protected]> wrote:

Some devices can timestamp system lines/signals/Buses in real-time using the hardware counter or other hardware means which can give finer granularity and help avoid jitter introduced by software means of timestamping. To utilize such functionality there has to be framework where such devices can register themselves as producers or providers so that the consumers or clients devices can request specific line from the providers. This patch introduces such subsystem as hardware timestamping engine (HTE).

It provides below APIs for the provider:
- hte_register_chip() -- To register the HTE chip.
- hte_unregister_chip() -- To unregister the HTE chip.
- hte_push_ts_ns_atomic() -- To push timestamp data into HTE subsystem.

It provides below APIs for the consumer:
- of_hte_request_ts() -- To request timestamp functionality.
- devm_of_hte_request_ts() -- Managed version of the above.
- hte_req_ts_by_dt_node() -- To request timestamp functionality by using HTE provider dt node.
- devm_hte_release_ts() -- The managed version to release timestamp functionality and associated resources.
- hte_retrieve_ts_ns() -- To retrieve timestamps.
- hte_retrieve_ts_ns_wait() -- Same as above but blocking version.
- hte_enable_ts() -- To disable timestamp functionality.
- hte_disable_ts() -- To enable timestamp functionality.
- hte_available_ts() -- To query available timestamp data.
- hte_release_ts() -- To release timestamp functionality and its associated resources.
- hte_get_clk_src_info() -- To query clock source information from the provider

It provides centralized software buffer management per requested id to store the timestamp data for the consumers as below:
- hte_set_buf_len() -- To set the buffer length.
- hte_get_buf_len() -- To get the buffer length.
- hte_set_buf_watermark() -- To set the software threshold/watermark.
- hte_get_buf_watermark() -- To get the software threshold/watermark.

The detail about parameters and API usage are described in each functions definitions in drivers/hte/hte.c file.

Quoted 6 lines
Quoted 4 lines

The patch adds compilation support in Makefile and menu options in Kconfig.

Hi Dipen, this isn't a particularly thorough review as I'm still getting my head around what this is doing + it is an RFC :)

Quoted 7 lines

Having read on through the rest of the series, one of the biggest things that became clear is you have more layers of abstraction in here than make sense. Squash things together so you have fewer allocations (and hence fewer error paths etc). Don't introduce ops functions unless you have more than one answer to what they
are (and a clear justification for those). It's easy to add layers of indirection
later, but for now they just make your code harder to read. Reality is that the buffer is a kfifo, make it so everywhere, rather than pretending otherwise.

Quoted 3 lines

I can remove buffer abstraction for sure. Do you find any other not needed

abstractions that I can rethink of?

Ah, I should have read both replies before responding to either.

It was a while ago so I can't remember which others I noticed.

Looking quickly at it again, I think the lifetimes of the desc and buffer are the same (note that I'd normally expect a release() to be a result of reference counting rather that directly called which confused me a little whilst looking at this code). You could make that explicit and embed the buffer in the desc.

Quoted 9 lines
Quoted 8 lines

I thought for a while that you were allowing a different buffer implementation for each of the your hte chips and was very confused as to why that would make sense.

Anyhow, it's interesting. I'm not sure yet if the way it all fits together makes sense and you will almost certainly want to support hardware FIFOs and those tend to want to be partly exposed through to the consumer.

Quoted 5 lines

For now I am dealing with the providers which has hardware fifo but it is not per event/entity i.e. it stores timestamps from all the enabled entities. For such providers it is not feasible to expose hardware fifo. Can you point to some references where it is exposed so that if needed I can accommodate similar changes for any future providers.

At the moment all I have to go on is what has been done in sensor hubs where it is a single purpose timestamp. An example is drivers/iio/imu/st_lsm6dsx/ which has hardware timestamping support (and some nasty code to align that with system timestamps).

You may still be able to do some stuff with your hwfifo. For example if only
one event is currently enabled, you could match the hwfifo watermark to the software one and hence enable batching of handling the timestamps.

Quoted 7 lines
Quoted 6 lines

As to similar devices. Lots of sensorhubs have timestamping facilities but it is tightly coupled to the data streams, so probably doesn't make sense to map to a generic subsystem like this. You'll hit some of the same issues as those though when you try to align these timestamps with system ones etc.

What mechanism does sensorhub/iio now have to retrieve timestamp?

They are just another type of channel giving a measurement of time alongside other elements of a channel scan (ADC channels etC), so for userspace you can get them via the chrdev / buffered interface. In kernel you can get them via the consumer buffer interface (drivers/iio/buffers/industrialio-buffer-cb.c) though interestingly I don't think any in kernel consumers use the timestamp channels. The actually mangling of a hardware timestamp into one aligned with the system timestamps is done in each driver.

Quoted 4 lines
Quoted 4 lines

otherwise, some of the counter devices are closer to this. Perhaps the ti ecap?
https://www.ti.com/lit/ug/spru807b/spru807b.pdf?ts=1625431159791&ref_url=https%253A%252F%252Fwww.google.com%252F

Quoted 8 lines
Quoted 2 lines

That has a short hardware buffer and can be used for absolute timestamp grabbing on rising triggers etc.

I certainly have to read about this device. Initial target was to address in chip

HTEs and see (based on upstream comments) how can it be expanded to other

devices.

Understood. It's possible some of the sensor hubs will timestamp things other than their main flow but no one has enabled driver support yet if they do. Some sensorhubs are tightly integrated with the application processor so you may run into some of those.

Good luck!

Jonathan

Quoted 1,756 lines
Quoted 187 lines

Jonathan

Quoted 182 lines
Quoted 39 lines
---
 drivers/Kconfig      |    2 +
 drivers/Makefile     |    1 +
 drivers/hte/Kconfig  |   22 +
 drivers/hte/Makefile |    1 +
 drivers/hte/hte.c    | 1368 ++++++++++++++++++++++++++++++++++++++++++
 include/linux/hte.h  |  278 +++++++++
 6 files changed, 1672 insertions(+)
 create mode 100644 drivers/hte/Kconfig
 create mode 100644 drivers/hte/Makefile
 create mode 100644 drivers/hte/hte.c
 create mode 100644 include/linux/hte.h
drivers/Kconfig +2 -0
index 47980c6b1945..9b078964974b 100644
@@ -238,4 +238,6 @@ source "drivers/interconnect/Kconfig"
 source "drivers/counter/Kconfig"
 
 source "drivers/most/Kconfig"
+
+source "drivers/hte/Kconfig"
 endmenu
drivers/Makefile +1 -0
index 5a6d613e868d..0a996a698e4c 100644
@@ -190,3 +190,4 @@ obj-$(CONFIG_GNSS)		+= gnss/
 obj-$(CONFIG_INTERCONNECT)	+= interconnect/
 obj-$(CONFIG_COUNTER)		+= counter/
 obj-$(CONFIG_MOST)		+= most/
+obj-$(CONFIG_HTE)		+= hte/
drivers/hte/Kconfig new file +0 -0
new file mode 100644
index 000000000000..394e112f7dfb

drivers/hte/Kconfig line 5

Quoted 5 lines
drivers/hte/Kconfig new file +5 -0
@@ -0,0 +1,22 @@
+# SPDX-License-Identifier: GPL-2.0-only
+menuconfig HTE
+        bool "Hardware Timestamping Engine (HTE) Support"
+        help
+          Hardware Timestamping Engine (HTE) Support.    

Tidy this up, but think that's already been commented on.

Quoted 136 lines
drivers/hte/Kconfig new file +17 -0
+
+          Some devices provide hardware timestamping engine which can timestamp
+	  certain device lines/signals in realtime. This way to provide
+	  hardware assisted timestamp to generic signals like GPIOs, IRQs lines
+	  comes with benefit for the applications like autonomous machines
+	  needing accurate timestamping event with less jitter.
+
+	  This framework provides a generic interface to such HTE devices
+          within the Linux kernel. It provides an API to register and
+	  unregister a HTE provider chip, configurable sw buffer to
+	  store the timestamps, push the timestamp from the HTE providers and
+	  retrieve timestamps for the consumers. It also provides means for the
+	  consumers to request signals it wishes to hardware timestamp and
+	  release them if not required.
+
+          If unsure, say no.
+
drivers/hte/Makefile new file +1 -0
new file mode 100644
index 000000000000..9899dbe516f7
@@ -0,0 +1 @@
+obj-$(CONFIG_HTE)		+= hte.o
drivers/hte/hte.c new file +106 -0
new file mode 100644
index 000000000000..c53260d1e250
@@ -0,0 +1,1368 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2021 NVIDIA Corporation
+ *
+ * Author: Dipen Patel <[email protected]>
+ */
+
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/err.h>
+#include <linux/slab.h>
+#include <linux/of.h>
+#include <linux/of_device.h>
+#include <linux/kfifo.h>
+#include <linux/mutex.h>
+#include <linux/sched.h>
+#include <linux/uaccess.h>
+#include <linux/hte.h>
+#include <linux/delay.h>
+#include <linux/debugfs.h>
+
+/* Global list of the HTE devices */
+static DEFINE_SPINLOCK(hte_lock);
+static LIST_HEAD(hte_devices);
+
+enum {
+	HTE_TS_REGISTERED,
+	HTE_TS_DISABLE,
+};
+
+/* Default FIFO depth */
+#define HTE_EV_FIFO_EL		32
+
+#define HTE_TS_NAME_LEN		10
+
+struct hte_ts_buf;
+
+/**
+ * struct hte_ts_buf_acc_func - Software buffer management functions.
+ * @store: Store timestamp from atomic context as providers most likely
+ * be pushing timestamps from their interrupt handlers.
+ * @read: Read timestamps from the buffer.
+ * @el_available: Available timestamps to retrieve. The client can use this to
+ * query available elements so that it can pre-allocate internal buffer to send
+ * to during hte_retrieve_ts_ns API.
+ * @set_length: Set length/depth of the buffer.
+ * @get_length: Get length/depth of the buffer.
+ * @set_watermark: Set software threshold of the buffer.
+ * @get_watermark: Get software threshold of the buffer.
+ * @release: Release/free buffer.
+ * @reset: Reset the buffer.
+ */
+struct hte_ts_buf_acc_func {
+	unsigned int (*store)(struct hte_ts_buf *buf, void *data, size_t n);
+	int (*read)(struct hte_ts_buf *buf, unsigned char *data, size_t n,
+		    size_t *copied);
+	size_t (*el_available)(struct hte_ts_buf *buf);
+	int (*set_length)(struct hte_ts_buf *buf,
+			  size_t length, size_t bpd);
+	size_t (*get_length)(struct hte_ts_buf *buf);
+	int (*set_watermark)(struct hte_ts_buf *buf,
+			     size_t val);
+	size_t (*get_watermark)(struct hte_ts_buf *buf);
+	void (*release)(struct hte_ts_buf *buf);
+	void (*reset)(struct hte_ts_buf *buf);
+};
+
+/**
+ * struct hte_ts_buf - Software buffer per requested id or entity to store
+ * timestamps.
+ *
+ * @datum_len: Buffer depth or number of elements.
+ * @bytes_per_datum: Element size in bytes.
+ * @watermark: Software threshold at which client will be notified.
+ * @valid: Validity of the buffer.
+ * @pollq: Waitqueue for the blocking clients.
+ * @access: Various buffer management functions.
+ */
+struct hte_ts_buf {
+	size_t datum_len;
+	size_t bytes_per_datum;
+	size_t watermark;
+	bool valid;
+	wait_queue_head_t pollq;
+	const struct hte_ts_buf_acc_func *access;
+};
+
+/**
+ * struct hte_ts_info - Information related to requested timestamp.
+ *
+ * @xlated_id: Timestamp ID as understood between HTE subsys and HTE provider,
+ * See xlate callback API.
+ * @flags: Flags holding state informations.
+ * @seq: Timestamp sequence counter.
+ * @dropped_ts: Dropped timestamps.
+ * @cb: Callback to notify clients.
+ * @mlock: Lock during timestamp request/release APIs.
+ * @ts_dbg_root: Root for the debug fs.
+ * @gdev: HTE abstract device that this timestamp belongs to.
+ * @buf: Per requested timestamp software buffer.
+ * @desc: Timestamp descriptor understood between clients and HTE subsystem.
+ */
+struct hte_ts_info {
+	u32 xlated_id;
+	unsigned long flags;
+	u64 seq;
Quoted 8 lines
Quoted 6 lines

drivers/hte/hte.c line 112

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+	atomic_t dropped_ts;
+	void (*cb)(enum hte_notify n);
+	struct mutex mlock;
+	struct dentry *ts_dbg_root;
+	struct hte_device *gdev;
+	struct hte_ts_buf *buf;  

Where there is one instance, just embed it. Lots of small allocations just make for less readable code.

Which specific instance you are alluding to desc and buf types?

Quoted 175 lines
Quoted 164 lines

drivers/hte/hte.c line 123

Quoted 12 lines
drivers/hte/hte.c new file +11 -0
+	struct hte_ts_desc *desc;
+};
+
+/**
+ * struct hte_device - HTE abstract device
+ * @nlines: Number of entities this device supports.
+ * @ts_req: Total number of entities requested.
+ * @ei: Timestamp information.
+ * @sdev: Device used at various debug prints.
+ * @dbg_root: Root directory for debug fs.
+ * @list: List node for internal use.    

Be more specific of what sort of internal use.

Quoted 150 lines
drivers/hte/hte.c new file +150 -0
+ * @chip: HTE chip providing this HTE device.
+ * @owner: helps prevent removal of modules when in use.
+ */
+struct hte_device {
+	u32 nlines;
+	atomic_t ts_req;
+	struct hte_ts_info *ei;
+	struct device *sdev;
+	struct dentry *dbg_root;
+	struct list_head list;
+	struct hte_chip *chip;
+	struct module *owner;
+};
+
+/* Buffer management functions */
+
+/**
+ * struct hte_kfifo - Software buffer wrapper.
+ * @buffer: Abstract buffer device.
+ * @gkf: Actual software buffer type, this case its FIFO.
+ */
+struct hte_kfifo {
+	struct hte_ts_buf buffer;
+	struct kfifo gkf;
+};
+
+#define buf_to_kfifo(r) container_of(r, struct hte_kfifo, buffer)
+
+static unsigned int hte_ts_store_to_buf(struct hte_ts_buf *r, void *data,
+					size_t n)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if (unlikely(!r->valid))
+		return 0;
+
+	return kfifo_in(&kf->gkf, (unsigned char *)data, n);
+}
+
+static inline int hte_ts_buf_read(struct hte_ts_buf *r,
+				  unsigned char *buf, size_t n,
+				  size_t *copied)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if ((!r->valid) || (n < kfifo_esize(&kf->gkf)))
+		return -EINVAL;
+
+	*copied = kfifo_out(&kf->gkf, buf, n);
+
+	return 0;
+}
+
+static size_t hte_ts_buf_el_available(struct hte_ts_buf *r)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if (!r->valid)
+		return 0;
+
+	return (kfifo_len(&kf->gkf) / r->bytes_per_datum);
+}
+
+static int hte_ts_buf_set_length(struct hte_ts_buf *r,
+				 size_t length, size_t bpd)
+{
+	int ret = 0;
+	struct hte_kfifo *buf;
+
+	if ((length == 0) || (bpd == 0) || !r)
+		return -EINVAL;
+
+	buf = buf_to_kfifo(r);
+
+	if (r->datum_len != length) {
+		if (r->valid)
+			kfifo_free(&buf->gkf);
+		r->valid = false;
+		r->datum_len = length;
+		r->bytes_per_datum = bpd;
+		ret = kfifo_alloc(&buf->gkf, length * bpd, GFP_KERNEL);
+		if (!ret)
+			r->valid = true;
+	}
+
+	return ret;
+}
+
+static inline size_t hte_ts_buf_get_length(struct hte_ts_buf *r)
+{
+	if ((!r->valid) || !r->datum_len)
+		return 0;
+
+	return r->datum_len;
+}
+
+static inline int hte_ts_buf_set_watermark(struct hte_ts_buf *r, size_t val)
+{
+	if ((!r->valid) || (val > r->datum_len))
+		return -EINVAL;
+
+	r->watermark = val;
+
+	return 0;
+}
+
+static inline size_t hte_ts_buf_get_watermark(struct hte_ts_buf *r)
+{
+	if (!r->valid)
+		return 0;
+
+	return r->watermark;
+}
+
+static inline void hte_ts_buf_release(struct hte_ts_buf *r)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	r->valid = false;
+	kfifo_free(&kf->gkf);
+	kfree(kf);
+}
+
+static inline void hte_ts_buf_reset(struct hte_ts_buf *r)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if (!r->valid)
+		return;
+
+	kfifo_reset(&kf->gkf);
+}
+
+static const struct hte_ts_buf_acc_func kfifo_access_funcs = {
+	.store = &hte_ts_store_to_buf,
+	.read = &hte_ts_buf_read,
+	.el_available = &hte_ts_buf_el_available,
+	.set_length = &hte_ts_buf_set_length,
+	.get_length = &hte_ts_buf_get_length,
+	.set_watermark = &hte_ts_buf_set_watermark,
+	.get_watermark = &hte_ts_buf_get_watermark,
+	.release = &hte_ts_buf_release,
+	.reset = &hte_ts_buf_reset,
+};
+
+static struct hte_ts_buf *hte_ts_buf_allocate(void)
+{
+	struct hte_kfifo *kf;
+
+	kf = kzalloc(sizeof(*kf), GFP_KERNEL);
Quoted 8 lines

drivers/hte/hte.c line 281

Quoted 8 lines
drivers/hte/hte.c new file +8 -0
+	if (!kf)
+		return ERR_PTR(-ENOMEM);
+
+	init_waitqueue_head(&kf->buffer.pollq);
+	kf->buffer.watermark = 1;
+	kf->buffer.datum_len = 0;
+	kf->buffer.valid = false;
+	kf->buffer.access = &kfifo_access_funcs;  

Why do you have this level abstraction? I would suggest you flatten all this into direct calls until you have some clear need for multiple buffer types.

Quoted 4 lines

A long long time ago (10 years or more) we had similar abstractions in IIO because we though it would be helpful to support ring buffers and kfifos. It wasn't, we ended up ripping them all out because all they resulted in was a more complex code base when in reality everyone was happy with a kfifo.

I agree. Initially I thought future providers may need different type of buffers so had

abstraction layer. But I guess its ok to not worry about that for now. I will remove this

in next RFC version.

Quoted 1,374 lines

Jonathan

Quoted 1,370 lines
Quoted 97 lines
drivers/hte/hte.c new file +97 -0
+
+	return &kf->buffer;
+}
+/* End of buffer management */
+
+/* Debugfs management */
+
+#ifdef CONFIG_DEBUG_FS
+
+static struct dentry *hte_root;
+
+static void __init hte_subsys_dbgfs_init(void)
+{
+	/* creates /sys/kernel/debug/hte/ */
+	hte_root = debugfs_create_dir("hte", NULL);
+}
+subsys_initcall(hte_subsys_dbgfs_init);
+
+static void hte_chip_dbgfs_init(struct hte_device *gdev)
+{
+	const struct hte_chip *chip = gdev->chip;
+	const char *name = chip->name ? chip->name : dev_name(chip->dev);
+
+	gdev->dbg_root = debugfs_create_dir(name, hte_root);
+	if (!gdev->dbg_root)
+		return;
+
+	debugfs_create_atomic_t("ts_requested", 0444, gdev->dbg_root,
+				&gdev->ts_req);
+	debugfs_create_u32("total_ts", 0444, gdev->dbg_root,
+			   &gdev->nlines);
+}
+
+static void hte_ts_dbgfs_init(const char *name, struct hte_ts_info *ei)
+{
+	if (!ei->gdev->dbg_root || !name)
+		return;
+
+	ei->ts_dbg_root = debugfs_create_dir(name, ei->gdev->dbg_root);
+	if (!ei->ts_dbg_root)
+		return;
+
+	debugfs_create_size_t("ts_buffer_depth", 0444, ei->ts_dbg_root,
+			      &ei->buf->datum_len);
+	debugfs_create_size_t("ts_buffer_watermark", 0444, ei->ts_dbg_root,
+			      &ei->buf->watermark);
+	debugfs_create_atomic_t("dropped_timestamps", 0444, ei->ts_dbg_root,
+				&ei->dropped_ts);
+}
+
+static inline void hte_dbgfs_deinit(struct dentry *root)
+{
+	if (!root)
+		return;
+
+	debugfs_remove_recursive(root);
+}
+
+#else
+
+static void hte_chip_dbgfs_init(struct hte_device *gdev)
+{
+}
+
+static void hte_ts_dbgfs_init(const char *name, struct hte_ts_info *ei)
+{
+}
+
+static inline void hte_dbgfs_deinit(struct dentry *root)
+{
+}
+
+#endif
+/* end of debugfs management*/
+
+/* Driver APIs */
+
+/**
+ * hte_release_ts() - Consumer calls this API to release the entity, where
+ * entity could be anything providers support, like lines, signals, buses,
+ * etc...
+ *
+ * The correct sequence to call this API is as below:
+ * 1) Call hte_disable_ts, this stops the timestamp push from the provider.
+ * 2) Retrieve timestamps by calling non blocking hte_retrieve_ts_ns API if you
+ * still care about the data.
+ * 3) Call this API.
+ * Above sequence makes sure that entity gets released race free.
+ *
+ * @desc: timestamp descriptor, this is the same as returned by the request API.
+ *
+ * Context: hte_dbgfs_deinit() function call may use sleeping locks,
+ *	    not suitable from atomic context in that case.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_release_ts(struct hte_ts_desc *desc)
+{

drivers/hte/hte.c line 388

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	u32 id;
+	int ret = 0;
+	struct hte_device *gdev;
+	struct hte_ts_info *ei;
+	struct hte_ts_buf *buf;
+
+	if (!desc)
+		return -EINVAL;
+
+	ei = (struct hte_ts_info *)desc->data_subsys;    

As data_subsys is void * you don't need to explicitly cast it to another pointer type.

Quoted 40 lines
drivers/hte/hte.c new file +40 -0
+
+	if (!ei || !ei->gdev || !ei->buf)
+		return -EINVAL;
+
+	gdev = ei->gdev;
+	buf = ei->buf;
+	id = desc->con_id;
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags)) {
+		dev_info(gdev->sdev, "id:%d is not registered", id);
+		return -EUSERS;
+	}
+
+	ret = gdev->chip->ops->release(gdev->chip, ei->xlated_id);
+	if (ret) {
+		dev_err(gdev->sdev, "id: %d free failed\n", id);
+		goto out;
+	}
+
+	atomic_dec(&gdev->ts_req);
+	atomic_set(&ei->dropped_ts, 0);
+
+	kfree(desc->name);
+	kfree(desc);
+	ei->desc = NULL;
+	ei->seq = 0;
+	buf->access->release(buf);
+
+	hte_dbgfs_deinit(ei->ts_dbg_root);
+	module_put(gdev->owner);
+
+	clear_bit(HTE_TS_REGISTERED, &ei->flags);
+
+out:
+	dev_dbg(gdev->sdev, "%s: id: %d\n", __func__, id);
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_release_ts);
+
+static int hte_ts_dis_en_common(struct hte_ts_desc *desc, bool en)

drivers/hte/hte.c line 438

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+{
+	u32 ts_id;
+	struct hte_device *gdev;
+	struct hte_ts_info *ei;
+	int ret;
+
+	if (!desc)
+		return -EINVAL;
+
+	ei = (struct hte_ts_info *)desc->data_subsys;    

As above, no need to cast - though it rather implies the type of data_subsys should not be void *.

Quoted 19 lines
drivers/hte/hte.c new file +19 -0
+
+	if (!ei || !ei->gdev)
+		return -EINVAL;
+
+	gdev = ei->gdev;
+	ts_id = desc->con_id;
+
+	mutex_lock(&ei->mlock);
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags)) {
+		dev_dbg(gdev->sdev, "id:%d is not registered", ts_id);
+		ret = -EUSERS;
+		goto out;
+	}
+
+	if (en) {
+		if (!test_bit(HTE_TS_DISABLE, &ei->flags)) {
+			ret = 0;
+			goto out;

drivers/hte/hte.c line 467

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		}
+		ret = gdev->chip->ops->enable(gdev->chip, ei->xlated_id);
+		if (ret) {
+			dev_warn(gdev->sdev, "id: %d enable failed\n",
+				 ts_id);
+			goto out;
+		}
+
+		clear_bit(HTE_TS_DISABLE, &ei->flags);
+		ret = 0;    

ret is already 0 so no point in setting it again.

Quoted 135 lines
drivers/hte/hte.c new file +135 -0
+	} else {
+		if (test_bit(HTE_TS_DISABLE, &ei->flags)) {
+			ret = 0;
+			goto out;
+		}
+		ret = gdev->chip->ops->disable(gdev->chip, ei->xlated_id);
+		if (ret) {
+			dev_warn(gdev->sdev, "id: %d disable failed\n",
+				 ts_id);
+			goto out;
+		}
+
+		set_bit(HTE_TS_DISABLE, &ei->flags);
+		ret = 0;
+	}
+
+out:
+	mutex_unlock(&ei->mlock);
+	return ret;
+}
+
+/**
+ * hte_disable_ts() - Disable timestamp on given descriptor.
+ *
+ * @desc: ts descriptor, this is the same as returned by the request API.
+ *
+ * Context: Holds mutex lock, not suitable from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_disable_ts(struct hte_ts_desc *desc)
+{
+	return hte_ts_dis_en_common(desc, false);
+}
+EXPORT_SYMBOL_GPL(hte_disable_ts);
+
+/**
+ * hte_enable_ts() - Enable timestamp on given descriptor.
+ *
+ * @desc: ts descriptor, this is the same as returned by the request API.
+ *
+ * Context: Holds mutex lock, not suitable from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_enable_ts(struct hte_ts_desc *desc)
+{
+	return hte_ts_dis_en_common(desc, true);
+}
+EXPORT_SYMBOL_GPL(hte_enable_ts);
+
+static int hte_simple_xlate(struct hte_chip *gc,
+			    const struct of_phandle_args *args,
+			    struct hte_ts_desc *desc,
+			    u32 *id)
+{
+	if (!id || !desc || !gc)
+		return -EINVAL;
+
+	/*
+	 * For the providers which do not have any internal mappings between
+	 * logically exposed ids and actual ids, will set both
+	 * the same.
+	 *
+	 * In case there is a internal mapping needed, providers will need to
+	 * provide its own xlate function where con_id will be sent as
+	 * args[0] and it will return xlated id. Later xlated id will be
+	 * used for any future exchanges between provider and subsystems.
+	 */
+
+	if (args) {
+		if (gc->of_hte_n_cells < 1)
+			return -EINVAL;
+
+		if (args->args_count != gc->of_hte_n_cells)
+			return -EINVAL;
+
+		*id = args->args[0];
+		desc->con_id = *id;
+	} else {
+		*id = desc->con_id;
+	}
+
+	if (desc->con_id > gc->nlines)
+		return -EINVAL;
+
+	desc->data_subsys = NULL;
+
+	return 0;
+}
+
+static struct hte_device *of_node_to_htedevice(struct device_node *np)
+{
+	struct hte_device *gdev;
+
+	spin_lock(&hte_lock);
+
+	list_for_each_entry(gdev, &hte_devices, list)
+		if (gdev->chip && gdev->chip->dev &&
+		    gdev->chip->dev->of_node == np) {
+			spin_unlock(&hte_lock);
+			return gdev;
+		}
+
+	spin_unlock(&hte_lock);
+
+	return ERR_PTR(-ENODEV);
+}
+
+static int ___hte_req_ts(struct hte_device *gdev, struct hte_ts_desc *desc,
+			 u32 xlated_id, void (*cb)(enum hte_notify n))
+{
+	struct hte_ts_info *ei;
+	struct hte_ts_buf *buf;
+	int ret;
+	u32 con_id = desc->con_id;
+
+	if (!try_module_get(gdev->owner))
+		return -ENODEV;
+
+	ei = &gdev->ei[xlated_id];
+	ei->xlated_id = xlated_id;
+
+	/*
+	 * There a chance that multiple consumers requesting same entity,
+	 * lock here.
+	 */
+	mutex_lock(&ei->mlock);
+
+	if (test_bit(HTE_TS_REGISTERED, &ei->flags)) {
+		dev_dbg(gdev->chip->dev, "id:%u is already registered",
+			xlated_id);
+		ret = -EUSERS;
+		goto unlock;
+	}
+
+	buf = hte_ts_buf_allocate();

drivers/hte/hte.c line 612

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	if (IS_ERR(buf)) {
+		dev_err(gdev->chip->dev, "Buffer allocation failed");
+		ret = PTR_ERR(buf);
+		goto unlock;
+	}
+
+	/* Set default here, let consumer decide how much to set later */
+	ret = buf->access->set_length(buf, HTE_EV_FIFO_EL,
+				      sizeof(struct hte_ts_data));
+    

It's good to keep to consistent style of no line break between a statement and it's error check.

Quoted 140 lines
drivers/hte/hte.c new file +140 -0
+	if (ret) {
+		dev_err(gdev->chip->dev, "Fifo set length failed");
+		goto buf_rel;
+	}
+
+	buf->access->reset(buf);
+	buf->valid = true;
+
+	ei->buf = buf;
+	ei->cb = cb;
+
+	ret = gdev->chip->ops->request(gdev->chip, xlated_id);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev, "ts request failed\n");
+		goto buf_rel;
+	}
+
+	desc->data_subsys = ei;
+	ei->desc = desc;
+
+	atomic_inc(&gdev->ts_req);
+	set_bit(HTE_TS_REGISTERED, &ei->flags);
+	mutex_unlock(&ei->mlock);
+
+	if (!desc->name) {
+		desc->name = kzalloc(HTE_TS_NAME_LEN, GFP_KERNEL);
+		if (desc->name)
+			scnprintf(desc->name, HTE_TS_NAME_LEN, "ts_%u",
+				  con_id);
+	}
+
+	hte_ts_dbgfs_init(desc->name, ei);
+
+	dev_dbg(gdev->chip->dev, "%s: id: %u, xlated id:%u",
+		__func__, con_id, xlated_id);
+
+	return 0;
+
+buf_rel:
+	buf->access->release(buf);
+unlock:
+	module_put(gdev->owner);
+	mutex_unlock(&ei->mlock);
+
+	return ret;
+}
+
+static struct hte_device *of_hte_dev_get(struct device *dev,
+					 struct device_node *np,
+					 const char *label,
+					 struct of_phandle_args *args)
+{
+	struct hte_device *gdev = NULL;
+	int index = 0;
+	int err;
+
+	if (label) {
+		index = of_property_match_string(np, "hte-names", label);
+		if (index < 0)
+			return ERR_PTR(index);
+	}
+
+	err = of_parse_phandle_with_args(np, "htes", "#hte-cells", index,
+					 args);
+	if (err) {
+		pr_err("%s(): can't parse \"htes\" property\n", __func__);
+		return ERR_PTR(err);
+	}
+
+	gdev = of_node_to_htedevice(args->np);
+	if (IS_ERR(gdev)) {
+		pr_err("%s(): HTE chip not found\n", __func__);
+		of_node_put(args->np);
+		return gdev;
+	}
+
+	return gdev;
+}
+
+static struct hte_ts_desc *__hte_req_ts(struct device *dev,
+					struct device_node *np,
+					const char *label,
+					void (*cb)(enum hte_notify n))
+{
+	struct hte_device *gdev = NULL;
+	struct hte_ts_desc *desc;
+	struct of_phandle_args args;
+	int ret;
+	u32 xlated_id;
+
+	gdev = of_hte_dev_get(dev, np, label, &args);
+	if (IS_ERR(gdev))
+		return ERR_CAST(gdev);
+
+	if (!gdev->chip) {
+		pr_debug("requested id does not have provider\n");
+		return ERR_PTR(-ENODEV);
+	}
+
+	desc = kzalloc(sizeof(*desc), GFP_KERNEL);
+	if (!desc)
+		return ERR_PTR(-ENOMEM);
+
+	ret = gdev->chip->xlate(gdev->chip, &args, desc, &xlated_id);
+	if (ret < 0)
+		goto put;
+
+	desc->name = NULL;
+	if (label)
+		desc->name = kstrdup(label, GFP_KERNEL);
+
+	ret = ___hte_req_ts(gdev, desc, xlated_id, cb);
+	if (ret < 0)
+		goto put;
+
+	return desc;
+
+put:
+	of_node_put(args.np);
+	kfree(desc);
+
+	return ERR_PTR(ret);
+}
+
+/**
+ * of_hte_request_ts() - Consumer calls this API to request the HTE facility
+ * on the specified entity, where entity is provider specific for example,
+ * GPIO lines, signals, buses etc...
+ *
+ * @dev: Consumer device.
+ * @label: Optional label.
+ * @cb: Optional notify callback to consumer when data is pushed by the
+ * provider.
+ *
+ * Context: Holds mutex lock, not suitable from atomic context.
+ * Returns: Timestamp descriptor on success or error ptr on failure.
+ */
+struct hte_ts_desc *of_hte_request_ts(struct device *dev,
+				      const char *label,
+				      void (*cb)(enum hte_notify n))

drivers/hte/hte.c line 762

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+{
+
+	if (dev && dev->of_node)
+		return __hte_req_ts(dev, dev->of_node, label, cb);
+	else
+		return ERR_PTR(-EOPNOTSUPP);
+}
+EXPORT_SYMBOL_GPL(of_hte_request_ts);
+
+static int devm_hte_ts_match_desc(struct device *dev, void *res, void *data)    

I'm not seeing what is devm about this.

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+{
+	struct hte_ts_desc **p = res;
+
+	if (WARN_ON(!p || !*p))
+		return 0;
+

drivers/hte/hte.c line 778

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	return *p == data;
+}
+
+static void __devm_hte_release_ts(struct device *dev, void *res)
+{
+	hte_release_ts(*(struct hte_ts_desc **)res);
+}
+
+/**
+ * devm_hte_release_ts() - Resource managed hte_release_ts().    

I'd not introduce this until you have a user. It very rarely actually makes sense to call a devm release manually. Not having one makes people think harder about it.

Quoted 9 lines
drivers/hte/hte.c new file +9 -0
+ * @dev: HTE consumer/client device.
+ * @desc: HTE ts descriptor.
+ *
+ * Release timestamp functionality and its resources previously allocated using
+ * of_hte_request_ts(). Calling this function is usually not needed because
+ * devm-allocated resources are automatically released on driver detach.
+ *
+ * Context: Same as hte_release_ts() function.
+ * Returns: 0 on success otherwise negative error code.

drivers/hte/hte.c line 797

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+ */
+int devm_hte_release_ts(struct device *dev, struct hte_ts_desc *desc)
+{
+	return devres_release(dev, __devm_hte_release_ts,
+			      devm_hte_ts_match_desc, desc);
+}
+EXPORT_SYMBOL_GPL(devm_hte_release_ts);
+
+/**
+ * devm_of_hte_request_ts() - Resource managed of_hte_request_ts().    

If it's kernel-doc it needs to give no warnings when you point the kernel-doc scripts at it. They insist on full parameter documentation.

drivers/hte/hte.c line 806

Quoted 9 lines
drivers/hte/hte.c new file +9 -0
+ */
+struct hte_ts_desc *devm_of_hte_request_ts(struct device *dev,
+					   const char *label,
+					   void (*cb)(enum hte_notify n))
+{
+
+	struct hte_ts_desc **ptr, *desc;
+
+	ptr = devres_alloc(__devm_hte_release_ts, sizeof(*ptr), GFP_KERNEL);    

Superficially looks like you might get way with just calling dev_add_action_or_reset() in here and avoid this boilerplate. A lot of cases that looked like this got cleaned up in the last kernel cycle.

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+	if (!ptr)
+		return ERR_PTR(-ENOMEM);
+
+	desc = of_hte_request_ts(dev, label, cb);
+	if (!IS_ERR(desc)) {
+		*ptr = desc;

drivers/hte/hte.c line 822

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		devres_add(dev, ptr);
+	} else {
+		devres_free(ptr);
+	}
+	return desc;
+}
+EXPORT_SYMBOL_GPL(devm_of_hte_request_ts);
+
+static struct hte_ts_info *hte_para_check(const struct hte_ts_desc *desc,
+					  size_t val)    

Not a good name or indeed combination of different things. hte_desc_to_info() and some separate check on val would be better.

Quoted 14 lines
drivers/hte/hte.c new file +14 -0
+{
+	struct hte_ts_info *ei;
+
+	if (!desc || !desc->data_subsys || !val) {
+		pr_debug("%s:%d: val :%lu\n", __func__, __LINE__, val);
+		return NULL;
+	}
+
+	ei = desc->data_subsys;
+	if (!ei || !ei->buf) {
+		pr_debug("%s:%d\n", __func__, __LINE__);
+		return NULL;
+	}
+

drivers/hte/hte.c line 846

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	return ei;
+}
+
+static inline bool hte_ts_buf_wait(struct hte_ts_buf *buffer, size_t to_read)
+{
+	size_t el_avail;
+
+	el_avail = buffer->access->el_available(buffer);
+
+	return (el_avail >= to_read) ? false : true;    

return el_avail < to_read;

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+}
+
+static int _hte_retrieve_ts_ns(const struct hte_ts_desc *desc,
+			       struct hte_ts_data *el, size_t n, bool block)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;

drivers/hte/hte.c line 863

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	int ret;
+	size_t to_read, copied;
+
+	ei = hte_para_check(desc, n);
+	if (!ei)
+		return -EINVAL;
+
+	buffer = ei->buf;
+
+	to_read = min_t(size_t, n, buffer->watermark);    

Needs a comment as not obvious why you'd read the min of that requested or the watermark if there might be more available.

Quoted 5 lines
drivers/hte/hte.c new file +5 -0
+
+	do {
+		if (hte_ts_buf_wait(buffer, to_read)) {
+			if (!block) {
+				/* Possibly early here to retrieve, try again */

drivers/hte/hte.c line 878

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+				dev_dbg(ei->gdev->chip->dev, "%s: %d\n",
+					__func__, ret);
+				return -EAGAIN;
+			}
+			ret = wait_event_interruptible(buffer->pollq,
+					!hte_ts_buf_wait(buffer, to_read));
+			if (ret)
+				return ret;
+		}
+		ret = buffer->access->read(buffer, (void *)el,    

If you have to cast to a void * that usually means something is wrong in your definitions. Why is it needed here? Looks like read has an inappropriate definition.

Quoted 56 lines
drivers/hte/hte.c new file +56 -0
+					   n * buffer->bytes_per_datum,
+					   &copied);
+		if (ret < 0)
+			return ret;
+
+		if (copied > 0)
+			return 0;
+		else if (copied == 0 && !block)
+			return -EAGAIN;
+	} while (copied == 0);
+
+	return 0;
+}
+
+/**
+ * hte_retrieve_ts_ns() - Consumer calls this API to retrieve timestamp in
+ * nano seconds i.e. el->tsc will be in ns.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ * @el: buffer to store the timestamp details.
+ * @n: Number of struct hte_timestamp_el elements.
+ *
+ * Context: Can be called from the atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_retrieve_ts_ns(const struct hte_ts_desc *desc,
+		       struct hte_ts_data *el, size_t n)
+{
+	return _hte_retrieve_ts_ns(desc, el, n, false);
+}
+EXPORT_SYMBOL_GPL(hte_retrieve_ts_ns);
+
+/**
+ * hte_retrieve_ts_ns_wait() - Blocking version of the hte_retrieve_ts_ns.
+ * @desc: ts descriptor, same as returned from request API.
+ * @el: buffer to store the timestamp data.
+ * @n: Number of struct hte_ts_data data.
+ *
+ * Context: Can not be called from the atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_retrieve_ts_ns_wait(const struct hte_ts_desc *desc,
+			    struct hte_ts_data *el, size_t n)
+{
+	return _hte_retrieve_ts_ns(desc, el, n, true);
+}
+EXPORT_SYMBOL_GPL(hte_retrieve_ts_ns_wait);
+
+/**
+ * hte_set_buf_len() - Consumer calls this API to set timestamp software buffer
+ * depth.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ * @len: New length/depth.
+ *
+ * The correct sequence to set buffer length is as below:

drivers/hte/hte.c line 944

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+ * 1) Disable timestamp by calling hte_disable_ts API.
+ * 2) Optionally retrieve all the timestamps by calling non blocking
+ *    hte_retrieve_ts_ns() API. This step only needed if you still care about
+ *    the data.
+ * 3) Call this API.
+ * 4) Enable timestamp by calling hte_enable_ts API.
+ *
+ * This API destroys previously allocated buffer and creates new one, because
+ * of that, it is mandatory to follow above sequence to make sure there is no
+ * race between various other APIs in the subsystem.    

Good docs. This is why I mentioned in review of docs patch that it is better to just have that refer to the kernel-doc in these files. Keep all this good information in one place.

Quoted 13 lines
drivers/hte/hte.c new file +13 -0
+ *
+ * By default during the request API call, HTE subsystem allocates software
+ * buffer with predefined length, this API gives flexibility to adjust the
+ * length according to consumer's need.
+ *
+ * Context: Can not be called from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_set_buf_len(const struct hte_ts_desc *desc, size_t len)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+	int ret;

drivers/hte/hte.c line 967

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+
+	ei = hte_para_check(desc, len);
+	if (!ei)
+		return -EINVAL;
+
+	buffer = ei->buf;
+	ret = buffer->access->set_length(buffer, len,
+					 sizeof(struct hte_ts_data));
+	if (ret)
+		dev_err(ei->gdev->chip->dev, "%s: ret:%d\n", __func__, ret);    

Not point in printing things line __func__ manually in dev_err() etc. Dynamic debug includes that and gives far more information + control of this.

Quoted 65 lines
drivers/hte/hte.c new file +65 -0
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_set_buf_len);
+
+/**
+ * hte_get_buf_len() - Consumer calls this API to get timestamp software buffer
+ * depth or length.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: Positive length on success or 0 on failure.
+ */
+size_t hte_get_buf_len(const struct hte_ts_desc *desc)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	ei = hte_para_check(desc, 1);
+	if (!ei)
+		return 0;
+
+	buffer = ei->buf;
+
+	return buffer->access->get_length(buffer);
+}
+EXPORT_SYMBOL_GPL(hte_get_buf_len);
+
+/**
+ * hte_available_ts() - Returns total available timestamps.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * The API helps consumers to pre-allocate its internal buffer required
+ * during hte_retrieve_ts_ns call.
+ *
+ * Context: Any context.
+ * Returns: Positive value if elements are available else 0. The value is
+ * number of total available struct hte_timestamp_el elements available not
+ * the size in bytes.
+ */
+size_t hte_available_ts(const struct hte_ts_desc *desc)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	ei = hte_para_check(desc, 1);
+	if (!ei)
+		return 0;
+
+	buffer = ei->buf;
+
+	return buffer->access->el_available(buffer);
+}
+EXPORT_SYMBOL_GPL(hte_available_ts);
+
+/**
+ * hte_set_buf_watermark() - Consumer calls this API to set timestamp software
+ * buffer watermark. The correct sequence to call this API is as below:
+ * 1) Disable timestamp by calling hte_disable_ts API.
+ * 2) Call this API.
+ * 3) Enable timestamp by calling hte_enable_ts API.
+ *
+ * @desc: ts descriptor, same as returned from request API.

drivers/hte/hte.c line 1042

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+ * @val: New watermark.
+ *
+ * By default during the request API call, HTE subsystem sets watermark as 1,
+ * this API gives flexibility to adjust the watermark according to consumer's
+ * need. The consumers will get notification through callback registered during
+ * request API either when timestamp is dropped or watermark is reached or will
+ * wait till watermark is reached. Refer hte_retrieve_ts_ns() and
+ * hte_push_ts_ns_atomic() APIs to understand how watermark is used.
+ *
+ * Context: Any context.    

You have no way of knowing that as will depend on the driver - I'd definitely suggest not from atomic context, but then that would be crazy so you are better
off not documenting any specific requirement at all.

Quoted 44 lines
drivers/hte/hte.c new file +44 -0
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_set_buf_watermark(const struct hte_ts_desc *desc, size_t val)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+	int ret;
+
+	ei = hte_para_check(desc, val);
+	if (!ei)
+		return -EINVAL;
+
+	buffer = ei->buf;
+	ret = buffer->access->set_watermark(buffer, val);
+	if (ret)
+		dev_dbg(ei->gdev->chip->dev, "%s: ret:%d\n", __func__, ret);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_set_buf_watermark);
+
+/**
+ * hte_get_buf_watermark() - Consumer calls this API to get software
+ * buffer watermark.
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: Positive current watermark on success or 0 on failure.
+ */
+size_t hte_get_buf_watermark(const struct hte_ts_desc *desc)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	ei = hte_para_check(desc, 1);
+	if (!ei)
+		return 0;
+
+	buffer = ei->buf;
+
+	return buffer->access->get_watermark(buffer);
+}
+EXPORT_SYMBOL_GPL(hte_get_buf_watermark);
+

drivers/hte/hte.c line 1096

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+/**
+ * hte_req_ts_by_dt_node() - Request entity to monitor by passing HTE device
+ * node directly, where meaning of the entity is provider specific, for example
+ * lines, signals, GPIOs, buses etc...
+ *
+ * @of_node: HTE provider device node.
+ * @id: entity id to monitor, this id belongs to HTE provider of_node.
+ * @cb: Optional callback to notify.
+ *
+ * Context: Holds mutex lock, can not be called from atomic context.    

What mutex and why? If it is one you can check is held even better.

Quoted 13 lines
drivers/hte/hte.c new file +13 -0
+ * Returns: ts descriptor on success or error pointers.
+ */
+struct hte_ts_desc *hte_req_ts_by_dt_node(struct device_node *of_node,
+					  unsigned int id,
+					  void (*cb)(enum hte_notify n))
+{
+	struct hte_device *gdev;
+	struct hte_ts_desc *desc;
+	int ret;
+	u32 xlated_id;
+
+	gdev = of_node_to_htedevice(of_node);
+	if (IS_ERR(gdev))

drivers/hte/hte.c line 1119

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		return ERR_PTR(-ENOTSUPP);
+
+	if (!gdev->chip || !gdev->chip->ops)
+		return ERR_PTR(-ENOTSUPP);
+
+	desc = kzalloc(sizeof(*desc), GFP_KERNEL);
+	if (!desc) {
+		ret = -ENOMEM;
+		goto out_put_device;
+	}    

Pass a desc pointer into this function rather than allocating the structure in here. That lets the caller embed that structure inside one of it's own structures if it wants to, resulting in fewer small allocations which is always good.

It's far from obvious that the caller needs to free desc.

Quoted 51 lines
drivers/hte/hte.c new file +51 -0
+
+	desc->con_id = id;
+	ret = gdev->chip->xlate(gdev->chip, NULL, desc, &xlated_id);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev,
+			"failed to xlate id: %d\n", id);
+		goto out_free_desc;
+	}
+
+	ret = ___hte_req_ts(gdev, desc, xlated_id, cb);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev,
+			"failed to request id: %d\n", id);
+		goto out_free_desc;
+	}
+
+	return desc;
+
+out_free_desc:
+	kfree(desc);
+
+out_put_device:
+	return ERR_PTR(ret);
+}
+EXPORT_SYMBOL_GPL(hte_req_ts_by_dt_node);
+
+/**
+ * hte_get_clk_src_info() - Consumer calls this API to query clock source
+ * information of the desc.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: 0 on success else negative error code on failure.
+ */
+int hte_get_clk_src_info(const struct hte_ts_desc *desc,
+			 struct hte_clk_info *ci)
+{
+	struct hte_chip *chip;
+	struct hte_ts_info *ei;
+
+	if (!desc || !desc->data_subsys || !ci) {
+		pr_debug("%s:%d\n", __func__, __LINE__);
+		return -EINVAL;
+	}
+
+	ei = desc->data_subsys;
+	if (!ei || !ei->gdev || !ei->gdev->chip)
+		return -EINVAL;
+
+	chip = ei->gdev->chip;

drivers/hte/hte.c line 1180

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	if (!chip->ops->get_clk_src_info)
+		return -ENOTSUPP;
+
+	return chip->ops->get_clk_src_info(chip, ci);
+}
+EXPORT_SYMBOL_GPL(hte_get_clk_src_info);
+
+static inline void hte_add_to_device_list(struct hte_device *gdev)
+{
+	struct hte_device *prev;    

Needs to take an appropriate lock as you may have concurrent calls.

drivers/hte/hte.c line 1183

Quoted 3 lines
drivers/hte/hte.c new file +3 -0
+
+	if (list_empty(&hte_devices)) {
+		list_add_tail(&gdev->list, &hte_devices);    

Needs a comment. I've no idea why you might want to only add it if there were no other hte_devices already there.

drivers/hte/hte.c line 1187

Quoted 4 lines
drivers/hte/hte.c new file +4 -0
+		return;
+	}
+
+	prev = list_last_entry(&hte_devices, struct hte_device, list);    

Why woud you do this?

Quoted 36 lines
drivers/hte/hte.c new file +36 -0
+	list_add_tail(&gdev->list, &hte_devices);
+}
+
+/**
+ * hte_push_ts_ns_atomic() - Used by the provider to push timestamp in nano
+ * seconds i.e data->tsc will be in ns, it is assumed that provider will be
+ * using this API from its ISR or atomic context.
+ *
+ * @chip: The HTE chip, used during the registration.
+ * @xlated_id: entity id understood by both subsystem and provider, usually this
+ * is obtained from xlate callback during request API.
+ * @data: timestamp data.
+ * @n: Size of the data.
+ *
+ * Context: Atomic.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_push_ts_ns_atomic(const struct hte_chip *chip, u32 xlated_id,
+			  struct hte_ts_data *data, size_t n)
+{
+	unsigned int ret;
+	bool notify;
+	size_t el_avail;
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	if (!chip || !data || !chip->gdev)
+		return -EINVAL;
+
+	if (xlated_id > chip->nlines)
+		return -EINVAL;
+
+	ei = &chip->gdev->ei[xlated_id];
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags) ||
+	    test_bit(HTE_TS_DISABLE, &ei->flags)) {

drivers/hte/hte.c line 1233

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		dev_dbg(chip->dev, "Unknown timestamp push\n");
+		return -EINVAL;
+	}
+
+	/* timestamp sequence counter, start from 0 */
+	data->seq = ei->seq++;
+
+	buffer = ei->buf;
+	el_avail = buffer->access->el_available(buffer);  
+	ret = buffer->access->store(buffer, data, n);    

If we are doing this from the hte core, why is buffer definition in the scope of the drivers rather than the core? That seems backwards to me.

drivers/hte/hte.c line 1241

Quoted 8 lines
drivers/hte/hte.c new file +8 -0
+	if (ret != n) {
+		atomic_inc(&ei->dropped_ts);
+		if (ei->cb)
+			ei->cb(HTE_TS_DROPPED);
+		return -ENOMEM;
+	}
+
+	notify = ((el_avail + 1) >= buffer->watermark) ? true : false;    

You push n but only check on el_avail + 1 here.
Also, this is the same as

	notify = ((el_avail + 1) >= buffer->watermark;

drivers/hte/hte.c line 1249

Quoted 8 lines
drivers/hte/hte.c new file +8 -0
+
+	/*
+	 * If there is a callback, its consumer's job to retrieve the timestamp.
+	 * For the rest, wake up the process.
+	 */
+	if (notify && ei->cb) {
+		ei->cb(HTE_TS_AVAIL);
+		return 0;    

Given you return 0 anyway, might as well not have this line.

drivers/hte/hte.c line 1262

Quoted 13 lines
drivers/hte/hte.c new file +13 -0
+	} else if (notify) {
+		wake_up_interruptible(&buffer->pollq);
+	}
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(hte_push_ts_ns_atomic);
+
+/**
+ * hte_register_chip() - Used by provider to register a HTE chip.
+ * @chip: the HTE chip to add to subsystem.
+ *
+ * Context: Can not be called from atomic context.    

Whilst true, I'd think that was common sense as it would be insane to register something like this from atomic context. So I'd say no need to comment on it! Keep those comments for things that might be used like that.

Quoted 25 lines
drivers/hte/hte.c new file +25 -0
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_register_chip(struct hte_chip *chip)
+{
+	struct hte_device *gdev;
+	int ret;
+	u32 i;
+
+	if (!chip || !chip->dev || !chip->dev->of_node)
+		return -EINVAL;
+
+	if (!chip->ops || !chip->ops->request || !chip->ops->release) {
+		dev_err(chip->dev, "Driver needs to provide ops\n");
+		return -EINVAL;
+	}
+
+	gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
+	if (!gdev)
+		return -ENOMEM;
+
+	gdev->chip = chip;
+	chip->gdev = gdev;
+	gdev->nlines = chip->nlines;
+	gdev->sdev = chip->dev;
+

drivers/hte/hte.c line 1297

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	/*
+	 * Allocate all the supported entities here at once, this will have
+	 * following advantages:
+	 * When provider pushes timestamp, it can then just send the
+	 * xlated_id, subsystem will use it as an index which
+	 * gives us the constant time access; this is important as mostly
+	 * providers will be pushing the timestamps from their ISR.
+	 */
+	gdev->ei = kcalloc(chip->nlines, sizeof(struct hte_ts_info),
+			   GFP_KERNEL);    

I'd be tempted to do this as a 0 length element at the end of gdev then do the allocation in one go use struct_size() etc to work out how long it is. Cuts down on allocations + error paths to deal with for no obvious disadvantage.

drivers/hte/hte.c line 1304

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+	if (!gdev->ei) {
+		ret = -ENOMEM;
+		goto err_free_gdev;
+	}
+
+	for (i = 0; i < chip->nlines; i++) {
+		gdev->ei[i].flags = 0;    

zero allocated, so don't bother setting things to 0 where it's a fairly obvious base state. If you set something to 0 to act as some form of documentation then that's fine, but I don't think that's true here.

Quoted 54 lines
drivers/hte/hte.c new file +54 -0
+		gdev->ei[i].gdev = gdev;
+		gdev->ei[i].seq = 0;
+		mutex_init(&gdev->ei[i].mlock);
+	}
+
+	if (chip->dev->driver)
+		gdev->owner = chip->dev->driver->owner;
+	else
+		gdev->owner = THIS_MODULE;
+
+	if (!chip->xlate) {
+		chip->xlate = hte_simple_xlate;
+		/* Just a id number to monitor */
+		chip->of_hte_n_cells = 1;
+	}
+
+	of_node_get(chip->dev->of_node);
+
+	INIT_LIST_HEAD(&gdev->list);
+
+	spin_lock(&hte_lock);
+	hte_add_to_device_list(gdev);
+	spin_unlock(&hte_lock);
+
+	hte_chip_dbgfs_init(gdev);
+
+	dev_dbg(chip->dev, "Added hte chip\n");
+	return 0;
+
+err_free_gdev:
+	kfree(gdev);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_register_chip);
+
+/**
+ * hte_unregister_chip() - Used by the provider to remove a HTE chip.
+ * @chip: the HTE chip to remove.
+ *
+ * Context: Can not be called from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_unregister_chip(struct hte_chip *chip)
+{
+	struct hte_device *gdev = chip->gdev;
+
+	spin_lock(&hte_lock);
+	list_del(&gdev->list);
+	spin_unlock(&hte_lock);
+
+	gdev->chip = NULL;
+
+	of_node_put(chip->dev->of_node);

drivers/hte/hte.c line 1368

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+	hte_dbgfs_deinit(gdev->dbg_root);
+	kfree(gdev->ei);
+	kfree(gdev);
+
+	dev_dbg(chip->dev, "Removed hte chip\n");
+	return 0;
+}
+EXPORT_SYMBOL_GPL(hte_unregister_chip);
+
+/* Driver APIs ends */    

Don't bother with file layout type comments. They don't add that much and tend to rot horribly over time as people move code around in files.

Quoted 15 lines
include/linux/hte.h new file +9 -0
new file mode 100644
index 000000000000..e1737579d4c4
@@ -0,0 +1,278 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2021 NVIDIA Corporation
+ *
+ * Author: Dipen Patel <[email protected]>
+ */
+
+#ifndef __LINUX_HTE_H
+#define __LINUX_HTE_H

include/linux/hte.h line 19

Quoted 10 lines
include/linux/hte.h new file +10 -0
+
+struct hte_chip;
+struct hte_device;
+struct of_phandle_args;
+
+/**
+ * Used by providers to indicate the direction of the timestamp.
+ */
+#define HTE_EVENT_RISING_EDGE          0x1
+#define HTE_EVENT_FALLING_EDGE         0x2    

Use an enum rather than a define for this as it's a value that can take a set of distinct values. Also, provide a name for 'I've no idea' which I'm guessing is 0 currently.

Quoted 13 lines
include/linux/hte.h new file +13 -0
+
+/**
+ * struct hte_ts_data - HTE timestamp data.
+ * The provider uses and fills timestamp related details during push_timestamp
+ * API call. The consumer uses during retrieve_timestamp API call.
+ *
+ * @tsc: Timestamp value.
+ * @seq: Sequence counter of the timestamps.
+ * @dir: Direction of the event at the time of timestamp.
+ */
+struct hte_ts_data {
+	u64 tsc;
+	u64 seq;

include/linux/hte.h line 42

Quoted 10 lines
include/linux/hte.h new file +10 -0
+	int dir;
+};
+
+/**
+ * struct hte_clk_info - Clock source info that HTE provider uses.
+ * The provider uses hardware clock as a source to timestamp real time. This
+ * structure presents the clock information to consumers. 
+ *
+ * @hz: Clock rate in HZ, for example 1KHz clock = 1000.
+ * @type: Clock type. CLOCK_* types.    

So this is something we got a it wrong in IIO. It's much better to define a subset of clocks that can be potentially used. There are some that make absolutely no sense and consumers really don't want to have to deal with them.

include/linux/hte.h line 53

Quoted 11 lines
include/linux/hte.h new file +11 -0
+ */
+struct hte_clk_info {
+	u64 hz;
+	clockid_t type;
+};
+
+/**
+ * HTE subsystem notifications for the consumers.
+ *
+ * @HTE_TS_AVAIL: Timestamps available notification.
+ * @HTE_TS_DROPPED: Timestamps dropped notification.    

Something I've missed so far is whether drops are in a kfifo or a ring fashion. I'm guess that's stated somewhere, but it might be useful to have it here.

Quoted 27 lines
include/linux/hte.h new file +27 -0
+ */
+enum hte_notify {
+	HTE_TS_AVAIL = 1,
+	HTE_TS_DROPPED,
+	HTE_NUM_NOTIFIER,
+};
+
+/**
+ * struct hte_ts_desc - HTE timestamp descriptor, this structure will be
+ * communication token between consumers to subsystem and subsystem to
+ * providers.
+ *
+ * @con_id: This is the same id sent in request APIs.
+ * @name: Descriptive name of the entity that is being monitored for the
+ * realtime timestamping.
+ * @data_subsys: Subsystem's private data relate to requested con_id.
+ */
+struct hte_ts_desc {
+	u32 con_id;
+	char *name;
+	void *data_subsys;
+};
+
+/**
+ * struct hte_ops - HTE operations set by providers.
+ *
+ * @request: Hook for requesting a HTE timestamp. Returns 0 on success,

include/linux/hte.h line 90

Quoted 10 lines
include/linux/hte.h new file +10 -0
+ * non-zero for failures.
+ * @release: Hook for releasing a HTE timestamp. Returns 0 on success,
+ * non-zero for failures.
+ * @enable: Hook to enable the specified timestamp. Returns 0 on success,
+ * non-zero for failures.
+ * @disable: Hook to disable specified timestamp. Returns 0 on success,
+ * non-zero for failures.
+ * @get_clk_src_info: Optional hook to get the clock information provider uses
+ * to timestamp. Returns 0 for success and negative error code for failure. On
+ * success HTE subsystem fills up provided struct hte_clk_info.    

Why optional? Consumers will probably need that information.

Quoted 10 lines
include/linux/hte.h new file +10 -0
+ *
+ * xlated_id parameter is used to communicate between HTE subsystem and the
+ * providers. It is the same id returned during xlate API call and translated
+ * by the provider. This may be helpful as both subsystem and provider locate
+ * the requested entity in constant time, where entity could be anything from
+ * lines, signals, events, buses etc.. that providers support.
+ */
+struct hte_ops {
+	int (*request)(struct hte_chip *chip, u32 xlated_id);
+	int (*release)(struct hte_chip *chip, u32 xlated_id);

include/linux/hte.h line 110

Quoted 10 lines
include/linux/hte.h new file +10 -0
+	int (*enable)(struct hte_chip *chip, u32 xlated_id);
+	int (*disable)(struct hte_chip *chip, u32 xlated_id);
+	int (*get_clk_src_info)(struct hte_chip *chip,
+				struct hte_clk_info *ci);
+};
+
+/**
+ * struct hte_chip - Abstract HTE chip structure.
+ * @name: functional name of the HTE IP block.
+ * @dev: device providing the HTE.    

Unclear naming. Is this the parent device, or one associated with the HTE itself? I'm guessing today you don't have one associated with the HTE, but it is plausible you might gain on in future to make it fit nicely in the device model as a function of another device.

Quoted 59 lines
include/linux/hte.h new file +58 -0
+ * @ops: callbacks for this HTE.
+ * @nlines: number of lines/signals supported by this chip.
+ * @xlate: Callback which translates consumer supplied logical ids to
+ * physical ids, return from 0 for the success and negative for the
+ * failures. It stores (0 to @nlines) in xlated_id parameter for the success.
+ * @of_hte_n_cells: Number of cells used to form the HTE specifier.
+ * @gdev: HTE subsystem abstract device, internal to the HTE subsystem.
+ * @data: chip specific private data.
+ */
+struct hte_chip {
+	const char *name;
+	struct device *dev;
+	const struct hte_ops *ops;
+	u32 nlines;
+	int (*xlate)(struct hte_chip *gc,
+		     const struct of_phandle_args *args,
+		     struct hte_ts_desc *desc, u32 *xlated_id);
+	u8 of_hte_n_cells;
+
+	/* only used internally by the HTE framework */
+	struct hte_device *gdev;
+	void *data;
+};
+
+#if IS_ENABLED(CONFIG_HTE)
+/* HTE APIs for the providers */
+int hte_register_chip(struct hte_chip *chip);
+int hte_unregister_chip(struct hte_chip *chip);
+int hte_push_ts_ns_atomic(const struct hte_chip *chip, u32 xlated_id,
+			  struct hte_ts_data *data, size_t n);
+
+/* HTE APIs for the consumers */
+
+int hte_release_ts(struct hte_ts_desc *desc);
+struct hte_ts_desc *of_hte_request_ts(struct device *dev, const char *label,
+				      void (*cb)(enum hte_notify n));
+
+struct hte_ts_desc *devm_of_hte_request_ts(struct device *dev,
+					   const char *label,
+					   void (*cb)(enum hte_notify n));
+struct hte_ts_desc *hte_req_ts_by_dt_node(struct device_node *of_node,
+					  unsigned int id,
+					  void (*cb)(enum hte_notify n));
+int devm_hte_release_ts(struct device *dev, struct hte_ts_desc *desc);
+int hte_retrieve_ts_ns(const struct hte_ts_desc *desc, struct hte_ts_data *el,
+		       size_t n);
+int hte_retrieve_ts_ns_wait(const struct hte_ts_desc *desc,
+			    struct hte_ts_data *el, size_t n);
+int hte_set_buf_len(const struct hte_ts_desc *desc, size_t len);
+size_t hte_get_buf_len(const struct hte_ts_desc *desc);
+int hte_set_buf_watermark(const struct hte_ts_desc *desc, size_t val);
+size_t hte_get_buf_watermark(const struct hte_ts_desc *desc);
+size_t hte_available_ts(const struct hte_ts_desc *desc);
+int hte_enable_ts(struct hte_ts_desc *desc);
+int hte_disable_ts(struct hte_ts_desc *desc);
+int hte_get_clk_src_info(const struct hte_ts_desc *desc,
+			 struct hte_clk_info *ci);
+
author maintainer
#13 lore raw

Re: [RFC 02/11] drivers: Add HTE subsystem

In reply to Jonathan Cameron
Quoted 44 lines · Jonathan Cameron
Quoted 41 lines · On Fri, 25 Jun 2021 16:55:23 -0700 Dipen Patel <[email protected]> wrote:

Some devices can timestamp system lines/signals/Buses in real-time using the hardware counter or other hardware means which can give finer granularity and help avoid jitter introduced by software means of timestamping. To utilize such functionality there has to be framework where such devices can register themselves as producers or providers so that the consumers or clients devices can request specific line from the providers. This patch introduces such subsystem as hardware timestamping engine (HTE).

It provides below APIs for the provider:
- hte_register_chip() -- To register the HTE chip.
- hte_unregister_chip() -- To unregister the HTE chip.
- hte_push_ts_ns_atomic() -- To push timestamp data into HTE subsystem.

It provides below APIs for the consumer:
- of_hte_request_ts() -- To request timestamp functionality.
- devm_of_hte_request_ts() -- Managed version of the above.
- hte_req_ts_by_dt_node() -- To request timestamp functionality by using HTE provider dt node.
- devm_hte_release_ts() -- The managed version to release timestamp functionality and associated resources.
- hte_retrieve_ts_ns() -- To retrieve timestamps.
- hte_retrieve_ts_ns_wait() -- Same as above but blocking version.
- hte_enable_ts() -- To disable timestamp functionality.
- hte_disable_ts() -- To enable timestamp functionality.
- hte_available_ts() -- To query available timestamp data.
- hte_release_ts() -- To release timestamp functionality and its associated resources.
- hte_get_clk_src_info() -- To query clock source information from the provider

It provides centralized software buffer management per requested id to store the timestamp data for the consumers as below:
- hte_set_buf_len() -- To set the buffer length.
- hte_get_buf_len() -- To get the buffer length.
- hte_set_buf_watermark() -- To set the software threshold/watermark.
- hte_get_buf_watermark() -- To get the software threshold/watermark.

The detail about parameters and API usage are described in each functions definitions in drivers/hte/hte.c file.

Quoted 6 lines
Quoted 4 lines

The patch adds compilation support in Makefile and menu options in Kconfig.

Hi Dipen, this isn't a particularly thorough review as I'm still getting my head around what this is doing + it is an RFC :)

Thanks for the review comments. My responses inline.

Quoted 38 lines
Quoted 38 lines
---
 drivers/Kconfig      |    2 +
 drivers/Makefile     |    1 +
 drivers/hte/Kconfig  |   22 +
 drivers/hte/Makefile |    1 +
 drivers/hte/hte.c    | 1368 ++++++++++++++++++++++++++++++++++++++++++
 include/linux/hte.h  |  278 +++++++++
 6 files changed, 1672 insertions(+)
 create mode 100644 drivers/hte/Kconfig
 create mode 100644 drivers/hte/Makefile
 create mode 100644 drivers/hte/hte.c
 create mode 100644 include/linux/hte.h
drivers/Kconfig +2 -0
index 47980c6b1945..9b078964974b 100644
@@ -238,4 +238,6 @@ source "drivers/interconnect/Kconfig"
 source "drivers/counter/Kconfig"
 
 source "drivers/most/Kconfig"
+
+source "drivers/hte/Kconfig"
 endmenu
drivers/Makefile +1 -0
index 5a6d613e868d..0a996a698e4c 100644
@@ -190,3 +190,4 @@ obj-$(CONFIG_GNSS)		+= gnss/
 obj-$(CONFIG_INTERCONNECT)	+= interconnect/
 obj-$(CONFIG_COUNTER)		+= counter/
 obj-$(CONFIG_MOST)		+= most/
+obj-$(CONFIG_HTE)		+= hte/
drivers/hte/Kconfig new file +0 -1
new file mode 100644
index 000000000000..394e112f7dfb
--- /dev/null
Quoted 8 lines

drivers/hte/Kconfig line 5

Quoted 7 lines

+++ b/drivers/hte/Kconfig

drivers/hte/Kconfig new file +5 -0
@@ -0,0 +1,22 @@
+# SPDX-License-Identifier: GPL-2.0-only
+menuconfig HTE
+        bool "Hardware Timestamping Engine (HTE) Support"
+        help
+          Hardware Timestamping Engine (HTE) Support.

Tidy this up, but think that's already been commented on.

Will do, not sure why my editor did not show this issue.

Quoted 147 lines
Quoted 147 lines
drivers/hte/Kconfig new file +17 -0
+
+          Some devices provide hardware timestamping engine which can timestamp
+	  certain device lines/signals in realtime. This way to provide
+	  hardware assisted timestamp to generic signals like GPIOs, IRQs lines
+	  comes with benefit for the applications like autonomous machines
+	  needing accurate timestamping event with less jitter.
+
+	  This framework provides a generic interface to such HTE devices
+          within the Linux kernel. It provides an API to register and
+	  unregister a HTE provider chip, configurable sw buffer to
+	  store the timestamps, push the timestamp from the HTE providers and
+	  retrieve timestamps for the consumers. It also provides means for the
+	  consumers to request signals it wishes to hardware timestamp and
+	  release them if not required.
+
+          If unsure, say no.
+
drivers/hte/Makefile new file +1 -0
new file mode 100644
index 000000000000..9899dbe516f7
@@ -0,0 +1 @@
+obj-$(CONFIG_HTE)		+= hte.o
drivers/hte/hte.c new file +116 -0
new file mode 100644
index 000000000000..c53260d1e250
@@ -0,0 +1,1368 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2021 NVIDIA Corporation
+ *
+ * Author: Dipen Patel <[email protected]>
+ */
+
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/err.h>
+#include <linux/slab.h>
+#include <linux/of.h>
+#include <linux/of_device.h>
+#include <linux/kfifo.h>
+#include <linux/mutex.h>
+#include <linux/sched.h>
+#include <linux/uaccess.h>
+#include <linux/hte.h>
+#include <linux/delay.h>
+#include <linux/debugfs.h>
+
+/* Global list of the HTE devices */
+static DEFINE_SPINLOCK(hte_lock);
+static LIST_HEAD(hte_devices);
+
+enum {
+	HTE_TS_REGISTERED,
+	HTE_TS_DISABLE,
+};
+
+/* Default FIFO depth */
+#define HTE_EV_FIFO_EL		32
+
+#define HTE_TS_NAME_LEN		10
+
+struct hte_ts_buf;
+
+/**
+ * struct hte_ts_buf_acc_func - Software buffer management functions.
+ * @store: Store timestamp from atomic context as providers most likely
+ * be pushing timestamps from their interrupt handlers.
+ * @read: Read timestamps from the buffer.
+ * @el_available: Available timestamps to retrieve. The client can use this to
+ * query available elements so that it can pre-allocate internal buffer to send
+ * to during hte_retrieve_ts_ns API.
+ * @set_length: Set length/depth of the buffer.
+ * @get_length: Get length/depth of the buffer.
+ * @set_watermark: Set software threshold of the buffer.
+ * @get_watermark: Get software threshold of the buffer.
+ * @release: Release/free buffer.
+ * @reset: Reset the buffer.
+ */
+struct hte_ts_buf_acc_func {
+	unsigned int (*store)(struct hte_ts_buf *buf, void *data, size_t n);
+	int (*read)(struct hte_ts_buf *buf, unsigned char *data, size_t n,
+		    size_t *copied);
+	size_t (*el_available)(struct hte_ts_buf *buf);
+	int (*set_length)(struct hte_ts_buf *buf,
+			  size_t length, size_t bpd);
+	size_t (*get_length)(struct hte_ts_buf *buf);
+	int (*set_watermark)(struct hte_ts_buf *buf,
+			     size_t val);
+	size_t (*get_watermark)(struct hte_ts_buf *buf);
+	void (*release)(struct hte_ts_buf *buf);
+	void (*reset)(struct hte_ts_buf *buf);
+};
+
+/**
+ * struct hte_ts_buf - Software buffer per requested id or entity to store
+ * timestamps.
+ *
+ * @datum_len: Buffer depth or number of elements.
+ * @bytes_per_datum: Element size in bytes.
+ * @watermark: Software threshold at which client will be notified.
+ * @valid: Validity of the buffer.
+ * @pollq: Waitqueue for the blocking clients.
+ * @access: Various buffer management functions.
+ */
+struct hte_ts_buf {
+	size_t datum_len;
+	size_t bytes_per_datum;
+	size_t watermark;
+	bool valid;
+	wait_queue_head_t pollq;
+	const struct hte_ts_buf_acc_func *access;
+};
+
+/**
+ * struct hte_ts_info - Information related to requested timestamp.
+ *
+ * @xlated_id: Timestamp ID as understood between HTE subsys and HTE provider,
+ * See xlate callback API.
+ * @flags: Flags holding state informations.
+ * @seq: Timestamp sequence counter.
+ * @dropped_ts: Dropped timestamps.
+ * @cb: Callback to notify clients.
+ * @mlock: Lock during timestamp request/release APIs.
+ * @ts_dbg_root: Root for the debug fs.
+ * @gdev: HTE abstract device that this timestamp belongs to.
+ * @buf: Per requested timestamp software buffer.
+ * @desc: Timestamp descriptor understood between clients and HTE subsystem.
+ */
+struct hte_ts_info {
+	u32 xlated_id;
+	unsigned long flags;
+	u64 seq;
+	atomic_t dropped_ts;
+	void (*cb)(enum hte_notify n);
+	struct mutex mlock;
+	struct dentry *ts_dbg_root;
+	struct hte_device *gdev;
+	struct hte_ts_buf *buf;
+	struct hte_ts_desc *desc;
+};
+
+/**
Quoted 8 lines

drivers/hte/hte.c line 123

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+ * struct hte_device - HTE abstract device
+ * @nlines: Number of entities this device supports.
+ * @ts_req: Total number of entities requested.
+ * @ei: Timestamp information.
+ * @sdev: Device used at various debug prints.
+ * @dbg_root: Root directory for debug fs.
+ * @list: List node for internal use.

Be more specific of what sort of internal use.

Sure..

Quoted 259 lines
Quoted 259 lines
drivers/hte/hte.c new file +258 -0
+ * @chip: HTE chip providing this HTE device.
+ * @owner: helps prevent removal of modules when in use.
+ */
+struct hte_device {
+	u32 nlines;
+	atomic_t ts_req;
+	struct hte_ts_info *ei;
+	struct device *sdev;
+	struct dentry *dbg_root;
+	struct list_head list;
+	struct hte_chip *chip;
+	struct module *owner;
+};
+
+/* Buffer management functions */
+
+/**
+ * struct hte_kfifo - Software buffer wrapper.
+ * @buffer: Abstract buffer device.
+ * @gkf: Actual software buffer type, this case its FIFO.
+ */
+struct hte_kfifo {
+	struct hte_ts_buf buffer;
+	struct kfifo gkf;
+};
+
+#define buf_to_kfifo(r) container_of(r, struct hte_kfifo, buffer)
+
+static unsigned int hte_ts_store_to_buf(struct hte_ts_buf *r, void *data,
+					size_t n)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if (unlikely(!r->valid))
+		return 0;
+
+	return kfifo_in(&kf->gkf, (unsigned char *)data, n);
+}
+
+static inline int hte_ts_buf_read(struct hte_ts_buf *r,
+				  unsigned char *buf, size_t n,
+				  size_t *copied)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if ((!r->valid) || (n < kfifo_esize(&kf->gkf)))
+		return -EINVAL;
+
+	*copied = kfifo_out(&kf->gkf, buf, n);
+
+	return 0;
+}
+
+static size_t hte_ts_buf_el_available(struct hte_ts_buf *r)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if (!r->valid)
+		return 0;
+
+	return (kfifo_len(&kf->gkf) / r->bytes_per_datum);
+}
+
+static int hte_ts_buf_set_length(struct hte_ts_buf *r,
+				 size_t length, size_t bpd)
+{
+	int ret = 0;
+	struct hte_kfifo *buf;
+
+	if ((length == 0) || (bpd == 0) || !r)
+		return -EINVAL;
+
+	buf = buf_to_kfifo(r);
+
+	if (r->datum_len != length) {
+		if (r->valid)
+			kfifo_free(&buf->gkf);
+		r->valid = false;
+		r->datum_len = length;
+		r->bytes_per_datum = bpd;
+		ret = kfifo_alloc(&buf->gkf, length * bpd, GFP_KERNEL);
+		if (!ret)
+			r->valid = true;
+	}
+
+	return ret;
+}
+
+static inline size_t hte_ts_buf_get_length(struct hte_ts_buf *r)
+{
+	if ((!r->valid) || !r->datum_len)
+		return 0;
+
+	return r->datum_len;
+}
+
+static inline int hte_ts_buf_set_watermark(struct hte_ts_buf *r, size_t val)
+{
+	if ((!r->valid) || (val > r->datum_len))
+		return -EINVAL;
+
+	r->watermark = val;
+
+	return 0;
+}
+
+static inline size_t hte_ts_buf_get_watermark(struct hte_ts_buf *r)
+{
+	if (!r->valid)
+		return 0;
+
+	return r->watermark;
+}
+
+static inline void hte_ts_buf_release(struct hte_ts_buf *r)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	r->valid = false;
+	kfifo_free(&kf->gkf);
+	kfree(kf);
+}
+
+static inline void hte_ts_buf_reset(struct hte_ts_buf *r)
+{
+	struct hte_kfifo *kf = buf_to_kfifo(r);
+
+	if (!r->valid)
+		return;
+
+	kfifo_reset(&kf->gkf);
+}
+
+static const struct hte_ts_buf_acc_func kfifo_access_funcs = {
+	.store = &hte_ts_store_to_buf,
+	.read = &hte_ts_buf_read,
+	.el_available = &hte_ts_buf_el_available,
+	.set_length = &hte_ts_buf_set_length,
+	.get_length = &hte_ts_buf_get_length,
+	.set_watermark = &hte_ts_buf_set_watermark,
+	.get_watermark = &hte_ts_buf_get_watermark,
+	.release = &hte_ts_buf_release,
+	.reset = &hte_ts_buf_reset,
+};
+
+static struct hte_ts_buf *hte_ts_buf_allocate(void)
+{
+	struct hte_kfifo *kf;
+
+	kf = kzalloc(sizeof(*kf), GFP_KERNEL);
+	if (!kf)
+		return ERR_PTR(-ENOMEM);
+
+	init_waitqueue_head(&kf->buffer.pollq);
+	kf->buffer.watermark = 1;
+	kf->buffer.datum_len = 0;
+	kf->buffer.valid = false;
+	kf->buffer.access = &kfifo_access_funcs;
+
+	return &kf->buffer;
+}
+/* End of buffer management */
+
+/* Debugfs management */
+
+#ifdef CONFIG_DEBUG_FS
+
+static struct dentry *hte_root;
+
+static void __init hte_subsys_dbgfs_init(void)
+{
+	/* creates /sys/kernel/debug/hte/ */
+	hte_root = debugfs_create_dir("hte", NULL);
+}
+subsys_initcall(hte_subsys_dbgfs_init);
+
+static void hte_chip_dbgfs_init(struct hte_device *gdev)
+{
+	const struct hte_chip *chip = gdev->chip;
+	const char *name = chip->name ? chip->name : dev_name(chip->dev);
+
+	gdev->dbg_root = debugfs_create_dir(name, hte_root);
+	if (!gdev->dbg_root)
+		return;
+
+	debugfs_create_atomic_t("ts_requested", 0444, gdev->dbg_root,
+				&gdev->ts_req);
+	debugfs_create_u32("total_ts", 0444, gdev->dbg_root,
+			   &gdev->nlines);
+}
+
+static void hte_ts_dbgfs_init(const char *name, struct hte_ts_info *ei)
+{
+	if (!ei->gdev->dbg_root || !name)
+		return;
+
+	ei->ts_dbg_root = debugfs_create_dir(name, ei->gdev->dbg_root);
+	if (!ei->ts_dbg_root)
+		return;
+
+	debugfs_create_size_t("ts_buffer_depth", 0444, ei->ts_dbg_root,
+			      &ei->buf->datum_len);
+	debugfs_create_size_t("ts_buffer_watermark", 0444, ei->ts_dbg_root,
+			      &ei->buf->watermark);
+	debugfs_create_atomic_t("dropped_timestamps", 0444, ei->ts_dbg_root,
+				&ei->dropped_ts);
+}
+
+static inline void hte_dbgfs_deinit(struct dentry *root)
+{
+	if (!root)
+		return;
+
+	debugfs_remove_recursive(root);
+}
+
+#else
+
+static void hte_chip_dbgfs_init(struct hte_device *gdev)
+{
+}
+
+static void hte_ts_dbgfs_init(const char *name, struct hte_ts_info *ei)
+{
+}
+
+static inline void hte_dbgfs_deinit(struct dentry *root)
+{
+}
+
+#endif
+/* end of debugfs management*/
+
+/* Driver APIs */
+
+/**
+ * hte_release_ts() - Consumer calls this API to release the entity, where
+ * entity could be anything providers support, like lines, signals, buses,
+ * etc...
+ *
+ * The correct sequence to call this API is as below:
+ * 1) Call hte_disable_ts, this stops the timestamp push from the provider.
+ * 2) Retrieve timestamps by calling non blocking hte_retrieve_ts_ns API if you
+ * still care about the data.
+ * 3) Call this API.
+ * Above sequence makes sure that entity gets released race free.
+ *
+ * @desc: timestamp descriptor, this is the same as returned by the request API.
+ *
+ * Context: hte_dbgfs_deinit() function call may use sleeping locks,
+ *	    not suitable from atomic context in that case.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_release_ts(struct hte_ts_desc *desc)
+{
+	u32 id;
+	int ret = 0;
+	struct hte_device *gdev;
Quoted 8 lines

drivers/hte/hte.c line 388

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+	struct hte_ts_info *ei;
+	struct hte_ts_buf *buf;
+
+	if (!desc)
+		return -EINVAL;
+
+	ei = (struct hte_ts_info *)desc->data_subsys;

As data_subsys is void * you don't need to explicitly cast it to another pointer type.

Sure..

Quoted 45 lines
Quoted 45 lines
drivers/hte/hte.c new file +44 -0
+
+	if (!ei || !ei->gdev || !ei->buf)
+		return -EINVAL;
+
+	gdev = ei->gdev;
+	buf = ei->buf;
+	id = desc->con_id;
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags)) {
+		dev_info(gdev->sdev, "id:%d is not registered", id);
+		return -EUSERS;
+	}
+
+	ret = gdev->chip->ops->release(gdev->chip, ei->xlated_id);
+	if (ret) {
+		dev_err(gdev->sdev, "id: %d free failed\n", id);
+		goto out;
+	}
+
+	atomic_dec(&gdev->ts_req);
+	atomic_set(&ei->dropped_ts, 0);
+
+	kfree(desc->name);
+	kfree(desc);
+	ei->desc = NULL;
+	ei->seq = 0;
+	buf->access->release(buf);
+
+	hte_dbgfs_deinit(ei->ts_dbg_root);
+	module_put(gdev->owner);
+
+	clear_bit(HTE_TS_REGISTERED, &ei->flags);
+
+out:
+	dev_dbg(gdev->sdev, "%s: id: %d\n", __func__, id);
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_release_ts);
+
+static int hte_ts_dis_en_common(struct hte_ts_desc *desc, bool en)
+{
+	u32 ts_id;
+	struct hte_device *gdev;
+	struct hte_ts_info *ei;
Quoted 8 lines

drivers/hte/hte.c line 438

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+	int ret;
+
+	if (!desc)
+		return -EINVAL;
+
+	ei = (struct hte_ts_info *)desc->data_subsys;

As above, no need to cast - though it rather implies the type of data_subsys should not be void *.

desc is public facing structure, I wanted to make subsystem related

information opaque that is why I had it void *.

Quoted 23 lines
Quoted 23 lines
drivers/hte/hte.c new file +22 -0
+
+	if (!ei || !ei->gdev)
+		return -EINVAL;
+
+	gdev = ei->gdev;
+	ts_id = desc->con_id;
+
+	mutex_lock(&ei->mlock);
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags)) {
+		dev_dbg(gdev->sdev, "id:%d is not registered", ts_id);
+		ret = -EUSERS;
+		goto out;
+	}
+
+	if (en) {
+		if (!test_bit(HTE_TS_DISABLE, &ei->flags)) {
+			ret = 0;
+			goto out;
+		}
+		ret = gdev->chip->ops->enable(gdev->chip, ei->xlated_id);
+		if (ret) {
Quoted 8 lines

drivers/hte/hte.c line 467

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+			dev_warn(gdev->sdev, "id: %d enable failed\n",
+				 ts_id);
+			goto out;
+		}
+
+		clear_bit(HTE_TS_DISABLE, &ei->flags);
+		ret = 0;

ret is already 0 so no point in setting it again.

Yes, will clean up.

Quoted 140 lines
Quoted 140 lines
drivers/hte/hte.c new file +139 -0
+	} else {
+		if (test_bit(HTE_TS_DISABLE, &ei->flags)) {
+			ret = 0;
+			goto out;
+		}
+		ret = gdev->chip->ops->disable(gdev->chip, ei->xlated_id);
+		if (ret) {
+			dev_warn(gdev->sdev, "id: %d disable failed\n",
+				 ts_id);
+			goto out;
+		}
+
+		set_bit(HTE_TS_DISABLE, &ei->flags);
+		ret = 0;
+	}
+
+out:
+	mutex_unlock(&ei->mlock);
+	return ret;
+}
+
+/**
+ * hte_disable_ts() - Disable timestamp on given descriptor.
+ *
+ * @desc: ts descriptor, this is the same as returned by the request API.
+ *
+ * Context: Holds mutex lock, not suitable from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_disable_ts(struct hte_ts_desc *desc)
+{
+	return hte_ts_dis_en_common(desc, false);
+}
+EXPORT_SYMBOL_GPL(hte_disable_ts);
+
+/**
+ * hte_enable_ts() - Enable timestamp on given descriptor.
+ *
+ * @desc: ts descriptor, this is the same as returned by the request API.
+ *
+ * Context: Holds mutex lock, not suitable from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_enable_ts(struct hte_ts_desc *desc)
+{
+	return hte_ts_dis_en_common(desc, true);
+}
+EXPORT_SYMBOL_GPL(hte_enable_ts);
+
+static int hte_simple_xlate(struct hte_chip *gc,
+			    const struct of_phandle_args *args,
+			    struct hte_ts_desc *desc,
+			    u32 *id)
+{
+	if (!id || !desc || !gc)
+		return -EINVAL;
+
+	/*
+	 * For the providers which do not have any internal mappings between
+	 * logically exposed ids and actual ids, will set both
+	 * the same.
+	 *
+	 * In case there is a internal mapping needed, providers will need to
+	 * provide its own xlate function where con_id will be sent as
+	 * args[0] and it will return xlated id. Later xlated id will be
+	 * used for any future exchanges between provider and subsystems.
+	 */
+
+	if (args) {
+		if (gc->of_hte_n_cells < 1)
+			return -EINVAL;
+
+		if (args->args_count != gc->of_hte_n_cells)
+			return -EINVAL;
+
+		*id = args->args[0];
+		desc->con_id = *id;
+	} else {
+		*id = desc->con_id;
+	}
+
+	if (desc->con_id > gc->nlines)
+		return -EINVAL;
+
+	desc->data_subsys = NULL;
+
+	return 0;
+}
+
+static struct hte_device *of_node_to_htedevice(struct device_node *np)
+{
+	struct hte_device *gdev;
+
+	spin_lock(&hte_lock);
+
+	list_for_each_entry(gdev, &hte_devices, list)
+		if (gdev->chip && gdev->chip->dev &&
+		    gdev->chip->dev->of_node == np) {
+			spin_unlock(&hte_lock);
+			return gdev;
+		}
+
+	spin_unlock(&hte_lock);
+
+	return ERR_PTR(-ENODEV);
+}
+
+static int ___hte_req_ts(struct hte_device *gdev, struct hte_ts_desc *desc,
+			 u32 xlated_id, void (*cb)(enum hte_notify n))
+{
+	struct hte_ts_info *ei;
+	struct hte_ts_buf *buf;
+	int ret;
+	u32 con_id = desc->con_id;
+
+	if (!try_module_get(gdev->owner))
+		return -ENODEV;
+
+	ei = &gdev->ei[xlated_id];
+	ei->xlated_id = xlated_id;
+
+	/*
+	 * There a chance that multiple consumers requesting same entity,
+	 * lock here.
+	 */
+	mutex_lock(&ei->mlock);
+
+	if (test_bit(HTE_TS_REGISTERED, &ei->flags)) {
+		dev_dbg(gdev->chip->dev, "id:%u is already registered",
+			xlated_id);
+		ret = -EUSERS;
+		goto unlock;
+	}
+
+	buf = hte_ts_buf_allocate();
+	if (IS_ERR(buf)) {
+		dev_err(gdev->chip->dev, "Buffer allocation failed");
+		ret = PTR_ERR(buf);
+		goto unlock;
Quoted 8 lines

drivers/hte/hte.c line 612

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+	}
+
+	/* Set default here, let consumer decide how much to set later */
+	ret = buf->access->set_length(buf, HTE_EV_FIFO_EL,
+				      sizeof(struct hte_ts_data));
+

It's good to keep to consistent style of no line break between a statement and it's error check.

Sure...

Quoted 144 lines
Quoted 144 lines
drivers/hte/hte.c new file +143 -0
+	if (ret) {
+		dev_err(gdev->chip->dev, "Fifo set length failed");
+		goto buf_rel;
+	}
+
+	buf->access->reset(buf);
+	buf->valid = true;
+
+	ei->buf = buf;
+	ei->cb = cb;
+
+	ret = gdev->chip->ops->request(gdev->chip, xlated_id);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev, "ts request failed\n");
+		goto buf_rel;
+	}
+
+	desc->data_subsys = ei;
+	ei->desc = desc;
+
+	atomic_inc(&gdev->ts_req);
+	set_bit(HTE_TS_REGISTERED, &ei->flags);
+	mutex_unlock(&ei->mlock);
+
+	if (!desc->name) {
+		desc->name = kzalloc(HTE_TS_NAME_LEN, GFP_KERNEL);
+		if (desc->name)
+			scnprintf(desc->name, HTE_TS_NAME_LEN, "ts_%u",
+				  con_id);
+	}
+
+	hte_ts_dbgfs_init(desc->name, ei);
+
+	dev_dbg(gdev->chip->dev, "%s: id: %u, xlated id:%u",
+		__func__, con_id, xlated_id);
+
+	return 0;
+
+buf_rel:
+	buf->access->release(buf);
+unlock:
+	module_put(gdev->owner);
+	mutex_unlock(&ei->mlock);
+
+	return ret;
+}
+
+static struct hte_device *of_hte_dev_get(struct device *dev,
+					 struct device_node *np,
+					 const char *label,
+					 struct of_phandle_args *args)
+{
+	struct hte_device *gdev = NULL;
+	int index = 0;
+	int err;
+
+	if (label) {
+		index = of_property_match_string(np, "hte-names", label);
+		if (index < 0)
+			return ERR_PTR(index);
+	}
+
+	err = of_parse_phandle_with_args(np, "htes", "#hte-cells", index,
+					 args);
+	if (err) {
+		pr_err("%s(): can't parse \"htes\" property\n", __func__);
+		return ERR_PTR(err);
+	}
+
+	gdev = of_node_to_htedevice(args->np);
+	if (IS_ERR(gdev)) {
+		pr_err("%s(): HTE chip not found\n", __func__);
+		of_node_put(args->np);
+		return gdev;
+	}
+
+	return gdev;
+}
+
+static struct hte_ts_desc *__hte_req_ts(struct device *dev,
+					struct device_node *np,
+					const char *label,
+					void (*cb)(enum hte_notify n))
+{
+	struct hte_device *gdev = NULL;
+	struct hte_ts_desc *desc;
+	struct of_phandle_args args;
+	int ret;
+	u32 xlated_id;
+
+	gdev = of_hte_dev_get(dev, np, label, &args);
+	if (IS_ERR(gdev))
+		return ERR_CAST(gdev);
+
+	if (!gdev->chip) {
+		pr_debug("requested id does not have provider\n");
+		return ERR_PTR(-ENODEV);
+	}
+
+	desc = kzalloc(sizeof(*desc), GFP_KERNEL);
+	if (!desc)
+		return ERR_PTR(-ENOMEM);
+
+	ret = gdev->chip->xlate(gdev->chip, &args, desc, &xlated_id);
+	if (ret < 0)
+		goto put;
+
+	desc->name = NULL;
+	if (label)
+		desc->name = kstrdup(label, GFP_KERNEL);
+
+	ret = ___hte_req_ts(gdev, desc, xlated_id, cb);
+	if (ret < 0)
+		goto put;
+
+	return desc;
+
+put:
+	of_node_put(args.np);
+	kfree(desc);
+
+	return ERR_PTR(ret);
+}
+
+/**
+ * of_hte_request_ts() - Consumer calls this API to request the HTE facility
+ * on the specified entity, where entity is provider specific for example,
+ * GPIO lines, signals, buses etc...
+ *
+ * @dev: Consumer device.
+ * @label: Optional label.
+ * @cb: Optional notify callback to consumer when data is pushed by the
+ * provider.
+ *
+ * Context: Holds mutex lock, not suitable from atomic context.
+ * Returns: Timestamp descriptor on success or error ptr on failure.
+ */
+struct hte_ts_desc *of_hte_request_ts(struct device *dev,
+				      const char *label,
+				      void (*cb)(enum hte_notify n))
+{
+
+	if (dev && dev->of_node)
Quoted 8 lines

drivers/hte/hte.c line 762

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+		return __hte_req_ts(dev, dev->of_node, label, cb);
+	else
+		return ERR_PTR(-EOPNOTSUPP);
+}
+EXPORT_SYMBOL_GPL(of_hte_request_ts);
+
+static int devm_hte_ts_match_desc(struct device *dev, void *res, void *data)

I'm not seeing what is devm about this.

It was part of devm release. However I am planing to remove devm release

function, in turns this will be deleted as well.

Quoted 12 lines
Quoted 12 lines
drivers/hte/hte.c new file +11 -0
+{
+	struct hte_ts_desc **p = res;
+
+	if (WARN_ON(!p || !*p))
+		return 0;
+
+	return *p == data;
+}
+
+static void __devm_hte_release_ts(struct device *dev, void *res)
+{
Quoted 8 lines

drivers/hte/hte.c line 778

Quoted 5 lines
drivers/hte/hte.c new file +5 -0
+	hte_release_ts(*(struct hte_ts_desc **)res);
+}
+
+/**
+ * devm_hte_release_ts() - Resource managed hte_release_ts().

I'd not introduce this until you have a user. It very rarely actually makes sense to call a devm release manually. Not having one makes people think harder about it.

Will remove.

Quoted 23 lines
Quoted 10 lines
drivers/hte/hte.c new file +9 -0
+ * @dev: HTE consumer/client device.
+ * @desc: HTE ts descriptor.
+ *
+ * Release timestamp functionality and its resources previously allocated using
+ * of_hte_request_ts(). Calling this function is usually not needed because
+ * devm-allocated resources are automatically released on driver detach.
+ *
+ * Context: Same as hte_release_ts() function.
+ * Returns: 0 on success otherwise negative error code.

drivers/hte/hte.c line 797

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+ */
+int devm_hte_release_ts(struct device *dev, struct hte_ts_desc *desc)
+{
+	return devres_release(dev, __devm_hte_release_ts,
+			      devm_hte_ts_match_desc, desc);
+}
+EXPORT_SYMBOL_GPL(devm_hte_release_ts);
+
+/**
+ * devm_of_hte_request_ts() - Resource managed of_hte_request_ts().

If it's kernel-doc it needs to give no warnings when you point the kernel-doc scripts at it. They insist on full parameter documentation.

Quoted 12 lines

drivers/hte/hte.c line 806

Quoted 9 lines
drivers/hte/hte.c new file +9 -0
+ */
+struct hte_ts_desc *devm_of_hte_request_ts(struct device *dev,
+					   const char *label,
+					   void (*cb)(enum hte_notify n))
+{
+
+	struct hte_ts_desc **ptr, *desc;
+
+	ptr = devres_alloc(__devm_hte_release_ts, sizeof(*ptr), GFP_KERNEL);

Superficially looks like you might get way with just calling dev_add_action_or_reset() in here and avoid this boilerplate. A lot of cases that looked like this got cleaned up in the last kernel cycle.

I based my patches from linux-next/master. Not sure if that has

dev_add_action_or_reset

Quoted 12 lines
Quoted 12 lines
drivers/hte/hte.c new file +10 -0
+	if (!ptr)
+		return ERR_PTR(-ENOMEM);
+
+	desc = of_hte_request_ts(dev, label, cb);
+	if (!IS_ERR(desc)) {
+		*ptr = desc;
+		devres_add(dev, ptr);
+	} else {
+		devres_free(ptr);
+	}
Quoted 8 lines

drivers/hte/hte.c line 822

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+	return desc;
+}
+EXPORT_SYMBOL_GPL(devm_of_hte_request_ts);
+
+static struct hte_ts_info *hte_para_check(const struct hte_ts_desc *desc,
+					  size_t val)

Not a good name or indeed combination of different things. hte_desc_to_info() and some separate check on val would be better.

Good suggestion, will follow new name.

Quoted 18 lines
Quoted 18 lines
drivers/hte/hte.c new file +17 -0
+{
+	struct hte_ts_info *ei;
+
+	if (!desc || !desc->data_subsys || !val) {
+		pr_debug("%s:%d: val :%lu\n", __func__, __LINE__, val);
+		return NULL;
+	}
+
+	ei = desc->data_subsys;
+	if (!ei || !ei->buf) {
+		pr_debug("%s:%d\n", __func__, __LINE__);
+		return NULL;
+	}
+
+	return ei;
+}
+
Quoted 8 lines

drivers/hte/hte.c line 846

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+static inline bool hte_ts_buf_wait(struct hte_ts_buf *buffer, size_t to_read)
+{
+	size_t el_avail;
+
+	el_avail = buffer->access->el_available(buffer);
+
+	return (el_avail >= to_read) ? false : true;

return el_avail < to_read;

Sure...

Quoted 12 lines
Quoted 12 lines
drivers/hte/hte.c new file +11 -0
+}
+
+static int _hte_retrieve_ts_ns(const struct hte_ts_desc *desc,
+			       struct hte_ts_data *el, size_t n, bool block)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+	int ret;
+	size_t to_read, copied;
+
+	ei = hte_para_check(desc, n);
Quoted 8 lines

drivers/hte/hte.c line 863

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+	if (!ei)
+		return -EINVAL;
+
+	buffer = ei->buf;
+
+	to_read = min_t(size_t, n, buffer->watermark);

Needs a comment as not obvious why you'd read the min of that requested or the watermark if there might be more available.

I will add detailed comment in next version of the RFC.

Quoted 10 lines
Quoted 10 lines
drivers/hte/hte.c new file +9 -0
+
+	do {
+		if (hte_ts_buf_wait(buffer, to_read)) {
+			if (!block) {
+				/* Possibly early here to retrieve, try again */
+				dev_dbg(ei->gdev->chip->dev, "%s: %d\n",
+					__func__, ret);
+				return -EAGAIN;
+			}
Quoted 8 lines

drivers/hte/hte.c line 878

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+			ret = wait_event_interruptible(buffer->pollq,
+					!hte_ts_buf_wait(buffer, to_read));
+			if (ret)
+				return ret;
+		}
+		ret = buffer->access->read(buffer, (void *)el,

If you have to cast to a void * that usually means something is wrong in your definitions. Why is it needed here? Looks like read has an inappropriate definition.

Will change to void* in read definitions to remove this cast.

Quoted 62 lines
Quoted 62 lines
drivers/hte/hte.c new file +61 -0
+					   n * buffer->bytes_per_datum,
+					   &copied);
+		if (ret < 0)
+			return ret;
+
+		if (copied > 0)
+			return 0;
+		else if (copied == 0 && !block)
+			return -EAGAIN;
+	} while (copied == 0);
+
+	return 0;
+}
+
+/**
+ * hte_retrieve_ts_ns() - Consumer calls this API to retrieve timestamp in
+ * nano seconds i.e. el->tsc will be in ns.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ * @el: buffer to store the timestamp details.
+ * @n: Number of struct hte_timestamp_el elements.
+ *
+ * Context: Can be called from the atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_retrieve_ts_ns(const struct hte_ts_desc *desc,
+		       struct hte_ts_data *el, size_t n)
+{
+	return _hte_retrieve_ts_ns(desc, el, n, false);
+}
+EXPORT_SYMBOL_GPL(hte_retrieve_ts_ns);
+
+/**
+ * hte_retrieve_ts_ns_wait() - Blocking version of the hte_retrieve_ts_ns.
+ * @desc: ts descriptor, same as returned from request API.
+ * @el: buffer to store the timestamp data.
+ * @n: Number of struct hte_ts_data data.
+ *
+ * Context: Can not be called from the atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_retrieve_ts_ns_wait(const struct hte_ts_desc *desc,
+			    struct hte_ts_data *el, size_t n)
+{
+	return _hte_retrieve_ts_ns(desc, el, n, true);
+}
+EXPORT_SYMBOL_GPL(hte_retrieve_ts_ns_wait);
+
+/**
+ * hte_set_buf_len() - Consumer calls this API to set timestamp software buffer
+ * depth.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ * @len: New length/depth.
+ *
+ * The correct sequence to set buffer length is as below:
+ * 1) Disable timestamp by calling hte_disable_ts API.
+ * 2) Optionally retrieve all the timestamps by calling non blocking
+ *    hte_retrieve_ts_ns() API. This step only needed if you still care about
+ *    the data.
+ * 3) Call this API.
Quoted 8 lines

drivers/hte/hte.c line 944

Quoted 5 lines
drivers/hte/hte.c new file +5 -0
+ * 4) Enable timestamp by calling hte_enable_ts API.
+ *
+ * This API destroys previously allocated buffer and creates new one, because
+ * of that, it is mandatory to follow above sequence to make sure there is no
+ * race between various other APIs in the subsystem.

Good docs. This is why I mentioned in review of docs patch that it is better to just have that refer to the kernel-doc in these files. Keep all this good information in one place.

Agree..

Quoted 18 lines
Quoted 18 lines
drivers/hte/hte.c new file +17 -0
+ *
+ * By default during the request API call, HTE subsystem allocates software
+ * buffer with predefined length, this API gives flexibility to adjust the
+ * length according to consumer's need.
+ *
+ * Context: Can not be called from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_set_buf_len(const struct hte_ts_desc *desc, size_t len)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+	int ret;
+
+	ei = hte_para_check(desc, len);
+	if (!ei)
+		return -EINVAL;
Quoted 8 lines

drivers/hte/hte.c line 967

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+
+	buffer = ei->buf;
+	ret = buffer->access->set_length(buffer, len,
+					 sizeof(struct hte_ts_data));
+	if (ret)
+		dev_err(ei->gdev->chip->dev, "%s: ret:%d\n", __func__, ret);

Not point in printing things line __func__ manually in dev_err() etc. Dynamic debug includes that and gives far more information + control of this.

yes, will remove.

Quoted 71 lines
Quoted 71 lines
drivers/hte/hte.c new file +70 -0
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_set_buf_len);
+
+/**
+ * hte_get_buf_len() - Consumer calls this API to get timestamp software buffer
+ * depth or length.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: Positive length on success or 0 on failure.
+ */
+size_t hte_get_buf_len(const struct hte_ts_desc *desc)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	ei = hte_para_check(desc, 1);
+	if (!ei)
+		return 0;
+
+	buffer = ei->buf;
+
+	return buffer->access->get_length(buffer);
+}
+EXPORT_SYMBOL_GPL(hte_get_buf_len);
+
+/**
+ * hte_available_ts() - Returns total available timestamps.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * The API helps consumers to pre-allocate its internal buffer required
+ * during hte_retrieve_ts_ns call.
+ *
+ * Context: Any context.
+ * Returns: Positive value if elements are available else 0. The value is
+ * number of total available struct hte_timestamp_el elements available not
+ * the size in bytes.
+ */
+size_t hte_available_ts(const struct hte_ts_desc *desc)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	ei = hte_para_check(desc, 1);
+	if (!ei)
+		return 0;
+
+	buffer = ei->buf;
+
+	return buffer->access->el_available(buffer);
+}
+EXPORT_SYMBOL_GPL(hte_available_ts);
+
+/**
+ * hte_set_buf_watermark() - Consumer calls this API to set timestamp software
+ * buffer watermark. The correct sequence to call this API is as below:
+ * 1) Disable timestamp by calling hte_disable_ts API.
+ * 2) Call this API.
+ * 3) Enable timestamp by calling hte_enable_ts API.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ * @val: New watermark.
+ *
+ * By default during the request API call, HTE subsystem sets watermark as 1,
+ * this API gives flexibility to adjust the watermark according to consumer's
+ * need. The consumers will get notification through callback registered during
Quoted 8 lines

drivers/hte/hte.c line 1042

Quoted 5 lines
drivers/hte/hte.c new file +5 -0
+ * request API either when timestamp is dropped or watermark is reached or will
+ * wait till watermark is reached. Refer hte_retrieve_ts_ns() and
+ * hte_push_ts_ns_atomic() APIs to understand how watermark is used.
+ *
+ * Context: Any context.

You have no way of knowing that as will depend on the driver - I'd definitely suggest not from atomic context, but then that would be crazy so you are better
off not documenting any specific requirement at all.

set watermark does not talk to driver, at least for now as it is totally software

managed buffer from the hte core. I will remove context.

Quoted 48 lines
Quoted 48 lines
drivers/hte/hte.c new file +47 -0
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_set_buf_watermark(const struct hte_ts_desc *desc, size_t val)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+	int ret;
+
+	ei = hte_para_check(desc, val);
+	if (!ei)
+		return -EINVAL;
+
+	buffer = ei->buf;
+	ret = buffer->access->set_watermark(buffer, val);
+	if (ret)
+		dev_dbg(ei->gdev->chip->dev, "%s: ret:%d\n", __func__, ret);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_set_buf_watermark);
+
+/**
+ * hte_get_buf_watermark() - Consumer calls this API to get software
+ * buffer watermark.
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: Positive current watermark on success or 0 on failure.
+ */
+size_t hte_get_buf_watermark(const struct hte_ts_desc *desc)
+{
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	ei = hte_para_check(desc, 1);
+	if (!ei)
+		return 0;
+
+	buffer = ei->buf;
+
+	return buffer->access->get_watermark(buffer);
+}
+EXPORT_SYMBOL_GPL(hte_get_buf_watermark);
+
+/**
+ * hte_req_ts_by_dt_node() - Request entity to monitor by passing HTE device
+ * node directly, where meaning of the entity is provider specific, for example
Quoted 8 lines

drivers/hte/hte.c line 1096

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+ * lines, signals, GPIOs, buses etc...
+ *
+ * @of_node: HTE provider device node.
+ * @id: entity id to monitor, this id belongs to HTE provider of_node.
+ * @cb: Optional callback to notify.
+ *
+ * Context: Holds mutex lock, can not be called from atomic context.

What mutex and why? If it is one you can check is held even better.

___hte_req_ts holds the mutex lock to serialize multiple consumers

requesting same entity.

Quoted 28 lines
Quoted 14 lines
drivers/hte/hte.c new file +13 -0
+ * Returns: ts descriptor on success or error pointers.
+ */
+struct hte_ts_desc *hte_req_ts_by_dt_node(struct device_node *of_node,
+					  unsigned int id,
+					  void (*cb)(enum hte_notify n))
+{
+	struct hte_device *gdev;
+	struct hte_ts_desc *desc;
+	int ret;
+	u32 xlated_id;
+
+	gdev = of_node_to_htedevice(of_node);
+	if (IS_ERR(gdev))

drivers/hte/hte.c line 1119

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		return ERR_PTR(-ENOTSUPP);
+
+	if (!gdev->chip || !gdev->chip->ops)
+		return ERR_PTR(-ENOTSUPP);
+
+	desc = kzalloc(sizeof(*desc), GFP_KERNEL);
+	if (!desc) {
+		ret = -ENOMEM;
+		goto out_put_device;
+	}

Pass a desc pointer into this function rather than allocating the structure in here. That lets the caller embed that structure inside one of it's own structures if it wants to, resulting in fewer small allocations which is always good.

Quoted 1 line

It's far from obvious that the caller needs to free desc.

Are you suggesting to shift burden of allocation/deallocation (static or dynamic)

at client/consumer side?

Quoted 55 lines
Quoted 55 lines
drivers/hte/hte.c new file +54 -0
+
+	desc->con_id = id;
+	ret = gdev->chip->xlate(gdev->chip, NULL, desc, &xlated_id);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev,
+			"failed to xlate id: %d\n", id);
+		goto out_free_desc;
+	}
+
+	ret = ___hte_req_ts(gdev, desc, xlated_id, cb);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev,
+			"failed to request id: %d\n", id);
+		goto out_free_desc;
+	}
+
+	return desc;
+
+out_free_desc:
+	kfree(desc);
+
+out_put_device:
+	return ERR_PTR(ret);
+}
+EXPORT_SYMBOL_GPL(hte_req_ts_by_dt_node);
+
+/**
+ * hte_get_clk_src_info() - Consumer calls this API to query clock source
+ * information of the desc.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: 0 on success else negative error code on failure.
+ */
+int hte_get_clk_src_info(const struct hte_ts_desc *desc,
+			 struct hte_clk_info *ci)
+{
+	struct hte_chip *chip;
+	struct hte_ts_info *ei;
+
+	if (!desc || !desc->data_subsys || !ci) {
+		pr_debug("%s:%d\n", __func__, __LINE__);
+		return -EINVAL;
+	}
+
+	ei = desc->data_subsys;
+	if (!ei || !ei->gdev || !ei->gdev->chip)
+		return -EINVAL;
+
+	chip = ei->gdev->chip;
+	if (!chip->ops->get_clk_src_info)
+		return -ENOTSUPP;
+
Quoted 8 lines

drivers/hte/hte.c line 1180

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+	return chip->ops->get_clk_src_info(chip, ci);
+}
+EXPORT_SYMBOL_GPL(hte_get_clk_src_info);
+
+static inline void hte_add_to_device_list(struct hte_device *gdev)
+{
+	struct hte_device *prev;

Needs to take an appropriate lock as you may have concurrent calls.

There is spin_lock held from register API from where this gets

called.

Quoted 7 lines

drivers/hte/hte.c line 1183

Quoted 4 lines
drivers/hte/hte.c new file +3 -0
+
+	if (list_empty(&hte_devices)) {
+		list_add_tail(&gdev->list, &hte_devices);

Needs a comment. I've no idea why you might want to only add it if there were no other hte_devices already there.

Quoted 5 lines

drivers/hte/hte.c line 1187

Quoted 4 lines
drivers/hte/hte.c new file +4 -0
+		return;
+	}
+
+	prev = list_last_entry(&hte_devices, struct hte_device, list);

Why woud you do this?

Thanks for pointing out. I definitely missed cleaning this up. Now, I will

remove this function in next RFC version as one line can be added directly

in register API.

Quoted 41 lines
Quoted 41 lines
drivers/hte/hte.c new file +40 -0
+	list_add_tail(&gdev->list, &hte_devices);
+}
+
+/**
+ * hte_push_ts_ns_atomic() - Used by the provider to push timestamp in nano
+ * seconds i.e data->tsc will be in ns, it is assumed that provider will be
+ * using this API from its ISR or atomic context.
+ *
+ * @chip: The HTE chip, used during the registration.
+ * @xlated_id: entity id understood by both subsystem and provider, usually this
+ * is obtained from xlate callback during request API.
+ * @data: timestamp data.
+ * @n: Size of the data.
+ *
+ * Context: Atomic.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_push_ts_ns_atomic(const struct hte_chip *chip, u32 xlated_id,
+			  struct hte_ts_data *data, size_t n)
+{
+	unsigned int ret;
+	bool notify;
+	size_t el_avail;
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	if (!chip || !data || !chip->gdev)
+		return -EINVAL;
+
+	if (xlated_id > chip->nlines)
+		return -EINVAL;
+
+	ei = &chip->gdev->ei[xlated_id];
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags) ||
+	    test_bit(HTE_TS_DISABLE, &ei->flags)) {
+		dev_dbg(chip->dev, "Unknown timestamp push\n");
+		return -EINVAL;
+	}
+
Quoted 8 lines

drivers/hte/hte.c line 1233

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+	/* timestamp sequence counter, start from 0 */
+	data->seq = ei->seq++;
+
+	buffer = ei->buf;
+	el_avail = buffer->access->el_available(buffer);
+	ret = buffer->access->store(buffer, data, n);

If we are doing this from the hte core, why is buffer definition in the scope of the drivers rather than the core? That seems backwards to me.

I do not understand this comment. The buffer definition is in scope of hte core

as it is the only entity that manages it.

Quoted 11 lines

drivers/hte/hte.c line 1241

Quoted 9 lines
drivers/hte/hte.c new file +8 -0
+	if (ret != n) {
+		atomic_inc(&ei->dropped_ts);
+		if (ei->cb)
+			ei->cb(HTE_TS_DROPPED);
+		return -ENOMEM;
+	}
+
+	notify = ((el_avail + 1) >= buffer->watermark) ? true : false;

You push n but only check on el_avail + 1 here.
Also, this is the same as

Good catch, will correct that.

Quoted 2 lines
	notify = ((el_avail + 1) >= buffer->watermark;

right, not sure why do I have obsession with ternary operators :)

Quoted 11 lines

drivers/hte/hte.c line 1249

Quoted 10 lines
drivers/hte/hte.c new file +8 -0
+
+	/*
+	 * If there is a callback, its consumer's job to retrieve the timestamp.
+	 * For the rest, wake up the process.
+	 */
+	if (notify && ei->cb) {
+		ei->cb(HTE_TS_AVAIL);
+		return 0;

Given you return 0 anyway, might as well not have this line.

True, will remove.

Quoted 10 lines
Quoted 10 lines
drivers/hte/hte.c new file +9 -0
+	} else if (notify) {
+		wake_up_interruptible(&buffer->pollq);
+	}
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(hte_push_ts_ns_atomic);
+
+/**
Quoted 8 lines

drivers/hte/hte.c line 1262

Quoted 4 lines
drivers/hte/hte.c new file +4 -0
+ * hte_register_chip() - Used by provider to register a HTE chip.
+ * @chip: the HTE chip to add to subsystem.
+ *
+ * Context: Can not be called from atomic context.

Whilst true, I'd think that was common sense as it would be insane to register something like this from atomic context. So I'd say no need to comment on it! Keep those comments for things that might be used like that.

Will remove...

Quoted 32 lines
Quoted 32 lines
drivers/hte/hte.c new file +31 -0
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_register_chip(struct hte_chip *chip)
+{
+	struct hte_device *gdev;
+	int ret;
+	u32 i;
+
+	if (!chip || !chip->dev || !chip->dev->of_node)
+		return -EINVAL;
+
+	if (!chip->ops || !chip->ops->request || !chip->ops->release) {
+		dev_err(chip->dev, "Driver needs to provide ops\n");
+		return -EINVAL;
+	}
+
+	gdev = kzalloc(sizeof(*gdev), GFP_KERNEL);
+	if (!gdev)
+		return -ENOMEM;
+
+	gdev->chip = chip;
+	chip->gdev = gdev;
+	gdev->nlines = chip->nlines;
+	gdev->sdev = chip->dev;
+
+	/*
+	 * Allocate all the supported entities here at once, this will have
+	 * following advantages:
+	 * When provider pushes timestamp, it can then just send the
+	 * xlated_id, subsystem will use it as an index which
+	 * gives us the constant time access; this is important as mostly
Quoted 8 lines

drivers/hte/hte.c line 1297

Quoted 4 lines
drivers/hte/hte.c new file +4 -0
+	 * providers will be pushing the timestamps from their ISR.
+	 */
+	gdev->ei = kcalloc(chip->nlines, sizeof(struct hte_ts_info),
+			   GFP_KERNEL);

I'd be tempted to do this as a 0 length element at the end of gdev then do the allocation in one go use struct_size() etc to work out how long it is. Cuts down on allocations + error paths to deal with for no obvious disadvantage.

Sure...

Quoted 11 lines

drivers/hte/hte.c line 1304

Quoted 8 lines
drivers/hte/hte.c new file +7 -0
+	if (!gdev->ei) {
+		ret = -ENOMEM;
+		goto err_free_gdev;
+	}
+
+	for (i = 0; i < chip->nlines; i++) {
+		gdev->ei[i].flags = 0;

zero allocated, so don't bother setting things to 0 where it's a fairly obvious base state. If you set something to 0 to act as some form of documentation then that's fine, but I don't think that's true here.

True, will remove.

Quoted 59 lines
Quoted 59 lines
drivers/hte/hte.c new file +58 -0
+		gdev->ei[i].gdev = gdev;
+		gdev->ei[i].seq = 0;
+		mutex_init(&gdev->ei[i].mlock);
+	}
+
+	if (chip->dev->driver)
+		gdev->owner = chip->dev->driver->owner;
+	else
+		gdev->owner = THIS_MODULE;
+
+	if (!chip->xlate) {
+		chip->xlate = hte_simple_xlate;
+		/* Just a id number to monitor */
+		chip->of_hte_n_cells = 1;
+	}
+
+	of_node_get(chip->dev->of_node);
+
+	INIT_LIST_HEAD(&gdev->list);
+
+	spin_lock(&hte_lock);
+	hte_add_to_device_list(gdev);
+	spin_unlock(&hte_lock);
+
+	hte_chip_dbgfs_init(gdev);
+
+	dev_dbg(chip->dev, "Added hte chip\n");
+	return 0;
+
+err_free_gdev:
+	kfree(gdev);
+
+	return ret;
+}
+EXPORT_SYMBOL_GPL(hte_register_chip);
+
+/**
+ * hte_unregister_chip() - Used by the provider to remove a HTE chip.
+ * @chip: the HTE chip to remove.
+ *
+ * Context: Can not be called from atomic context.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_unregister_chip(struct hte_chip *chip)
+{
+	struct hte_device *gdev = chip->gdev;
+
+	spin_lock(&hte_lock);
+	list_del(&gdev->list);
+	spin_unlock(&hte_lock);
+
+	gdev->chip = NULL;
+
+	of_node_put(chip->dev->of_node);
+	hte_dbgfs_deinit(gdev->dbg_root);
+	kfree(gdev->ei);
+	kfree(gdev);
+
Quoted 8 lines

drivers/hte/hte.c line 1368

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+	dev_dbg(chip->dev, "Removed hte chip\n");
+	return 0;
+}
+EXPORT_SYMBOL_GPL(hte_unregister_chip);
+
+/* Driver APIs ends */

Don't bother with file layout type comments. They don't add that much and tend to rot horribly over time as people move code around in files.

Sure..

Quoted 21 lines
Quoted 21 lines
include/linux/hte.h new file +14 -0
new file mode 100644
index 000000000000..e1737579d4c4
@@ -0,0 +1,278 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2021 NVIDIA Corporation
+ *
+ * Author: Dipen Patel <[email protected]>
+ */
+
+#ifndef __LINUX_HTE_H
+#define __LINUX_HTE_H
+
+struct hte_chip;
+struct hte_device;
+struct of_phandle_args;
+
Quoted 8 lines

include/linux/hte.h line 19

Quoted 5 lines
include/linux/hte.h new file +5 -0
+/**
+ * Used by providers to indicate the direction of the timestamp.
+ */
+#define HTE_EVENT_RISING_EDGE          0x1
+#define HTE_EVENT_FALLING_EDGE         0x2

Use an enum rather than a define for this as it's a value that can take a set of distinct values. Also, provide a name for 'I've no idea' which I'm guessing is 0 currently.

I will change to enum.

Quoted 19 lines
Quoted 19 lines
include/linux/hte.h new file +18 -0
+
+/**
+ * struct hte_ts_data - HTE timestamp data.
+ * The provider uses and fills timestamp related details during push_timestamp
+ * API call. The consumer uses during retrieve_timestamp API call.
+ *
+ * @tsc: Timestamp value.
+ * @seq: Sequence counter of the timestamps.
+ * @dir: Direction of the event at the time of timestamp.
+ */
+struct hte_ts_data {
+	u64 tsc;
+	u64 seq;
+	int dir;
+};
+
+/**
+ * struct hte_clk_info - Clock source info that HTE provider uses.
Quoted 8 lines

include/linux/hte.h line 42

Quoted 5 lines
include/linux/hte.h new file +5 -0
+ * The provider uses hardware clock as a source to timestamp real time. This
+ * structure presents the clock information to consumers. 
+ *
+ * @hz: Clock rate in HZ, for example 1KHz clock = 1000.
+ * @type: Clock type. CLOCK_* types.

So this is something we got a it wrong in IIO. It's much better to define a subset of clocks that can be potentially used. There are some that make absolutely no sense and consumers really don't want to have to deal with them.

Is there anything I have to change here?

Quoted 15 lines

include/linux/hte.h line 53

Quoted 12 lines
include/linux/hte.h new file +11 -0
+ */
+struct hte_clk_info {
+	u64 hz;
+	clockid_t type;
+};
+
+/**
+ * HTE subsystem notifications for the consumers.
+ *
+ * @HTE_TS_AVAIL: Timestamps available notification.
+ * @HTE_TS_DROPPED: Timestamps dropped notification.

Something I've missed so far is whether drops are in a kfifo or a ring fashion. I'm guess that's stated somewhere, but it might be useful to have it here.

Dropped are from kfifo if kfifo does not have space.

Quoted 31 lines
Quoted 31 lines
include/linux/hte.h new file +30 -0
+ */
+enum hte_notify {
+	HTE_TS_AVAIL = 1,
+	HTE_TS_DROPPED,
+	HTE_NUM_NOTIFIER,
+};
+
+/**
+ * struct hte_ts_desc - HTE timestamp descriptor, this structure will be
+ * communication token between consumers to subsystem and subsystem to
+ * providers.
+ *
+ * @con_id: This is the same id sent in request APIs.
+ * @name: Descriptive name of the entity that is being monitored for the
+ * realtime timestamping.
+ * @data_subsys: Subsystem's private data relate to requested con_id.
+ */
+struct hte_ts_desc {
+	u32 con_id;
+	char *name;
+	void *data_subsys;
+};
+
+/**
+ * struct hte_ops - HTE operations set by providers.
+ *
+ * @request: Hook for requesting a HTE timestamp. Returns 0 on success,
+ * non-zero for failures.
+ * @release: Hook for releasing a HTE timestamp. Returns 0 on success,
+ * non-zero for failures.
Quoted 8 lines

include/linux/hte.h line 90

Quoted 7 lines
include/linux/hte.h new file +7 -0
+ * @enable: Hook to enable the specified timestamp. Returns 0 on success,
+ * non-zero for failures.
+ * @disable: Hook to disable specified timestamp. Returns 0 on success,
+ * non-zero for failures.
+ * @get_clk_src_info: Optional hook to get the clock information provider uses
+ * to timestamp. Returns 0 for success and negative error code for failure. On
+ * success HTE subsystem fills up provided struct hte_clk_info.

Why optional? Consumers will probably need that information.

Sure, will remove optional. But you wrote "probably", that would make it

optional :).

Quoted 17 lines
Quoted 17 lines
include/linux/hte.h new file +16 -0
+ *
+ * xlated_id parameter is used to communicate between HTE subsystem and the
+ * providers. It is the same id returned during xlate API call and translated
+ * by the provider. This may be helpful as both subsystem and provider locate
+ * the requested entity in constant time, where entity could be anything from
+ * lines, signals, events, buses etc.. that providers support.
+ */
+struct hte_ops {
+	int (*request)(struct hte_chip *chip, u32 xlated_id);
+	int (*release)(struct hte_chip *chip, u32 xlated_id);
+	int (*enable)(struct hte_chip *chip, u32 xlated_id);
+	int (*disable)(struct hte_chip *chip, u32 xlated_id);
+	int (*get_clk_src_info)(struct hte_chip *chip,
+				struct hte_clk_info *ci);
+};
+
Quoted 8 lines

include/linux/hte.h line 110

Quoted 4 lines
include/linux/hte.h new file +4 -0
+/**
+ * struct hte_chip - Abstract HTE chip structure.
+ * @name: functional name of the HTE IP block.
+ * @dev: device providing the HTE.

Unclear naming. Is this the parent device, or one associated with the HTE itself? I'm guessing today you don't have one associated with the HTE, but it is plausible you might gain on in future to make it fit nicely in the device model as a function of another device.

This is provider's device, could be &pdev->dev or any dev provider deems fit hence the

generic name.

Quoted 60 lines
Quoted 60 lines
include/linux/hte.h new file +58 -0
+ * @ops: callbacks for this HTE.
+ * @nlines: number of lines/signals supported by this chip.
+ * @xlate: Callback which translates consumer supplied logical ids to
+ * physical ids, return from 0 for the success and negative for the
+ * failures. It stores (0 to @nlines) in xlated_id parameter for the success.
+ * @of_hte_n_cells: Number of cells used to form the HTE specifier.
+ * @gdev: HTE subsystem abstract device, internal to the HTE subsystem.
+ * @data: chip specific private data.
+ */
+struct hte_chip {
+	const char *name;
+	struct device *dev;
+	const struct hte_ops *ops;
+	u32 nlines;
+	int (*xlate)(struct hte_chip *gc,
+		     const struct of_phandle_args *args,
+		     struct hte_ts_desc *desc, u32 *xlated_id);
+	u8 of_hte_n_cells;
+
+	/* only used internally by the HTE framework */
+	struct hte_device *gdev;
+	void *data;
+};
+
+#if IS_ENABLED(CONFIG_HTE)
+/* HTE APIs for the providers */
+int hte_register_chip(struct hte_chip *chip);
+int hte_unregister_chip(struct hte_chip *chip);
+int hte_push_ts_ns_atomic(const struct hte_chip *chip, u32 xlated_id,
+			  struct hte_ts_data *data, size_t n);
+
+/* HTE APIs for the consumers */
+
+int hte_release_ts(struct hte_ts_desc *desc);
+struct hte_ts_desc *of_hte_request_ts(struct device *dev, const char *label,
+				      void (*cb)(enum hte_notify n));
+
+struct hte_ts_desc *devm_of_hte_request_ts(struct device *dev,
+					   const char *label,
+					   void (*cb)(enum hte_notify n));
+struct hte_ts_desc *hte_req_ts_by_dt_node(struct device_node *of_node,
+					  unsigned int id,
+					  void (*cb)(enum hte_notify n));
+int devm_hte_release_ts(struct device *dev, struct hte_ts_desc *desc);
+int hte_retrieve_ts_ns(const struct hte_ts_desc *desc, struct hte_ts_data *el,
+		       size_t n);
+int hte_retrieve_ts_ns_wait(const struct hte_ts_desc *desc,
+			    struct hte_ts_data *el, size_t n);
+int hte_set_buf_len(const struct hte_ts_desc *desc, size_t len);
+size_t hte_get_buf_len(const struct hte_ts_desc *desc);
+int hte_set_buf_watermark(const struct hte_ts_desc *desc, size_t val);
+size_t hte_get_buf_watermark(const struct hte_ts_desc *desc);
+size_t hte_available_ts(const struct hte_ts_desc *desc);
+int hte_enable_ts(struct hte_ts_desc *desc);
+int hte_disable_ts(struct hte_ts_desc *desc);
+int hte_get_clk_src_info(const struct hte_ts_desc *desc,
+			 struct hte_clk_info *ci);
+
maintainer
#14 lore raw

Re: [RFC 02/11] drivers: Add HTE subsystem

Quoted 45 lines · On Tue, 27 Jul 2021 21:38:45 -0700 Dipen Patel <[email protected]> wrote:
Quoted 44 lines · Jonathan Cameron
Quoted 41 lines · On Fri, 25 Jun 2021 16:55:23 -0700 Dipen Patel <[email protected]> wrote:

Some devices can timestamp system lines/signals/Buses in real-time using the hardware counter or other hardware means which can give finer granularity and help avoid jitter introduced by software means of timestamping. To utilize such functionality there has to be framework where such devices can register themselves as producers or providers so that the consumers or clients devices can request specific line from the providers. This patch introduces such subsystem as hardware timestamping engine (HTE).

It provides below APIs for the provider:
- hte_register_chip() -- To register the HTE chip.
- hte_unregister_chip() -- To unregister the HTE chip.
- hte_push_ts_ns_atomic() -- To push timestamp data into HTE subsystem.

It provides below APIs for the consumer:
- of_hte_request_ts() -- To request timestamp functionality.
- devm_of_hte_request_ts() -- Managed version of the above.
- hte_req_ts_by_dt_node() -- To request timestamp functionality by using HTE provider dt node.
- devm_hte_release_ts() -- The managed version to release timestamp functionality and associated resources.
- hte_retrieve_ts_ns() -- To retrieve timestamps.
- hte_retrieve_ts_ns_wait() -- Same as above but blocking version.
- hte_enable_ts() -- To disable timestamp functionality.
- hte_disable_ts() -- To enable timestamp functionality.
- hte_available_ts() -- To query available timestamp data.
- hte_release_ts() -- To release timestamp functionality and its associated resources.
- hte_get_clk_src_info() -- To query clock source information from the provider

It provides centralized software buffer management per requested id to store the timestamp data for the consumers as below:
- hte_set_buf_len() -- To set the buffer length.
- hte_get_buf_len() -- To get the buffer length.
- hte_set_buf_watermark() -- To set the software threshold/watermark.
- hte_get_buf_watermark() -- To get the software threshold/watermark.

The detail about parameters and API usage are described in each functions definitions in drivers/hte/hte.c file.

Quoted 7 lines
Quoted 6 lines
Quoted 4 lines

The patch adds compilation support in Makefile and menu options in Kconfig.

Hi Dipen, this isn't a particularly thorough review as I'm still getting my head around what this is doing + it is an RFC :)

Thanks for the review comments. My responses inline.

You are welcome, some follow up responses inline.
I've tried to crop this down a bit so only kept the bits we are discussing.

Quoted 15 lines
Quoted 6 lines
Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+
+static int hte_ts_dis_en_common(struct hte_ts_desc *desc, bool en)
+{
+	u32 ts_id;
+	struct hte_device *gdev;
+	struct hte_ts_info *ei;
Quoted 8 lines

drivers/hte/hte.c line 438

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+	int ret;
+
+	if (!desc)
+		return -EINVAL;
+
+	ei = (struct hte_ts_info *)desc->data_subsys;  

As above, no need to cast - though it rather implies the type of data_subsys should not be void *.

Quoted 4 lines

desc is public facing structure, I wanted to make subsystem related

information opaque that is why I had it void *.

you can keep it opaque, just have a forwards definition of
struct hte_ts_desc;
which just means it is defined somewhere. You can have that in the header with the definition hidden away.

It will only need to have a visible complete definition when you dereference it inside the the core.

Mind you, I'm suggesting allowing it to be embedded in another structure anyway which would require you to have it exposed. Perhaps this desire to keep it opaque is a reason to not take that suggestion but it isn't relevant for this one.

Quoted 12 lines
Quoted 4 lines
Quoted 4 lines

+ */

drivers/hte/hte.c new file +3 -0
+struct hte_ts_desc *devm_of_hte_request_ts(struct device *dev,
+					   const char *label,
+					   void (*cb)(enum hte_notify n))
Quoted 8 lines

drivers/hte/hte.c line 806

Quoted 5 lines
drivers/hte/hte.c new file +5 -0
+{
+
+	struct hte_ts_desc **ptr, *desc;
+
+	ptr = devres_alloc(__devm_hte_release_ts, sizeof(*ptr), GFP_KERNEL);  

Superficially looks like you might get way with just calling dev_add_action_or_reset() in here and avoid this boilerplate. A lot of cases that looked like this got cleaned up in the last kernel cycle.

Quoted 3 lines

I based my patches from linux-next/master. Not sure if that has

dev_add_action_or_reset

typo on my part was meant to be

devm_add_action_or_reset()

Quoted 16 lines
Quoted 15 lines
Quoted 4 lines
drivers/hte/hte.c new file +1 -0
+

drivers/hte/hte.c line 1096

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+/**
+ * hte_req_ts_by_dt_node() - Request entity to monitor by passing HTE device
+ * node directly, where meaning of the entity is provider specific, for example
+ * lines, signals, GPIOs, buses etc...
+ *
+ * @of_node: HTE provider device node.
+ * @id: entity id to monitor, this id belongs to HTE provider of_node.
+ * @cb: Optional callback to notify.
+ *
+ * Context: Holds mutex lock, can not be called from atomic context.  

What mutex and why? If it is one you can check is held even better.

Quoted 3 lines

___hte_req_ts holds the mutex lock to serialize multiple consumers

requesting same entity.

Add that detail to the comment.

Quoted 29 lines
Quoted 29 lines
Quoted 15 lines

+ * Returns: ts descriptor on success or error pointers.
+ */

drivers/hte/hte.c new file +11 -0
+struct hte_ts_desc *hte_req_ts_by_dt_node(struct device_node *of_node,
+					  unsigned int id,
+					  void (*cb)(enum hte_notify n))
+{
+	struct hte_device *gdev;
+	struct hte_ts_desc *desc;
+	int ret;
+	u32 xlated_id;
+
+	gdev = of_node_to_htedevice(of_node);
+	if (IS_ERR(gdev))

drivers/hte/hte.c line 1119

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		return ERR_PTR(-ENOTSUPP);
+
+	if (!gdev->chip || !gdev->chip->ops)
+		return ERR_PTR(-ENOTSUPP);
+
+	desc = kzalloc(sizeof(*desc), GFP_KERNEL);
+	if (!desc) {
+		ret = -ENOMEM;
+		goto out_put_device;
+	}  

Pass a desc pointer into this function rather than allocating the structure in here. That lets the caller embed that structure inside one of it's own structures if it wants to, resulting in fewer small allocations which is always good.

Quoted 5 lines
Quoted 1 line

It's far from obvious that the caller needs to free desc.

Are you suggesting to shift burden of allocation/deallocation (static or dynamic)

at client/consumer side?

It's been a while so I've forgotten how this works, but 'probably' yes... If a function creates some sort of record (of fixed known size and type) then letting that be passed in + filled in by the function is normally more efficient
than having an allocation in here. Chances are the consumer will just have
it embedded in an existing state structure and not need to do any explicit allocation / deallocation. Disadvantage is you can't keep it opaque.

Quoted 65 lines
Quoted 56 lines
Quoted 56 lines
drivers/hte/hte.c new file +54 -0
+
+	desc->con_id = id;
+	ret = gdev->chip->xlate(gdev->chip, NULL, desc, &xlated_id);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev,
+			"failed to xlate id: %d\n", id);
+		goto out_free_desc;
+	}
+
+	ret = ___hte_req_ts(gdev, desc, xlated_id, cb);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev,
+			"failed to request id: %d\n", id);
+		goto out_free_desc;
+	}
+
+	return desc;
+
+out_free_desc:
+	kfree(desc);
+
+out_put_device:
+	return ERR_PTR(ret);
+}
+EXPORT_SYMBOL_GPL(hte_req_ts_by_dt_node);
+
+/**
+ * hte_get_clk_src_info() - Consumer calls this API to query clock source
+ * information of the desc.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: 0 on success else negative error code on failure.
+ */
+int hte_get_clk_src_info(const struct hte_ts_desc *desc,
+			 struct hte_clk_info *ci)
+{
+	struct hte_chip *chip;
+	struct hte_ts_info *ei;
+
+	if (!desc || !desc->data_subsys || !ci) {
+		pr_debug("%s:%d\n", __func__, __LINE__);
+		return -EINVAL;
+	}
+
+	ei = desc->data_subsys;
+	if (!ei || !ei->gdev || !ei->gdev->chip)
+		return -EINVAL;
+
+	chip = ei->gdev->chip;
+	if (!chip->ops->get_clk_src_info)
+		return -ENOTSUPP;
+
Quoted 8 lines

drivers/hte/hte.c line 1180

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+	return chip->ops->get_clk_src_info(chip, ci);
+}
+EXPORT_SYMBOL_GPL(hte_get_clk_src_info);
+
+static inline void hte_add_to_device_list(struct hte_device *gdev)
+{
+	struct hte_device *prev;  

Needs to take an appropriate lock as you may have concurrent calls.

Quoted 2 lines

There is spin_lock held from register API from where this gets called.

Great. I'd missed that.

Quoted 70 lines
Quoted 8 lines

drivers/hte/hte.c line 1183

Quoted 5 lines
drivers/hte/hte.c new file +3 -0
+
+	if (list_empty(&hte_devices)) {
+		list_add_tail(&gdev->list, &hte_devices);  

Needs a comment. I've no idea why you might want to only add it if there were no other hte_devices already there.

Quoted 5 lines

drivers/hte/hte.c line 1187

Quoted 4 lines
drivers/hte/hte.c new file +4 -0
+		return;
+	}
+
+	prev = list_last_entry(&hte_devices, struct hte_device, list);  

Why woud you do this?

Thanks for pointing out. I definitely missed cleaning this up. Now, I will

remove this function in next RFC version as one line can be added directly

in register API.

Quoted 41 lines
Quoted 41 lines
drivers/hte/hte.c new file +40 -0
+	list_add_tail(&gdev->list, &hte_devices);
+}
+
+/**
+ * hte_push_ts_ns_atomic() - Used by the provider to push timestamp in nano
+ * seconds i.e data->tsc will be in ns, it is assumed that provider will be
+ * using this API from its ISR or atomic context.
+ *
+ * @chip: The HTE chip, used during the registration.
+ * @xlated_id: entity id understood by both subsystem and provider, usually this
+ * is obtained from xlate callback during request API.
+ * @data: timestamp data.
+ * @n: Size of the data.
+ *
+ * Context: Atomic.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_push_ts_ns_atomic(const struct hte_chip *chip, u32 xlated_id,
+			  struct hte_ts_data *data, size_t n)
+{
+	unsigned int ret;
+	bool notify;
+	size_t el_avail;
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	if (!chip || !data || !chip->gdev)
+		return -EINVAL;
+
+	if (xlated_id > chip->nlines)
+		return -EINVAL;
+
+	ei = &chip->gdev->ei[xlated_id];
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags) ||
+	    test_bit(HTE_TS_DISABLE, &ei->flags)) {
+		dev_dbg(chip->dev, "Unknown timestamp push\n");
+		return -EINVAL;
+	}
+
Quoted 8 lines

drivers/hte/hte.c line 1233

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+	/* timestamp sequence counter, start from 0 */
+	data->seq = ei->seq++;
+
+	buffer = ei->buf;
+	el_avail = buffer->access->el_available(buffer);
+	ret = buffer->access->store(buffer, data, n);  

If we are doing this from the hte core, why is buffer definition in the scope of the drivers rather than the core? That seems backwards to me.

Quoted 3 lines

I do not understand this comment. The buffer definition is in scope of hte core

as it is the only entity that manages it.

I think I figured that out later and forgot to come back and edit this comment. However...

In that case, why is it an ops function? Don't introduce abstraction until you need it. Will be simpler and easier to review if you just call those functions directly for now. e.g.

	ret = hs_ts_store_to_buf(buffer, data, n);

Chances are you'll never introduce another buffer choice.
For a long time I thought we'd have both fifo and ring options in IIO but it turned out no one really cared. We do have an ops structure, but that's because in IIO the buffer interface is used for two things:
1) Pushing to a kfifo that is going to userspace.
2) Pushing to a callback function owned by a consumer.
and there is a rather fiddly data demux on the front end to ensure each of those only gets the data requested via that path - at least with timestamps there is only one type of data!

Hmm, thinking about this raises an interesting question. Why do we want a kfifo here at all for HTE? You could just call a callback function registered by the consumer of that kfifo directly. If that consumer then wants to buffer then of course it can, but it not (perhaps it only cares about the latest value and will drop the rest) then it can chose not to. Maybe it's just gathering stats rather than caring about individual timestamps? Probably lots of other things that might happen in the consumer that I've not thought of. We need a buffer if userspace becomes involved, but here IIRC that's not (yet) true.

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
drivers/hte/hte.c new file +6 -0
+	if (ret != n) {
+		atomic_inc(&ei->dropped_ts);
+		if (ei->cb)
+			ei->cb(HTE_TS_DROPPED);
+		return -ENOMEM;
+	}

...

Quoted 27 lines
Quoted 19 lines
Quoted 19 lines
include/linux/hte.h new file +18 -0
+
+/**
+ * struct hte_ts_data - HTE timestamp data.
+ * The provider uses and fills timestamp related details during push_timestamp
+ * API call. The consumer uses during retrieve_timestamp API call.
+ *
+ * @tsc: Timestamp value.
+ * @seq: Sequence counter of the timestamps.
+ * @dir: Direction of the event at the time of timestamp.
+ */
+struct hte_ts_data {
+	u64 tsc;
+	u64 seq;
+	int dir;
+};
+
+/**
+ * struct hte_clk_info - Clock source info that HTE provider uses.
Quoted 8 lines
Quoted 5 lines

+ * The provider uses hardware clock as a source to timestamp real time. This
+ * structure presents the clock information to consumers.
+ *
+ * @hz: Clock rate in HZ, for example 1KHz clock = 1000.
+ * @type: Clock type. CLOCK_* types.

So this is something we got a it wrong in IIO. It's much better to define a subset of clocks that can be potentially used. There are some that make absolutely no sense and consumers really don't want to have to deal with them.

Quoted 1 line

Is there anything I have to change here?

Yes - specify which clocks would make sense. You might not need to explicitly allow only those, but that might also be worthwhile. Otherwise, the chances are you'll end up with a bunch of special purpose code in consumers on the basis they might get CLOCK_TAI or similar and have to deal with it.
As for exactly which clocks do make sense, that's one which may take some figuring out. Probably REALTIME, MONOTONIC and BOOTTIME depending on whether you care what happens when the time of the system gets adjusted, or whether it carries
on measuring time across suspend. Very application dependent but there are some
you can definitely rule out. Don't repeat my mistake of leaving it vague (which incidentally was a follow up to picking a silly clock to use for timestamps
before we allowed it to be configured).

Quoted 15 lines
Quoted 15 lines

include/linux/hte.h line 53

Quoted 12 lines

+ */

include/linux/hte.h new file +10 -0
+struct hte_clk_info {
+	u64 hz;
+	clockid_t type;
+};
+
+/**
+ * HTE subsystem notifications for the consumers.
+ *
+ * @HTE_TS_AVAIL: Timestamps available notification.
+ * @HTE_TS_DROPPED: Timestamps dropped notification.  

Something I've missed so far is whether drops are in a kfifo or a ring fashion. I'm guess that's stated somewhere, but it might be useful to have it here.

Quoted 1 line

Dropped are from kfifo if kfifo does not have space.

Ok, perhaps expand the comment?

...

Quoted 27 lines
Quoted 18 lines
Quoted 18 lines

+ *
+ * xlated_id parameter is used to communicate between HTE subsystem and the
+ * providers. It is the same id returned during xlate API call and translated
+ * by the provider. This may be helpful as both subsystem and provider locate
+ * the requested entity in constant time, where entity could be anything from
+ * lines, signals, events, buses etc.. that providers support.
+ */

include/linux/hte.h new file +9 -0
+struct hte_ops {
+	int (*request)(struct hte_chip *chip, u32 xlated_id);
+	int (*release)(struct hte_chip *chip, u32 xlated_id);
+	int (*enable)(struct hte_chip *chip, u32 xlated_id);
+	int (*disable)(struct hte_chip *chip, u32 xlated_id);
+	int (*get_clk_src_info)(struct hte_chip *chip,
+				struct hte_clk_info *ci);
+};
+
Quoted 8 lines
Quoted 4 lines

+/**
+ * struct hte_chip - Abstract HTE chip structure.
+ * @name: functional name of the HTE IP block.
+ * @dev: device providing the HTE.

Unclear naming. Is this the parent device, or one associated with the HTE itself? I'm guessing today you don't have one associated with the HTE, but it is plausible you might gain on in future to make it fit nicely in the device model as a function of another device.

Quoted 3 lines

This is provider's device, could be &pdev->dev or any dev provider deems fit hence the

generic name.

Ok, for now this works as a name, but I wonder if you will end up growing another layer in the device model as would happen for majority of subsystems. You may end up doing so when adding support to query the provider via a handle in the dt of the consumer. It could probably be avoided, but throwing this into a class might make your life easier as you can use more standard infrastructure.

Quoted 17 lines
Quoted 17 lines
Quoted 17 lines

+ * @ops: callbacks for this HTE.
+ * @nlines: number of lines/signals supported by this chip.
+ * @xlate: Callback which translates consumer supplied logical ids to
+ * physical ids, return from 0 for the success and negative for the
+ * failures. It stores (0 to @nlines) in xlated_id parameter for the success.
+ * @of_hte_n_cells: Number of cells used to form the HTE specifier.
+ * @gdev: HTE subsystem abstract device, internal to the HTE subsystem.
+ * @data: chip specific private data.
+ */

include/linux/hte.h new file +6 -0
+struct hte_chip {
+	const char *name;
+	struct device *dev;
+	const struct hte_ops *ops;
+	u32 nlines;
+	int (*xlate)(struct hte_chip *gc,
Quoted 8 lines
Quoted 8 lines

include/linux/hte.h line 133

Quoted 8 lines
include/linux/hte.h new file +8 -0
+		     const struct of_phandle_args *args,
+		     struct hte_ts_desc *desc, u32 *xlated_id);
+	u8 of_hte_n_cells;
+
+	/* only used internally by the HTE framework */
+	struct hte_device *gdev;
+	void *data;
+};

...

Jonathan

author maintainer
#15 lore raw

Re: [RFC 02/11] drivers: Add HTE subsystem

Hi Jonathan,

I got some time to implement RFC version 2 while doing so I have a follow up comment

inline regarding clock source comment of yours.

Best Regards,

Dipen Patel

Quoted 368 lines · Jonathan Cameron
Quoted 45 lines · On Tue, 27 Jul 2021 21:38:45 -0700 Dipen Patel <[email protected]> wrote:
Quoted 44 lines · Jonathan Cameron
Quoted 41 lines · On Fri, 25 Jun 2021 16:55:23 -0700 Dipen Patel <[email protected]> wrote:

Some devices can timestamp system lines/signals/Buses in real-time using the hardware counter or other hardware means which can give finer granularity and help avoid jitter introduced by software means of timestamping. To utilize such functionality there has to be framework where such devices can register themselves as producers or providers so that the consumers or clients devices can request specific line from the providers. This patch introduces such subsystem as hardware timestamping engine (HTE).

It provides below APIs for the provider:
- hte_register_chip() -- To register the HTE chip.
- hte_unregister_chip() -- To unregister the HTE chip.
- hte_push_ts_ns_atomic() -- To push timestamp data into HTE subsystem.

It provides below APIs for the consumer:
- of_hte_request_ts() -- To request timestamp functionality.
- devm_of_hte_request_ts() -- Managed version of the above.
- hte_req_ts_by_dt_node() -- To request timestamp functionality by using HTE provider dt node.
- devm_hte_release_ts() -- The managed version to release timestamp functionality and associated resources.
- hte_retrieve_ts_ns() -- To retrieve timestamps.
- hte_retrieve_ts_ns_wait() -- Same as above but blocking version.
- hte_enable_ts() -- To disable timestamp functionality.
- hte_disable_ts() -- To enable timestamp functionality.
- hte_available_ts() -- To query available timestamp data.
- hte_release_ts() -- To release timestamp functionality and its associated resources.
- hte_get_clk_src_info() -- To query clock source information from the provider

It provides centralized software buffer management per requested id to store the timestamp data for the consumers as below:
- hte_set_buf_len() -- To set the buffer length.
- hte_get_buf_len() -- To get the buffer length.
- hte_set_buf_watermark() -- To set the software threshold/watermark.
- hte_get_buf_watermark() -- To get the software threshold/watermark.

The detail about parameters and API usage are described in each functions definitions in drivers/hte/hte.c file.

Quoted 7 lines
Quoted 6 lines
Quoted 4 lines

The patch adds compilation support in Makefile and menu options in Kconfig.

Hi Dipen, this isn't a particularly thorough review as I'm still getting my head around what this is doing + it is an RFC :)

Thanks for the review comments. My responses inline.

You are welcome, some follow up responses inline.
I've tried to crop this down a bit so only kept the bits we are discussing.

Quoted 14 lines
Quoted 6 lines
Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+
+static int hte_ts_dis_en_common(struct hte_ts_desc *desc, bool en)
+{
+	u32 ts_id;
+	struct hte_device *gdev;
+	struct hte_ts_info *ei;
Quoted 8 lines

drivers/hte/hte.c line 438

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+	int ret;
+
+	if (!desc)
+		return -EINVAL;
+
+	ei = (struct hte_ts_info *)desc->data_subsys;  

As above, no need to cast - though it rather implies the type of data_subsys should not be void *.

Quoted 4 lines

desc is public facing structure, I wanted to make subsystem related

information opaque that is why I had it void *.

you can keep it opaque, just have a forwards definition of
struct hte_ts_desc;
which just means it is defined somewhere. You can have that in the header with the definition hidden away.

It will only need to have a visible complete definition when you dereference it inside the the core.

Mind you, I'm suggesting allowing it to be embedded in another structure anyway which would require you to have it exposed. Perhaps this desire to keep it opaque is a reason to not take that suggestion but it isn't relevant for this one.

Quoted 12 lines
Quoted 4 lines
Quoted 4 lines

+ */

drivers/hte/hte.c new file +3 -0
+struct hte_ts_desc *devm_of_hte_request_ts(struct device *dev,
+					   const char *label,
+					   void (*cb)(enum hte_notify n))
Quoted 8 lines

drivers/hte/hte.c line 806

Quoted 5 lines
drivers/hte/hte.c new file +5 -0
+{
+
+	struct hte_ts_desc **ptr, *desc;
+
+	ptr = devres_alloc(__devm_hte_release_ts, sizeof(*ptr), GFP_KERNEL);  

Superficially looks like you might get way with just calling dev_add_action_or_reset() in here and avoid this boilerplate. A lot of cases that looked like this got cleaned up in the last kernel cycle.

Quoted 3 lines

I based my patches from linux-next/master. Not sure if that has

dev_add_action_or_reset

typo on my part was meant to be

devm_add_action_or_reset()

Quoted 12 lines
Quoted 4 lines
Quoted 4 lines
drivers/hte/hte.c new file +4 -0
+
+/**
+ * hte_req_ts_by_dt_node() - Request entity to monitor by passing HTE device
+ * node directly, where meaning of the entity is provider specific, for example
Quoted 8 lines
Quoted 7 lines

+ * lines, signals, GPIOs, buses etc...
+ *
+ * @of_node: HTE provider device node.
+ * @id: entity id to monitor, this id belongs to HTE provider of_node.
+ * @cb: Optional callback to notify.
+ *
+ * Context: Holds mutex lock, can not be called from atomic context.

What mutex and why? If it is one you can check is held even better.

Quoted 3 lines

___hte_req_ts holds the mutex lock to serialize multiple consumers

requesting same entity.

Add that detail to the comment.

Quoted 28 lines
Quoted 28 lines
Quoted 14 lines

+ * Returns: ts descriptor on success or error pointers.
+ */

drivers/hte/hte.c new file +11 -0
+struct hte_ts_desc *hte_req_ts_by_dt_node(struct device_node *of_node,
+					  unsigned int id,
+					  void (*cb)(enum hte_notify n))
+{
+	struct hte_device *gdev;
+	struct hte_ts_desc *desc;
+	int ret;
+	u32 xlated_id;
+
+	gdev = of_node_to_htedevice(of_node);
+	if (IS_ERR(gdev))

drivers/hte/hte.c line 1119

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+		return ERR_PTR(-ENOTSUPP);
+
+	if (!gdev->chip || !gdev->chip->ops)
+		return ERR_PTR(-ENOTSUPP);
+
+	desc = kzalloc(sizeof(*desc), GFP_KERNEL);
+	if (!desc) {
+		ret = -ENOMEM;
+		goto out_put_device;
+	}  

Pass a desc pointer into this function rather than allocating the structure in here. That lets the caller embed that structure inside one of it's own structures if it wants to, resulting in fewer small allocations which is always good.

Quoted 4 lines
Quoted 1 line

It's far from obvious that the caller needs to free desc.

Are you suggesting to shift burden of allocation/deallocation (static or dynamic)

at client/consumer side?

It's been a while so I've forgotten how this works, but 'probably' yes... If a function creates some sort of record (of fixed known size and type) then letting that be passed in + filled in by the function is normally more efficient
than having an allocation in here. Chances are the consumer will just have
it embedded in an existing state structure and not need to do any explicit allocation / deallocation. Disadvantage is you can't keep it opaque.

Quoted 63 lines
Quoted 55 lines
Quoted 55 lines
drivers/hte/hte.c new file +54 -0
+
+	desc->con_id = id;
+	ret = gdev->chip->xlate(gdev->chip, NULL, desc, &xlated_id);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev,
+			"failed to xlate id: %d\n", id);
+		goto out_free_desc;
+	}
+
+	ret = ___hte_req_ts(gdev, desc, xlated_id, cb);
+	if (ret < 0) {
+		dev_err(gdev->chip->dev,
+			"failed to request id: %d\n", id);
+		goto out_free_desc;
+	}
+
+	return desc;
+
+out_free_desc:
+	kfree(desc);
+
+out_put_device:
+	return ERR_PTR(ret);
+}
+EXPORT_SYMBOL_GPL(hte_req_ts_by_dt_node);
+
+/**
+ * hte_get_clk_src_info() - Consumer calls this API to query clock source
+ * information of the desc.
+ *
+ * @desc: ts descriptor, same as returned from request API.
+ *
+ * Context: Any context.
+ * Returns: 0 on success else negative error code on failure.
+ */
+int hte_get_clk_src_info(const struct hte_ts_desc *desc,
+			 struct hte_clk_info *ci)
+{
+	struct hte_chip *chip;
+	struct hte_ts_info *ei;
+
+	if (!desc || !desc->data_subsys || !ci) {
+		pr_debug("%s:%d\n", __func__, __LINE__);
+		return -EINVAL;
+	}
+
+	ei = desc->data_subsys;
+	if (!ei || !ei->gdev || !ei->gdev->chip)
+		return -EINVAL;
+
+	chip = ei->gdev->chip;
+	if (!chip->ops->get_clk_src_info)
+		return -ENOTSUPP;
+
Quoted 8 lines

drivers/hte/hte.c line 1180

Quoted 7 lines
drivers/hte/hte.c new file +7 -0
+	return chip->ops->get_clk_src_info(chip, ci);
+}
+EXPORT_SYMBOL_GPL(hte_get_clk_src_info);
+
+static inline void hte_add_to_device_list(struct hte_device *gdev)
+{
+	struct hte_device *prev;  

Needs to take an appropriate lock as you may have concurrent calls.

Quoted 2 lines

There is spin_lock held from register API from where this gets called.

Great. I'd missed that.

Quoted 67 lines
Quoted 7 lines

drivers/hte/hte.c line 1183

Quoted 4 lines
drivers/hte/hte.c new file +3 -0
+
+	if (list_empty(&hte_devices)) {
+		list_add_tail(&gdev->list, &hte_devices);  

Needs a comment. I've no idea why you might want to only add it if there were no other hte_devices already there.

Quoted 5 lines

drivers/hte/hte.c line 1187

Quoted 4 lines
drivers/hte/hte.c new file +4 -0
+		return;
+	}
+
+	prev = list_last_entry(&hte_devices, struct hte_device, list);  

Why woud you do this?

Thanks for pointing out. I definitely missed cleaning this up. Now, I will

remove this function in next RFC version as one line can be added directly

in register API.

Quoted 41 lines
Quoted 41 lines
drivers/hte/hte.c new file +40 -0
+	list_add_tail(&gdev->list, &hte_devices);
+}
+
+/**
+ * hte_push_ts_ns_atomic() - Used by the provider to push timestamp in nano
+ * seconds i.e data->tsc will be in ns, it is assumed that provider will be
+ * using this API from its ISR or atomic context.
+ *
+ * @chip: The HTE chip, used during the registration.
+ * @xlated_id: entity id understood by both subsystem and provider, usually this
+ * is obtained from xlate callback during request API.
+ * @data: timestamp data.
+ * @n: Size of the data.
+ *
+ * Context: Atomic.
+ * Returns: 0 on success or a negative error code on failure.
+ */
+int hte_push_ts_ns_atomic(const struct hte_chip *chip, u32 xlated_id,
+			  struct hte_ts_data *data, size_t n)
+{
+	unsigned int ret;
+	bool notify;
+	size_t el_avail;
+	struct hte_ts_buf *buffer;
+	struct hte_ts_info *ei;
+
+	if (!chip || !data || !chip->gdev)
+		return -EINVAL;
+
+	if (xlated_id > chip->nlines)
+		return -EINVAL;
+
+	ei = &chip->gdev->ei[xlated_id];
+
+	if (!test_bit(HTE_TS_REGISTERED, &ei->flags) ||
+	    test_bit(HTE_TS_DISABLE, &ei->flags)) {
+		dev_dbg(chip->dev, "Unknown timestamp push\n");
+		return -EINVAL;
+	}
+
Quoted 8 lines

drivers/hte/hte.c line 1233

Quoted 6 lines
drivers/hte/hte.c new file +6 -0
+	/* timestamp sequence counter, start from 0 */
+	data->seq = ei->seq++;
+
+	buffer = ei->buf;
+	el_avail = buffer->access->el_available(buffer);
+	ret = buffer->access->store(buffer, data, n);  

If we are doing this from the hte core, why is buffer definition in the scope of the drivers rather than the core? That seems backwards to me.

Quoted 3 lines

I do not understand this comment. The buffer definition is in scope of hte core

as it is the only entity that manages it.

I think I figured that out later and forgot to come back and edit this comment. However...

In that case, why is it an ops function? Don't introduce abstraction until you need it. Will be simpler and easier to review if you just call those functions directly for now. e.g.

	ret = hs_ts_store_to_buf(buffer, data, n);

Chances are you'll never introduce another buffer choice.
For a long time I thought we'd have both fifo and ring options in IIO but it turned out no one really cared. We do have an ops structure, but that's because in IIO the buffer interface is used for two things:
1) Pushing to a kfifo that is going to userspace.
2) Pushing to a callback function owned by a consumer.
and there is a rather fiddly data demux on the front end to ensure each of those only gets the data requested via that path - at least with timestamps there is only one type of data!

Hmm, thinking about this raises an interesting question. Why do we want a kfifo here at all for HTE? You could just call a callback function registered by the consumer of that kfifo directly. If that consumer then wants to buffer then of course it can, but it not (perhaps it only cares about the latest value and will drop the rest) then it can chose not to. Maybe it's just gathering stats rather than caring about individual timestamps? Probably lots of other things that might happen in the consumer that I've not thought of. We need a buffer if userspace becomes involved, but here IIRC that's not (yet) true.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
drivers/hte/hte.c new file +6 -0
+	if (ret != n) {
+		atomic_inc(&ei->dropped_ts);
+		if (ei->cb)
+			ei->cb(HTE_TS_DROPPED);
+		return -ENOMEM;
+	}

...

Quoted 27 lines
Quoted 19 lines
Quoted 19 lines
include/linux/hte.h new file +18 -0
+
+/**
+ * struct hte_ts_data - HTE timestamp data.
+ * The provider uses and fills timestamp related details during push_timestamp
+ * API call. The consumer uses during retrieve_timestamp API call.
+ *
+ * @tsc: Timestamp value.
+ * @seq: Sequence counter of the timestamps.
+ * @dir: Direction of the event at the time of timestamp.
+ */
+struct hte_ts_data {
+	u64 tsc;
+	u64 seq;
+	int dir;
+};
+
+/**
+ * struct hte_clk_info - Clock source info that HTE provider uses.
Quoted 8 lines
Quoted 5 lines

+ * The provider uses hardware clock as a source to timestamp real time. This
+ * structure presents the clock information to consumers.
+ *
+ * @hz: Clock rate in HZ, for example 1KHz clock = 1000.
+ * @type: Clock type. CLOCK_* types.

So this is something we got a it wrong in IIO. It's much better to define a subset of clocks that can be potentially used. There are some that make absolutely no sense and consumers really don't want to have to deal with them.

Quoted 1 line

Is there anything I have to change here?

Quoted 11 lines

Yes - specify which clocks would make sense. You might not need to explicitly allow only those, but that might also be worthwhile. Otherwise, the chances are you'll end up with a bunch of special purpose code in consumers on the basis they might get CLOCK_TAI or similar and have to deal with it.
As for exactly which clocks do make sense, that's one which may take some figuring out. Probably REALTIME, MONOTONIC and BOOTTIME depending on whether you care what happens when the time of the system gets adjusted, or whether it carries
on measuring time across suspend. Very application dependent but there are some
you can definitely rule out. Don't repeat my mistake of leaving it vague (which incidentally was a follow up to picking a silly clock to use for timestamps
before we allowed it to be configured).

I believe your comment is under assumption that providers have choice in selecting

clock source to timestamp in turns clients have it as well. For now, the provider

I have implemented has single clock source and hence I only implemented get_clock*

hook that provider implement and client can retrieve that information. I guess I can

always implement set_clock* hook as well for the future providers which support

multiple clock sources. Please let me if I missed your point.

Quoted 81 lines
Quoted 15 lines
Quoted 15 lines

include/linux/hte.h line 53

Quoted 12 lines

+ */

include/linux/hte.h new file +10 -0
+struct hte_clk_info {
+	u64 hz;
+	clockid_t type;
+};
+
+/**
+ * HTE subsystem notifications for the consumers.
+ *
+ * @HTE_TS_AVAIL: Timestamps available notification.
+ * @HTE_TS_DROPPED: Timestamps dropped notification.  

Something I've missed so far is whether drops are in a kfifo or a ring fashion. I'm guess that's stated somewhere, but it might be useful to have it here.

Quoted 1 line

Dropped are from kfifo if kfifo does not have space.

Ok, perhaps expand the comment?

...

Quoted 25 lines
Quoted 17 lines
Quoted 17 lines

+ *
+ * xlated_id parameter is used to communicate between HTE subsystem and the
+ * providers. It is the same id returned during xlate API call and translated
+ * by the provider. This may be helpful as both subsystem and provider locate
+ * the requested entity in constant time, where entity could be anything from
+ * lines, signals, events, buses etc.. that providers support.
+ */

include/linux/hte.h new file +9 -0
+struct hte_ops {
+	int (*request)(struct hte_chip *chip, u32 xlated_id);
+	int (*release)(struct hte_chip *chip, u32 xlated_id);
+	int (*enable)(struct hte_chip *chip, u32 xlated_id);
+	int (*disable)(struct hte_chip *chip, u32 xlated_id);
+	int (*get_clk_src_info)(struct hte_chip *chip,
+				struct hte_clk_info *ci);
+};
+
Quoted 8 lines
Quoted 4 lines

+/**
+ * struct hte_chip - Abstract HTE chip structure.
+ * @name: functional name of the HTE IP block.
+ * @dev: device providing the HTE.

Unclear naming. Is this the parent device, or one associated with the HTE itself? I'm guessing today you don't have one associated with the HTE, but it is plausible you might gain on in future to make it fit nicely in the device model as a function of another device.

Quoted 3 lines

This is provider's device, could be &pdev->dev or any dev provider deems fit hence the

generic name.

Ok, for now this works as a name, but I wonder if you will end up growing another layer in the device model as would happen for majority of subsystems. You may end up doing so when adding support to query the provider via a handle in the dt of the consumer. It could probably be avoided, but throwing this into a class might make your life easier as you can use more standard infrastructure.

Quoted 16 lines
Quoted 16 lines
Quoted 16 lines

+ * @ops: callbacks for this HTE.
+ * @nlines: number of lines/signals supported by this chip.
+ * @xlate: Callback which translates consumer supplied logical ids to
+ * physical ids, return from 0 for the success and negative for the
+ * failures. It stores (0 to @nlines) in xlated_id parameter for the success.
+ * @of_hte_n_cells: Number of cells used to form the HTE specifier.
+ * @gdev: HTE subsystem abstract device, internal to the HTE subsystem.
+ * @data: chip specific private data.
+ */

include/linux/hte.h new file +6 -0
+struct hte_chip {
+	const char *name;
+	struct device *dev;
+	const struct hte_ops *ops;
+	u32 nlines;
+	int (*xlate)(struct hte_chip *gc,
Quoted 8 lines
Quoted 8 lines

include/linux/hte.h line 133

Quoted 8 lines
include/linux/hte.h new file +8 -0
+		     const struct of_phandle_args *args,
+		     struct hte_ts_desc *desc, u32 *xlated_id);
+	u8 of_hte_n_cells;
+
+	/* only used internally by the HTE framework */
+	struct hte_device *gdev;
+	void *data;
+};

...

Jonathan

maintainer
#16 lore raw

Re: [RFC 02/11] drivers: Add HTE subsystem

Quoted 10 lines · On Mon, 13 Sep 2021 22:43:02 -0700 Dipen Patel <[email protected]> wrote:

Hi Jonathan,

I got some time to implement RFC version 2 while doing so I have a follow up comment

inline regarding clock source comment of yours.

Best Regards,

Dipen Patel

...

Quoted 27 lines
Quoted 11 lines
Quoted 11 lines
Quoted 10 lines
Quoted 7 lines

+/**
+ * struct hte_clk_info - Clock source info that HTE provider uses.
+ * The provider uses hardware clock as a source to timestamp real time. This
+ * structure presents the clock information to consumers.
+ *
+ * @hz: Clock rate in HZ, for example 1KHz clock = 1000.
+ * @type: Clock type. CLOCK_* types.

So this is something we got a it wrong in IIO. It's much better to define a subset of clocks that can be potentially used. There are some that make absolutely no sense and consumers really don't want to have to deal with them.

Is there anything I have to change here?

Quoted 11 lines

Yes - specify which clocks would make sense. You might not need to explicitly allow only those, but that might also be worthwhile. Otherwise, the chances are you'll end up with a bunch of special purpose code in consumers on the basis they might get CLOCK_TAI or similar and have to deal with it.
As for exactly which clocks do make sense, that's one which may take some figuring out. Probably REALTIME, MONOTONIC and BOOTTIME depending on whether you care what happens when the time of the system gets adjusted, or whether it carries
on measuring time across suspend. Very application dependent but there are some
you can definitely rule out. Don't repeat my mistake of leaving it vague (which incidentally was a follow up to picking a silly clock to use for timestamps
before we allowed it to be configured).

I believe your comment is under assumption that providers have choice in selecting

clock source to timestamp in turns clients have it as well. For now, the provider

Quoted 7 lines

I have implemented has single clock source and hence I only implemented get_clock*

hook that provider implement and client can retrieve that information. I guess I can

always implement set_clock* hook as well for the future providers which support

multiple clock sources. Please let me if I missed your point.

I'll be honest I can't really remember :( too many sleeps.

Sorry - if it is still relevant perhaps it'll come back to me on v2.

Thanks,

Jonathan

#17 lore raw

Re: [RFC 02/11] drivers: Add HTE subsystem

In reply to Dipen Patel

drivers/hte/hte.c line 307

Quoted 8 lines · Dipen Patel
drivers/hte/hte.c new file +8 -0
+static void hte_chip_dbgfs_init(struct hte_device *gdev)
+{
+	const struct hte_chip *chip = gdev->chip;
+	const char *name = chip->name ? chip->name : dev_name(chip->dev);
+
+	gdev->dbg_root = debugfs_create_dir(name, hte_root);
+	if (!gdev->dbg_root)
+		return;

No need to check for this, if it fails, your other debugfs calls will handle it just fine.

Quoted 5 lines
drivers/hte/hte.c new file +5 -0
+
+	debugfs_create_atomic_t("ts_requested", 0444, gdev->dbg_root,
+				&gdev->ts_req);
+	debugfs_create_u32("total_ts", 0444, gdev->dbg_root,
+			   &gdev->nlines);

drivers/hte/hte.c line 322

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+}
+
+static void hte_ts_dbgfs_init(const char *name, struct hte_ts_info *ei)
+{
+	if (!ei->gdev->dbg_root || !name)
+		return;
+
+	ei->ts_dbg_root = debugfs_create_dir(name, ei->gdev->dbg_root);
+	if (!ei->ts_dbg_root)
+		return;

Again, no need to check.

drivers/hte/hte.c line 335

Quoted 13 lines
drivers/hte/hte.c new file +13 -0
+
+	debugfs_create_size_t("ts_buffer_depth", 0444, ei->ts_dbg_root,
+			      &ei->buf->datum_len);
+	debugfs_create_size_t("ts_buffer_watermark", 0444, ei->ts_dbg_root,
+			      &ei->buf->watermark);
+	debugfs_create_atomic_t("dropped_timestamps", 0444, ei->ts_dbg_root,
+				&ei->dropped_ts);
+}
+
+static inline void hte_dbgfs_deinit(struct dentry *root)
+{
+	if (!root)
+		return;

No need to check this.

drivers/hte/hte.c line 337

Quoted 2 lines
drivers/hte/hte.c new file +2 -0
+
+	debugfs_remove_recursive(root);

Do not wrap a single call with another call :)

thanks,

greg k-h

author maintainer
#18 lore raw

Re: [RFC 02/11] drivers: Add HTE subsystem

Thanks Greg for the review comments. I will address all in next RFC version2.

Best Regards,

Dipen Patel

Quoted 53 lines · Greg KH

drivers/hte/hte.c line 307

Quoted 8 lines · Dipen Patel
drivers/hte/hte.c new file +8 -0
+static void hte_chip_dbgfs_init(struct hte_device *gdev)
+{
+	const struct hte_chip *chip = gdev->chip;
+	const char *name = chip->name ? chip->name : dev_name(chip->dev);
+
+	gdev->dbg_root = debugfs_create_dir(name, hte_root);
+	if (!gdev->dbg_root)
+		return;

No need to check for this, if it fails, your other debugfs calls will handle it just fine.

Quoted 5 lines
drivers/hte/hte.c new file +5 -0
+
+	debugfs_create_atomic_t("ts_requested", 0444, gdev->dbg_root,
+				&gdev->ts_req);
+	debugfs_create_u32("total_ts", 0444, gdev->dbg_root,
+			   &gdev->nlines);

drivers/hte/hte.c line 322

Quoted 10 lines
drivers/hte/hte.c new file +10 -0
+}
+
+static void hte_ts_dbgfs_init(const char *name, struct hte_ts_info *ei)
+{
+	if (!ei->gdev->dbg_root || !name)
+		return;
+
+	ei->ts_dbg_root = debugfs_create_dir(name, ei->gdev->dbg_root);
+	if (!ei->ts_dbg_root)
+		return;

Again, no need to check.

drivers/hte/hte.c line 335

Quoted 13 lines
drivers/hte/hte.c new file +13 -0
+
+	debugfs_create_size_t("ts_buffer_depth", 0444, ei->ts_dbg_root,
+			      &ei->buf->datum_len);
+	debugfs_create_size_t("ts_buffer_watermark", 0444, ei->ts_dbg_root,
+			      &ei->buf->watermark);
+	debugfs_create_atomic_t("dropped_timestamps", 0444, ei->ts_dbg_root,
+				&ei->dropped_ts);
+}
+
+static inline void hte_dbgfs_deinit(struct dentry *root)
+{
+	if (!root)
+		return;

No need to check this.

drivers/hte/hte.c line 337

Quoted 2 lines
drivers/hte/hte.c new file +2 -0
+
+	debugfs_remove_recursive(root);

Do not wrap a single call with another call :)

thanks,

greg k-h

author maintainer
#19 lore raw

RFC 3/11 hte: Add tegra194 HTE kernel provider

In reply to Dipen Patel

Tegra194 device has multiple HTE instances also known as GTE (Generic hardware Timestamping Engine) which can timestamp subset of SoC lines/signals. This provider driver focuses on IRQ and GPIO lines and exposes timestamping ability on those lines to the consumers through HTE subsystem.

Also, with this patch, added:
- documentation about this provider and its capabilities at Documentation/hte.
- Compilation support in Makefile and Kconfig

---
 Documentation/hte/index.rst        |  21 ++
 Documentation/hte/tegra194-hte.rst |  65 ++++
 Documentation/index.rst            |   1 +
 drivers/hte/Kconfig                |  12 +
 drivers/hte/Makefile               |   1 +
 drivers/hte/hte-tegra194.c         | 554 +++++++++++++++++++++++++++++
 6 files changed, 654 insertions(+)
 create mode 100644 Documentation/hte/index.rst
 create mode 100644 Documentation/hte/tegra194-hte.rst
 create mode 100644 drivers/hte/hte-tegra194.c
Documentation/hte/index.rst new file +21 -0
new file mode 100644
index 000000000000..f311ebec6b47
@@ -0,0 +1,21 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+The HTE Subsystem
+=================
+
+.. toctree::
+   :maxdepth: 1
+
+   hte
+
+HTE Tegra Provider
+==================
+
+.. toctree::
+   :maxdepth: 1
+
+   tegra194-hte
\ No newline at end of file
Documentation/hte/tegra194-hte.rst new file +65 -0

66 lines not on this page · raw message

Documentation/index.rst +1 -0
index 1b13c2445e87..b41118577fe6 100644
@@ -138,6 +138,7 @@ needed).
    misc-devices/index
    scheduler/index
    mhi/index
+   hte/index
 
 Architecture-agnostic documentation
 -----------------------------------
drivers/hte/Kconfig +12 -0
index 394e112f7dfb..f7b01fcc7190 100644
@@ -20,3 +20,15 @@ menuconfig HTE
 
           If unsure, say no.
 
+if HTE
+
+config HTE_TEGRA194
+	tristate "NVIDIA Tegra194 HTE Support"
+	depends on ARCH_TEGRA_194_SOC
+	help
+	  Enable this option for integrated hardware timestamping engine also
+	  known as generic timestamping engine (GTE) support on NVIDIA Tegra194
+	  systems-on-chip. The driver supports 352 LIC IRQs and 39 AON GPIOs
+	  lines for timestamping in realtime.
+
+endif
drivers/hte/Makefile +1 -0
index 9899dbe516f7..52f978cfc913 100644
@@ -1 +1,2 @@
 obj-$(CONFIG_HTE)		+= hte.o
+obj-$(CONFIG_HTE_TEGRA194)	+= hte-tegra194.o
\ No newline at end of file
drivers/hte/hte-tegra194.c new file +554 -0

554 lines not on this page · raw message

Signature · 1 line
2.17.1
reviewer
#20 lore raw

Re: [RFC 03/11] hte: Add tegra194 HTE kernel provider

Quoted 102 lines · Dipen Patel

Tegra194 device has multiple HTE instances also known as GTE (Generic hardware Timestamping Engine) which can timestamp subset of SoC lines/signals. This provider driver focuses on IRQ and GPIO lines and exposes timestamping ability on those lines to the consumers through HTE subsystem.

Also, with this patch, added:
- documentation about this provider and its capabilities at Documentation/hte.
- Compilation support in Makefile and Kconfig

---
 Documentation/hte/index.rst        |  21 ++
 Documentation/hte/tegra194-hte.rst |  65 ++++
 Documentation/index.rst            |   1 +
 drivers/hte/Kconfig                |  12 +
 drivers/hte/Makefile               |   1 +
 drivers/hte/hte-tegra194.c         | 554 +++++++++++++++++++++++++++++
 6 files changed, 654 insertions(+)
 create mode 100644 Documentation/hte/index.rst
 create mode 100644 Documentation/hte/tegra194-hte.rst
 create mode 100644 drivers/hte/hte-tegra194.c
Documentation/hte/index.rst new file +21 -0
new file mode 100644
index 000000000000..f311ebec6b47
@@ -0,0 +1,21 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+The HTE Subsystem
+=================
+
+.. toctree::
+   :maxdepth: 1
+
+   hte
+
+HTE Tegra Provider
+==================
+
+.. toctree::
+   :maxdepth: 1
+
+   tegra194-hte
\ No newline at end of file
Documentation/hte/tegra194-hte.rst new file +44 -0
new file mode 100644
index 000000000000..c23eaafcf080
@@ -0,0 +1,65 @@
+HTE Kernel provider driver
+==========================
+
+Description
+-----------
+The Nvidia tegra194 chip has many hardware timestamping engine (HTE) instances
+known as generic timestamping engine (GTE). This provider driver implements
+two GTE instances 1) GPIO GTE and 2) IRQ GTE. The both GTEs instances get the
+timestamp from the system counter TSC which has 31.25MHz clock rate, and the
+driver converts clock tick rate to nano seconds before storing it as timestamp
+value.
+
+GPIO GTE
+--------
+
+This GTE instance help timestamps GPIO in real time, for that to happen GPIO
+needs to be configured as input and IRQ needs to ba enabled as well. The only
+always on (AON) gpio controller instance supports timestamping GPIOs in
+realtime and it has 39 GPIO lines. There is also a dependency on AON GPIO
+controller as it requires very specific bits to be set in GPIO config register.
+It in a way creates cyclic dependency between GTE and GPIO controller. The GTE
+GPIO functionality is accessed from the GPIOLIB. It can support both the in
+kernel and userspace consumers. In the later case, requests go through GPIOLIB
+CDEV framework. The below APIs are added in GPIOLIB framework to access HTE
+subsystem and GPIO GTE for in kernel consumers.
+
+.. c:function:: int gpiod_hw_timestamp_control( struct gpio_desc *desc, bool enable )
+
+	To enable HTE on given GPIO line.
+
+.. c:function:: u64 gpiod_get_hw_timestamp( struct gpio_desc *desc, bool block )
+
+	To retrieve hardwre timestamp in nano seconds.
+
+.. c:function:: bool gpiod_is_hw_timestamp_enabled( const struct gpio_desc *desc )
+
+	To query if HTE is enabled on the given GPIO.
+
+There is hte-tegra194-gpio-test.c, located in ``drivers/hte/`` directory, test
+driver which demonstrates above APIs for the Jetson AGX platform. For userspace
+consumers, GPIO_V2_LINE_FLAG_EVENT_CLOCK_HARDWARE flag must be specifed during
+IOCTL calls, refer ``tools/gpio/gpio-event-mon.c``, which returns the timestamp
+in nano second.
+

<snip>

Quoted 29 lines
Documentation/hte/tegra194-hte.rst new file +29 -0
+
+static void tegra_hte_read_fifo(struct tegra_hte_soc *gs)
+{
+	u32 tsh, tsl, src, pv, cv, acv, slice, bit_index, line_id;
+	u64 tsc;
+	int dir;
+	struct hte_ts_data el;
+
+	while ((tegra_hte_readl(gs, HTE_TESTATUS) >>
+		HTE_TESTATUS_OCCUPANCY_SHIFT) &
+		HTE_TESTATUS_OCCUPANCY_MASK) {
+		tsh = tegra_hte_readl(gs, HTE_TETSCH);
+		tsl = tegra_hte_readl(gs, HTE_TETSCL);
+		tsc = (((u64)tsh << 32) | tsl);
+
+		src = tegra_hte_readl(gs, HTE_TESRC);
+		slice = (src >> HTE_TESRC_SLICE_SHIFT) &
+			    HTE_TESRC_SLICE_DEFAULT_MASK;
+
+		pv = tegra_hte_readl(gs, HTE_TEPCV);
+		cv = tegra_hte_readl(gs, HTE_TECCV);
+		acv = pv ^ cv;
+		while (acv) {
+			bit_index = __builtin_ctz(acv);
+			if ((pv >> bit_index) & BIT(0))
+				dir = HTE_EVENT_RISING_EDGE;
+			else
+				dir = HTE_EVENT_FALLING_EDGE;
+

Documentation/hte/tegra194-hte.rst

Quoted 10 lines
Documentation/hte/tegra194-hte.rst new file +10 -0
+			line_id = bit_index + (slice << 5);
+			el.dir = dir;
+			el.tsc = tsc << HTE_TS_NS_SHIFT;
+			hte_push_ts_ns_atomic(gs->chip, line_id, &el,
+					      sizeof(el));
+			acv &= ~BIT(bit_index);
+		}
+		tegra_hte_writel(gs, HTE_TECMD, HTE_TECMD_CMD_POP);
+	}
+}

What happens when the hte_push_ts_ns_atomic() fails?
The timestamp will be quietly dropped?
What happens when the interrupt corresponding to that dropped timestamp asks for it? The irq handler thread will block until it can get a timestamp from the subsequent interrupt?

Which brings me back to the concern I have with the approach used in the hte/gpiolib integration - how do you guarantee that the timestamp returned by gpiod_get_hw_timestamp() corresponds to the irq interrupt being handled, particularly in the face of errors such as:
- overflows of the timestamp FIFO in the chip
- overflows of software FIFOs as here
- lost interupts (if the hw generates interrupts faster than the CPU can service them)
?

Cheers,
Kent.

author maintainer
#21 lore raw

Re: [RFC 03/11] hte: Add tegra194 HTE kernel provider

Thanks Kent for the review comment. My responses inline.

Quoted 141 lines · Kent Gibson
Quoted 102 lines · Dipen Patel

Tegra194 device has multiple HTE instances also known as GTE (Generic hardware Timestamping Engine) which can timestamp subset of SoC lines/signals. This provider driver focuses on IRQ and GPIO lines and exposes timestamping ability on those lines to the consumers through HTE subsystem.

Also, with this patch, added:
- documentation about this provider and its capabilities at Documentation/hte.
- Compilation support in Makefile and Kconfig

---
 Documentation/hte/index.rst        |  21 ++
 Documentation/hte/tegra194-hte.rst |  65 ++++
 Documentation/index.rst            |   1 +
 drivers/hte/Kconfig                |  12 +
 drivers/hte/Makefile               |   1 +
 drivers/hte/hte-tegra194.c         | 554 +++++++++++++++++++++++++++++
 6 files changed, 654 insertions(+)
 create mode 100644 Documentation/hte/index.rst
 create mode 100644 Documentation/hte/tegra194-hte.rst
 create mode 100644 drivers/hte/hte-tegra194.c
Documentation/hte/index.rst new file +21 -0
new file mode 100644
index 000000000000..f311ebec6b47
@@ -0,0 +1,21 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+The HTE Subsystem
+=================
+
+.. toctree::
+   :maxdepth: 1
+
+   hte
+
+HTE Tegra Provider
+==================
+
+.. toctree::
+   :maxdepth: 1
+
+   tegra194-hte
\ No newline at end of file
Documentation/hte/tegra194-hte.rst new file +44 -0
new file mode 100644
index 000000000000..c23eaafcf080
@@ -0,0 +1,65 @@
+HTE Kernel provider driver
+==========================
+
+Description
+-----------
+The Nvidia tegra194 chip has many hardware timestamping engine (HTE) instances
+known as generic timestamping engine (GTE). This provider driver implements
+two GTE instances 1) GPIO GTE and 2) IRQ GTE. The both GTEs instances get the
+timestamp from the system counter TSC which has 31.25MHz clock rate, and the
+driver converts clock tick rate to nano seconds before storing it as timestamp
+value.
+
+GPIO GTE
+--------
+
+This GTE instance help timestamps GPIO in real time, for that to happen GPIO
+needs to be configured as input and IRQ needs to ba enabled as well. The only
+always on (AON) gpio controller instance supports timestamping GPIOs in
+realtime and it has 39 GPIO lines. There is also a dependency on AON GPIO
+controller as it requires very specific bits to be set in GPIO config register.
+It in a way creates cyclic dependency between GTE and GPIO controller. The GTE
+GPIO functionality is accessed from the GPIOLIB. It can support both the in
+kernel and userspace consumers. In the later case, requests go through GPIOLIB
+CDEV framework. The below APIs are added in GPIOLIB framework to access HTE
+subsystem and GPIO GTE for in kernel consumers.
+
+.. c:function:: int gpiod_hw_timestamp_control( struct gpio_desc *desc, bool enable )
+
+	To enable HTE on given GPIO line.
+
+.. c:function:: u64 gpiod_get_hw_timestamp( struct gpio_desc *desc, bool block )
+
+	To retrieve hardwre timestamp in nano seconds.
+
+.. c:function:: bool gpiod_is_hw_timestamp_enabled( const struct gpio_desc *desc )
+
+	To query if HTE is enabled on the given GPIO.
+
+There is hte-tegra194-gpio-test.c, located in ``drivers/hte/`` directory, test
+driver which demonstrates above APIs for the Jetson AGX platform. For userspace
+consumers, GPIO_V2_LINE_FLAG_EVENT_CLOCK_HARDWARE flag must be specifed during
+IOCTL calls, refer ``tools/gpio/gpio-event-mon.c``, which returns the timestamp
+in nano second.
+

<snip>

Quoted 36 lines
Documentation/hte/tegra194-hte.rst new file +36 -0
+
+static void tegra_hte_read_fifo(struct tegra_hte_soc *gs)
+{
+	u32 tsh, tsl, src, pv, cv, acv, slice, bit_index, line_id;
+	u64 tsc;
+	int dir;
+	struct hte_ts_data el;
+
+	while ((tegra_hte_readl(gs, HTE_TESTATUS) >>
+		HTE_TESTATUS_OCCUPANCY_SHIFT) &
+		HTE_TESTATUS_OCCUPANCY_MASK) {
+		tsh = tegra_hte_readl(gs, HTE_TETSCH);
+		tsl = tegra_hte_readl(gs, HTE_TETSCL);
+		tsc = (((u64)tsh << 32) | tsl);
+
+		src = tegra_hte_readl(gs, HTE_TESRC);
+		slice = (src >> HTE_TESRC_SLICE_SHIFT) &
+			    HTE_TESRC_SLICE_DEFAULT_MASK;
+
+		pv = tegra_hte_readl(gs, HTE_TEPCV);
+		cv = tegra_hte_readl(gs, HTE_TECCV);
+		acv = pv ^ cv;
+		while (acv) {
+			bit_index = __builtin_ctz(acv);
+			if ((pv >> bit_index) & BIT(0))
+				dir = HTE_EVENT_RISING_EDGE;
+			else
+				dir = HTE_EVENT_FALLING_EDGE;
+
+			line_id = bit_index + (slice << 5);
+			el.dir = dir;
+			el.tsc = tsc << HTE_TS_NS_SHIFT;
+			hte_push_ts_ns_atomic(gs->chip, line_id, &el,
+					      sizeof(el));
+			acv &= ~BIT(bit_index);
+		}
Quoted 8 lines

Documentation/hte/tegra194-hte.rst

Quoted 3 lines
Documentation/hte/tegra194-hte.rst new file +3 -0
+		tegra_hte_writel(gs, HTE_TECMD, HTE_TECMD_CMD_POP);
+	}
+}

What happens when the hte_push_ts_ns_atomic() fails?
The timestamp will be quietly dropped?
What happens when the interrupt corresponding to that dropped timestamp asks for it? The irq handler thread will block until it can get a timestamp from the subsequent interrupt?

Two things happen, 1) at the push, HTE core increments seq counter

2) If the consumer has provided callback, it will either call that callback

with HTE_TS_DROPPED or HTE_TS_AVAIL. The seq counter gives indirect

view of dropped ts. However, I see the problem with the consumers not

providing callback, in that case, push_ts* API just wakes up process without

indicating why (assuming notify variable is true or else there is a chance for

the thread to block forever). One easy approach I can think of for now is to

make callback mandatory (which is optional right now), I will have to rethink

that scenario and will push corrected version next RFC version.

Thanks for pointing out.

Quoted 6 lines

Which brings me back to the concern I have with the approach used in the hte/gpiolib integration - how do you guarantee that the timestamp returned by gpiod_get_hw_timestamp() corresponds to the irq interrupt being handled, particularly in the face of errors such as:
- overflows of the timestamp FIFO in the chip

I currently do not have any indication mechanism as the providers

I am dealing with right now does not have overflow hardware detection

support. If the chip supports, it should be easy to integrate that feature.

I will provide some hook function or change in push_* API to accommodate

this in next version of RFC.

Quoted 1 line

- overflows of software FIFOs as here

HTE core records sequence counter as well it callsback the consumer with

HTE_TS_DROPPED.

Quoted 2 lines

- lost interupts (if the hw generates interrupts faster than the CPU can service them)

For this, I have no idea unless hardware supports some sort of mechanism

to catch that. For the current providers, as soon as it detects changes on lines

it captures TS in its hw fifo. Its interrupt gets generated based on threshold

set in that hw fifo. This interrupt is different than the lines of actual device

that is why I said I have no idea how we can tackle that. Let me know if there

is any idea or reference of the codes which does tackle this.

Regarding HTE/GPIOLIB integration comment:

You are right, currently, I have only tsc field returned from struct hte_ts_data

to gpiolib. If I can extend that to return hte_ts_data structure which has seq

counter, which I believe can be used to track the overflow situation. The

dropped scenario can be easily tracked if gpiolib can be notified with above

mentioned DROP event through callback. If that is the case, is it ok to have

some sort of callback per gpio in gpiolib?

Any idea how I can integrate callback notification with gpiolib if you do not agree on

above callback suggestion?

Quoted 5 lines

?

Cheers,
Kent.

author maintainer
#22 lore raw

Re: [RFC 03/11] hte: Add tegra194 HTE kernel provider

Quoted 207 lines · Dipen Patel

Thanks Kent for the review comment. My responses inline.

Quoted 141 lines · Kent Gibson
Quoted 102 lines · Dipen Patel

Tegra194 device has multiple HTE instances also known as GTE (Generic hardware Timestamping Engine) which can timestamp subset of SoC lines/signals. This provider driver focuses on IRQ and GPIO lines and exposes timestamping ability on those lines to the consumers through HTE subsystem.

Also, with this patch, added:
- documentation about this provider and its capabilities at Documentation/hte.
- Compilation support in Makefile and Kconfig

---
 Documentation/hte/index.rst        |  21 ++
 Documentation/hte/tegra194-hte.rst |  65 ++++
 Documentation/index.rst            |   1 +
 drivers/hte/Kconfig                |  12 +
 drivers/hte/Makefile               |   1 +
 drivers/hte/hte-tegra194.c         | 554 +++++++++++++++++++++++++++++
 6 files changed, 654 insertions(+)
 create mode 100644 Documentation/hte/index.rst
 create mode 100644 Documentation/hte/tegra194-hte.rst
 create mode 100644 drivers/hte/hte-tegra194.c
Documentation/hte/index.rst new file +21 -0
new file mode 100644
index 000000000000..f311ebec6b47
@@ -0,0 +1,21 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+The HTE Subsystem
+=================
+
+.. toctree::
+   :maxdepth: 1
+
+   hte
+
+HTE Tegra Provider
+==================
+
+.. toctree::
+   :maxdepth: 1
+
+   tegra194-hte
\ No newline at end of file
Documentation/hte/tegra194-hte.rst new file +44 -0
new file mode 100644
index 000000000000..c23eaafcf080
@@ -0,0 +1,65 @@
+HTE Kernel provider driver
+==========================
+
+Description
+-----------
+The Nvidia tegra194 chip has many hardware timestamping engine (HTE) instances
+known as generic timestamping engine (GTE). This provider driver implements
+two GTE instances 1) GPIO GTE and 2) IRQ GTE. The both GTEs instances get the
+timestamp from the system counter TSC which has 31.25MHz clock rate, and the
+driver converts clock tick rate to nano seconds before storing it as timestamp
+value.
+
+GPIO GTE
+--------
+
+This GTE instance help timestamps GPIO in real time, for that to happen GPIO
+needs to be configured as input and IRQ needs to ba enabled as well. The only
+always on (AON) gpio controller instance supports timestamping GPIOs in
+realtime and it has 39 GPIO lines. There is also a dependency on AON GPIO
+controller as it requires very specific bits to be set in GPIO config register.
+It in a way creates cyclic dependency between GTE and GPIO controller. The GTE
+GPIO functionality is accessed from the GPIOLIB. It can support both the in
+kernel and userspace consumers. In the later case, requests go through GPIOLIB
+CDEV framework. The below APIs are added in GPIOLIB framework to access HTE
+subsystem and GPIO GTE for in kernel consumers.
+
+.. c:function:: int gpiod_hw_timestamp_control( struct gpio_desc *desc, bool enable )
+
+	To enable HTE on given GPIO line.
+
+.. c:function:: u64 gpiod_get_hw_timestamp( struct gpio_desc *desc, bool block )
+
+	To retrieve hardwre timestamp in nano seconds.
+
+.. c:function:: bool gpiod_is_hw_timestamp_enabled( const struct gpio_desc *desc )
+
+	To query if HTE is enabled on the given GPIO.
+
+There is hte-tegra194-gpio-test.c, located in ``drivers/hte/`` directory, test
+driver which demonstrates above APIs for the Jetson AGX platform. For userspace
+consumers, GPIO_V2_LINE_FLAG_EVENT_CLOCK_HARDWARE flag must be specifed during
+IOCTL calls, refer ``tools/gpio/gpio-event-mon.c``, which returns the timestamp
+in nano second.
+

<snip>

Quoted 36 lines
Documentation/hte/tegra194-hte.rst new file +36 -0
+
+static void tegra_hte_read_fifo(struct tegra_hte_soc *gs)
+{
+	u32 tsh, tsl, src, pv, cv, acv, slice, bit_index, line_id;
+	u64 tsc;
+	int dir;
+	struct hte_ts_data el;
+
+	while ((tegra_hte_readl(gs, HTE_TESTATUS) >>
+		HTE_TESTATUS_OCCUPANCY_SHIFT) &
+		HTE_TESTATUS_OCCUPANCY_MASK) {
+		tsh = tegra_hte_readl(gs, HTE_TETSCH);
+		tsl = tegra_hte_readl(gs, HTE_TETSCL);
+		tsc = (((u64)tsh << 32) | tsl);
+
+		src = tegra_hte_readl(gs, HTE_TESRC);
+		slice = (src >> HTE_TESRC_SLICE_SHIFT) &
+			    HTE_TESRC_SLICE_DEFAULT_MASK;
+
+		pv = tegra_hte_readl(gs, HTE_TEPCV);
+		cv = tegra_hte_readl(gs, HTE_TECCV);
+		acv = pv ^ cv;
+		while (acv) {
+			bit_index = __builtin_ctz(acv);
+			if ((pv >> bit_index) & BIT(0))
+				dir = HTE_EVENT_RISING_EDGE;
+			else
+				dir = HTE_EVENT_FALLING_EDGE;
+
+			line_id = bit_index + (slice << 5);
+			el.dir = dir;
+			el.tsc = tsc << HTE_TS_NS_SHIFT;
+			hte_push_ts_ns_atomic(gs->chip, line_id, &el,
+					      sizeof(el));
+			acv &= ~BIT(bit_index);
+		}
Quoted 8 lines

Documentation/hte/tegra194-hte.rst

Quoted 3 lines
Documentation/hte/tegra194-hte.rst new file +3 -0
+		tegra_hte_writel(gs, HTE_TECMD, HTE_TECMD_CMD_POP);
+	}
+}

What happens when the hte_push_ts_ns_atomic() fails?
The timestamp will be quietly dropped?
What happens when the interrupt corresponding to that dropped timestamp asks for it? The irq handler thread will block until it can get a timestamp from the subsequent interrupt?

Two things happen, 1) at the push, HTE core increments seq counter

2) If the consumer has provided callback, it will either call that callback

with HTE_TS_DROPPED or HTE_TS_AVAIL. The seq counter gives indirect

view of dropped ts. However, I see the problem with the consumers not

providing callback, in that case, push_ts* API just wakes up process without

indicating why (assuming notify variable is true or else there is a chance for

the thread to block forever). One easy approach I can think of for now is to

make callback mandatory (which is optional right now), I will have to rethink

that scenario and will push corrected version next RFC version.

Thanks for pointing out.

Quoted 5 lines

Which brings me back to the concern I have with the approach used in the hte/gpiolib integration - how do you guarantee that the timestamp returned by gpiod_get_hw_timestamp() corresponds to the irq interrupt being handled, particularly in the face of errors such as:
- overflows of the timestamp FIFO in the chip

I currently do not have any indication mechanism as the providers

I am dealing with right now does not have overflow hardware detection

support. If the chip supports, it should be easy to integrate that feature.

I will provide some hook function or change in push_* API to accommodate

this in next version of RFC.

Quoted 1 line

- overflows of software FIFOs as here

HTE core records sequence counter as well it callsback the consumer with

HTE_TS_DROPPED.

Quoted 2 lines

- lost interupts (if the hw generates interrupts faster than the CPU can service them)

For this, I have no idea unless hardware supports some sort of mechanism

to catch that. For the current providers, as soon as it detects changes on lines

it captures TS in its hw fifo. Its interrupt gets generated based on threshold

set in that hw fifo. This interrupt is different than the lines of actual device

that is why I said I have no idea how we can tackle that. Let me know if there

is any idea or reference of the codes which does tackle this.

Quoted 7 lines

Regarding HTE/GPIOLIB integration comment:

You are right, currently, I have only tsc field returned from struct hte_ts_data

to gpiolib. If I can extend that to return hte_ts_data structure which has seq

counter, which I believe can be used to track the overflow situation. The

The reason I only return timestamp and not other details like its seq

counter, is because to comply with line_event_timestamp since it returns

only u64. Not sure which is the best way to extend and bring out its seq.

Quoted 17 lines

dropped scenario can be easily tracked if gpiolib can be notified with above

mentioned DROP event through callback. If that is the case, is it ok to have

some sort of callback per gpio in gpiolib?

Any idea how I can integrate callback notification with gpiolib if you do not agree on

above callback suggestion?

Quoted 5 lines

?

Cheers,
Kent.

reviewer
#23 lore raw

Re: [RFC 03/11] hte: Add tegra194 HTE kernel provider

In reply to Dipen Patel
Quoted 165 lines · Dipen Patel

Thanks Kent for the review comment. My responses inline.

Quoted 141 lines · Kent Gibson
Quoted 102 lines · Dipen Patel

Tegra194 device has multiple HTE instances also known as GTE (Generic hardware Timestamping Engine) which can timestamp subset of SoC lines/signals. This provider driver focuses on IRQ and GPIO lines and exposes timestamping ability on those lines to the consumers through HTE subsystem.

Also, with this patch, added:
- documentation about this provider and its capabilities at Documentation/hte.
- Compilation support in Makefile and Kconfig

---
 Documentation/hte/index.rst        |  21 ++
 Documentation/hte/tegra194-hte.rst |  65 ++++
 Documentation/index.rst            |   1 +
 drivers/hte/Kconfig                |  12 +
 drivers/hte/Makefile               |   1 +
 drivers/hte/hte-tegra194.c         | 554 +++++++++++++++++++++++++++++
 6 files changed, 654 insertions(+)
 create mode 100644 Documentation/hte/index.rst
 create mode 100644 Documentation/hte/tegra194-hte.rst
 create mode 100644 drivers/hte/hte-tegra194.c
Documentation/hte/index.rst new file +21 -0
new file mode 100644
index 000000000000..f311ebec6b47
@@ -0,0 +1,21 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+The HTE Subsystem
+=================
+
+.. toctree::
+   :maxdepth: 1
+
+   hte
+
+HTE Tegra Provider
+==================
+
+.. toctree::
+   :maxdepth: 1
+
+   tegra194-hte
\ No newline at end of file
Documentation/hte/tegra194-hte.rst new file +44 -0
new file mode 100644
index 000000000000..c23eaafcf080
@@ -0,0 +1,65 @@
+HTE Kernel provider driver
+==========================
+
+Description
+-----------
+The Nvidia tegra194 chip has many hardware timestamping engine (HTE) instances
+known as generic timestamping engine (GTE). This provider driver implements
+two GTE instances 1) GPIO GTE and 2) IRQ GTE. The both GTEs instances get the
+timestamp from the system counter TSC which has 31.25MHz clock rate, and the
+driver converts clock tick rate to nano seconds before storing it as timestamp
+value.
+
+GPIO GTE
+--------
+
+This GTE instance help timestamps GPIO in real time, for that to happen GPIO
+needs to be configured as input and IRQ needs to ba enabled as well. The only
+always on (AON) gpio controller instance supports timestamping GPIOs in
+realtime and it has 39 GPIO lines. There is also a dependency on AON GPIO
+controller as it requires very specific bits to be set in GPIO config register.
+It in a way creates cyclic dependency between GTE and GPIO controller. The GTE
+GPIO functionality is accessed from the GPIOLIB. It can support both the in
+kernel and userspace consumers. In the later case, requests go through GPIOLIB
+CDEV framework. The below APIs are added in GPIOLIB framework to access HTE
+subsystem and GPIO GTE for in kernel consumers.
+
+.. c:function:: int gpiod_hw_timestamp_control( struct gpio_desc *desc, bool enable )
+
+	To enable HTE on given GPIO line.
+
+.. c:function:: u64 gpiod_get_hw_timestamp( struct gpio_desc *desc, bool block )
+
+	To retrieve hardwre timestamp in nano seconds.
+
+.. c:function:: bool gpiod_is_hw_timestamp_enabled( const struct gpio_desc *desc )
+
+	To query if HTE is enabled on the given GPIO.
+
+There is hte-tegra194-gpio-test.c, located in ``drivers/hte/`` directory, test
+driver which demonstrates above APIs for the Jetson AGX platform. For userspace
+consumers, GPIO_V2_LINE_FLAG_EVENT_CLOCK_HARDWARE flag must be specifed during
+IOCTL calls, refer ``tools/gpio/gpio-event-mon.c``, which returns the timestamp
+in nano second.
+

<snip>

Quoted 36 lines
Documentation/hte/tegra194-hte.rst new file +36 -0
+
+static void tegra_hte_read_fifo(struct tegra_hte_soc *gs)
+{
+	u32 tsh, tsl, src, pv, cv, acv, slice, bit_index, line_id;
+	u64 tsc;
+	int dir;
+	struct hte_ts_data el;
+
+	while ((tegra_hte_readl(gs, HTE_TESTATUS) >>
+		HTE_TESTATUS_OCCUPANCY_SHIFT) &
+		HTE_TESTATUS_OCCUPANCY_MASK) {
+		tsh = tegra_hte_readl(gs, HTE_TETSCH);
+		tsl = tegra_hte_readl(gs, HTE_TETSCL);
+		tsc = (((u64)tsh << 32) | tsl);
+
+		src = tegra_hte_readl(gs, HTE_TESRC);
+		slice = (src >> HTE_TESRC_SLICE_SHIFT) &
+			    HTE_TESRC_SLICE_DEFAULT_MASK;
+
+		pv = tegra_hte_readl(gs, HTE_TEPCV);
+		cv = tegra_hte_readl(gs, HTE_TECCV);
+		acv = pv ^ cv;
+		while (acv) {
+			bit_index = __builtin_ctz(acv);
+			if ((pv >> bit_index) & BIT(0))
+				dir = HTE_EVENT_RISING_EDGE;
+			else
+				dir = HTE_EVENT_FALLING_EDGE;
+
+			line_id = bit_index + (slice << 5);
+			el.dir = dir;
+			el.tsc = tsc << HTE_TS_NS_SHIFT;
+			hte_push_ts_ns_atomic(gs->chip, line_id, &el,
+					      sizeof(el));
+			acv &= ~BIT(bit_index);
+		}
Quoted 8 lines

Documentation/hte/tegra194-hte.rst

Quoted 3 lines
Documentation/hte/tegra194-hte.rst new file +3 -0
+		tegra_hte_writel(gs, HTE_TECMD, HTE_TECMD_CMD_POP);
+	}
+}

What happens when the hte_push_ts_ns_atomic() fails?
The timestamp will be quietly dropped?
What happens when the interrupt corresponding to that dropped timestamp asks for it? The irq handler thread will block until it can get a timestamp from the subsequent interrupt?

Two things happen, 1) at the push, HTE core increments seq counter

2) If the consumer has provided callback, it will either call that callback

with HTE_TS_DROPPED or HTE_TS_AVAIL. The seq counter gives indirect

view of dropped ts. However, I see the problem with the consumers not

providing callback, in that case, push_ts* API just wakes up process without

indicating why (assuming notify variable is true or else there is a chance for

Quoted 8 lines

the thread to block forever). One easy approach I can think of for now is to

make callback mandatory (which is optional right now), I will have to rethink

that scenario and will push corrected version next RFC version.

Thanks for pointing out.

I'm not sure you understood my question, which was intended to demonstrate how an overflow here would break your gpio integration, but I am certain that I don't understand your answer.

Using the callback to signal fifo overflow to the consumer is crazy. If the consumer is too busy to service the fifo then they probably wont be prepared to deal with the callback either. And the primary purpose of the fifo is to decouple the producer and consumer, so requiring a callback defeats the whole purpose of having the fifo there in the first place.

Quoted 30 lines
Quoted 6 lines

Which brings me back to the concern I have with the approach used in the hte/gpiolib integration - how do you guarantee that the timestamp returned by gpiod_get_hw_timestamp() corresponds to the irq interrupt being handled, particularly in the face of errors such as:
- overflows of the timestamp FIFO in the chip

I currently do not have any indication mechanism as the providers

I am dealing with right now does not have overflow hardware detection

support. If the chip supports, it should be easy to integrate that feature.

I will provide some hook function or change in push_* API to accommodate

this in next version of RFC.

Quoted 1 line

- overflows of software FIFOs as here

HTE core records sequence counter as well it callsback the consumer with

HTE_TS_DROPPED.

Quoted 2 lines

- lost interupts (if the hw generates interrupts faster than the CPU can service them)

For this, I have no idea unless hardware supports some sort of mechanism

to catch that. For the current providers, as soon as it detects changes on lines

Quoted 8 lines

it captures TS in its hw fifo. Its interrupt gets generated based on threshold

set in that hw fifo. This interrupt is different than the lines of actual device

that is why I said I have no idea how we can tackle that. Let me know if there

is any idea or reference of the codes which does tackle this.

As far as I am aware there is no solution, given your suggested architecture.

Your architecture is inherently fragile, as you try to use one stream of data (the timestamp fifo) to provide supplementary info for another (the physical irq). Guaranteeing that the two are synchronised is impossible - even if you can get them synced at some point, they can fall out of sync without any indication.
That is a recipe for Ingenuity flight 6.

My solution would be to use the hte timestamp fifo as the event source, rather than the physical irq. With only one event source the synchronisation problem disappears. As to how to implement that, gpiolib-cdev would request a line from the hte subsystem and register and event handler for it, much as it does currently with the irq subsystem. That event handler would translate the hte events into gpio events.

You still have to deal with possible fifo overflows, but if the fifo overflows result in discarding the oldest event, rather than the most recent, then everything comes out in the wash. If not then the final event in a burst may not correspond to the actual state so you need some additional mechanism to address that.
Either way the consumer needs to be aware that events may be lost - but with the event seqno for consumers to detect those lost events we already have that covered.

Quoted 7 lines

Regarding HTE/GPIOLIB integration comment:

You are right, currently, I have only tsc field returned from struct hte_ts_data

to gpiolib. If I can extend that to return hte_ts_data structure which has seq

Quoted 8 lines

counter, which I believe can be used to track the overflow situation. The

dropped scenario can be easily tracked if gpiolib can be notified with above

mentioned DROP event through callback. If that is the case, is it ok to have

some sort of callback per gpio in gpiolib?

Even better if you can provide the whole struct hte_ts_data so we have the direction as well (assuming all hte providers provide direction?). Otherwise gpiolib-cdev may need to read the physical line state and that may have changed since the hardware captured the event.
In the solution I outlined above, the hte_ts_data would be provided to the event handler registered by gpiolib-cdev.
And in this case you could skip buffering the event in hte - it could be passed to the event handler as soon as it is read from the hardware - gpiolib-cdev does its own buffering of gpio events.

Quoted 5 lines

Any idea how I can integrate callback notification with gpiolib if you do not agree on

above callback suggestion?

See above. But this is just my take, so I would get feedback from the relevant maintainers or SMEs before you act on anything suggested above.

Cheers,
Kent.

author maintainer
#24 lore raw

Re: [RFC 03/11] hte: Add tegra194 HTE kernel provider

Quoted 227 lines · Kent Gibson
Quoted 164 lines · Dipen Patel

Thanks Kent for the review comment. My responses inline.

Quoted 141 lines · Kent Gibson
Quoted 102 lines · Dipen Patel

Tegra194 device has multiple HTE instances also known as GTE (Generic hardware Timestamping Engine) which can timestamp subset of SoC lines/signals. This provider driver focuses on IRQ and GPIO lines and exposes timestamping ability on those lines to the consumers through HTE subsystem.

Also, with this patch, added:
- documentation about this provider and its capabilities at Documentation/hte.
- Compilation support in Makefile and Kconfig

---
 Documentation/hte/index.rst        |  21 ++
 Documentation/hte/tegra194-hte.rst |  65 ++++
 Documentation/index.rst            |   1 +
 drivers/hte/Kconfig                |  12 +
 drivers/hte/Makefile               |   1 +
 drivers/hte/hte-tegra194.c         | 554 +++++++++++++++++++++++++++++
 6 files changed, 654 insertions(+)
 create mode 100644 Documentation/hte/index.rst
 create mode 100644 Documentation/hte/tegra194-hte.rst
 create mode 100644 drivers/hte/hte-tegra194.c
Documentation/hte/index.rst new file +21 -0
new file mode 100644
index 000000000000..f311ebec6b47
@@ -0,0 +1,21 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+The HTE Subsystem
+=================
+
+.. toctree::
+   :maxdepth: 1
+
+   hte
+
+HTE Tegra Provider
+==================
+
+.. toctree::
+   :maxdepth: 1
+
+   tegra194-hte
\ No newline at end of file
Documentation/hte/tegra194-hte.rst new file +44 -0
new file mode 100644
index 000000000000..c23eaafcf080
@@ -0,0 +1,65 @@
+HTE Kernel provider driver
+==========================
+
+Description
+-----------
+The Nvidia tegra194 chip has many hardware timestamping engine (HTE) instances
+known as generic timestamping engine (GTE). This provider driver implements
+two GTE instances 1) GPIO GTE and 2) IRQ GTE. The both GTEs instances get the
+timestamp from the system counter TSC which has 31.25MHz clock rate, and the
+driver converts clock tick rate to nano seconds before storing it as timestamp
+value.
+
+GPIO GTE
+--------
+
+This GTE instance help timestamps GPIO in real time, for that to happen GPIO
+needs to be configured as input and IRQ needs to ba enabled as well. The only
+always on (AON) gpio controller instance supports timestamping GPIOs in
+realtime and it has 39 GPIO lines. There is also a dependency on AON GPIO
+controller as it requires very specific bits to be set in GPIO config register.
+It in a way creates cyclic dependency between GTE and GPIO controller. The GTE
+GPIO functionality is accessed from the GPIOLIB. It can support both the in
+kernel and userspace consumers. In the later case, requests go through GPIOLIB
+CDEV framework. The below APIs are added in GPIOLIB framework to access HTE
+subsystem and GPIO GTE for in kernel consumers.
+
+.. c:function:: int gpiod_hw_timestamp_control( struct gpio_desc *desc, bool enable )
+
+	To enable HTE on given GPIO line.
+
+.. c:function:: u64 gpiod_get_hw_timestamp( struct gpio_desc *desc, bool block )
+
+	To retrieve hardwre timestamp in nano seconds.
+
+.. c:function:: bool gpiod_is_hw_timestamp_enabled( const struct gpio_desc *desc )
+
+	To query if HTE is enabled on the given GPIO.
+
+There is hte-tegra194-gpio-test.c, located in ``drivers/hte/`` directory, test
+driver which demonstrates above APIs for the Jetson AGX platform. For userspace
+consumers, GPIO_V2_LINE_FLAG_EVENT_CLOCK_HARDWARE flag must be specifed during
+IOCTL calls, refer ``tools/gpio/gpio-event-mon.c``, which returns the timestamp
+in nano second.
+

<snip>

Quoted 36 lines
Documentation/hte/tegra194-hte.rst new file +36 -0
+
+static void tegra_hte_read_fifo(struct tegra_hte_soc *gs)
+{
+	u32 tsh, tsl, src, pv, cv, acv, slice, bit_index, line_id;
+	u64 tsc;
+	int dir;
+	struct hte_ts_data el;
+
+	while ((tegra_hte_readl(gs, HTE_TESTATUS) >>
+		HTE_TESTATUS_OCCUPANCY_SHIFT) &
+		HTE_TESTATUS_OCCUPANCY_MASK) {
+		tsh = tegra_hte_readl(gs, HTE_TETSCH);
+		tsl = tegra_hte_readl(gs, HTE_TETSCL);
+		tsc = (((u64)tsh << 32) | tsl);
+
+		src = tegra_hte_readl(gs, HTE_TESRC);
+		slice = (src >> HTE_TESRC_SLICE_SHIFT) &
+			    HTE_TESRC_SLICE_DEFAULT_MASK;
+
+		pv = tegra_hte_readl(gs, HTE_TEPCV);
+		cv = tegra_hte_readl(gs, HTE_TECCV);
+		acv = pv ^ cv;
+		while (acv) {
+			bit_index = __builtin_ctz(acv);
+			if ((pv >> bit_index) & BIT(0))
+				dir = HTE_EVENT_RISING_EDGE;
+			else
+				dir = HTE_EVENT_FALLING_EDGE;
+
+			line_id = bit_index + (slice << 5);
+			el.dir = dir;
+			el.tsc = tsc << HTE_TS_NS_SHIFT;
+			hte_push_ts_ns_atomic(gs->chip, line_id, &el,
+					      sizeof(el));
+			acv &= ~BIT(bit_index);
+		}
Quoted 8 lines

Documentation/hte/tegra194-hte.rst

Quoted 3 lines
Documentation/hte/tegra194-hte.rst new file +3 -0
+		tegra_hte_writel(gs, HTE_TECMD, HTE_TECMD_CMD_POP);
+	}
+}

What happens when the hte_push_ts_ns_atomic() fails?
The timestamp will be quietly dropped?
What happens when the interrupt corresponding to that dropped timestamp asks for it? The irq handler thread will block until it can get a timestamp from the subsequent interrupt?

Two things happen, 1) at the push, HTE core increments seq counter

2) If the consumer has provided callback, it will either call that callback

with HTE_TS_DROPPED or HTE_TS_AVAIL. The seq counter gives indirect

view of dropped ts. However, I see the problem with the consumers not

providing callback, in that case, push_ts* API just wakes up process without

indicating why (assuming notify variable is true or else there is a chance for

Quoted 8 lines

the thread to block forever). One easy approach I can think of for now is to

make callback mandatory (which is optional right now), I will have to rethink

that scenario and will push corrected version next RFC version.

Thanks for pointing out.

I'm not sure you understood my question, which was intended to demonstrate how an overflow here would break your gpio integration, but I am certain that I don't understand your answer.

Using the callback to signal fifo overflow to the consumer is crazy. If the consumer is too busy to service the fifo then they probably wont be prepared to deal with the callback either. And the primary purpose of the fifo is to decouple the producer and consumer, so requiring a callback defeats the whole purpose of having the fifo there in the first place.

Quoted 26 lines
Quoted 5 lines

Which brings me back to the concern I have with the approach used in the hte/gpiolib integration - how do you guarantee that the timestamp returned by gpiod_get_hw_timestamp() corresponds to the irq interrupt being handled, particularly in the face of errors such as:
- overflows of the timestamp FIFO in the chip

I currently do not have any indication mechanism as the providers

I am dealing with right now does not have overflow hardware detection

support. If the chip supports, it should be easy to integrate that feature.

I will provide some hook function or change in push_* API to accommodate

this in next version of RFC.

Quoted 1 line

- overflows of software FIFOs as here

HTE core records sequence counter as well it callsback the consumer with

HTE_TS_DROPPED.

Quoted 2 lines

- lost interupts (if the hw generates interrupts faster than the CPU can service them)

For this, I have no idea unless hardware supports some sort of mechanism

to catch that. For the current providers, as soon as it detects changes on lines

Quoted 8 lines

it captures TS in its hw fifo. Its interrupt gets generated based on threshold

set in that hw fifo. This interrupt is different than the lines of actual device

that is why I said I have no idea how we can tackle that. Let me know if there

is any idea or reference of the codes which does tackle this.

As far as I am aware there is no solution, given your suggested architecture.

Your architecture is inherently fragile, as you try to use one stream of data (the timestamp fifo) to provide supplementary info for another (the physical irq). Guaranteeing that the two are synchronised is impossible - even if you can get them synced at some point, they can fall out of sync without any indication.
That is a recipe for Ingenuity flight 6.

Quoted 6 lines

My solution would be to use the hte timestamp fifo as the event source, rather than the physical irq. With only one event source the synchronisation problem disappears. As to how to implement that, gpiolib-cdev would request a line from the hte subsystem and register and event handler for it, much as it does currently with the irq subsystem.

Regarding "

much as it does currently with the irq
subsystem

" Statment, do you mean edge_irq_handler?

Quoted 24 lines

That event handler would translate the hte events into gpio events.

You still have to deal with possible fifo overflows, but if the fifo overflows result in discarding the oldest event, rather than the most recent, then everything comes out in the wash. If not then the final event in a burst may not correspond to the actual state so you need some additional mechanism to address that.
Either way the consumer needs to be aware that events may be lost - but with the event seqno for consumers to detect those lost events we already have that covered.

Quoted 12 lines

Regarding HTE/GPIOLIB integration comment:

You are right, currently, I have only tsc field returned from struct hte_ts_data

to gpiolib. If I can extend that to return hte_ts_data structure which has seq

counter, which I believe can be used to track the overflow situation. The

dropped scenario can be easily tracked if gpiolib can be notified with above

mentioned DROP event through callback. If that is the case, is it ok to have

Quoted 8 lines
Quoted 2 lines

some sort of callback per gpio in gpiolib?

Even better if you can provide the whole struct hte_ts_data so we have the direction as well (assuming all hte providers provide direction?). Otherwise gpiolib-cdev may need to read the physical line state and that may have changed since the hardware captured the event.
In the solution I outlined above, the hte_ts_data would be provided to the event handler registered by gpiolib-cdev.

How is this event handler different then cdev providing callback to

hte core? I am guessing even cdev registers event handler with HTE

it is some sort of function  pointer so does callbacks.

Quoted 14 lines

And in this case you could skip buffering the event in hte - it could be passed to the event handler as soon as it is read from the hardware - gpiolib-cdev does its own buffering of gpio events.

Quoted 4 lines

Any idea how I can integrate callback notification with gpiolib if you do not agree on

above callback suggestion?

See above. But this is just my take, so I would get feedback from the relevant maintainers or SMEs before you act on anything suggested above.

Cheers,
Kent.

reviewer
#25 lore raw

Re: [RFC 03/11] hte: Add tegra194 HTE kernel provider

Quoted 235 lines · Dipen Patel
Quoted 227 lines · Kent Gibson
Quoted 164 lines · Dipen Patel

Thanks Kent for the review comment. My responses inline.

Quoted 141 lines · Kent Gibson
Quoted 102 lines · Dipen Patel

Tegra194 device has multiple HTE instances also known as GTE (Generic hardware Timestamping Engine) which can timestamp subset of SoC lines/signals. This provider driver focuses on IRQ and GPIO lines and exposes timestamping ability on those lines to the consumers through HTE subsystem.

Also, with this patch, added:
- documentation about this provider and its capabilities at Documentation/hte.
- Compilation support in Makefile and Kconfig

---
 Documentation/hte/index.rst        |  21 ++
 Documentation/hte/tegra194-hte.rst |  65 ++++
 Documentation/index.rst            |   1 +
 drivers/hte/Kconfig                |  12 +
 drivers/hte/Makefile               |   1 +
 drivers/hte/hte-tegra194.c         | 554 +++++++++++++++++++++++++++++
 6 files changed, 654 insertions(+)
 create mode 100644 Documentation/hte/index.rst
 create mode 100644 Documentation/hte/tegra194-hte.rst
 create mode 100644 drivers/hte/hte-tegra194.c
Documentation/hte/index.rst new file +21 -0
new file mode 100644
index 000000000000..f311ebec6b47
@@ -0,0 +1,21 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+The HTE Subsystem
+=================
+
+.. toctree::
+   :maxdepth: 1
+
+   hte
+
+HTE Tegra Provider
+==================
+
+.. toctree::
+   :maxdepth: 1
+
+   tegra194-hte
\ No newline at end of file
Documentation/hte/tegra194-hte.rst new file +44 -0
new file mode 100644
index 000000000000..c23eaafcf080
@@ -0,0 +1,65 @@
+HTE Kernel provider driver
+==========================
+
+Description
+-----------
+The Nvidia tegra194 chip has many hardware timestamping engine (HTE) instances
+known as generic timestamping engine (GTE). This provider driver implements
+two GTE instances 1) GPIO GTE and 2) IRQ GTE. The both GTEs instances get the
+timestamp from the system counter TSC which has 31.25MHz clock rate, and the
+driver converts clock tick rate to nano seconds before storing it as timestamp
+value.
+
+GPIO GTE
+--------
+
+This GTE instance help timestamps GPIO in real time, for that to happen GPIO
+needs to be configured as input and IRQ needs to ba enabled as well. The only
+always on (AON) gpio controller instance supports timestamping GPIOs in
+realtime and it has 39 GPIO lines. There is also a dependency on AON GPIO
+controller as it requires very specific bits to be set in GPIO config register.
+It in a way creates cyclic dependency between GTE and GPIO controller. The GTE
+GPIO functionality is accessed from the GPIOLIB. It can support both the in
+kernel and userspace consumers. In the later case, requests go through GPIOLIB
+CDEV framework. The below APIs are added in GPIOLIB framework to access HTE
+subsystem and GPIO GTE for in kernel consumers.
+
+.. c:function:: int gpiod_hw_timestamp_control( struct gpio_desc *desc, bool enable )
+
+	To enable HTE on given GPIO line.
+
+.. c:function:: u64 gpiod_get_hw_timestamp( struct gpio_desc *desc, bool block )
+
+	To retrieve hardwre timestamp in nano seconds.
+
+.. c:function:: bool gpiod_is_hw_timestamp_enabled( const struct gpio_desc *desc )
+
+	To query if HTE is enabled on the given GPIO.
+
+There is hte-tegra194-gpio-test.c, located in ``drivers/hte/`` directory, test
+driver which demonstrates above APIs for the Jetson AGX platform. For userspace
+consumers, GPIO_V2_LINE_FLAG_EVENT_CLOCK_HARDWARE flag must be specifed during
+IOCTL calls, refer ``tools/gpio/gpio-event-mon.c``, which returns the timestamp
+in nano second.
+

<snip>

Quoted 36 lines
Documentation/hte/tegra194-hte.rst new file +36 -0
+
+static void tegra_hte_read_fifo(struct tegra_hte_soc *gs)
+{
+	u32 tsh, tsl, src, pv, cv, acv, slice, bit_index, line_id;
+	u64 tsc;
+	int dir;
+	struct hte_ts_data el;
+
+	while ((tegra_hte_readl(gs, HTE_TESTATUS) >>
+		HTE_TESTATUS_OCCUPANCY_SHIFT) &
+		HTE_TESTATUS_OCCUPANCY_MASK) {
+		tsh = tegra_hte_readl(gs, HTE_TETSCH);
+		tsl = tegra_hte_readl(gs, HTE_TETSCL);
+		tsc = (((u64)tsh << 32) | tsl);
+
+		src = tegra_hte_readl(gs, HTE_TESRC);
+		slice = (src >> HTE_TESRC_SLICE_SHIFT) &
+			    HTE_TESRC_SLICE_DEFAULT_MASK;
+
+		pv = tegra_hte_readl(gs, HTE_TEPCV);
+		cv = tegra_hte_readl(gs, HTE_TECCV);
+		acv = pv ^ cv;
+		while (acv) {
+			bit_index = __builtin_ctz(acv);
+			if ((pv >> bit_index) & BIT(0))
+				dir = HTE_EVENT_RISING_EDGE;
+			else
+				dir = HTE_EVENT_FALLING_EDGE;
+
+			line_id = bit_index + (slice << 5);
+			el.dir = dir;
+			el.tsc = tsc << HTE_TS_NS_SHIFT;
+			hte_push_ts_ns_atomic(gs->chip, line_id, &el,
+					      sizeof(el));
+			acv &= ~BIT(bit_index);
+		}
Quoted 8 lines

Documentation/hte/tegra194-hte.rst

Quoted 3 lines
Documentation/hte/tegra194-hte.rst new file +3 -0
+		tegra_hte_writel(gs, HTE_TECMD, HTE_TECMD_CMD_POP);
+	}
+}

What happens when the hte_push_ts_ns_atomic() fails?
The timestamp will be quietly dropped?
What happens when the interrupt corresponding to that dropped timestamp asks for it? The irq handler thread will block until it can get a timestamp from the subsequent interrupt?

Two things happen, 1) at the push, HTE core increments seq counter

2) If the consumer has provided callback, it will either call that callback

with HTE_TS_DROPPED or HTE_TS_AVAIL. The seq counter gives indirect

view of dropped ts. However, I see the problem with the consumers not

providing callback, in that case, push_ts* API just wakes up process without

indicating why (assuming notify variable is true or else there is a chance for

Quoted 8 lines

the thread to block forever). One easy approach I can think of for now is to

make callback mandatory (which is optional right now), I will have to rethink

that scenario and will push corrected version next RFC version.

Thanks for pointing out.

I'm not sure you understood my question, which was intended to demonstrate how an overflow here would break your gpio integration, but I am certain that I don't understand your answer.

Using the callback to signal fifo overflow to the consumer is crazy. If the consumer is too busy to service the fifo then they probably wont be prepared to deal with the callback either. And the primary purpose of the fifo is to decouple the producer and consumer, so requiring a callback defeats the whole purpose of having the fifo there in the first place.

Quoted 26 lines
Quoted 5 lines

Which brings me back to the concern I have with the approach used in the hte/gpiolib integration - how do you guarantee that the timestamp returned by gpiod_get_hw_timestamp() corresponds to the irq interrupt being handled, particularly in the face of errors such as:
- overflows of the timestamp FIFO in the chip

I currently do not have any indication mechanism as the providers

I am dealing with right now does not have overflow hardware detection

support. If the chip supports, it should be easy to integrate that feature.

I will provide some hook function or change in push_* API to accommodate

this in next version of RFC.

Quoted 1 line

- overflows of software FIFOs as here

HTE core records sequence counter as well it callsback the consumer with

HTE_TS_DROPPED.

Quoted 2 lines

- lost interupts (if the hw generates interrupts faster than the CPU can service them)

For this, I have no idea unless hardware supports some sort of mechanism

to catch that. For the current providers, as soon as it detects changes on lines

Quoted 8 lines

it captures TS in its hw fifo. Its interrupt gets generated based on threshold

set in that hw fifo. This interrupt is different than the lines of actual device

that is why I said I have no idea how we can tackle that. Let me know if there

is any idea or reference of the codes which does tackle this.

As far as I am aware there is no solution, given your suggested architecture.

Your architecture is inherently fragile, as you try to use one stream of data (the timestamp fifo) to provide supplementary info for another (the physical irq). Guaranteeing that the two are synchronised is impossible - even if you can get them synced at some point, they can fall out of sync without any indication.
That is a recipe for Ingenuity flight 6.

Quoted 6 lines

My solution would be to use the hte timestamp fifo as the event source, rather than the physical irq. With only one event source the synchronisation problem disappears. As to how to implement that, gpiolib-cdev would request a line from the hte subsystem and register and event handler for it, much as it does currently with the irq subsystem.

Quoted 6 lines

Regarding "

much as it does currently with the irq
subsystem

" Statment, do you mean edge_irq_handler?

I mean that style of API. Obviously it would be a new handler function. But it would perform the same as edge_irq_handler and edge_irq_thread, just with a different event source.

Quoted 33 lines
Quoted 24 lines

That event handler would translate the hte events into gpio events.

You still have to deal with possible fifo overflows, but if the fifo overflows result in discarding the oldest event, rather than the most recent, then everything comes out in the wash. If not then the final event in a burst may not correspond to the actual state so you need some additional mechanism to address that.
Either way the consumer needs to be aware that events may be lost - but with the event seqno for consumers to detect those lost events we already have that covered.

Quoted 12 lines

Regarding HTE/GPIOLIB integration comment:

You are right, currently, I have only tsc field returned from struct hte_ts_data

to gpiolib. If I can extend that to return hte_ts_data structure which has seq

counter, which I believe can be used to track the overflow situation. The

dropped scenario can be easily tracked if gpiolib can be notified with above

mentioned DROP event through callback. If that is the case, is it ok to have

Quoted 8 lines
Quoted 2 lines

some sort of callback per gpio in gpiolib?

Even better if you can provide the whole struct hte_ts_data so we have the direction as well (assuming all hte providers provide direction?). Otherwise gpiolib-cdev may need to read the physical line state and that may have changed since the hardware captured the event.
In the solution I outlined above, the hte_ts_data would be provided to the event handler registered by gpiolib-cdev.

Quoted 6 lines

How is this event handler different then cdev providing callback to

hte core? I am guessing even cdev registers event handler with HTE

it is some sort of function  pointer so does callbacks.

If you mean your proposed callbacks, well for starters it wouldn't pass it a DROPPED event.

But other than that registering a handler it essentially a callback. Your existing callback is at interrupt context, right? The irq subsystem also has provision for handling the event at interrupt context or thread context - gpiolib-cdev uses both. You might want to do the same here - depends on what your expected consumers would prefer.

Way back when you initially proposed this I said "this is an irq problem", meaning that it makes sense to me that this should be integrated with irq, and provide functions to return additional detail to the irq handlers, such as the event timestamp.
Not sure what the irq guys think of that - it may be simpler and clearer to provide a separate subsystem.
Either way, a hte subsystem that provides an irq-like API might be a good way to start.

Cheers,
Kent.

author maintainer
#26 lore raw

Re: [RFC 03/11] hte: Add tegra194 HTE kernel provider

In reply to Kent Gibson
Quoted 227 lines · Kent Gibson
Quoted 164 lines · Dipen Patel

Thanks Kent for the review comment. My responses inline.

Quoted 141 lines · Kent Gibson
Quoted 102 lines · Dipen Patel

Tegra194 device has multiple HTE instances also known as GTE (Generic hardware Timestamping Engine) which can timestamp subset of SoC lines/signals. This provider driver focuses on IRQ and GPIO lines and exposes timestamping ability on those lines to the consumers through HTE subsystem.

Also, with this patch, added:
- documentation about this provider and its capabilities at Documentation/hte.
- Compilation support in Makefile and Kconfig

---
 Documentation/hte/index.rst        |  21 ++
 Documentation/hte/tegra194-hte.rst |  65 ++++
 Documentation/index.rst            |   1 +
 drivers/hte/Kconfig                |  12 +
 drivers/hte/Makefile               |   1 +
 drivers/hte/hte-tegra194.c         | 554 +++++++++++++++++++++++++++++
 6 files changed, 654 insertions(+)
 create mode 100644 Documentation/hte/index.rst
 create mode 100644 Documentation/hte/tegra194-hte.rst
 create mode 100644 drivers/hte/hte-tegra194.c
Documentation/hte/index.rst new file +21 -0
new file mode 100644
index 000000000000..f311ebec6b47
@@ -0,0 +1,21 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+The HTE Subsystem
+=================
+
+.. toctree::
+   :maxdepth: 1
+
+   hte
+
+HTE Tegra Provider
+==================
+
+.. toctree::
+   :maxdepth: 1
+
+   tegra194-hte
\ No newline at end of file
Documentation/hte/tegra194-hte.rst new file +44 -0
new file mode 100644
index 000000000000..c23eaafcf080
@@ -0,0 +1,65 @@
+HTE Kernel provider driver
+==========================
+
+Description
+-----------
+The Nvidia tegra194 chip has many hardware timestamping engine (HTE) instances
+known as generic timestamping engine (GTE). This provider driver implements
+two GTE instances 1) GPIO GTE and 2) IRQ GTE. The both GTEs instances get the
+timestamp from the system counter TSC which has 31.25MHz clock rate, and the
+driver converts clock tick rate to nano seconds before storing it as timestamp
+value.
+
+GPIO GTE
+--------
+
+This GTE instance help timestamps GPIO in real time, for that to happen GPIO
+needs to be configured as input and IRQ needs to ba enabled as well. The only
+always on (AON) gpio controller instance supports timestamping GPIOs in
+realtime and it has 39 GPIO lines. There is also a dependency on AON GPIO
+controller as it requires very specific bits to be set in GPIO config register.
+It in a way creates cyclic dependency between GTE and GPIO controller. The GTE
+GPIO functionality is accessed from the GPIOLIB. It can support both the in
+kernel and userspace consumers. In the later case, requests go through GPIOLIB
+CDEV framework. The below APIs are added in GPIOLIB framework to access HTE
+subsystem and GPIO GTE for in kernel consumers.
+
+.. c:function:: int gpiod_hw_timestamp_control( struct gpio_desc *desc, bool enable )
+
+	To enable HTE on given GPIO line.
+
+.. c:function:: u64 gpiod_get_hw_timestamp( struct gpio_desc *desc, bool block )
+
+	To retrieve hardwre timestamp in nano seconds.
+
+.. c:function:: bool gpiod_is_hw_timestamp_enabled( const struct gpio_desc *desc )
+
+	To query if HTE is enabled on the given GPIO.
+
+There is hte-tegra194-gpio-test.c, located in ``drivers/hte/`` directory, test
+driver which demonstrates above APIs for the Jetson AGX platform. For userspace
+consumers, GPIO_V2_LINE_FLAG_EVENT_CLOCK_HARDWARE flag must be specifed during
+IOCTL calls, refer ``tools/gpio/gpio-event-mon.c``, which returns the timestamp
+in nano second.
+

<snip>

Quoted 36 lines
Documentation/hte/tegra194-hte.rst new file +36 -0
+
+static void tegra_hte_read_fifo(struct tegra_hte_soc *gs)
+{
+	u32 tsh, tsl, src, pv, cv, acv, slice, bit_index, line_id;
+	u64 tsc;
+	int dir;
+	struct hte_ts_data el;
+
+	while ((tegra_hte_readl(gs, HTE_TESTATUS) >>
+		HTE_TESTATUS_OCCUPANCY_SHIFT) &
+		HTE_TESTATUS_OCCUPANCY_MASK) {
+		tsh = tegra_hte_readl(gs, HTE_TETSCH);
+		tsl = tegra_hte_readl(gs, HTE_TETSCL);
+		tsc = (((u64)tsh << 32) | tsl);
+
+		src = tegra_hte_readl(gs, HTE_TESRC);
+		slice = (src >> HTE_TESRC_SLICE_SHIFT) &
+			    HTE_TESRC_SLICE_DEFAULT_MASK;
+
+		pv = tegra_hte_readl(gs, HTE_TEPCV);
+		cv = tegra_hte_readl(gs, HTE_TECCV);
+		acv = pv ^ cv;
+		while (acv) {
+			bit_index = __builtin_ctz(acv);
+			if ((pv >> bit_index) & BIT(0))
+				dir = HTE_EVENT_RISING_EDGE;
+			else
+				dir = HTE_EVENT_FALLING_EDGE;
+
+			line_id = bit_index + (slice << 5);
+			el.dir = dir;
+			el.tsc = tsc << HTE_TS_NS_SHIFT;
+			hte_push_ts_ns_atomic(gs->chip, line_id, &el,
+					      sizeof(el));
+			acv &= ~BIT(bit_index);
+		}
Quoted 8 lines

Documentation/hte/tegra194-hte.rst

Quoted 3 lines
Documentation/hte/tegra194-hte.rst new file +3 -0
+		tegra_hte_writel(gs, HTE_TECMD, HTE_TECMD_CMD_POP);
+	}
+}

What happens when the hte_push_ts_ns_atomic() fails?
The timestamp will be quietly dropped?
What happens when the interrupt corresponding to that dropped timestamp asks for it? The irq handler thread will block until it can get a timestamp from the subsequent interrupt?

Two things happen, 1) at the push, HTE core increments seq counter

2) If the consumer has provided callback, it will either call that callback

with HTE_TS_DROPPED or HTE_TS_AVAIL. The seq counter gives indirect

view of dropped ts. However, I see the problem with the consumers not

providing callback, in that case, push_ts* API just wakes up process without

indicating why (assuming notify variable is true or else there is a chance for

Quoted 8 lines

the thread to block forever). One easy approach I can think of for now is to

make callback mandatory (which is optional right now), I will have to rethink

that scenario and will push corrected version next RFC version.

Thanks for pointing out.

I'm not sure you understood my question, which was intended to demonstrate how an overflow here would break your gpio integration, but I am certain that I don't understand your answer.

Using the callback to signal fifo overflow to the consumer is crazy. If the consumer is too busy to service the fifo then they probably wont be prepared to deal with the callback either. And the primary purpose of the fifo is to decouple the producer and consumer, so requiring a callback defeats the whole purpose of having the fifo there in the first place.

Quoted 26 lines
Quoted 5 lines

Which brings me back to the concern I have with the approach used in the hte/gpiolib integration - how do you guarantee that the timestamp returned by gpiod_get_hw_timestamp() corresponds to the irq interrupt being handled, particularly in the face of errors such as:
- overflows of the timestamp FIFO in the chip

I currently do not have any indication mechanism as the providers

I am dealing with right now does not have overflow hardware detection

support. If the chip supports, it should be easy to integrate that feature.

I will provide some hook function or change in push_* API to accommodate

this in next version of RFC.

Quoted 1 line

- overflows of software FIFOs as here

HTE core records sequence counter as well it callsback the consumer with

HTE_TS_DROPPED.

Quoted 2 lines

- lost interupts (if the hw generates interrupts faster than the CPU can service them)

For this, I have no idea unless hardware supports some sort of mechanism

to catch that. For the current providers, as soon as it detects changes on lines

Quoted 8 lines

it captures TS in its hw fifo. Its interrupt gets generated based on threshold

set in that hw fifo. This interrupt is different than the lines of actual device

that is why I said I have no idea how we can tackle that. Let me know if there

is any idea or reference of the codes which does tackle this.

As far as I am aware there is no solution, given your suggested architecture.

Your architecture is inherently fragile, as you try to use one stream of data (the timestamp fifo) to provide supplementary info for another (the physical irq). Guaranteeing that the two are synchronised is impossible - even if you can get them synced at some point, they can fall out of sync without any indication.
That is a recipe for Ingenuity flight 6.

Quoted 7 lines

My solution would be to use the hte timestamp fifo as the event source, rather than the physical irq. With only one event source the synchronisation problem disappears. As to how to implement that, gpiolib-cdev would request a line from the hte subsystem and register and event handler for it, much as it does currently with the irq subsystem. That event handler would translate the hte events into gpio events.

I have to circle back to here regarding the event handler thing. I

surely did not understand fifo as event source rather than physical irq

part? I believe you are suggesting to have somekind of buffer abstraction

layer for the hardware fifo similar to what I have with software buffer and

register handler to that buffer, right?

The current implementation I have (not with gpiolib/HTE integration)

is partially simlar to event handler mechanism except that it does not send data

with it. See hte-tegra194-irq-test.c in this patch.

Coming back to gpiolib/hte integration part and your suggestion about

providing event handler during hte registration. I have below doubts:

1. When HTE calls this provided hte_handler, will it store data into

hte->timestamp_ns directly, I am guessing yes.

2. Does hte handler solution create race between two handlers? i.e. edge_irq_handler and

hte_handler, for the worst case scenario as below?

2.a edge_irq_handler runs first, checks some kind of flag to see if

we are using hardware clock and if yes, directly accesses timestamp_ns

instead of calling line_event_timestamp.

2.b finds timestamp_ns to be invalid since it ran first before hte event handler did.

2.c returns and invokes edge_irq_thread.

2.c.1 Here, should edge_irq_thread wait in cdev till hte handler to be called? If yes,

Doesn't it have case where it will wait forever till hte handler gets called, also not

to mention keeping irq line disabled since IRQF_ONESHOT is specified, could be possible

when provider has gone rogue?

3. I am guessing there will not be dropped event in this suggestion since are

directly sending data without buffering in HTE, that is the good part I believe.

Quoted 9 lines

You still have to deal with possible fifo overflows, but if the fifo overflows result in discarding the oldest event, rather than the most recent, then everything comes out in the wash. If not then the final event in a burst may not correspond to the actual state so you need some additional mechanism to address that.
Either way the consumer needs to be aware that events may be lost - but with the event seqno for consumers to detect those lost events we already have that covered.

Correct (for the seqno part), you already have seqno, cdev does not need

struct hte_ts_data's u64 seq counter.

On similar note, I was looking at the linereq_put_event

function and I have below doubts:

1. IIUC, you are discarding oldest data when fifo is full, right?

2. There is no indication to waiting client if overflow is true beside pr_debug print.

2.a Does this not block waiting client infinitely since there is no wake_up_poll call

in case of overflow == 1?

2.c If I have missed, what current mechanism cdev provides to client beside seqno

to indicate there is a drop and if there is a drop, what it does to re-sync?

Quoted 35 lines
Quoted 7 lines

Regarding HTE/GPIOLIB integration comment:

You are right, currently, I have only tsc field returned from struct hte_ts_data

to gpiolib. If I can extend that to return hte_ts_data structure which has seq

Quoted 8 lines

counter, which I believe can be used to track the overflow situation. The

dropped scenario can be easily tracked if gpiolib can be notified with above

mentioned DROP event through callback. If that is the case, is it ok to have

some sort of callback per gpio in gpiolib?

Even better if you can provide the whole struct hte_ts_data so we have the direction as well (assuming all hte providers provide direction?). Otherwise gpiolib-cdev may need to read the physical line state and that may have changed since the hardware captured the event.
In the solution I outlined above, the hte_ts_data would be provided to the event handler registered by gpiolib-cdev.
And in this case you could skip buffering the event in hte - it could be passed to the event handler as soon as it is read from the hardware - gpiolib-cdev does its own buffering of gpio events.

Quoted 4 lines

Any idea how I can integrate callback notification with gpiolib if you do not agree on

above callback suggestion?

See above. But this is just my take, so I would get feedback from the relevant maintainers or SMEs before you act on anything suggested above.

Cheers,
Kent.

reviewer
#27 lore raw

Re: [RFC 03/11] hte: Add tegra194 HTE kernel provider

Quoted 239 lines · Dipen Patel
Quoted 227 lines · Kent Gibson
Quoted 164 lines · Dipen Patel

Thanks Kent for the review comment. My responses inline.

Quoted 141 lines · Kent Gibson
Quoted 102 lines · Dipen Patel

Tegra194 device has multiple HTE instances also known as GTE (Generic hardware Timestamping Engine) which can timestamp subset of SoC lines/signals. This provider driver focuses on IRQ and GPIO lines and exposes timestamping ability on those lines to the consumers through HTE subsystem.

Also, with this patch, added:
- documentation about this provider and its capabilities at Documentation/hte.
- Compilation support in Makefile and Kconfig

---
 Documentation/hte/index.rst        |  21 ++
 Documentation/hte/tegra194-hte.rst |  65 ++++
 Documentation/index.rst            |   1 +
 drivers/hte/Kconfig                |  12 +
 drivers/hte/Makefile               |   1 +
 drivers/hte/hte-tegra194.c         | 554 +++++++++++++++++++++++++++++
 6 files changed, 654 insertions(+)
 create mode 100644 Documentation/hte/index.rst
 create mode 100644 Documentation/hte/tegra194-hte.rst
 create mode 100644 drivers/hte/hte-tegra194.c
Documentation/hte/index.rst new file +21 -0
new file mode 100644
index 000000000000..f311ebec6b47
@@ -0,0 +1,21 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+The HTE Subsystem
+=================
+
+.. toctree::
+   :maxdepth: 1
+
+   hte
+
+HTE Tegra Provider
+==================
+
+.. toctree::
+   :maxdepth: 1
+
+   tegra194-hte
\ No newline at end of file
Documentation/hte/tegra194-hte.rst new file +44 -0
new file mode 100644
index 000000000000..c23eaafcf080
@@ -0,0 +1,65 @@
+HTE Kernel provider driver
+==========================
+
+Description
+-----------
+The Nvidia tegra194 chip has many hardware timestamping engine (HTE) instances
+known as generic timestamping engine (GTE). This provider driver implements
+two GTE instances 1) GPIO GTE and 2) IRQ GTE. The both GTEs instances get the
+timestamp from the system counter TSC which has 31.25MHz clock rate, and the
+driver converts clock tick rate to nano seconds before storing it as timestamp
+value.
+
+GPIO GTE
+--------
+
+This GTE instance help timestamps GPIO in real time, for that to happen GPIO
+needs to be configured as input and IRQ needs to ba enabled as well. The only
+always on (AON) gpio controller instance supports timestamping GPIOs in
+realtime and it has 39 GPIO lines. There is also a dependency on AON GPIO
+controller as it requires very specific bits to be set in GPIO config register.
+It in a way creates cyclic dependency between GTE and GPIO controller. The GTE
+GPIO functionality is accessed from the GPIOLIB. It can support both the in
+kernel and userspace consumers. In the later case, requests go through GPIOLIB
+CDEV framework. The below APIs are added in GPIOLIB framework to access HTE
+subsystem and GPIO GTE for in kernel consumers.
+
+.. c:function:: int gpiod_hw_timestamp_control( struct gpio_desc *desc, bool enable )
+
+	To enable HTE on given GPIO line.
+
+.. c:function:: u64 gpiod_get_hw_timestamp( struct gpio_desc *desc, bool block )
+
+	To retrieve hardwre timestamp in nano seconds.
+
+.. c:function:: bool gpiod_is_hw_timestamp_enabled( const struct gpio_desc *desc )
+
+	To query if HTE is enabled on the given GPIO.
+
+There is hte-tegra194-gpio-test.c, located in ``drivers/hte/`` directory, test
+driver which demonstrates above APIs for the Jetson AGX platform. For userspace
+consumers, GPIO_V2_LINE_FLAG_EVENT_CLOCK_HARDWARE flag must be specifed during
+IOCTL calls, refer ``tools/gpio/gpio-event-mon.c``, which returns the timestamp
+in nano second.
+

<snip>

Quoted 36 lines
Documentation/hte/tegra194-hte.rst new file +36 -0
+
+static void tegra_hte_read_fifo(struct tegra_hte_soc *gs)
+{
+	u32 tsh, tsl, src, pv, cv, acv, slice, bit_index, line_id;
+	u64 tsc;
+	int dir;
+	struct hte_ts_data el;
+
+	while ((tegra_hte_readl(gs, HTE_TESTATUS) >>
+		HTE_TESTATUS_OCCUPANCY_SHIFT) &
+		HTE_TESTATUS_OCCUPANCY_MASK) {
+		tsh = tegra_hte_readl(gs, HTE_TETSCH);
+		tsl = tegra_hte_readl(gs, HTE_TETSCL);
+		tsc = (((u64)tsh << 32) | tsl);
+
+		src = tegra_hte_readl(gs, HTE_TESRC);
+		slice = (src >> HTE_TESRC_SLICE_SHIFT) &
+			    HTE_TESRC_SLICE_DEFAULT_MASK;
+
+		pv = tegra_hte_readl(gs, HTE_TEPCV);
+		cv = tegra_hte_readl(gs, HTE_TECCV);
+		acv = pv ^ cv;
+		while (acv) {
+			bit_index = __builtin_ctz(acv);
+			if ((pv >> bit_index) & BIT(0))
+				dir = HTE_EVENT_RISING_EDGE;
+			else
+				dir = HTE_EVENT_FALLING_EDGE;
+
+			line_id = bit_index + (slice << 5);
+			el.dir = dir;
+			el.tsc = tsc << HTE_TS_NS_SHIFT;
+			hte_push_ts_ns_atomic(gs->chip, line_id, &el,
+					      sizeof(el));
+			acv &= ~BIT(bit_index);
+		}
Quoted 8 lines

Documentation/hte/tegra194-hte.rst

Quoted 3 lines
Documentation/hte/tegra194-hte.rst new file +3 -0
+		tegra_hte_writel(gs, HTE_TECMD, HTE_TECMD_CMD_POP);
+	}
+}

What happens when the hte_push_ts_ns_atomic() fails?
The timestamp will be quietly dropped?
What happens when the interrupt corresponding to that dropped timestamp asks for it? The irq handler thread will block until it can get a timestamp from the subsequent interrupt?

Two things happen, 1) at the push, HTE core increments seq counter

2) If the consumer has provided callback, it will either call that callback

with HTE_TS_DROPPED or HTE_TS_AVAIL. The seq counter gives indirect

view of dropped ts. However, I see the problem with the consumers not

providing callback, in that case, push_ts* API just wakes up process without

indicating why (assuming notify variable is true or else there is a chance for

Quoted 8 lines

the thread to block forever). One easy approach I can think of for now is to

make callback mandatory (which is optional right now), I will have to rethink

that scenario and will push corrected version next RFC version.

Thanks for pointing out.

I'm not sure you understood my question, which was intended to demonstrate how an overflow here would break your gpio integration, but I am certain that I don't understand your answer.

Using the callback to signal fifo overflow to the consumer is crazy. If the consumer is too busy to service the fifo then they probably wont be prepared to deal with the callback either. And the primary purpose of the fifo is to decouple the producer and consumer, so requiring a callback defeats the whole purpose of having the fifo there in the first place.

Quoted 26 lines
Quoted 5 lines

Which brings me back to the concern I have with the approach used in the hte/gpiolib integration - how do you guarantee that the timestamp returned by gpiod_get_hw_timestamp() corresponds to the irq interrupt being handled, particularly in the face of errors such as:
- overflows of the timestamp FIFO in the chip

I currently do not have any indication mechanism as the providers

I am dealing with right now does not have overflow hardware detection

support. If the chip supports, it should be easy to integrate that feature.

I will provide some hook function or change in push_* API to accommodate

this in next version of RFC.

Quoted 1 line

- overflows of software FIFOs as here

HTE core records sequence counter as well it callsback the consumer with

HTE_TS_DROPPED.

Quoted 2 lines

- lost interupts (if the hw generates interrupts faster than the CPU can service them)

For this, I have no idea unless hardware supports some sort of mechanism

to catch that. For the current providers, as soon as it detects changes on lines

Quoted 8 lines

it captures TS in its hw fifo. Its interrupt gets generated based on threshold

set in that hw fifo. This interrupt is different than the lines of actual device

that is why I said I have no idea how we can tackle that. Let me know if there

is any idea or reference of the codes which does tackle this.

As far as I am aware there is no solution, given your suggested architecture.

Your architecture is inherently fragile, as you try to use one stream of data (the timestamp fifo) to provide supplementary info for another (the physical irq). Guaranteeing that the two are synchronised is impossible - even if you can get them synced at some point, they can fall out of sync without any indication.
That is a recipe for Ingenuity flight 6.

Quoted 7 lines

My solution would be to use the hte timestamp fifo as the event source, rather than the physical irq. With only one event source the synchronisation problem disappears. As to how to implement that, gpiolib-cdev would request a line from the hte subsystem and register and event handler for it, much as it does currently with the irq subsystem. That event handler would translate the hte events into gpio events.

I have to circle back to here regarding the event handler thing. I

Quoted 8 lines

surely did not understand fifo as event source rather than physical irq

part? I believe you are suggesting to have somekind of buffer abstraction

layer for the hardware fifo similar to what I have with software buffer and

register handler to that buffer, right?

No, what is the purpose of that buffering and watermarking in software? Just pass the timestamped edge event direct to the consumer. Let the consumer do any buffering if necessary, as Jonathon Cameron also suggested in the 02/11 thread.

Quoted 8 lines

The current implementation I have (not with gpiolib/HTE integration)

is partially simlar to event handler mechanism except that it does not send data

with it. See hte-tegra194-irq-test.c in this patch.

Quoted 8 lines

Coming back to gpiolib/hte integration part and your suggestion about

providing event handler during hte registration. I have below doubts:

1. When HTE calls this provided hte_handler, will it store data into

hte->timestamp_ns directly, I am guessing yes.

This is implementation detail of the hte/gpiolib interface that I leave for you to suggest. Work something out.

Quoted 4 lines

2. Does hte handler solution create race between two handlers? i.e. edge_irq_handler and

hte_handler, for the worst case scenario as below?

No. If hardware timestamp is selected then no irq is requested from the irq subsystem for that line - only from the hte subsystem instead. So there will be no edge_irq_handler call for that line, so no possible race.

Quoted 35 lines

2.a edge_irq_handler runs first, checks some kind of flag to see if

we are using hardware clock and if yes, directly accesses timestamp_ns

instead of calling line_event_timestamp.

2.b finds timestamp_ns to be invalid since it ran first before hte event handler did.

2.c returns and invokes edge_irq_thread.

2.c.1 Here, should edge_irq_thread wait in cdev till hte handler to be called? If yes,

Doesn't it have case where it will wait forever till hte handler gets called, also not

to mention keeping irq line disabled since IRQF_ONESHOT is specified, could be possible

when provider has gone rogue?

3. I am guessing there will not be dropped event in this suggestion since are

directly sending data without buffering in HTE, that is the good part I believe.

Quoted 9 lines

You still have to deal with possible fifo overflows, but if the fifo overflows result in discarding the oldest event, rather than the most recent, then everything comes out in the wash. If not then the final event in a burst may not correspond to the actual state so you need some additional mechanism to address that.
Either way the consumer needs to be aware that events may be lost - but with the event seqno for consumers to detect those lost events we already have that covered.

Correct (for the seqno part), you already have seqno, cdev does not need

Quoted 9 lines

struct hte_ts_data's u64 seq counter.

On similar note, I was looking at the linereq_put_event

function and I have below doubts:

1. IIUC, you are discarding oldest data when fifo is full, right?

Correct.

Quoted 6 lines

2. There is no indication to waiting client if overflow is true beside pr_debug print.

2.a Does this not block waiting client infinitely since there is no wake_up_poll call

in case of overflow == 1?

No - there already was a wake_up_poll call for the entry discarded by the kfifo_skip().

You dropped 2.b intentionally, right? Buffer overflow perhaps??

Quoted 4 lines

2.c If I have missed, what current mechanism cdev provides to client beside seqno

to indicate there is a drop and if there is a drop, what it does to re-sync?

Just seqno. Overflows in the cdev event buffer discard the oldest events, so the final event that the client reads will correspond to current state. There is an event waiting for the client that, due to the seqno jump, indicates the overflow. What else do they need? And what is there to resync?

Not sorry if I'm getting short with you here - I'm getting really tired of this subject as we're clearly not communicating well and are repeatedly covering the same ground.

Cheers,
Kent.

author maintainer
#28 lore raw

Re: [RFC 03/11] hte: Add tegra194 HTE kernel provider

Quoted 269 lines · Kent Gibson
Quoted 237 lines · Dipen Patel
Quoted 227 lines · Kent Gibson
Quoted 164 lines · Dipen Patel

Thanks Kent for the review comment. My responses inline.

Quoted 141 lines · Kent Gibson
Quoted 102 lines · Dipen Patel

Tegra194 device has multiple HTE instances also known as GTE (Generic hardware Timestamping Engine) which can timestamp subset of SoC lines/signals. This provider driver focuses on IRQ and GPIO lines and exposes timestamping ability on those lines to the consumers through HTE subsystem.

Also, with this patch, added:
- documentation about this provider and its capabilities at Documentation/hte.
- Compilation support in Makefile and Kconfig

---
 Documentation/hte/index.rst        |  21 ++
 Documentation/hte/tegra194-hte.rst |  65 ++++
 Documentation/index.rst            |   1 +
 drivers/hte/Kconfig                |  12 +
 drivers/hte/Makefile               |   1 +
 drivers/hte/hte-tegra194.c         | 554 +++++++++++++++++++++++++++++
 6 files changed, 654 insertions(+)
 create mode 100644 Documentation/hte/index.rst
 create mode 100644 Documentation/hte/tegra194-hte.rst
 create mode 100644 drivers/hte/hte-tegra194.c
Documentation/hte/index.rst new file +21 -0
new file mode 100644
index 000000000000..f311ebec6b47
@@ -0,0 +1,21 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+The HTE Subsystem
+=================
+
+.. toctree::
+   :maxdepth: 1
+
+   hte
+
+HTE Tegra Provider
+==================
+
+.. toctree::
+   :maxdepth: 1
+
+   tegra194-hte
\ No newline at end of file
Documentation/hte/tegra194-hte.rst new file +44 -0
new file mode 100644
index 000000000000..c23eaafcf080
@@ -0,0 +1,65 @@
+HTE Kernel provider driver
+==========================
+
+Description
+-----------
+The Nvidia tegra194 chip has many hardware timestamping engine (HTE) instances
+known as generic timestamping engine (GTE). This provider driver implements
+two GTE instances 1) GPIO GTE and 2) IRQ GTE. The both GTEs instances get the
+timestamp from the system counter TSC which has 31.25MHz clock rate, and the
+driver converts clock tick rate to nano seconds before storing it as timestamp
+value.
+
+GPIO GTE
+--------
+
+This GTE instance help timestamps GPIO in real time, for that to happen GPIO
+needs to be configured as input and IRQ needs to ba enabled as well. The only
+always on (AON) gpio controller instance supports timestamping GPIOs in
+realtime and it has 39 GPIO lines. There is also a dependency on AON GPIO
+controller as it requires very specific bits to be set in GPIO config register.
+It in a way creates cyclic dependency between GTE and GPIO controller. The GTE
+GPIO functionality is accessed from the GPIOLIB. It can support both the in
+kernel and userspace consumers. In the later case, requests go through GPIOLIB
+CDEV framework. The below APIs are added in GPIOLIB framework to access HTE
+subsystem and GPIO GTE for in kernel consumers.
+
+.. c:function:: int gpiod_hw_timestamp_control( struct gpio_desc *desc, bool enable )
+
+	To enable HTE on given GPIO line.
+
+.. c:function:: u64 gpiod_get_hw_timestamp( struct gpio_desc *desc, bool block )
+
+	To retrieve hardwre timestamp in nano seconds.
+
+.. c:function:: bool gpiod_is_hw_timestamp_enabled( const struct gpio_desc *desc )
+
+	To query if HTE is enabled on the given GPIO.
+
+There is hte-tegra194-gpio-test.c, located in ``drivers/hte/`` directory, test
+driver which demonstrates above APIs for the Jetson AGX platform. For userspace
+consumers, GPIO_V2_LINE_FLAG_EVENT_CLOCK_HARDWARE flag must be specifed during
+IOCTL calls, refer ``tools/gpio/gpio-event-mon.c``, which returns the timestamp
+in nano second.
+

<snip>

Quoted 36 lines
Documentation/hte/tegra194-hte.rst new file +36 -0
+
+static void tegra_hte_read_fifo(struct tegra_hte_soc *gs)
+{
+	u32 tsh, tsl, src, pv, cv, acv, slice, bit_index, line_id;
+	u64 tsc;
+	int dir;
+	struct hte_ts_data el;
+
+	while ((tegra_hte_readl(gs, HTE_TESTATUS) >>
+		HTE_TESTATUS_OCCUPANCY_SHIFT) &
+		HTE_TESTATUS_OCCUPANCY_MASK) {
+		tsh = tegra_hte_readl(gs, HTE_TETSCH);
+		tsl = tegra_hte_readl(gs, HTE_TETSCL);
+		tsc = (((u64)tsh << 32) | tsl);
+
+		src = tegra_hte_readl(gs, HTE_TESRC);
+		slice = (src >> HTE_TESRC_SLICE_SHIFT) &
+			    HTE_TESRC_SLICE_DEFAULT_MASK;
+
+		pv = tegra_hte_readl(gs, HTE_TEPCV);
+		cv = tegra_hte_readl(gs, HTE_TECCV);
+		acv = pv ^ cv;
+		while (acv) {
+			bit_index = __builtin_ctz(acv);
+			if ((pv >> bit_index) & BIT(0))
+				dir = HTE_EVENT_RISING_EDGE;
+			else
+				dir = HTE_EVENT_FALLING_EDGE;
+
+			line_id = bit_index + (slice << 5);
+			el.dir = dir;
+			el.tsc = tsc << HTE_TS_NS_SHIFT;
+			hte_push_ts_ns_atomic(gs->chip, line_id, &el,
+					      sizeof(el));
+			acv &= ~BIT(bit_index);
+		}
Quoted 8 lines

Documentation/hte/tegra194-hte.rst

Quoted 3 lines
Documentation/hte/tegra194-hte.rst new file +3 -0
+		tegra_hte_writel(gs, HTE_TECMD, HTE_TECMD_CMD_POP);
+	}
+}

What happens when the hte_push_ts_ns_atomic() fails?
The timestamp will be quietly dropped?
What happens when the interrupt corresponding to that dropped timestamp asks for it? The irq handler thread will block until it can get a timestamp from the subsequent interrupt?

Two things happen, 1) at the push, HTE core increments seq counter

2) If the consumer has provided callback, it will either call that callback

with HTE_TS_DROPPED or HTE_TS_AVAIL. The seq counter gives indirect

view of dropped ts. However, I see the problem with the consumers not

providing callback, in that case, push_ts* API just wakes up process without

indicating why (assuming notify variable is true or else there is a chance for

Quoted 8 lines

the thread to block forever). One easy approach I can think of for now is to

make callback mandatory (which is optional right now), I will have to rethink

that scenario and will push corrected version next RFC version.

Thanks for pointing out.

I'm not sure you understood my question, which was intended to demonstrate how an overflow here would break your gpio integration, but I am certain that I don't understand your answer.

Using the callback to signal fifo overflow to the consumer is crazy. If the consumer is too busy to service the fifo then they probably wont be prepared to deal with the callback either. And the primary purpose of the fifo is to decouple the producer and consumer, so requiring a callback defeats the whole purpose of having the fifo there in the first place.

Quoted 26 lines
Quoted 5 lines

Which brings me back to the concern I have with the approach used in the hte/gpiolib integration - how do you guarantee that the timestamp returned by gpiod_get_hw_timestamp() corresponds to the irq interrupt being handled, particularly in the face of errors such as:
- overflows of the timestamp FIFO in the chip

I currently do not have any indication mechanism as the providers

I am dealing with right now does not have overflow hardware detection

support. If the chip supports, it should be easy to integrate that feature.

I will provide some hook function or change in push_* API to accommodate

this in next version of RFC.

Quoted 1 line

- overflows of software FIFOs as here

HTE core records sequence counter as well it callsback the consumer with

HTE_TS_DROPPED.

Quoted 2 lines

- lost interupts (if the hw generates interrupts faster than the CPU can service them)

For this, I have no idea unless hardware supports some sort of mechanism

to catch that. For the current providers, as soon as it detects changes on lines

Quoted 8 lines

it captures TS in its hw fifo. Its interrupt gets generated based on threshold

set in that hw fifo. This interrupt is different than the lines of actual device

that is why I said I have no idea how we can tackle that. Let me know if there

is any idea or reference of the codes which does tackle this.

As far as I am aware there is no solution, given your suggested architecture.

Your architecture is inherently fragile, as you try to use one stream of data (the timestamp fifo) to provide supplementary info for another (the physical irq). Guaranteeing that the two are synchronised is impossible - even if you can get them synced at some point, they can fall out of sync without any indication.
That is a recipe for Ingenuity flight 6.

Quoted 7 lines

My solution would be to use the hte timestamp fifo as the event source, rather than the physical irq. With only one event source the synchronisation problem disappears. As to how to implement that, gpiolib-cdev would request a line from the hte subsystem and register and event handler for it, much as it does currently with the irq subsystem. That event handler would translate the hte events into gpio events.

I have to circle back to here regarding the event handler thing. I

Quoted 8 lines

surely did not understand fifo as event source rather than physical irq

part? I believe you are suggesting to have somekind of buffer abstraction

layer for the hardware fifo similar to what I have with software buffer and

register handler to that buffer, right?

No, what is the purpose of that buffering and watermarking in software? Just pass the timestamped edge event direct to the consumer. Let the consumer do any buffering if necessary, as Jonathon Cameron also suggested in the 02/11 thread.

Quoted 7 lines

The current implementation I have (not with gpiolib/HTE integration)

is partially simlar to event handler mechanism except that it does not send data

with it. See hte-tegra194-irq-test.c in this patch.

Quoted 8 lines

Coming back to gpiolib/hte integration part and your suggestion about

providing event handler during hte registration. I have below doubts:

1. When HTE calls this provided hte_handler, will it store data into

hte->timestamp_ns directly, I am guessing yes.

This is implementation detail of the hte/gpiolib interface that I leave for you to suggest. Work something out.

Quoted 7 lines
Quoted 4 lines

2. Does hte handler solution create race between two handlers? i.e. edge_irq_handler and

hte_handler, for the worst case scenario as below?

No. If hardware timestamp is selected then no irq is requested from the irq subsystem for that line - only from the hte subsystem instead. So there will be no edge_irq_handler call for that line, so no possible race.

That is not possible for certain providers, for example the one I am dealing

with which requires GPIO line to be requested as input and IRQ needs to

be enabled on them.

Quoted 66 lines
Quoted 34 lines

2.a edge_irq_handler runs first, checks some kind of flag to see if

we are using hardware clock and if yes, directly accesses timestamp_ns

instead of calling line_event_timestamp.

2.b finds timestamp_ns to be invalid since it ran first before hte event handler did.

2.c returns and invokes edge_irq_thread.

2.c.1 Here, should edge_irq_thread wait in cdev till hte handler to be called? If yes,

Doesn't it have case where it will wait forever till hte handler gets called, also not

to mention keeping irq line disabled since IRQF_ONESHOT is specified, could be possible

when provider has gone rogue?

3. I am guessing there will not be dropped event in this suggestion since are

directly sending data without buffering in HTE, that is the good part I believe.

Quoted 8 lines

You still have to deal with possible fifo overflows, but if the fifo overflows result in discarding the oldest event, rather than the most recent, then everything comes out in the wash. If not then the final event in a burst may not correspond to the actual state so you need some additional mechanism to address that.
Either way the consumer needs to be aware that events may be lost - but with the event seqno for consumers to detect those lost events we already have that covered.

Correct (for the seqno part), you already have seqno, cdev does not need

Quoted 9 lines

struct hte_ts_data's u64 seq counter.

On similar note, I was looking at the linereq_put_event

function and I have below doubts:

1. IIUC, you are discarding oldest data when fifo is full, right?

Correct.

Quoted 6 lines

2. There is no indication to waiting client if overflow is true beside pr_debug print.

2.a Does this not block waiting client infinitely since there is no wake_up_poll call

in case of overflow == 1?

No - there already was a wake_up_poll call for the entry discarded by the kfifo_skip().

You dropped 2.b intentionally, right? Buffer overflow perhaps??

Quoted 4 lines

2.c If I have missed, what current mechanism cdev provides to client beside seqno

to indicate there is a drop and if there is a drop, what it does to re-sync?

Just seqno. Overflows in the cdev event buffer discard the oldest events, so the final event that the client reads will correspond to current state. There is an event waiting for the client that, due to the seqno jump, indicates the overflow. What else do they need? And what is there to resync?

Quoted 3 lines

Not sorry if I'm getting short with you here - I'm getting really tired of this subject as we're clearly not communicating well and are repeatedly covering the same ground.

Sure, no problem...

Quoted 3 lines

Cheers,
Kent.

reviewer
#29 lore raw

Re: [RFC 03/11] hte: Add tegra194 HTE kernel provider

Quoted 7 lines · Dipen Patel
Quoted 5 lines · Kent Gibson
Quoted 4 lines · Dipen Patel
Quoted 3 lines · Kent Gibson
Quoted 2 lines · Dipen Patel

Thanks Kent for the review comment. My responses inline.

<snip>

Quoted 9 lines
Quoted 8 lines
Quoted 5 lines

2. Does hte handler solution create race between two handlers? i.e. edge_irq_handler and

hte_handler, for the worst case scenario as below?

No. If hardware timestamp is selected then no irq is requested from the irq subsystem for that line - only from the hte subsystem instead. So there will be no edge_irq_handler call for that line, so no possible race.

Quoted 6 lines

That is not possible for certain providers, for example the one I am dealing

with which requires GPIO line to be requested as input and IRQ needs to

be enabled on them.

So, for your hte subsystem to work, the consumer has to also request a line from the irq subsystem? That makes sense to you? Have hte do that, rather than the consumer.

And another reason it makes sense to integrate this with irq...

Cheers,
Kent.

author maintainer
#30 lore raw

Re: [RFC 03/11] hte: Add tegra194 HTE kernel provider

Quoted 16 lines · Kent Gibson
Quoted 6 lines · Dipen Patel
Quoted 5 lines · Kent Gibson
Quoted 4 lines · Dipen Patel
Quoted 3 lines · Kent Gibson
Quoted 2 lines · Dipen Patel

Thanks Kent for the review comment. My responses inline.

<snip>

Quoted 7 lines
Quoted 7 lines
Quoted 4 lines

2. Does hte handler solution create race between two handlers? i.e. edge_irq_handler and

hte_handler, for the worst case scenario as below?

No. If hardware timestamp is selected then no irq is requested from the irq subsystem for that line - only from the hte subsystem instead. So there will be no edge_irq_handler call for that line, so no possible race.

Quoted 8 lines
Quoted 6 lines

That is not possible for certain providers, for example the one I am dealing

with which requires GPIO line to be requested as input and IRQ needs to

be enabled on them.

So, for your hte subsystem to work, the consumer has to also request a line from the irq subsystem?

Yes

Quoted 1 line

That makes sense to you?

Its not me, its peculiarity of the hardware that I am dealing with.

Quoted 1 line

Have hte do that, rather than the consumer.

Sure, for cdev it would mean to duplicate (most of) the edge* or line_create

code in HTE. For such hardware, my initial doubt remains the same about

the worst case scenario between two handlers, but perhaps that's

implementation details for hte to handle.

Quoted 2 lines

And another reason it makes sense to integrate this with irq...

Alright, will explore this route as well. I remember both Thierry[1] and

Marc[2] raised some doubts (time to revive that discussion).

[1]: https://lore.kernel.org/lkml/YFm9r%[email protected]/

[2]: https://lore.kernel.org/lkml/[email protected]/

Quoted 3 lines

Cheers,
Kent.

author maintainer
#31 lore raw

Re: [RFC 03/11] hte: Add tegra194 HTE kernel provider

Quoted 25 lines · Dipen Patel
Quoted 16 lines · Kent Gibson
Quoted 6 lines · Dipen Patel
Quoted 5 lines · Kent Gibson
Quoted 4 lines · Dipen Patel
Quoted 3 lines · Kent Gibson
Quoted 2 lines · Dipen Patel

Thanks Kent for the review comment. My responses inline.

<snip>

Quoted 7 lines
Quoted 7 lines
Quoted 4 lines

2. Does hte handler solution create race between two handlers? i.e. edge_irq_handler and

hte_handler, for the worst case scenario as below?

No. If hardware timestamp is selected then no irq is requested from the irq subsystem for that line - only from the hte subsystem instead. So there will be no edge_irq_handler call for that line, so no possible race.

Quoted 8 lines
Quoted 6 lines

That is not possible for certain providers, for example the one I am dealing

with which requires GPIO line to be requested as input and IRQ needs to

be enabled on them.

So, for your hte subsystem to work, the consumer has to also request a line from the irq subsystem?

Quoted 8 lines

Yes

Quoted 1 line

That makes sense to you?

Its not me, its peculiarity of the hardware that I am dealing with.

Quoted 1 line

Have hte do that, rather than the consumer.

Sure, for cdev it would mean to duplicate (most of) the edge* or line_create

code in HTE.

Ignore code duplicate comment, shouldn't be big deal.

Quoted 18 lines

For such hardware, my initial doubt remains the same about

the worst case scenario between two handlers, but perhaps that's

implementation details for hte to handle.

Quoted 1 line

And another reason it makes sense to integrate this with irq...

Alright, will explore this route as well. I remember both Thierry[1] and

Marc[2] raised some doubts (time to revive that discussion).

[1]: https://lore.kernel.org/lkml/YFm9r%[email protected]/

[2]: https://lore.kernel.org/lkml/[email protected]/

Quoted 2 lines

Cheers,
Kent.

reviewer
#32 lore raw

Re: [RFC 03/11] hte: Add tegra194 HTE kernel provider

In reply to Dipen Patel
Quoted 24 lines · Dipen Patel
Quoted 22 lines · Kent Gibson
Quoted 6 lines · Dipen Patel
Quoted 5 lines · Kent Gibson
Quoted 4 lines · Dipen Patel
Quoted 3 lines · Kent Gibson
Quoted 2 lines · Dipen Patel

Thanks Kent for the review comment. My responses inline.

<snip>

Quoted 13 lines
Quoted 7 lines
Quoted 4 lines

2. Does hte handler solution create race between two handlers? i.e. edge_irq_handler and

hte_handler, for the worst case scenario as below?

No. If hardware timestamp is selected then no irq is requested from the irq subsystem for that line - only from the hte subsystem instead. So there will be no edge_irq_handler call for that line, so no possible race.

That is not possible for certain providers, for example the one I am dealing

with which requires GPIO line to be requested as input and IRQ needs to

be enabled on them.

Quoted 7 lines
Quoted 2 lines

So, for your hte subsystem to work, the consumer has to also request a line from the irq subsystem?

Yes

Quoted 1 line

That makes sense to you?

Its not me, its peculiarity of the hardware that I am dealing with.

My point is that the peculiarities of the hardware should be hidden from the hte API user, especially if it is only necessary for some hardware.

Quoted 5 lines
Quoted 1 line

Have hte do that, rather than the consumer.

Sure, for cdev it would mean to duplicate (most of) the edge* or line_create

code in HTE.

And your current way every other hte user will have to duplicate the gpiolib-cdev code....

Quoted 6 lines

For such hardware, my initial doubt remains the same about

the worst case scenario between two handlers, but perhaps that's

implementation details for hte to handle.

Indeed.

Cheers,
Kent.

Quoted 15 lines
Quoted 2 lines

And another reason it makes sense to integrate this with irq...

Alright, will explore this route as well. I remember both Thierry[1] and

Marc[2] raised some doubts (time to revive that discussion).

[1]: https://lore.kernel.org/lkml/YFm9r%[email protected]/

[2]: https://lore.kernel.org/lkml/[email protected]/

Quoted 3 lines

Cheers,
Kent.

maintainer
#33 lore raw

Re: [RFC 03/11] hte: Add tegra194 HTE kernel provider

In reply to Dipen Patel
Quoted 6 lines · On Fri, 25 Jun 2021 16:55:24 -0700 Dipen Patel <[email protected]> wrote:

Tegra194 device has multiple HTE instances also known as GTE (Generic hardware Timestamping Engine) which can timestamp subset of SoC lines/signals. This provider driver focuses on IRQ and GPIO lines and exposes timestamping ability on those lines to the consumers through HTE subsystem.

Quoted 6 lines

Also, with this patch, added:
- documentation about this provider and its capabilities at Documentation/hte.
- Compilation support in Makefile and Kconfig

A few comments inline,

J

Quoted 149 lines
---
 Documentation/hte/index.rst        |  21 ++
 Documentation/hte/tegra194-hte.rst |  65 ++++
 Documentation/index.rst            |   1 +
 drivers/hte/Kconfig                |  12 +
 drivers/hte/Makefile               |   1 +
 drivers/hte/hte-tegra194.c         | 554 +++++++++++++++++++++++++++++
 6 files changed, 654 insertions(+)
 create mode 100644 Documentation/hte/index.rst
 create mode 100644 Documentation/hte/tegra194-hte.rst
 create mode 100644 drivers/hte/hte-tegra194.c
Documentation/hte/index.rst new file +21 -0
new file mode 100644
index 000000000000..f311ebec6b47
@@ -0,0 +1,21 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+The HTE Subsystem
+=================
+
+.. toctree::
+   :maxdepth: 1
+
+   hte
+
+HTE Tegra Provider
+==================
+
+.. toctree::
+   :maxdepth: 1
+
+   tegra194-hte
\ No newline at end of file
Documentation/hte/tegra194-hte.rst new file +65 -0
new file mode 100644
index 000000000000..c23eaafcf080
@@ -0,0 +1,65 @@
+HTE Kernel provider driver
+==========================
+
+Description
+-----------
+The Nvidia tegra194 chip has many hardware timestamping engine (HTE) instances
+known as generic timestamping engine (GTE). This provider driver implements
+two GTE instances 1) GPIO GTE and 2) IRQ GTE. The both GTEs instances get the
+timestamp from the system counter TSC which has 31.25MHz clock rate, and the
+driver converts clock tick rate to nano seconds before storing it as timestamp
+value.
+
+GPIO GTE
+--------
+
+This GTE instance help timestamps GPIO in real time, for that to happen GPIO
+needs to be configured as input and IRQ needs to ba enabled as well. The only
+always on (AON) gpio controller instance supports timestamping GPIOs in
+realtime and it has 39 GPIO lines. There is also a dependency on AON GPIO
+controller as it requires very specific bits to be set in GPIO config register.
+It in a way creates cyclic dependency between GTE and GPIO controller. The GTE
+GPIO functionality is accessed from the GPIOLIB. It can support both the in
+kernel and userspace consumers. In the later case, requests go through GPIOLIB
+CDEV framework. The below APIs are added in GPIOLIB framework to access HTE
+subsystem and GPIO GTE for in kernel consumers.
+
+.. c:function:: int gpiod_hw_timestamp_control( struct gpio_desc *desc, bool enable )
+
+	To enable HTE on given GPIO line.
+
+.. c:function:: u64 gpiod_get_hw_timestamp( struct gpio_desc *desc, bool block )
+
+	To retrieve hardwre timestamp in nano seconds.
+
+.. c:function:: bool gpiod_is_hw_timestamp_enabled( const struct gpio_desc *desc )
+
+	To query if HTE is enabled on the given GPIO.
+
+There is hte-tegra194-gpio-test.c, located in ``drivers/hte/`` directory, test
+driver which demonstrates above APIs for the Jetson AGX platform. For userspace
+consumers, GPIO_V2_LINE_FLAG_EVENT_CLOCK_HARDWARE flag must be specifed during
+IOCTL calls, refer ``tools/gpio/gpio-event-mon.c``, which returns the timestamp
+in nano second.
+
+IRQ GTE
+--------
+
+This GTE instance helps timestamp LIC IRQ lines in real time. There are 352 IRQ
+lines which this instance can help timestamp realtime. The hte devicetree
+binding described at ``Documentation/devicetree/bindings/hte/`` gives out
+example how consumer can request IRQ line, since it is one to one mapping,
+consumers can simply specify IRQ number that they are interested in. There is
+no userspace consumer support for this GTE instance. The sample test code
+hte-tegra194-irq-test.c, located in ``drivers/hte/`` directory,
+demonstrates how to use IRQ GTE instance. The below is sample device tree
+snippet code for the test driver::
+
+ tegra_hte_irq_test {
+        compatible = "nvidia,tegra194-hte-irq-test";
+        htes = <&tegra_hte_lic 0x19>;
+        hte-names = "hte-lic";
+ };
+
+The source code of the driver both IRQ and GPIO GTE is locate at
+``drivers/hte/hte-tegra194.c``.
\ No newline at end of file
Documentation/index.rst +1 -0
index 1b13c2445e87..b41118577fe6 100644
@@ -138,6 +138,7 @@ needed).
    misc-devices/index
    scheduler/index
    mhi/index
+   hte/index
 
 Architecture-agnostic documentation
 -----------------------------------
drivers/hte/Kconfig +12 -0
index 394e112f7dfb..f7b01fcc7190 100644
@@ -20,3 +20,15 @@ menuconfig HTE
 
           If unsure, say no.
 
+if HTE
+
+config HTE_TEGRA194
+	tristate "NVIDIA Tegra194 HTE Support"
+	depends on ARCH_TEGRA_194_SOC
+	help
+	  Enable this option for integrated hardware timestamping engine also
+	  known as generic timestamping engine (GTE) support on NVIDIA Tegra194
+	  systems-on-chip. The driver supports 352 LIC IRQs and 39 AON GPIOs
+	  lines for timestamping in realtime.
+
+endif
drivers/hte/Makefile +0 -0
index 9899dbe516f7..52f978cfc913 100644

drivers/hte/Makefile line 2

Quoted 3 lines
drivers/hte/Makefile +1 -0
@@ -1 +1,2 @@
 obj-$(CONFIG_HTE)		+= hte.o
+obj-$(CONFIG_HTE_TEGRA194)	+= hte-tegra194.o
\ No newline at end of file

fix that

Quoted 435 lines
drivers/hte/hte-tegra194.c new file +429 -0
new file mode 100644
index 000000000000..8ad10efd3641
@@ -0,0 +1,554 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2021 NVIDIA Corporation
+ *
+ * Author: Dipen Patel <[email protected]>
+ */
+
+#include <linux/err.h>
+#include <linux/io.h>
+#include <linux/module.h>
+#include <linux/slab.h>
+#include <linux/stat.h>
+#include <linux/interrupt.h>
+#include <linux/of.h>
+#include <linux/of_device.h>
+#include <linux/platform_device.h>
+#include <linux/hte.h>
+#include <linux/uaccess.h>
+
+#define HTE_SUSPEND	0
+
+/* HTE source clock TSC is 31.25MHz */
+#define HTE_TS_CLK_RATE_HZ	31250000ULL
+#define HTE_CLK_RATE_NS		32
+#define HTE_TS_NS_SHIFT	__builtin_ctz(HTE_CLK_RATE_NS)
+
+#define NV_AON_SLICE_INVALID	-1
+
+/* AON HTE line map For slice 1 */
+#define NV_AON_HTE_SLICE1_IRQ_GPIO_28	12
+#define NV_AON_HTE_SLICE1_IRQ_GPIO_29	13
+
+/* AON HTE line map For slice 2 */
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_0	0
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_1	1
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_2	2
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_3	3
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_4	4
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_5	5
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_6	6
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_7	7
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_8	8
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_9	9
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_10	10
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_11	11
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_12	12
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_13	13
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_14	14
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_15	15
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_16	16
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_17	17
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_18	18
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_19	19
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_20	20
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_21	21
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_22	22
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_23	23
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_24	24
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_25	25
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_26	26
+#define NV_AON_HTE_SLICE2_IRQ_GPIO_27	27
+
+/* AON GPIO port AA pins */
+#define NV_AON_GPIO_PORT_AA_0		0
+#define NV_AON_GPIO_PORT_AA_1		1
+#define NV_AON_GPIO_PORT_AA_2		2
+#define NV_AON_GPIO_PORT_AA_3		3
+#define NV_AON_GPIO_PORT_AA_4		4
+#define NV_AON_GPIO_PORT_AA_5		5
+#define NV_AON_GPIO_PORT_AA_6		6
+#define NV_AON_GPIO_PORT_AA_7		7
+
+/* AON GPIO port BB pins */
+#define NV_AON_GPIO_PORT_BB_0		8
+#define NV_AON_GPIO_PORT_BB_1		9
+#define NV_AON_GPIO_PORT_BB_2		10
+#define NV_AON_GPIO_PORT_BB_3		11
+
+/* AON GPIO port CC pins */
+#define NV_AON_GPIO_PORT_CC_0		16
+#define NV_AON_GPIO_PORT_CC_1		17
+#define NV_AON_GPIO_PORT_CC_2		18
+#define NV_AON_GPIO_PORT_CC_3		19
+#define NV_AON_GPIO_PORT_CC_4		20
+#define NV_AON_GPIO_PORT_CC_5		21
+#define NV_AON_GPIO_PORT_CC_6		22
+#define NV_AON_GPIO_PORT_CC_7		23
+
+/* AON GPIO port DD pins */
+#define NV_AON_GPIO_PORT_DD_0		24
+#define NV_AON_GPIO_PORT_DD_1		25
+#define NV_AON_GPIO_PORT_DD_2		26
+
+/* AON GPIO port EE pins */
+#define NV_AON_GPIO_PORT_EE_0		32
+#define NV_AON_GPIO_PORT_EE_1		33
+#define NV_AON_GPIO_PORT_EE_2		34
+#define NV_AON_GPIO_PORT_EE_3		35
+#define NV_AON_GPIO_PORT_EE_4		36
+#define NV_AON_GPIO_PORT_EE_5		37
+#define NV_AON_GPIO_PORT_EE_6		38
+
+
+#define HTE_TECTRL		0x0
+#define HTE_TETSCH		0x4
+#define HTE_TETSCL		0x8
+#define HTE_TESRC		0xC
+#define HTE_TECCV		0x10
+#define HTE_TEPCV		0x14
+#define HTE_TECMD		0x1C
+#define HTE_TESTATUS		0x20
+#define HTE_SLICE0_TETEN	0x40
+#define HTE_SLICE1_TETEN	0x60
+
+#define HTE_SLICE_SIZE		(HTE_SLICE1_TETEN - HTE_SLICE0_TETEN)
+
+#define HTE_TECTRL_ENABLE_ENABLE	0x1
+
+#define HTE_TECTRL_OCCU_SHIFT		0x8
+#define HTE_TECTRL_INTR_SHIFT		0x1
+#define HTE_TECTRL_INTR_ENABLE		0x1
+
+#define HTE_TESRC_SLICE_SHIFT		16
+#define HTE_TESRC_SLICE_DEFAULT_MASK	0xFF
+
+#define HTE_TECMD_CMD_POP		0x1
+
+#define HTE_TESTATUS_OCCUPANCY_SHIFT	8
+#define HTE_TESTATUS_OCCUPANCY_MASK	0xFF
+
+struct hte_slices {
+	u32 r_val;
+	unsigned long flags;
+	/* to prevent lines mapped to same slice updating its register */
+	spinlock_t s_lock;
+};
+
+struct tegra_hte_line_mapped {
+	int slice;
+	u32 bit_index;
+};
+
+struct tegra_hte_line_table {
+	int map_sz;
+	const struct tegra_hte_line_mapped *map;
+};
+
+struct tegra_hte_soc {
+	int hte_irq;
+	u32 itr_thrshld;
+	u32 conf_rval;
+	struct hte_slices *sl;
+	const struct tegra_hte_line_table *line_map;
+	struct hte_chip *chip;
+	void __iomem *regs;
+};
+
+static const struct tegra_hte_line_mapped tegra194_aon_gpio_map[] = {
+	/* gpio, slice, bit_index */
+	[NV_AON_GPIO_PORT_AA_0]  = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_11},
+	[NV_AON_GPIO_PORT_AA_1]  = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_10},
+	[NV_AON_GPIO_PORT_AA_2]  = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_9},
+	[NV_AON_GPIO_PORT_AA_3]  = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_8},
+	[NV_AON_GPIO_PORT_AA_4]  = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_7},
+	[NV_AON_GPIO_PORT_AA_5]  = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_6},
+	[NV_AON_GPIO_PORT_AA_6]  = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_5},
+	[NV_AON_GPIO_PORT_AA_7]  = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_4},
+	[NV_AON_GPIO_PORT_BB_0]  = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_3},
+	[NV_AON_GPIO_PORT_BB_1]  = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_2},
+	[NV_AON_GPIO_PORT_BB_2] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_1},
+	[NV_AON_GPIO_PORT_BB_3] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_0},
+	[12] = {NV_AON_SLICE_INVALID, 0},
+	[13] = {NV_AON_SLICE_INVALID, 0},
+	[14] = {NV_AON_SLICE_INVALID, 0},
+	[15] = {NV_AON_SLICE_INVALID, 0},
+	[NV_AON_GPIO_PORT_CC_0] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_22},
+	[NV_AON_GPIO_PORT_CC_1] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_21},
+	[NV_AON_GPIO_PORT_CC_2] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_20},
+	[NV_AON_GPIO_PORT_CC_3] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_19},
+	[NV_AON_GPIO_PORT_CC_4] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_18},
+	[NV_AON_GPIO_PORT_CC_5] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_17},
+	[NV_AON_GPIO_PORT_CC_6] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_16},
+	[NV_AON_GPIO_PORT_CC_7] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_15},
+	[NV_AON_GPIO_PORT_DD_0] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_14},
+	[NV_AON_GPIO_PORT_DD_1] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_13},
+	[NV_AON_GPIO_PORT_DD_2] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_12},
+	[27] = {NV_AON_SLICE_INVALID, 0},
+	[28] = {NV_AON_SLICE_INVALID, 0},
+	[29] = {NV_AON_SLICE_INVALID, 0},
+	[30] = {NV_AON_SLICE_INVALID, 0},
+	[31] = {NV_AON_SLICE_INVALID, 0},
+	[NV_AON_GPIO_PORT_EE_0] = {1, NV_AON_HTE_SLICE1_IRQ_GPIO_29},
+	[NV_AON_GPIO_PORT_EE_1] = {1, NV_AON_HTE_SLICE1_IRQ_GPIO_28},
+	[NV_AON_GPIO_PORT_EE_2] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_27},
+	[NV_AON_GPIO_PORT_EE_3] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_26},
+	[NV_AON_GPIO_PORT_EE_4] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_25},
+	[NV_AON_GPIO_PORT_EE_5] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_24},
+	[NV_AON_GPIO_PORT_EE_6] = {2, NV_AON_HTE_SLICE2_IRQ_GPIO_23},
+};
+
+static const struct tegra_hte_line_table aon_hte_map = {
+	.map_sz = ARRAY_SIZE(tegra194_aon_gpio_map),
+	.map = tegra194_aon_gpio_map,
+};
+
+static inline u32 tegra_hte_readl(struct tegra_hte_soc *hte, u32 reg)
+{
+	return readl(hte->regs + reg);
+}
+
+static inline void tegra_hte_writel(struct tegra_hte_soc *hte, u32 reg,
+				    u32 val)
+{
+	writel(val, hte->regs + reg);
+}
+
+static inline int tegra_hte_map_to_line_id(u32 eid, struct tegra_hte_soc *gs,
+					  u32 *mapped)
+{
+	const struct tegra_hte_line_mapped *m;
+
+	if (gs->line_map) {
+		m = gs->line_map->map;
+		if (eid > gs->line_map->map_sz)
+			return -EINVAL;
+		if (m[eid].slice == NV_AON_SLICE_INVALID)
+			return -EINVAL;
+
+		*mapped = (m[eid].slice << 5) + m[eid].bit_index;
+	} else {
+		*mapped = eid;
+	}
+
+	return 0;
+}
+
+static int tegra_hte_line_xlate(struct hte_chip *gc,
+				 const struct of_phandle_args *args,
+				 struct hte_ts_desc *desc, u32 *xlated_id)
+{
+	int ret = 0;
+
+	if (!gc || !desc || !xlated_id)
+		return -EINVAL;
+
+	if (args) {
+		if (gc->of_hte_n_cells < 1)
+			return -EINVAL;
+
+		if (args->args_count != gc->of_hte_n_cells)
+			return -EINVAL;
+
+		desc->con_id = args->args[0];
+	}
+
+	ret = tegra_hte_map_to_line_id(desc->con_id, gc->data,
+				       xlated_id);
+	if (ret < 0) {
+		dev_dbg(gc->dev, "con_id:%u mapping failed\n",
+			desc->con_id);
+		return ret;
+	}
+
+	if (*xlated_id > gc->nlines)
+		return -EINVAL;
+
+	dev_dbg(gc->dev, "requested id:%u, xlated id:%u\n",
+		desc->con_id, *xlated_id);
+
+	return 0;
+}
+
+static int tegra_hte_en_dis_common(struct hte_chip *chip, u32 line_id, bool en)
+{
+	u32 slice, sl_bit_shift, line_bit, val, reg;
+	struct tegra_hte_soc *gs;
+
+	sl_bit_shift = __builtin_ctz(HTE_SLICE_SIZE);
+
+	if (!chip)
+		return -EINVAL;
+
+	gs = (struct tegra_hte_soc *)chip->data;
+
+	if (line_id > chip->nlines) {
+		dev_err(chip->dev,
+			"line id: %u is not supported by this controller\n",
+			line_id);
+		return -EINVAL;
+	}
+
+	slice = line_id >> sl_bit_shift;
+	line_bit = line_id & (HTE_SLICE_SIZE - 1);
+	reg = (slice << sl_bit_shift) + HTE_SLICE0_TETEN;
+
+	spin_lock(&gs->sl[slice].s_lock);
+
+	if (test_bit(HTE_SUSPEND, &gs->sl[slice].flags)) {
+		spin_unlock(&gs->sl[slice].s_lock);
+		dev_dbg(chip->dev, "device suspended");
+		return -EBUSY;
+	}
+
+	val = tegra_hte_readl(gs, reg);
+	if (en)
+		val = val | (1 << line_bit);
+	else
+		val = val & (~(1 << line_bit));
+	tegra_hte_writel(gs, reg, val);
+
+	spin_unlock(&gs->sl[slice].s_lock);
+
+	dev_dbg(chip->dev, "line: %u, slice %u, line_bit %u, reg:0x%x\n",
+		line_id, slice, line_bit, reg);
+
+	return 0;
+}
+
+static int tegra_hte_request(struct hte_chip *chip, u32 line_id)
+{
+	return tegra_hte_en_dis_common(chip, line_id, true);
+}
+
+static int tegra_hte_release(struct hte_chip *chip, u32 line_id)
+{
+	return tegra_hte_en_dis_common(chip, line_id, false);
+}
+
+static int tegra_hte_clk_src_info(struct hte_chip *chip,
+				  struct hte_clk_info *ci)
+{
+	(void)chip;
+
+	ci->hz = HTE_TS_CLK_RATE_HZ;
+	ci->type = CLOCK_MONOTONIC;
+
+	return 0;
+}
+
+static void tegra_hte_read_fifo(struct tegra_hte_soc *gs)
+{
+	u32 tsh, tsl, src, pv, cv, acv, slice, bit_index, line_id;
+	u64 tsc;
+	int dir;
+	struct hte_ts_data el;
+
+	while ((tegra_hte_readl(gs, HTE_TESTATUS) >>
+		HTE_TESTATUS_OCCUPANCY_SHIFT) &
+		HTE_TESTATUS_OCCUPANCY_MASK) {
+		tsh = tegra_hte_readl(gs, HTE_TETSCH);
+		tsl = tegra_hte_readl(gs, HTE_TETSCL);
+		tsc = (((u64)tsh << 32) | tsl);
+
+		src = tegra_hte_readl(gs, HTE_TESRC);
+		slice = (src >> HTE_TESRC_SLICE_SHIFT) &
+			    HTE_TESRC_SLICE_DEFAULT_MASK;
+
+		pv = tegra_hte_readl(gs, HTE_TEPCV);
+		cv = tegra_hte_readl(gs, HTE_TECCV);
+		acv = pv ^ cv;
+		while (acv) {
+			bit_index = __builtin_ctz(acv);
+			if ((pv >> bit_index) & BIT(0))
+				dir = HTE_EVENT_RISING_EDGE;
+			else
+				dir = HTE_EVENT_FALLING_EDGE;
+
+			line_id = bit_index + (slice << 5);
+			el.dir = dir;
+			el.tsc = tsc << HTE_TS_NS_SHIFT;
+			hte_push_ts_ns_atomic(gs->chip, line_id, &el,
+					      sizeof(el));
+			acv &= ~BIT(bit_index);
+		}
+		tegra_hte_writel(gs, HTE_TECMD, HTE_TECMD_CMD_POP);
+	}
+}
+
+static irqreturn_t tegra_hte_isr(int irq, void *dev_id)
+{
+	struct tegra_hte_soc *gs = dev_id;
+
+	tegra_hte_read_fifo(gs);
+
+	return IRQ_HANDLED;
+}
+
+static const struct of_device_id tegra_hte_of_match[] = {
+	{ .compatible = "nvidia,tegra194-gte-lic"},
+	{ .compatible = "nvidia,tegra194-gte-aon", .data = &aon_hte_map},
+	{ }
+};
+MODULE_DEVICE_TABLE(of, tegra_hte_of_match);
+
+static const struct hte_ops g_ops = {
+	.request = tegra_hte_request,
+	.release = tegra_hte_release,
+	.enable = tegra_hte_request,
+	.disable = tegra_hte_release,
+	.get_clk_src_info = tegra_hte_clk_src_info,
+};
+
+static int tegra_hte_probe(struct platform_device *pdev)
+{
+	int ret;
+	u32 i, slices, val = 0;
+	struct device *dev;
+	struct tegra_hte_soc *hte_dev;
+	struct hte_chip *gc;
+
+	dev = &pdev->dev;
+
+	hte_dev = devm_kzalloc(dev, sizeof(*hte_dev), GFP_KERNEL);
+	if (!hte_dev)
+		return -ENOMEM;
+
+	gc = devm_kzalloc(dev, sizeof(*gc), GFP_KERNEL);
+	if (!gc)
+		return -ENOMEM;
+
+	dev_set_drvdata(&pdev->dev, hte_dev);
+	hte_dev->line_map = of_device_get_match_data(&pdev->dev);
+
+	hte_dev->regs = devm_platform_ioremap_resource(pdev, 0);
+	if (IS_ERR(hte_dev->regs))
+		return PTR_ERR(hte_dev->regs);
+
+	ret = of_property_read_u32(dev->of_node, "int-threshold",
+				   &hte_dev->itr_thrshld);

drivers/hte/hte-tegra194.c line 439

Quoted 10 lines
drivers/hte/hte-tegra194.c new file +10 -0
+	if (ret != 0)
+		hte_dev->itr_thrshld = 1;
+
+	ret = of_property_read_u32(dev->of_node, "slices", &slices);
+	if (ret != 0) {
+		dev_err(dev, "Could not read slices\n");
+		return -EINVAL;
+	}
+
+	hte_dev->sl = devm_kzalloc(dev, sizeof(struct hte_slices) * slices,

Preference for sizeof(*hte_dev->sl) as it saves me checking the size is correct for the type.

drivers/hte/hte-tegra194.c line 446

Quoted 7 lines
drivers/hte/hte-tegra194.c new file +7 -0
+				   GFP_KERNEL);
+	if (!hte_dev->sl)
+		return -ENOMEM;
+
+	ret = platform_get_irq(pdev, 0);
+	if (ret < 0) {
+		dev_err(dev, "get irq failed.\n");

dev_err_probe() probably so you don't print the message if deferred probing is going on.

Quoted 5 lines
drivers/hte/hte-tegra194.c new file +5 -0
+		return ret;
+	}
+	hte_dev->hte_irq = ret;
+	ret = devm_request_irq(dev, hte_dev->hte_irq, tegra_hte_isr, 0,
+			       dev_name(dev), hte_dev);

drivers/hte/hte-tegra194.c line 461

Quoted 10 lines
drivers/hte/hte-tegra194.c new file +10 -0
+	if (ret < 0) {
+		dev_err(dev, "request irq failed.\n");
+		return ret;
+	}
+
+	gc->nlines = slices << 5;
+	gc->ops = &g_ops;
+	gc->dev = dev;
+	hte_dev->chip = gc;
+	gc->data = (void *)hte_dev;

Don't case to void * - cast to the actual type if necessary.
If it is a void * then most likely it shouldn't be if we always put something in particular it in it.

drivers/hte/hte-tegra194.c line 466

Quoted 5 lines
drivers/hte/hte-tegra194.c new file +5 -0
+	gc->xlate = tegra_hte_line_xlate;
+	gc->of_hte_n_cells = 1;
+
+	ret = hte_register_chip(hte_dev->chip);
+

No blank line before error handler. Under the circumstances is that not fatal?

drivers/hte/hte-tegra194.c line 478

Quoted 12 lines
drivers/hte/hte-tegra194.c new file +12 -0
+	if (ret)
+		dev_err(gc->dev, "hte chip register failed");
+
+	for (i = 0; i < slices; i++) {
+		hte_dev->sl[i].flags = 0;
+		spin_lock_init(&hte_dev->sl[i].s_lock);
+	}
+
+	val = HTE_TECTRL_ENABLE_ENABLE |
+	      (HTE_TECTRL_INTR_ENABLE << HTE_TECTRL_INTR_SHIFT) |
+	      (hte_dev->itr_thrshld << HTE_TECTRL_OCCU_SHIFT);
+	tegra_hte_writel(hte_dev, HTE_TECTRL, val);

You could use a devm_add_action_or_reset() to deal with unwinding this plus add a devm_hte_register_chip() and then you can get rid of remove entirely which is always nice.

Quoted 5 lines
drivers/hte/hte-tegra194.c new file +5 -0
+
+	dev_dbg(gc->dev, "lines: %d, slices:%d", gc->nlines, slices);
+	return 0;
+}
+

drivers/hte/hte-tegra194.c line 493

Quoted 10 lines
drivers/hte/hte-tegra194.c new file +10 -0
+static int tegra_hte_remove(struct platform_device *pdev)
+{
+	struct tegra_hte_soc *gs = dev_get_drvdata(&pdev->dev);
+
+	tegra_hte_writel(gs, HTE_TECTRL, 0);
+
+	return hte_unregister_chip(gs->chip);
+}
+
+#ifdef CONFIG_PM_SLEEP

Personally I prefer the approach of marking PM functions __maybe_unused and dropping the ifdef protections. There have been a lot of subtle issues in the build system in the past around those and it's much easier to just let the compiler drop them if they are unused.

drivers/hte/hte-tegra194.c line 498

Quoted 5 lines
drivers/hte/hte-tegra194.c new file +5 -0
+static int tegra_hte_resume_early(struct device *dev)
+{
+	u32 i;
+	struct tegra_hte_soc *gs = dev_get_drvdata(dev);
+	u32 slices = gs->chip->nlines >> 5;

Whilst it's the same thing, I'd prefer a divide there by however lines there are in a slice.

Quoted 56 lines
drivers/hte/hte-tegra194.c new file +56 -0
+	u32 sl_bit_shift = __builtin_ctz(HTE_SLICE_SIZE);
+
+	tegra_hte_writel(gs, HTE_TECTRL, gs->conf_rval);
+
+	for (i = 0; i < slices; i++) {
+		spin_lock(&gs->sl[i].s_lock);
+		tegra_hte_writel(gs,
+				 ((i << sl_bit_shift) + HTE_SLICE0_TETEN),
+				 gs->sl[i].r_val);
+		clear_bit(HTE_SUSPEND, &gs->sl[i].flags);
+		spin_unlock(&gs->sl[i].s_lock);
+	}
+
+	return 0;
+}
+
+static int tegra_hte_suspend_late(struct device *dev)
+{
+	u32 i;
+	struct tegra_hte_soc *gs = dev_get_drvdata(dev);
+	u32 slices = gs->chip->nlines >> 5;
+	u32 sl_bit_shift = __builtin_ctz(HTE_SLICE_SIZE);
+
+	gs->conf_rval = tegra_hte_readl(gs, HTE_TECTRL);
+	for (i = 0; i < slices; i++) {
+		spin_lock(&gs->sl[i].s_lock);
+		gs->sl[i].r_val = tegra_hte_readl(gs,
+				((i << sl_bit_shift) + HTE_SLICE0_TETEN));
+		set_bit(HTE_SUSPEND, &gs->sl[i].flags);
+		spin_unlock(&gs->sl[i].s_lock);
+	}
+
+	return 0;
+}
+#endif
+
+static const struct dev_pm_ops tegra_hte_pm = {
+	SET_LATE_SYSTEM_SLEEP_PM_OPS(tegra_hte_suspend_late,
+				     tegra_hte_resume_early)
+};
+
+static struct platform_driver tegra_hte_driver = {
+	.probe = tegra_hte_probe,
+	.remove = tegra_hte_remove,
+	.driver = {
+		.name = "tegra_hte",
+		.pm = &tegra_hte_pm,
+		.of_match_table = tegra_hte_of_match,
+	},
+};
+
+module_platform_driver(tegra_hte_driver);
+
+MODULE_AUTHOR("Dipen Patel <[email protected]>");
+MODULE_DESCRIPTION("NVIDIA Tegra HTE (Hardware Timestamping Engine) driver");
+MODULE_LICENSE("GPL v2");