brintos

brintos / linux-shallow public Read only

0
0
Text · 24.3 KiB · 71ccc30 Raw
574 lines · plain
1.. SPDX-License-Identifier: GPL-2.02 3=========================4Generic Counter Interface5=========================6 7Introduction8============9 10Counter devices are prevalent among a diverse spectrum of industries.11The ubiquitous presence of these devices necessitates a common interface12and standard of interaction and exposure. This driver API attempts to13resolve the issue of duplicate code found among existing counter device14drivers by introducing a generic counter interface for consumption. The15Generic Counter interface enables drivers to support and expose a common16set of components and functionality present in counter devices.17 18Theory19======20 21Counter devices can vary greatly in design, but regardless of whether22some devices are quadrature encoder counters or tally counters, all23counter devices consist of a core set of components. This core set of24components, shared by all counter devices, is what forms the essence of25the Generic Counter interface.26 27There are three core components to a counter:28 29* Signal:30  Stream of data to be evaluated by the counter.31 32* Synapse:33  Association of a Signal, and evaluation trigger, with a Count.34 35* Count:36  Accumulation of the effects of connected Synapses.37 38SIGNAL39------40A Signal represents a stream of data. This is the input data that is41evaluated by the counter to determine the count data; e.g. a quadrature42signal output line of a rotary encoder. Not all counter devices provide43user access to the Signal data, so exposure is optional for drivers.44 45When the Signal data is available for user access, the Generic Counter46interface provides the following available signal values:47 48* SIGNAL_LOW:49  Signal line is in a low state.50 51* SIGNAL_HIGH:52  Signal line is in a high state.53 54A Signal may be associated with one or more Counts.55 56SYNAPSE57-------58A Synapse represents the association of a Signal with a Count. Signal59data affects respective Count data, and the Synapse represents this60relationship.61 62The Synapse action mode specifies the Signal data condition that63triggers the respective Count's count function evaluation to update the64count data. The Generic Counter interface provides the following65available action modes:66 67* None:68  Signal does not trigger the count function. In Pulse-Direction count69  function mode, this Signal is evaluated as Direction.70 71* Rising Edge:72  Low state transitions to high state.73 74* Falling Edge:75  High state transitions to low state.76 77* Both Edges:78  Any state transition.79 80A counter is defined as a set of input signals associated with count81data that are generated by the evaluation of the state of the associated82input signals as defined by the respective count functions. Within the83context of the Generic Counter interface, a counter consists of Counts84each associated with a set of Signals, whose respective Synapse85instances represent the count function update conditions for the86associated Counts.87 88A Synapse associates one Signal with one Count.89 90COUNT91-----92A Count represents the accumulation of the effects of connected93Synapses; i.e. the count data for a set of Signals. The Generic94Counter interface represents the count data as a natural number.95 96A Count has a count function mode which represents the update behavior97for the count data. The Generic Counter interface provides the following98available count function modes:99 100* Increase:101  Accumulated count is incremented.102 103* Decrease:104  Accumulated count is decremented.105 106* Pulse-Direction:107  Rising edges on signal A updates the respective count. The input level108  of signal B determines direction.109 110* Quadrature:111  A pair of quadrature encoding signals are evaluated to determine112  position and direction. The following Quadrature modes are available:113 114  - x1 A:115    If direction is forward, rising edges on quadrature pair signal A116    updates the respective count; if the direction is backward, falling117    edges on quadrature pair signal A updates the respective count.118    Quadrature encoding determines the direction.119 120  - x1 B:121    If direction is forward, rising edges on quadrature pair signal B122    updates the respective count; if the direction is backward, falling123    edges on quadrature pair signal B updates the respective count.124    Quadrature encoding determines the direction.125 126  - x2 A:127    Any state transition on quadrature pair signal A updates the128    respective count. Quadrature encoding determines the direction.129 130  - x2 B:131    Any state transition on quadrature pair signal B updates the132    respective count. Quadrature encoding determines the direction.133 134  - x4:135    Any state transition on either quadrature pair signals updates the136    respective count. Quadrature encoding determines the direction.137 138A Count has a set of one or more associated Synapses.139 140Paradigm141========142 143The most basic counter device may be expressed as a single Count144associated with a single Signal via a single Synapse. Take for example145a counter device which simply accumulates a count of rising edges on a146source input line::147 148                Count                Synapse        Signal149                -----                -------        ------150        +---------------------+151        | Data: Count         |    Rising Edge     ________152        | Function: Increase  |  <-------------   / Source \153        |                     |                  ____________154        +---------------------+155 156In this example, the Signal is a source input line with a pulsing157voltage, while the Count is a persistent count value which is repeatedly158incremented. The Signal is associated with the respective Count via a159Synapse. The increase function is triggered by the Signal data condition160specified by the Synapse -- in this case a rising edge condition on the161voltage input line. In summary, the counter device existence and162behavior is aptly represented by respective Count, Signal, and Synapse163components: a rising edge condition triggers an increase function on an164accumulating count datum.165 166A counter device is not limited to a single Signal; in fact, in theory167many Signals may be associated with even a single Count. For example, a168quadrature encoder counter device can keep track of position based on169the states of two input lines::170 171                   Count                 Synapse     Signal172                   -----                 -------     ------173        +-------------------------+174        | Data: Position          |    Both Edges     ___175        | Function: Quadrature x4 |  <------------   / A \176        |                         |                 _______177        |                         |178        |                         |    Both Edges     ___179        |                         |  <------------   / B \180        |                         |                 _______181        +-------------------------+182 183In this example, two Signals (quadrature encoder lines A and B) are184associated with a single Count: a rising or falling edge on either A or185B triggers the "Quadrature x4" function which determines the direction186of movement and updates the respective position data. The "Quadrature187x4" function is likely implemented in the hardware of the quadrature188encoder counter device; the Count, Signals, and Synapses simply189represent this hardware behavior and functionality.190 191Signals associated with the same Count can have differing Synapse action192mode conditions. For example, a quadrature encoder counter device193operating in a non-quadrature Pulse-Direction mode could have one input194line dedicated for movement and a second input line dedicated for195direction::196 197                   Count                   Synapse      Signal198                   -----                   -------      ------199        +---------------------------+200        | Data: Position            |    Rising Edge     ___201        | Function: Pulse-Direction |  <-------------   / A \ (Movement)202        |                           |                  _______203        |                           |204        |                           |       None         ___205        |                           |  <-------------   / B \ (Direction)206        |                           |                  _______207        +---------------------------+208 209Only Signal A triggers the "Pulse-Direction" update function, but the210instantaneous state of Signal B is still required in order to know the211direction so that the position data may be properly updated. Ultimately,212both Signals are associated with the same Count via two respective213Synapses, but only one Synapse has an active action mode condition which214triggers the respective count function while the other is left with a215"None" condition action mode to indicate its respective Signal's216availability for state evaluation despite its non-triggering mode.217 218Keep in mind that the Signal, Synapse, and Count are abstract219representations which do not need to be closely married to their220respective physical sources. This allows the user of a counter to221divorce themselves from the nuances of physical components (such as222whether an input line is differential or single-ended) and instead focus223on the core idea of what the data and process represent (e.g. position224as interpreted from quadrature encoding data).225 226Driver API227==========228 229Driver authors may utilize the Generic Counter interface in their code230by including the include/linux/counter.h header file. This header file231provides several core data structures, function prototypes, and macros232for defining a counter device.233 234.. kernel-doc:: include/linux/counter.h235   :internal:236 237.. kernel-doc:: drivers/counter/counter-core.c238   :export:239 240.. kernel-doc:: drivers/counter/counter-chrdev.c241   :export:242 243Driver Implementation244=====================245 246To support a counter device, a driver must first allocate the available247Counter Signals via counter_signal structures. These Signals should248be stored as an array and set to the signals array member of an249allocated counter_device structure before the Counter is registered to250the system.251 252Counter Counts may be allocated via counter_count structures, and253respective Counter Signal associations (Synapses) made via254counter_synapse structures. Associated counter_synapse structures are255stored as an array and set to the synapses array member of the256respective counter_count structure. These counter_count structures are257set to the counts array member of an allocated counter_device structure258before the Counter is registered to the system.259 260Driver callbacks must be provided to the counter_device structure in261order to communicate with the device: to read and write various Signals262and Counts, and to set and get the "action mode" and "function mode" for263various Synapses and Counts respectively.264 265A counter_device structure is allocated using counter_alloc() and then266registered to the system by passing it to the counter_add() function, and267unregistered by passing it to the counter_unregister function. There are268device managed variants of these functions: devm_counter_alloc() and269devm_counter_add().270 271The struct counter_comp structure is used to define counter extensions272for Signals, Synapses, and Counts.273 274The "type" member specifies the type of high-level data (e.g. BOOL,275COUNT_DIRECTION, etc.) handled by this extension. The "``*_read``" and276"``*_write``" members can then be set by the counter device driver with277callbacks to handle that data using native C data types (i.e. u8, u64,278etc.).279 280Convenience macros such as ``COUNTER_COMP_COUNT_U64`` are provided for281use by driver authors. In particular, driver authors are expected to use282the provided macros for standard Counter subsystem attributes in order283to maintain a consistent interface for userspace. For example, a counter284device driver may define several standard attributes like so::285 286        struct counter_comp count_ext[] = {287                COUNTER_COMP_DIRECTION(count_direction_read),288                COUNTER_COMP_ENABLE(count_enable_read, count_enable_write),289                COUNTER_COMP_CEILING(count_ceiling_read, count_ceiling_write),290        };291 292This makes it simple to see, add, and modify the attributes that are293supported by this driver ("direction", "enable", and "ceiling") and to294maintain this code without getting lost in a web of struct braces.295 296Callbacks must match the function type expected for the respective297component or extension. These function types are defined in the struct298counter_comp structure as the "``*_read``" and "``*_write``" union299members.300 301The corresponding callback prototypes for the extensions mentioned in302the previous example above would be::303 304        int count_direction_read(struct counter_device *counter,305                                 struct counter_count *count,306                                 enum counter_count_direction *direction);307        int count_enable_read(struct counter_device *counter,308                              struct counter_count *count, u8 *enable);309        int count_enable_write(struct counter_device *counter,310                               struct counter_count *count, u8 enable);311        int count_ceiling_read(struct counter_device *counter,312                               struct counter_count *count, u64 *ceiling);313        int count_ceiling_write(struct counter_device *counter,314                                struct counter_count *count, u64 ceiling);315 316Determining the type of extension to create is a matter of scope.317 318* Signal extensions are attributes that expose information/control319  specific to a Signal. These types of attributes will exist under a320  Signal's directory in sysfs.321 322  For example, if you have an invert feature for a Signal, you can have323  a Signal extension called "invert" that toggles that feature:324  /sys/bus/counter/devices/counterX/signalY/invert325 326* Count extensions are attributes that expose information/control327  specific to a Count. These type of attributes will exist under a328  Count's directory in sysfs.329 330  For example, if you want to pause/unpause a Count from updating, you331  can have a Count extension called "enable" that toggles such:332  /sys/bus/counter/devices/counterX/countY/enable333 334* Device extensions are attributes that expose information/control335  non-specific to a particular Count or Signal. This is where you would336  put your global features or other miscellaneous functionality.337 338  For example, if your device has an overtemp sensor, you can report the339  chip overheated via a device extension called "error_overtemp":340  /sys/bus/counter/devices/counterX/error_overtemp341 342Subsystem Architecture343======================344 345Counter drivers pass and take data natively (i.e. ``u8``, ``u64``, etc.)346and the shared counter module handles the translation between the sysfs347interface. This guarantees a standard userspace interface for all348counter drivers, and enables a Generic Counter chrdev interface via a349generalized device driver ABI.350 351A high-level view of how a count value is passed down from a counter352driver is exemplified by the following. The driver callbacks are first353registered to the Counter core component for use by the Counter354userspace interface components::355 356        Driver callbacks registration:357        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~358                        +----------------------------+359                        | Counter device driver      |360                        +----------------------------+361                        | Processes data from device |362                        +----------------------------+363                                |364                         -------------------365                        / driver callbacks /366                        -------------------367                                |368                                V369                        +----------------------+370                        | Counter core         |371                        +----------------------+372                        | Routes device driver |373                        | callbacks to the     |374                        | userspace interfaces |375                        +----------------------+376                                |377                         -------------------378                        / driver callbacks /379                        -------------------380                                |381                +---------------+---------------+382                |                               |383                V                               V384        +--------------------+          +---------------------+385        | Counter sysfs      |          | Counter chrdev      |386        +--------------------+          +---------------------+387        | Translates to the  |          | Translates to the   |388        | standard Counter   |          | standard Counter    |389        | sysfs output       |          | character device    |390        +--------------------+          +---------------------+391 392Thereafter, data can be transferred directly between the Counter device393driver and Counter userspace interface::394 395        Count data request:396        ~~~~~~~~~~~~~~~~~~~397                         ----------------------398                        / Counter device       \399                        +----------------------+400                        | Count register: 0x28 |401                        +----------------------+402                                |403                         -----------------404                        / raw count data /405                        -----------------406                                |407                                V408                        +----------------------------+409                        | Counter device driver      |410                        +----------------------------+411                        | Processes data from device |412                        |----------------------------|413                        | Type: u64                  |414                        | Value: 42                  |415                        +----------------------------+416                                |417                         ----------418                        / u64     /419                        ----------420                                |421                +---------------+---------------+422                |                               |423                V                               V424        +--------------------+          +---------------------+425        | Counter sysfs      |          | Counter chrdev      |426        +--------------------+          +---------------------+427        | Translates to the  |          | Translates to the   |428        | standard Counter   |          | standard Counter    |429        | sysfs output       |          | character device    |430        |--------------------|          |---------------------|431        | Type: const char * |          | Type: u64           |432        | Value: "42"        |          | Value: 42           |433        +--------------------+          +---------------------+434                |                               |435         ---------------                 -----------------------436        / const char * /                / struct counter_event /437        ---------------                 -----------------------438                |                               |439                |                               V440                |                       +-----------+441                |                       | read      |442                |                       +-----------+443                |                       \ Count: 42 /444                |                        -----------445                |446                V447        +--------------------------------------------------+448        | `/sys/bus/counter/devices/counterX/countY/count` |449        +--------------------------------------------------+450        \ Count: "42"                                      /451         --------------------------------------------------452 453There are four primary components involved:454 455Counter device driver456---------------------457Communicates with the hardware device to read/write data; e.g. counter458drivers for quadrature encoders, timers, etc.459 460Counter core461------------462Registers the counter device driver to the system so that the respective463callbacks are called during userspace interaction.464 465Counter sysfs466-------------467Translates counter data to the standard Counter sysfs interface format468and vice versa.469 470Please refer to the ``Documentation/ABI/testing/sysfs-bus-counter`` file471for a detailed breakdown of the available Generic Counter interface472sysfs attributes.473 474Counter chrdev475--------------476Translates Counter events to the standard Counter character device; data477is transferred via standard character device read calls, while Counter478events are configured via ioctl calls.479 480Sysfs Interface481===============482 483Several sysfs attributes are generated by the Generic Counter interface,484and reside under the ``/sys/bus/counter/devices/counterX`` directory,485where ``X`` is to the respective counter device id. Please see486``Documentation/ABI/testing/sysfs-bus-counter`` for detailed information487on each Generic Counter interface sysfs attribute.488 489Through these sysfs attributes, programs and scripts may interact with490the Generic Counter paradigm Counts, Signals, and Synapses of respective491counter devices.492 493Counter Character Device494========================495 496Counter character device nodes are created under the ``/dev`` directory497as ``counterX``, where ``X`` is the respective counter device id.498Defines for the standard Counter data types are exposed via the499userspace ``include/uapi/linux/counter.h`` file.500 501Counter events502--------------503Counter device drivers can support Counter events by utilizing the504``counter_push_event`` function::505 506        void counter_push_event(struct counter_device *const counter, const u8 event,507                                const u8 channel);508 509The event id is specified by the ``event`` parameter; the event channel510id is specified by the ``channel`` parameter. When this function is511called, the Counter data associated with the respective event is512gathered, and a ``struct counter_event`` is generated for each datum and513pushed to userspace.514 515Counter events can be configured by users to report various Counter516data of interest. This can be conceptualized as a list of Counter517component read calls to perform. For example:518 519        +------------------------+------------------------+520        | COUNTER_EVENT_OVERFLOW | COUNTER_EVENT_INDEX    |521        +========================+========================+522        | Channel 0              | Channel 0              |523        +------------------------+------------------------+524        | * Count 0              | * Signal 0             |525        | * Count 1              | * Signal 0 Extension 0 |526        | * Signal 3             | * Extension 4          |527        | * Count 4 Extension 2  +------------------------+528        | * Signal 5 Extension 0 | Channel 1              |529        |                        +------------------------+530        |                        | * Signal 4             |531        |                        | * Signal 4 Extension 0 |532        |                        | * Count 7              |533        +------------------------+------------------------+534 535When ``counter_push_event(counter, COUNTER_EVENT_INDEX, 1)`` is called536for example, it will go down the list for the ``COUNTER_EVENT_INDEX``537event channel 1 and execute the read callbacks for Signal 4, Signal 4538Extension 0, and Count 7 -- the data returned for each is pushed to a539kfifo as a ``struct counter_event``, which userspace can retrieve via a540standard read operation on the respective character device node.541 542Userspace543---------544Userspace applications can configure Counter events via ioctl operations545on the Counter character device node. There following ioctl codes are546supported and provided by the ``linux/counter.h`` userspace header file:547 548* :c:macro:`COUNTER_ADD_WATCH_IOCTL`549 550* :c:macro:`COUNTER_ENABLE_EVENTS_IOCTL`551 552* :c:macro:`COUNTER_DISABLE_EVENTS_IOCTL`553 554To configure events to gather Counter data, users first populate a555``struct counter_watch`` with the relevant event id, event channel id,556and the information for the desired Counter component from which to557read, and then pass it via the ``COUNTER_ADD_WATCH_IOCTL`` ioctl558command.559 560Note that an event can be watched without gathering Counter data by561setting the ``component.type`` member equal to562``COUNTER_COMPONENT_NONE``. With this configuration the Counter563character device will simply populate the event timestamps for those564respective ``struct counter_event`` elements and ignore the component565value.566 567The ``COUNTER_ADD_WATCH_IOCTL`` command will buffer these Counter568watches. When ready, the ``COUNTER_ENABLE_EVENTS_IOCTL`` ioctl command569may be used to activate these Counter watches.570 571Userspace applications can then execute a ``read`` operation (optionally572calling ``poll`` first) on the Counter character device node to retrieve573``struct counter_event`` elements with the desired data.574