Skip to contentSkip to conversation

net: wwan: t9xx: Add MediaTek T9XX WWAN driver

PATCH Superseded Jack Wu 3 participants 19 messages Nov 17 – Nov 23

Subsystems (5)

v12 of 14 Superseded Latest is v14 →

lore
Share & tools
lore

Jack Wu

author
#0 lore raw

v12 cover net: wwan: t9xx: Add MediaTek T9XX WWAN driver

T9XX is the PCIe host device driver for MediaTek's t900 modem. The driver uses the WWAN framework infrastructure to create the following control ports and network interfaces for data transactions.
* /dev/wwan0at0 - Interface that supports AT commands.
* /dev/wwan0mbim0 - Interface conforming to the MBIM protocol.
* wwan0-X - Primary network interface for IP traffic.

The main blocks in the T9XX driver are:
* HW layer - Abstracts the hardware bus operations for the device, and provides generic interfaces for the transaction layer to get the device's information and control the device's behavior. It includes:

* PCIe - Implements probe, removal and interrupt handling.
* MHCCIF (Modem Host Cross-Core Interface) - Provides interrupt channels for bidirectional event notification such as handshake and port enumeration.

* Transaction layer - Implements data transactions for the control plane and the data plane. It includes:

* DPMAIF (Data Plane Modem AP Interface) - Controls the hardware that provides uplink and downlink queues for the data path. The data exchange takes place using circular buffers to share data buffer addresses and metadata to describe the packets.
* CLDMA (Cross Layer DMA) - Manages the hardware used by the port layer to send control messages to the device using MediaTek's CCCI (Cross-Core Communication Interface) protocol.
* TX Services - Dispatch packets from the port layer to the device.
* RX Services - Dispatch packets to the port layer when receiving packets from the device.

* Port layer - Provides control plane and data plane interfaces to userspace. It includes:

* Control Plane - Provides device node interfaces for controlling data transactions.
* Data Plane - Provides network link interfaces wwanX (0, 1, 2...) for IP data transactions.

* Device lifecycle management - Contains the logic that keeps the device working. It includes:

* FSM (Finite State Machine) - Drives the T9xx device lifecycle (boot handshake, error recovery, removal), and notifies each module when the state changes.

The compilation of the T9XX driver is enabled by the CONFIG_MTK_T9XX config option, which depends on CONFIG_WWAN.

This submission covers the control plane only (patches 1-6). The data plane will follow in a separate series once the control plane is accepted.

Statistics are intentionally left out of this series.

---
Changes in v12:
- Rebased onto net-next and tagged for it.
- Patch 1 (Add PCIe core):
- remove() saves the PCI state right before the modem reset and restores it right after, as t7xx does; probe() no longer keeps a copy (Brian Norris)
- The save runs after pci_clear_master(), so the restored command register has bus mastering off (Brian Norris)
- Removed the comment that tied the saved state to runtime PM, which the driver does not use (Brian Norris)
- mtk_pci_bar_init() checks both BAR lengths before mapping them and fails the probe with -ENODEV (Sashiko)
- pcim_iomap_region() gets KBUILD_MODNAME as the region name (Sashiko)
- The MSI-X vectors are freed after mtk_mhccif_exit(), so MSI-X stays on until the MHCCIF work is cancelled (Sashiko)
- remove(), doorbell reset: after the fixed wait, also poll for a link that is still down before restoring config space (Sashiko)
- Commit message: a crash kexec skips .shutdown, so kdump is not covered (Sashiko)
- No write to the MSI-X vector config register: 32 vectors map 1:1 at the MAC's power-on default; a comment says so (Sashiko)
- No change when the reset in remove() did not take effect: probe has no stronger reset; the commit message says so (Sashiko)
- No reset or firmware detection in probe: it would reboot the modem on every boot and has the same tools as remove() (Sashiko)
- .shutdown resets the modem only for a kexec reboot, using kexec_is_in_progress()
- Kconfig: dropped the ACPI dependency; net-next has !CONFIG_ACPI stubs for every ACPI call the driver makes
- Back to pcim_enable_device(): remove() now restores config space after the reset, so the managed disable that follows is harmless
- remove() saves config space only while the link is up
- The MHCCIF callback list is protected by a mutex instead of a BH-disabling spinlock; every user runs in process context
- The IRQ and MHCCIF event callbacks return void; the value was never used
- mtk_pci_map_evt_bit() is no longer marked inline
- Commit message: system suspend is not supported in this series
- Patch 2 (Add control plane transaction layer framework):
- Dropped a copyright line added by mistake
- Commit message describes struct mtk_ctrl_blk as it is in this patch
- Patch 3 (Add control DMA interface):
- mtk_cldma_rearm_queues() programs every TX queue from mtk_cldma_tx_start_idx() and starts one that still has HWO, so a kicked queue is not left stopped after a reset (Sashiko)
- mtk_cldma_hw_recovery() no longer re-initialises a running IP: a zero start address again means only lost queue state (Sashiko)
- mtk_cldma_rxq_restart() checks HWO at free_idx first, so RX no longer stalls on a descriptor completed before a reset (Sashiko)
- mtk_cldma_drv_reset() waits 1 ms after releasing the reset (Sashiko)
- The comment at the ILLEGAL_MEMORY_CHECK_DISABLE write says what the check covers and why it is off (Sashiko)
- No change to resetting a whole CLDMA instance when a queue does not stop; the commit message says it cuts the other queues, which the re-arm restarts (Sashiko)
- mtk_cldma_txq_flush() completes a request the device already sent with status 0, so a writer does not resend it
- Removed the all-zero TRB service mapping table (mtk_srv_cfg[])
- The TRB thread's wait condition reads a queue head under its lock
- Rate-limited the RX "HWO" error; dropped a duplicated probe error
- The mtk_cldma_fsm_state_listener() declaration and the acquire-load comments moved to the FSM patch, which adds what they refer to
- Commit message: the per-instance CLDMA setup (DMA pools, workqueue, IRQ) arrives with the FSM patch
- Patch 4 (Add control port):
- No change to RX routing by the header's channel: t7xx does the same, and queues can be shared by several channels (Sashiko)
- No change to the sequence number reset in mtk_port_ch_enable(): it only runs while the port is not enabled (Sashiko)
- The port table uses an XArray instead of the radix-tree API
- mtk_port_release() uses kfree(): since v10 no lookup relies on the RCU grace period added in v9
- mtk_port_internal_enable() sets PORT_S_ENABLE only after the channel was enabled
- mtk_port_ch_enable() logs an ENABLE that timed out or was refused
- mtk_port_tx_complete() reuses mtk_port_ch_trb_complete()
- Patch 5 (Add FSM thread):
- mtk_cldma_start_xfer() tests is_stopping before reading the start address, so a queue err_work owns returns -EPIPE (Sashiko)
- A stop that times out in mtk_cldma_tx() sets is_stopping, as err_work does (Sashiko)
- mtk_fsm_parse_hs2_msg() checks the HS2 patterns before running any feature action (Sashiko)
- A BACKWARD_COMPAT feature is used only if the host asked for it, as in t7xx; an unqueried slot is skipped (Sashiko)
- Removed the hif_err[] READY gate, so READY is no longer refused with the FSM left in BOOTUP: a failed transport init already keeps that side's handshake from completing (Sashiko)
- The mtk_fsm_hif_err_record() comment that implied a retry is gone with the gate (Sashiko)
- Commit message: an MD-only device needs only the MD handshake; a failed transport init leaves that handshake incomplete (Sashiko)
- Comments in mtk_fsm_init() and mtk_pci_dev_exit() say the thread is stopped, not parked (Sashiko)
- No change to is_stopping staying set after a failed stop; the comment no longer reads as if a re-arm cleared it (Sashiko)
- A failed handshake no longer re-opens its MHCCIF channel: the device sends HS1 once per boot and does not retry
- FSM events are allocated with GFP_KERNEL
- Dropped the hs_info->rt_data guard; a repeated HS2 is dropped when that side's handshake is already done
- DEV_RM before DEV_ADD returns success instead of -EPROTO
- Dropped the FSM_STATE_OFF indication to the transport, which no listener handles
- Removed the notifier priority and the unused from/evt_id fields of struct mtk_fsm_param
- mtk_port_tbl_destroy() uses mtk_port_disable()
- The CLDMA and MHCCIF callbacks return void (see patch 1)
- Commit message: port manager transitions; a modem that reboots after READY is not recovered until rebind
- Patch 6 (Add AT & MBIM WWAN ports):
- port->tx_mtu is used as the payload budget; the CCCI header was subtracted twice (Sashiko)
- mtk_port_enable_by_type() no longer clears port->enable: READY is reached at most once per bind (Sashiko)
- The PORT_S_* comment says how a WWAN open is ordered against

    ->disable() (Sashiko)

- No change for a retried handshake with a different port list:
clearing all flags would wipe the other side's (Sashiko)
- TX skbs are sized for the packet instead of a full MTU
- The wwan_create_port() failure message prints the error
- The HIF-teardown locking rule is documented on struct mtk_port_ops
and covers recv as well as tx_complete
- Commit message: a blocking write waits for queue space as t7xx does,
then for each packet to complete, to return the TX status
- Link to v11: https://patch.msgid.link/[email protected]

Changes in v11:
- Patch 1 (Add PCIe core):
- Trimmed mtk_dev.h to <linux/bits.h>, <linux/types.h> and a forward declaration of struct device; seven unused includes dropped (Loic Poulain)
- Replaced the SET_HW_BITS() statement-expression macro with a static inline helper, used for the reverse event mapping too (Loic Poulain)
- Removed mtk_pci_ack_dev_state(), which has no caller in the series (Sashiko)
- mtk_pci_probe() saves and stores the PCI state before pci_set_master(), so the restore in remove() no longer re-enables bus mastering; remove()'s pci_clear_master() is gone (Sashiko)
- Added .shutdown, which runs the remove() teardown and reset; without it a kexec reboot left the firmware running with its one-shot boot notification already consumed (Sashiko)
- Comments: irq_cb_lock covers irq_cb_list[] and the irq_cb_data[] store; a device misreporting its BAR sizes is out of scope rather than impossible (Sashiko)
- Still no pci_resource_len() checks: the kernel assumes a device behaves to its specification, and the BAR sizes of the two bound products are fixed in hardware (Sashiko)
- The probe error path disables the ATR tables it enabled; removed a leftover probe-time pci_restore_state(), an unused include and a duplicate mdev->dev store; file-local helpers are static
- remove(): warn if the ACPI reset fails with the link already down, sleep only after a doorbell that was actually sent, and poll up to 1 s for the device before restoring its config space
- Clear MHCCIF level 1 before reading level 2, so an event raised while the work runs is not lost
- pci_driver.name is KBUILD_MODNAME; .class and .class_mask are named in the ID table; parameter and registration errors return -EINVAL/-EBUSY/-ENOENT instead of -EFAULT
- Commit message and kernel-doc: the doorbell fallback also covers a failing MRST._RST, every shutdown resets the modem, and the MHCCIF callback registration states its context rules
- Patch 2 (Add control plane transaction layer framework):
- Removed the unused mtk_ctrl_trans.ctrl_blk back-pointer
- Patch 3 (Add control DMA interface):
- mtk_cldma_rx_done_work(): the buffer-reload and DMA-mapping-error exits go through the need_restart handling, so a queue waiting for a restart is not left stalled (Sashiko)
- Removed the BD (multi-descriptor) CLDMA path, its DMA pool and the

    frag_size fields: every queue has MTU == frag_size, so it never ran

- Removed dead code: 30 unread register-table fields, a duplicate queue-count macro, an MTU self-compare, a single-pass do/while, a stub dev_start(), the rx_done() -EAGAIN retry loop and its force_recv
- rearm_lock, introduced here, serialises the instance reset and re-arm against RX resume/restart and TX kicks; a re-armed TX queue starts at
the first descriptor the device still owns
- A re-arm that leaves a started TX queue stopped is no longer a failed recovery; a failed TX start with a dead link fails its requests at
once; a DISABLE flush no longer fails an ENABLE queued behind it
- The RX worker re-queues itself when a refill fails; the RX cursor high word is re-read and an all-ones half treated as link loss
- const register and queue tables; trans->available is a bool under submit_lock; queue numbers print with %u; static_assert() that struct
trb still fits in skb->cb
- Patch 4 (Add control port):
- mtk_port_status_update(): reject a port-enumeration message shorter
than its header; the only length check came after three header reads (Sashiko)
- Stamp the TX sequence number when the trb thread hands the packet to
CLDMA and advance it only on success, so a packet that fails after it
was queued takes no number instead of leaving a gap (Sashiko)
- mtk_port_check_rx_seq(): skip the check only while rx_seq holds a
reset sentinel, warn rate-limited and always deliver; a stored 0
disabled the check, and a gap dropped a valid packet (Sashiko)
- Port state transitions use test_and_set_bit()/test_and_clear_bit() (Sashiko)
- Commit message: the port-state, RX dispatch and TRB kref paths only
become live with the FSM patch, together with the teardown order they
rely on (Sashiko)
- Comments: tx_seq has a single writer, at hardware hand-off; a receive callback and its argument must stay valid until the receive path is drained, because close alone does not wait (Sashiko)
- The raw port pointers in trb->priv and rxq->arg are safe, and a failed channel disable is only logged: the queues and trb services are torn
down before the ports are freed (Sashiko)
- Removed dead code: the cdev RX buffering fields, trb->hdr_added, the
port counter, a duplicated completion callback and two macros that hid
a continue
- The blocking write waits with wait_event_interruptible() and its
result follows the TRB outcome; the PORT_S_FLUSH exit that reported a
full write is gone
- RX dispatch drops a packet whose channel peer does not match the
receiving CLDMA instance; mtk_port_strip_header() uses pskb_may_pull()
and does the pull; RX warnings are rate-limited
- The internal receive callback is published with release/acquire
ordering; control skbs are sized for their payload, not the queue MTU
- Comments: a port must outlive the trbs and RX queues holding its
pointer; PORT_S_FLUSH has one setter; status bits are state, not locks
- Patch 5 (Add FSM thread):
- mtk_cldma_dev_exit(): call dma_pool_destroy() unconditionally; a pool
with blocks outstanding keeps its pages anyway, so the special case
only leaked the struct dma_pool (Sashiko)
- mtk_cldma_rearm_queues(): never restart a queue that is being
stopped, and do nothing once the instance is quiesced; the quiesce
uses drain_workqueue() (Sashiko)
- mtk_fsm_startup_act(): on a handshake error unmask only that
handshake's channel, and re-check the event gate after unmasking so a callback racing removal cannot undo its masking (Sashiko)
- A MUST_SUPPORT feature carries no host data, so HS3 still echoes it
back with data_len 0; a comment there says why no per-feature handler table is needed (Sashiko)
- Removed the per-transition KOBJ_CHANGE uevent (non KEY=VALUE payload,
no consumer) and mtk_utility.h with it
- Removed dead code: the pre-transition notifier list and its register parameter, the event mdev and len fields, an impossible hs_id check,
an unreachable DEV_ADD state and mtk_fsm_start()
- mtk_fsm_evt_submit() returns 0 or a negative errno instead of private codes, always allocates with GFP_ATOMIC, and probe passes its error on
- QUEUE_ERROR is no longer re-unmasked from the ISR; txq/rxq_free()
clear the latched error and flush err_work after the final mask; a TX
stop failing with -ENODEV counts as stopped
- One HS2 handler for both peers, its duplicate guard claimed by
cmpxchg(); mtk_fsm_exit() reuses mtk_fsm_stop(); the MHCCIF callbacks unmask through a gate-aware helper
- pcie/mtk_trans_ctrl.h no longer includes mtk_port.h
- Patch 6 (Add AT & MBIM WWAN ports):
- mtk_port_common_write(): in blocking mode wait on the port's trb wait queue for HIF queue space instead of bypassing the depth check; v10
had left the blocking path with no bound (Sashiko)
- mtk_port_enable_by_type() walks the port table in place and clears port->enable before enabling; the blocking TX wait returns
-ERESTARTSYS; the tx_mtu guard rejects a header-only MTU
- Link to v10: https://patch.msgid.link/[email protected]

Changes in v10:
- Patch 1 (Add PCIe core):
- Kconfig: depends on PCI && ACPI -> PCI_MSI && ACPI; the driver only ever requests MSI-X, so a CONFIG_PCI_MSI=n build linked but could never probe
- t9xx_pci_table[] uses PCI_VENDOR_ID_MEDIATEK in place of the private MTK_PCI_VENDOR_ID define, matching t7xx
- Dropped CEI_PCI_VENDOR_ID, which named the wrong company; the second entry is a bare 0x03f0 with an /* HP RMM-G4 */ comment and the commit message now names both bound products
- ATR inbound WIN0 source address: pci_resource_start() -> pci_bus_address(); the endpoint matches a PCI bus address, not a CPU physical address
- mtk_pci_bar_init() comment: the MSI-X window reaches 0x3103, not 0x3080, and the fixed offsets are guaranteed by the only two devices this driver binds, whose BAR sizes are fixed by hardware
- mtk_pci_unregister_irq() publishes the NULL callback under irq_cb_lock before synchronize_irq() and clears irq_cb_data only afterwards, so a live callback cannot be paired with NULL data
- mtk_pci_free_irq() sets priv->irq_cnt = 0 after pci_free_irq_vectors(), so mtk_pci_get_virq_id() stops handing out virqs for vectors that no longer exist
- mtk_pci_remove() frees the IRQ vectors before mtk_mhccif_exit(), the order the probe error path already used, so the unmask at the tail of mtk_mhccif_isr_work() cannot re-open the source
- mtk_pci_remove() calls pci_restore_state() and pci_clear_master() after pci_load_and_free_saved_state(): the reset leaves the device at power-on defaults and the state was saved after pci_set_master()
- mtk_pci_remove() sleeps after the MHCCIF reset doorbell, which unlike MRST._RST returns before the device has reset, so the config restore needs it to settle first
- Commit message: MRST._RST is a platform-level reset that does not depend on firmware state, and the MHCCIF doorbell is a best-effort fallback that cannot recover stopped firmware
- The three ACPI capability checks in mtk_pci_pldr_setup() are dev_dbg() rather than dev_err(): probe does not require MRST._RST, and without it only removal is degraded
- Removed mtk_pci_clear_ext_evt() and its prototype; Patch 5 removed both callers, leaving no user in this series
- Declined a read-back after the MHCCIF mask write: the posted write is followed by synchronize_irq(), which orders it
- Deferred .shutdown to the follow-up series, where it lands together with dev_pm_ops
- Patch 2 (Add control plane transaction layer framework):
- Subject gains "framework", and the commit message says mtk_ctrl_init() and mtk_ctrl_exit() get their first callers in Patch 3; the patch is unreachable at its own commit by construction
- mtk_ctrl_init() kerneldoc: ctrl_blk is devres managed, so it is released at unbind and not by mtk_ctrl_exit()
- mtk_ctrl_blk::ctrl_hw_priv is void * from the start, instead of a PCIe-specific type in a generic header
- <linux/kref.h> is no longer added here; Patch 4 adds it together with struct trb::kref, its first user, so Patch 3 no longer has to delete it again
- Patch 3 (Add control DMA interface):
- BD-mode RX clamps each BD's received length with the host-side req->frag_size as well as the device-written data_allow_len, so an oversized device value cannot overrun the buffer
- mtk_cldma_rx_done() retries mtk_cldma_reload_rx_skb() on the next pass and re-arms the slot, instead of leaving a slot whose second reload failed marked complete
- mtk_cldma_reload_rx_skb() frees the skb and clears both req->skb and req->data_dma_addr on dma_map failure, so the retry does not re-map a stale address
- mtk_cldma_rxq_free() stops the RX queue again after the flush unless the stop returned -ETIMEDOUT; rx_done_work can resume or restart the engine after it read need_exit
- mtk_cldma_rearm_queues() clears tx_started instead of starting TX from req_pool[free_idx], which can already be complete, and queues tx_done_work so a lost XFER_DONE still advances free_idx
- mtk_cldma_start_xfer() stops the queue and clears tx_started on failure, so mtk_cldma_txq_flush() does not run against a queue the hardware still owns
- mtk_cldma_drv_reset() writes only this CLDMA's bit to RST0_SET and RST0_CLR instead of read-modify-writing the whole bank, and reads each register back to flush the posted write
- That reverses the answer already sent for the reset sequencing
question: the read-modify-write on RST0_CLR releases every other block held in reset in the same bank
- mtk_ctrl_srv_exit() calls mtk_ctrl_chs_flush(srv) right after kthread_stop() instead of at the thread's tail, so queued TRBs are flushed even when the thread never ran
- DISABLE insertion tracks the last ENABLE and __skb_queue_after() it; with no ENABLE present it falls back to __skb_queue_head() rather than the tail
- trans->queue_tbl is an xarray instead of a radix_tree, which removes the radix_tree_delete() inside a radix_tree_for_each_slot() walk and the missing rcu_read_lock()
- struct trb::kref moved out of mtk_ctrl_plane.h into Patch 4, where mtk_port_trb_init() first takes the reference, rather than taking the reference earlier here
- mtk_ctrl_trb_handler() publishes trb->status with smp_store_release(), pairing with the port layer's smp_load_acquire() so it cannot be seen before the geometry stores
- mtk_cldma_open() keeps the usr_cnt increment when the open completes -EBUSY, with a comment at the decrement: -EBUSY leaves the channel open, so its eventual DISABLE releases the count
- Patch 4 (Add control port):
- mtk_ctrl_init() drops the err_free_mem label, which freed nothing, and clears mdev->ctrl_blk on failure so probe does not leave a dangling block behind
- The cfg pointers are const through mtk_port_layer_cfg and the port table helpers, which also removes the (struct mtk_port_cfg *) cast on .port_cfg
- Driver prefix on three globals: mtk_port_mngr_grp_mtx, struct

    mtk_port_ops, and a static mtk_port_ops_tbl[] behind
    mtk_port_get_ops() in place of the exported ports_ops[] table

- Removed the MTK_TRB_HEADER_ADDED (0xADDED) in-flight sentinel,
which made a blocking write return 712173 as a byte count; struct
trb carries explicit bools and that write returns -EBADF
- mtk_port_trb_done() reads smp_load_acquire(&trb->done), set by smp_store_release() in all three completions, instead of inferring completion from a status written before the callback ran
- The queue geometry copy moved from mtk_port_open_trb_complete() to mtk_port_ch_enable() after the wait, and runs for -EBUSY too, so
such an ENABLE publishes tx_mtu like any other
- Deleted the empty mtk_port_io_init()/mtk_port_io_exit(), so this
patch no longer rewrites pcie/mtk_pci.c at all; the commit message documents the trb kref instead
- mtk_port_get_by_name() does the lookup and the kref_get() in one critical section; mtk_port_search_by_name() is static and gains lockdep_assert_held()
- mtk_port_add_header() calls skb_cow_head() before skb_push() and
returns the error instead of dropping it
- The tx_seq rollback samples seq_taken into a local first, with a
comment that the kref_put()s below it free the skb that trb lives
in
- port->tx_seq = 0 / rx_seq = -1 moved from mtk_port_struct_init() to
the top of mtk_port_ch_enable(), so CCCI sequence numbering
restarts with each modem session
- Patch 5 (Add FSM thread):
- mtk_fsm_idle_evt_handler() returns void, so the handshake channels
are unmasked whether or not the STARTUP submit succeeded; the old
early return left them masked forever
- mtk_fsm_hs1_handler() masks the channel before the submit and
unmasks it again on failure, so it cannot overwrite a re-arm the
FSM thread just did on its error path
- Removed both mtk_pci_clear_ext_evt() calls; the ISR already
acknowledges the MHCCIF event, so the handlers were acking twice
- mtk_cldma_dev_exit() leaves the CLDMA vector masked after the reset
so the ISR tail cannot re-open it, and moves the WRITE_ONCE()
unpublish to the top, where the comment claims it is
- mtk_cldma_txq_free()/mtk_cldma_rxq_free() mask QUEUE_XFER_DONE and QUEUE_ERROR first, clear the latched error bit, flush err_work then
the worker, and mask XFER_DONE once more after that final flush
- mtk_cldma_err_work() is split into mtk_cldma_err_tx_one() and mtk_cldma_err_rx_one(), so an early exit on the TX side cannot skip
the RX error carrying the same index
- mtk_cldma_rxq_restart() does the stop itself and leaves the queue stopped on failure, so the restart is the only context that
programs an RX queue
- TX submit returns early on -EPIPE instead of falling into the
flush, which would unmap buffers err_work kept for the device, and re-checks is_stopping under ring_lock before publishing a new HWO
- Added mtk_cldma_drv_quiesce() and exported mtk_cldma_quiesce(); mtk_pcie_hif_exit() calls it before joining the trb services, which
the IRQ handler and the workqueue read as well
- mtk_cldma_exit() comment corrected: not all of its callers hold submit_lock
- The dma_pool_destroy() comment now says it releases the backing
pages even when blocks are outstanding, so the rings are leaked deliberately, bounded by the device instance and reported
- mtk_fsm_feature_set_match() gained comments on three arms: a
mandatory feature is fatal only on an outright refusal, and the backward-compat arm decides on the device's declaration alone
- Patch 6 (Add AT & MBIM WWAN ports):
- mtk_port_common_write() caps one write() at MTK_PORT_MAX_TX_PKT
packets and rejects more with -EMSGSIZE; packets after the first
carry force_send, which bypasses the HIF depth check
- force_send starts out as the blocking flag, so a blocking fd no
longer gets -EAGAIN on its first packet and the blocking worst case
is one queue depth rather than depth - 1
- mtk_port_common_write() reports the prefix already on the wire with dev_err_ratelimited() when a submit fails mid-message, and samples skb->len before the submit, which may free the skb
- Its comment states why that write is not made atomic: the WWAN
core already turns a partial write into a whole-write failure, and
the failed submit cannot be retried once the skb is freed
- mtk_port_wwan_tx_pause() drops w_lock around
mtk_pcie_hif_cmd_func(), which takes submit_lock; teardown holds submit_lock while calling back into this port under w_lock
- mtk_port_wwan_open() publishes w_priv.w_port in the same critical section that sets PORT_S_OPEN, so mtk_port_wwan_recv() cannot see
an open port with a NULL w_port and drop a reply
- mtk_port_get_locked() returns void and only takes the reference;
the WWAN core owns the port pointer across its .start/.stop pair
- Link to v9: https://patch.msgid.link/[email protected]

Changes in v9:
- Patch 1 (Add PCIe core):
- Dropped the priv->irq_type term from the mask/unmask/clear IRQ
guards; the field was write-only and made the probe-failure path
log a false "input irq_id=28" error
- mtk_pci_pldr() no longer requests an ACPI_ALLOCATE_BUFFER output
buffer from acpi_evaluate_object(): nothing read it and the
failure branch leaked it
- mtk_mhccif_exit() masks the MHCCIF source again after cancel_work_sync(), so a work item already past the unregister
cannot leave remove() with an unmasked source and no callback
- pcim_enable_device() -> pci_enable_device(), with explicit pci_clear_master()/pci_disable_device() in remove(): the devres
action touched config space after the ACPI reset
- The AER handler prints pci_channel_state_t with %u
- Deleted struct mtk_dev_ops and the mtk_dev_* inline wrappers;
every caller uses the mtk_pci_* implementation directly, and mtk_dev_get_dev_cfg()/mtk_pci_get_dev_cfg() are gone (no callers)
- Single module: mtk_dev.c, pcie/Makefile and CONFIG_MTK_T9XX_PCI
are gone, driver init/exit live in pcie/mtk_pci.c, and every EXPORT_SYMBOL_GPL is removed with the module boundary
- Removed the PCI dispatch-by-hw_ver table; there is one
implementation and it is called directly
- Declined a BAR length sanity check: the driver binds two fixed PCI
IDs and pcim_iomap_region() already fails probe for the
generically detectable cases
- Declined reordering the probe unwind to match remove(): probe
unwinds in reverse acquisition order, remove() deviates
deliberately and the reason is commented at the call site
- No delay added after the reset: MRST._RST is an ACPI method, so acpi_evaluate_object() returns when the AML has finished, and it
is the last device access in remove()
- Removed the PCIe PM registers and the MHCCIF PM/DPMAIF/CLDMA
channel bits; nothing in this series reads them
- Removed the unused IRQ sources, MTK_USER_MIN/DATA, DEV_EVT_*_MAX, ATR_DST_AXIM_1-3 and the <linux/debugfs.h> include
- Patch 2 (Add control plane transaction layer):
- Deleted struct mtk_ctrl_hif_ops and ctrl_blk->ops with the rest of
the single-implementation dispatch layers; mtk_ctrl_blk now holds
only mdev and trans
- Patch 3 (Add control DMA interface):
- Deleted struct cldma_drv_ops, drv_info->drv_ops,
cldma_drv_info_tbl[] and mtk_cldma_drv_m9xx.c/.h; the register
table stays as data and is assigned directly in dev_init()
- Deleted pcie/mtk_ctrl_cfg_m9xx.c: the queue, service and port
tables are file-scope statics in pcie/mtk_trans_ctrl.c and the
hw_ver lookup is gone
- REG_CLDMA_INT_WF_MASK is no longer introduced here; it had no
reader and Patch 5 used to remove it again
- Removed CLDMA_GPD_FLAG_BPS, enum mtk_ip_busy_src, DIR_MAX, unused mtk_intr_type members, six reg_* fields and the *_done_cnt counters
- mtk_cldma_txq_alloc()/rxq_alloc() take the queue_info the caller
already resolved, dropping a repeated lookup that cannot fail
- Patch 4 (Add control port):
- Deleted the stale-list and device-id-IDA machinery instead of
hardening it: nothing here can reach the stale list and dev_id was
only handed back to ida_free(), so both reported call sites are gone
- mtk_port_tbl_destroy() uses the file's own radix-tree accessor (rcu_dereference_raw()); radix_tree_deref_slot() splats under CONFIG_PROVE_RCU in this lock-free teardown
- Added port_mngr->port_tbl_mtx around the radix insert/delete and
the port_cnt update, and struct mtk_port gained a rcu_head so mtk_port_release() frees with kfree_rcu()
- Removed PORT_F_ALLOW_DROP (set, never read) and PORT_F_FORCE_SEND
(read, never set, so the term was provably zero)
- mtk_port_internal_disable() logs a failed mtk_port_ch_disable()
with dev_warn(); teardown still continues and PORT_S_ENABLE is
still cleared, or the port could never re-enable
- clear_bit(PORT_S_WR) in mtk_port_internal_disable() is followed by wake_up_all(): the blocking writer loops back on timeout and
otherwise only noticed one trb timeout later
- mtk_ctrl_init() takes a struct mtk_port_layer_cfg * directly, the
struct mtk_ctrl_cfg wrapper is gone, and mtk_port.c calls mtk_pcie_hif_submit_skb() instead of dispatching through ops
- Removed the Q_MTU_*/Q_FRAG_* sizes no queue uses, MTK_PEER_ID_SAP
and _MD, and PORT_S_DFLT/PORT_S_RD/PORT_S_STOP
- Patch 5 (Add FSM thread):
- mtk_pcie_hif_exit() stops the TRB service kthreads before mtk_cldma_exit() frees the rings they walk; the two wake_up()
sites skip a NULL trb_srv so the reorder cannot oops instead
- One owner per direction on error: err_work sets txq->is_stopping
under ring_lock and mtk_cldma_start_xfer() rechecks it there, and
the RX side hands the queue to rx_done_work through need_restart
- mtk_cldma_rx_done_work() consumes need_restart before honouring
-ENXIO, so a queue left with no start address after a reset is
restarted instead of skipped
- The RX length is clamped against req->mtu (host state) instead of
the GPD's data_allow_len, and an oversized frame is dropped with
-EPROTO
- fsm->hif_err became a per-producer array and the recorder stores unconditionally, so a successful handshake retry clears its own
slot instead of refusing FSM_STATE_READY forever
- The invalid dev_stage path of mtk_fsm_early_bootup_handler() uses
goto exit, re-arming the boot-flow channel that was masked on
entry
- Both CLDMA dma_pools are created with align 16; with align 4 the
24-byte descriptors were only 8-byte aligned every other block
- cldma_drv_info[] is published with smp_store_release() and read
with smp_load_acquire(); the removal sites and the txq/rxq slots
use WRITE_ONCE(), completing the pairing already used elsewhere
- struct runtime_feature_entry is __packed: offset advances by a device-supplied length, so a later entry's data_len can land
unaligned. The layout is unchanged
- Removed MTK_UEVENT_MINIDUMP and MTK_UEVENT_LOWPOWER, declared with
no emitter anywhere in the series
- Commit message rewritten to cover the CLDMA scope: the ISR, the QUEUE_ERROR worker and its -EPIPE completion policy, the
ring_leaked rule, the teardown changes and the FSM uevent payload
- Kept the uevent rather than reporting state through the wwan
framework: wwan exposes ports and netdevs, neither carries a
driver state machine, and adding one is a core change
- Declined splitting the CLDMA work into its own patch: the ISR is registered by dev_init(), which only the FSM listener added here
calls, so either split order leaves a non-functional commit
- mtk_fsm.c calls mtk_pci_* directly and its six EXPORT_SYMBOL_GPL
are removed
- Removed FEATURE_TYPE_MUST/OPTIONAL, FSM_PRIO_0, MTK_UEVENT_UNDEF
and _MAX, DEV_CFG_NORMAL, QUERY_RTFT_ID_MAX and the TAG define
- Patch 6 (Add AT & MBIM WWAN ports):
- Dropped .tx_poll: it poll_wait()ed on a waitqueue inside struct mtk_port, which wwan_remove_port() releases while the fd stays
open, and wake_up_pollfree() is not available to modules
- TX back-pressure now reaches poll() through wwan_port_txon() and wwan_port_txoff() on the core's waitqueue, whose lifetime the open
file pins; this also removes the errno/queue-full poll confusion
- mtk_port_common_write() builds every CCCI packet onto a local
queue before submitting any, so an allocation or copy failure can
no longer truncate a message whose first packets are on the wire
- caps.frag_len is tx_mtu minus the CCCI header, so one core
fragment is exactly one CCCI packet instead of a full packet plus
a 16-byte runt
- w_lock now covers PORT_S_OPEN on the wwan ops: a receive that saw
the port open completes wwan_port_rx() before stop() returns and
the core purges its rx queue
- clear_bit(PORT_S_WR) in mtk_port_wwan_disable() is followed by wake_up_all(), and a failed mtk_port_ch_disable() is logged with dev_warn() as in Patch 4
- Commit message corrected: init() only prepares the port object, wwan_create_port() is in enable(), which FSM_STATE_READY reaches
through the new mtk_port_enable_by_type(PORT_TBL_MD) hook
- w_port is still published after PORT_S_ENABLE/PORT_S_WR: it is wwan_create_port()'s return value and the node becomes openable
inside that call, so a comment now records the -ENXIO window
- The AT/MBIM port and queue rows are added directly to the
file-scope tables in pcie/mtk_trans_ctrl.c, and mtk_port_io.c
calls mtk_pcie_hif_cmd_func() directly
- Link to v8: https://patch.msgid.link/[email protected]

Changes in v8:
- Patch 1 (Add PCIe core):
- Commit message: reworded the MHCCIF bullet (the driver masks all channels at init and does not clear pending status) and added a paragraph on the ACPI reset performed on removal
- Added irq_cb_lock around IRQ callback register/unregister; unregister now masks the vector and calls synchronize_irq() before clearing the slot, so no callback runs after it returns
- mtk_pci_pldr() evaluates MRST._RST on the device's own ACPI node instead of PXP._OFF/_ON on the upstream bridge: the bridge power resource is shared and its 500 ms off/on induced a link down/up that a hotplug-capable port reports as a remove/add
- Removed mtk_pci_fldr(), enum mtk_reset_type, mtk_pci_dev_reset() and mtk_pci_reset(): dead here, they belong with the devlink firmware-update series that will use them
- MHCCIF interrupts are now acked before dispatch, not after; mtk_mhccif_init() masks every channel but deliberately does not ack, as the status is one-shot latched by the device
- Removed the write-only bar[] array and MTK_PCI_BAR_NUM
- Switched to pcim_iomap_region(), replacing the deprecated pcim_iomap_regions()/pcim_iomap_table() pair
- Dropped the BIT(30) exemption from the all-ones MMIO check; a stray bit is now logged with dev_err_ratelimited() and cleared
- probe() masks all MHCCIF channels unconditionally; removed the dead configuration plumbing that used to select the mask
- Check pci_save_state() and return -ENOMEM instead of -EFAULT
- Reordered remove(): dev_exit, mask all 32 channels, mhccif_exit, free_irq, clear bus master, PLDR reset last
- Removed the unused enum mtk_atr_type and the .type field
- Patch 2 (Add control plane transaction layer):
- Converted the remaining EXPORT_SYMBOL() to EXPORT_SYMBOL_GPL() (mtk_ctrl_init/exit here, mtk_port_trb_free in Patch 4, mtk_fsm_start/evt_submit/init/exit in Patch 5) and deleted the unused mtk_fsm_notifier_register/unregister exports
- Patch 3 (Add control DMA interface):
- Clamp the RX length reported by the GPD against data_allow_len and drop the packet with -EPROTO instead of trusting the device
- Publish txq[]/rxq[] with smp_store_release(); the readers added in Patch 5 pair with smp_load_acquire()
- mtk_cldma_stop_queue() returns -ENODEV on an all-ones read, escalates to cldma_drv_reset() on timeout and only leaks the ring if the queue still refuses to stop
- Added NULL checks to all six radix_tree_lookup() call sites
- mtk_cldma_rxq_free() splits ownership three ways (host-owned, device-owned, in-flight) instead of unmapping everything
- New mtk_cldma_hw_recovery(); mtk_cldma_start_xfer() rewritten to run entirely under ring_lock so a resume cannot race a submit
- Populate the control-queue entries of the queue info table here instead of in Patch 4, keeping each commit self-consistent
- srv_cfg is const int (*)[HW_QUE_NUM] instead of int **, dropping the type-punning cast
- Use skb_queue_len_lockless() where the list lock is not held
- Hold the skb_list lock across every list read; the one place it must be dropped (sleeping submit) is documented
- Check mtk_cldma_trb_process() return and add mtk_cldma_txq_flush() to complete pending requests on error
- Initialise submit_lock and trans->available in mtk_trans_ctrl_init(), with a NULL srv guard
- mtk_pcie_hif_exit() order: cldma_exit, then trb_srv_exit, then remove the radix tree
- Evaluate CHECK_TX_FULL under submit_lock
- Removed dead code found while auditing the above
- Reject a non-linear skb with -EINVAL instead of WARN_ON_ONCE()
- Commit message: probe only registers the transport plane; the CLDMA instances and the TRB service thread are started by the later "Add FSM thread" patch
- A stop timeout in mtk_cldma_txq_free()/rxq_free() resets the whole IP, so the new mtk_cldma_rearm_queues() re-arms every queue still published on that instance, not just the one being freed
- The RX re-arm is handed to mtk_cldma_rx_done_work() through a need_restart flag; it owns free_idx, which the re-arm used to read without synchronisation
- mtk_cldma_submit_tx() rejects a NULL dev, closing the window between mtk_cldma_exit() clearing trans->dev and the TRB service thread being stopped
- Patch 5 (Add FSM thread):
- New mtk_fsm_hif_err_record(): a transport init failure is sticky, so the STARTUP handler refuses the BOOTUP->READY promotion instead of reaching READY on a dead transport; DEV_ADD clears it
- A feature the device reports as NOT_EXIST/NOT_SUPPORT now fails the handshake with -EPROTO when the host marks it MUST_SUPPORT
- Both ctrl-msg handlers consume the skb on every path and return 0; the caller no longer frees behind the handler's back
- The duplicate-HS2 and invalid-id paths no longer touch rt_data, so an epilogue cannot free data owned by a queued STARTUP event
- mtk_fsm_idle_evt_handler() returns an error on a failed submit and unmasks its handshake channels only on success; mtk_fsm_early_bootup_handler() latches last_dev_state only after the handler chain succeeded, so a failure is retried
- Re-arm BOOT_FLOW_SYNC in mtk_fsm_early_bootup_handler(): the channel was masked on entry and never unmasked, so a device still booting when the driver binds never delivered its DEV_STAGE_IDLE notification and the FSM stayed at FSM_STATE_ON with no ports
- The in-flight runtime-data skb is owned by the STARTUP event it was submitted with and freed when that event completes; rt_data is demoted to a duplicate-HS2 guard and rt_data_len removed
- mtk_fsm_init() unwinds through explicit labels and no longer leaks the kthread on any error path
- mtk_fsm_exit() calls mtk_fsm_ctrl_ch_stop(), releasing the control ports while the port table they reference is still alive
- Added the 0x0900 entry to cldma_drv_info_tbl[]; the primary MediaTek PCI ID no longer fails CLDMA dev_init with -EIO
- QUEUE_ERROR is now cleared, re-unmasked and handled by a new err_work that stops the errored queues and completes their pending requests with -EPIPE, instead of being logged against a masked interrupt that is never re-armed
- mtk_cldma_dev_exit() masks the L1 interrupt and calls synchronize_irq() before unregistering the callback
- mtk_cldma_dev_exit() quiesces the IP (interrupt output disabled, cldma_drv_reset()) before releasing descriptor memory, and leaks the DMA pools as well if a ring was already leaked
- New mtk_fsm_stop(), called by mtk_pci_dev_exit() after a possibly failed DEV_RM and before mtk_trans_ctrl_exit(), so the FSM thread cannot run on a dismantled transport plane; mtk_pcie_hif_exit() is idempotent, mtk_cldma_exit() latches trans->dev, and the FSM kthread is held with get_task_struct() so a thread that died abnormally cannot be stopped through a freed task_struct
- mtk_cldma_txq_free()/rxq_free() flush err_work as well: it may already hold the queue they are about to free
- err_work no longer completes and unmaps the requests of a queue that failed to stop; the device may still be reading them
- The rt_data duplicate-HS2 guard is accessed with READ_ONCE() and WRITE_ONCE(), the rx path and the FSM kthread being concurrent
- Patch 6 (Add AT & MBIM WWAN ports):
- Commit message: note the copy path now uses skb_copy_bits()
- Removed union user_buf and mtk_port_copy_data_from(); the kernel-buffer branch had no user
- Removed mtk_port_common_write_frag_skb() and the dead scatter-gather gate it was reached through
- Fixed a heap overread: the TX path copied from a paged skb as if it were linear; use skb_copy_bits()
- mtk_port_send_data() takes explicit blocking/force_send arguments, no longer mutates the caller's flags, and is all-or-nothing
- The AT and MBIM TX callbacks are thin wrappers over a shared

    mtk_port_wwan_tx()

- A port DISABLE is inserted ahead of pending ENABLEs (Patch 3) and mtk_port_internal_enable() unwinds on failure (Patch 4), so a
close cannot be starved by a queued enable
- Declined the reordering suggested in review, with a comment
explaining the ordering constraint; w_port is read inside w_lock
- wwan_port_rx() is called only when PORT_S_OPEN is set; otherwise
the packet is dropped with -ENXIO and dev_dbg_ratelimited()
- Link to v7: https://patch.msgid.link/[email protected]

Changes in v7:
- Cover letter: renamed "Core logic" to "Device lifecycle management". The FSM is T9xx-specific (same model as the in-tree t7xx driver) and stays in the driver rather than the WWAN framework.
- Patch 1 (Add PCIe core):
- Removed RGU wording from commit message, no RGU code in the series
- Removed select NET_DEVLINK from Kconfig, no devlink consumer
- Reordered ATR setup: program TRSL_ADDR/TRSL_PARAM before enabling ATR in SRC_ADDR_LSB, with a readback, matching t7xx
- Adopted the t7xx IRQ model: require exactly MTK_IRQ_CNT_MAX MSI-X vectors with one handler per vector; removed the merged-IRQ mode and scoped dispatch to each vector's own status bits
- Fixed IRQ callback publish ordering: WRITE_ONCE + smp_wmb on register, READ_ONCE + smp_rmb in the interrupt handler
- Added hw_bits == 0 guard in mtk_pci_send_ext_evt() to reject unmapped event channels
- MHCCIF callbacks stay under spin_lock_bh by design; added a comment documenting the must-not-sleep callback contract
- Added a drain loop in mtk_mhccif_exit() to free any remaining callback nodes
- Moved cancel_work_sync(&priv->mhccif_work) before mtk_pci_pldr() in remove, preventing worker MMIO during the power cycle
- Squashed the MAINTAINERS entry into this patch (was Patch 7); the series is now 6 patches
- Patch 2 (Add control plane transaction layer):
- Commit message and Kconfig help text now name both modules (mtk_t9xx and mtk_t9xx_pcie)
- Reworded mtk_ctrl_exit() kernel-doc: the allocation itself is devres-managed and freed on driver detach
- Patch 3 (Add control DMA interface):
- RX re-map failure now keeps the buffer in its slot instead of freeing it and advancing free_idx, preventing a permanent ring stall from a stale GPD DMA address
- mtk_cldma_stop_queue() returns -ETIMEDOUT on poll timeout; alloc paths abort on failure, free paths warn and proceed
- Added READ_ONCE() for the free_idx and tx_started reads in mtk_cldma_start_xfer()
- mtk_cldma_get_tx_start_addr() reads ADDRL+ADDRH as u64, so a >4GB DMA address is not mistaken for "queue not started"
- mtk_cldma_open() decrements usr_cnt on failure. Beyond the emailed
reply: mtk_pcie_hif_init() re-zeroes usr_cnt and ENABLE/DISABLE no longer gate on TX budget, so a channel reopens after devlink reload
- mtk_cldma_close() completes the TRB with -EPIPE when drv_info is already gone, instead of stalling the submitter until timeout
- mtk_cldma_txbuf_set() returns -ENOMEM instead of -EAGAIN on dma_map failure (no infinite retry); dev_err_ratelimited
- Added the 0x0900 (MTK reference) entry to mtk_ctrl_info_tbl[]; both PCI IDs are now present in all dispatch tables
- Documented the single-consumer assumption of mtk_ctrl_trb_handler() in a comment
- Added a submit_lock mutex closing the submit vs. hif_exit race on

    trans->available; hif_cmd_func() now checks available

- Kept the empty queue table: queue_info entries are populated by the next patch "Add control port"
- Commit message notes TX/RX paths are wired up by later patches
- hif_exit has no caller at this commit, but ops->init is not called either, so nothing is allocated to leak; patch 5 wires up both
- The trb_handler default case completes the TRB with -EINVAL instead of silently leaking the SKB
- Documented the non-BD skb_headlen() == skb->len invariant
- trb_open_priv overlay size is safe by construction
- Removed the unused CLDMA4 support here at the source, instead of introducing it and deleting it again in Patch 5
- Fixed an skb leak in the mtk_cldma_rxq_free() BD path: the parent skb was never freed after detaching frag_list
- Replaced the free_idx/wr_idx boundary check added in v5 with a per-queue ring_lock following drivers/net/wwan/t7xx: the check raced with submit_tx and could stall TX forever; the lock also closes the submit/reclaim race the check was originally added for
- Removed the write-only queues_cnt and tx_req.data_vm_addr fields
- Patch 5 (Add FSM thread):
- Commit message: five FSM states (not seven); now describes the HS1/HS2/HS3 handshake and CLDMA bring-up/teardown in detail
- Check ops->init() return in FSM_STATE_ON; NULL guard for srv in

    trb_srv_exit(); check mtk_cldma_dev_init() return in the listener
  - Kept the HS2 feature parser as is: the protocol requires dense
    ascending order and the ft_id check catches violations
  - Reject data_len == 0 before calling the query_rtft handler
  - Drop duplicate HS2 messages when hs_info->rt_data is already set
  - Added a notifier_lock mutex protecting FSM notifier list walks
  - Reordered HS2 handling: parse HS2, send HS3, and only then switch
    state, so FSM_STATE_READY implies HS3 was delivered
  - Unmask the HS channels on handshake error so the modem can retry
  - Moved wake_up_process() under evtq_lock with a fsm_handler NULL
    check; exit sets GATECLOSED and clears fsm_handler under the lock
  - mtk_fsm_hs_info_init() propagates event-registration failures and
    unwinds on error
  - The CLDMA ISR logs, clears and re-unmasks QUEUE_ERROR bits
  - CLDMA dev_exit unregisters the IRQ callback before mask +
    synchronize_irq, preventing ISR re-arm after teardown
  - Reordered FSM_STATE_OFF teardown: stop the TRB threads before
    freeing CLDMA, with the per-hif teardown moved into
    mtk_cldma_exit(); fixes a silently skipped teardown that broke the
    next reset cycle and leaked the CLDMA resources
  - mtk_trans_ctrl_exit() falls back to hif_exit when the
    FSM_STATE_OFF teardown never ran (guarded by trans->available)

- mtk_pci_dev_start() propagates evt_submit/fsm_start errors
- Restored TASK_INTERRUPTIBLE for the FSM event kthread: the v2 flip to TASK_UNINTERRUPTIBLE was not requested by review, and an idle D-state kthread blocks suspend and trips the hung-task detector
- Patch 6 (Add AT & MBIM WWAN ports):
- Check and log mtk_port_enable_by_type() failure in the FSM state handler
- A short WWAN write now returns -EIO; consume_skb() on success
- The wwan_enable failure path calls mtk_port_ch_disable() to undo usr_cnt and partial resources
- Publish the wwan_port pointer only after IS_ERR validation, so the RX path never sees an ERR_PTR
- Pass wwan_port_caps (frag_len = negotiated tx_mtu, CCCI header

    headroom) to wwan_create_port(); a tx_mtu == 0 guard prevents
    userspace write() from spinning forever on frag_len == 0

- Set PORT_S_WR/PORT_S_ENABLE before wwan_create_port() and clear
both bits on failure
- Link to v6: https://patch.msgid.link/[email protected]

Changes in v6:
- Patch 3 (Add control DMA interface):
- Move extern declarations for mtk_cldma_regs_m9xx and
cldma_drv_ops_m9xx from Patch 5 to Patch 3 where the
symbols are first defined, fixing sparse W=1 C=1 warnings
- Fix RX done recycle path: skip buffer recycle in BD mode
(nr_bds > 0) to prevent BDP flag mismatch causing HW to
misinterpret data buffer address as BD chain pointer
[sashiko]
- Fix RX done recycle path: on dma_map_single failure,
free skb and advance free_idx instead of goto out, to
prevent ring stall [sashiko]
- Patch 4 (Add control port):
- Replace wake_up_interruptible_all() with wake_up_all()
for trb_wq and rx_wq in open/close/tx completion
callbacks and common_close, fixing mismatch with
wait_event_timeout (TASK_UNINTERRUPTIBLE) waiters in ch_enable/ch_disable that caused spurious timeouts
[sashiko]
- Link to v5: https://patch.msgid.link/[email protected]

Changes in v5:
- Patch 1 (Add PCIe core):
- Remove LE32_TO_U32(cpu_to_le32()) no-op endianness
roundtrip, return hw_bits directly
- Use "%s" format string in pci_request_irq() to prevent
format string injection
- Return PCI_ERS_RESULT_DISCONNECT from AER error_detected,
driver does not support AER recovery
- Patch 2 (Add control plane transaction layer):
- Rewrite commit message to accurately describe skeleton
content
- Patch 3 (Add control DMA interface):
- Replace rmb() with dma_rmb() after HWO check in TX/RX
done paths for correct DMA descriptor ordering
- Add ring boundary check in TX done to prevent crossing
into submit territory
- Fix RX stall on reload failure: recycle old buffer with
skb_trim() + dma_map_single() instead of losing descriptor
- Convert devm_kcalloc to kcalloc for req_pool and
bd_dsc_pool, matching existing kfree in teardown
- Set bd_dsc->skb = NULL after dev_kfree_skb_any() in
reload error path to prevent use-after-free
- Use skb_headlen(skb) instead of skb->len for linear
segment size in txbuf_set non-BD path
- Use WRITE_ONCE() for wr_idx update in submit_tx
- Patch 4 (Add control port):
- Fix direct mtk_port_release() calls to use kref_put()
in mtk_port_free_or_backup and stale_list_grp_cleanup
- Add ida_free() before kfree(s_list) in stale list
cleanup to prevent IDA leak
- Remove double-free of skb in mtk_port_internal_recv()
drop_data path, caller owns the skb
- Add port_cnt bounds check against data_len in
mtk_port_status_update() to prevent OOB read
- Replace wait_event_interruptible_timeout with
wait_event_timeout in ch_enable/ch_disable to prevent
busy-spin on pending signals
- Patch 5 (Add FSM thread):
- Validate rtft data_len before passing to query_rtft
callback to prevent OOB access
- Zero-initialize HS3 skb data with memset() to prevent
heap infoleak
- Set hs_info->rt_data = NULL after dev_kfree_skb() in
SAP/MD ctrl msg handlers to prevent use-after-free
- Move wake_up_process() inside spinlock in evt_submit,
clear fsm_handler under lock in exit to fix race
- Replace kcalloc + radix_tree_gang_lookup with
radix_tree_for_each_slot() in mtk_port_disable()
- Add rt_data cleanup loop in FSM teardown path
- Patch 7 (Add maintainers entry):
- Add Robert Yu and Jeff Chang as maintainers
- Link to v4: https://patch.msgid.link/[email protected]

Changes in v4:
- Patch 1 (Add PCIe core):
- Add ACPI dependency to Kconfig (depends on PCI && ACPI)
and remove #ifdef CONFIG_ACPI / #else guards from
mtk_pci_fldr() and mtk_pci_pldr()
- Remove unnecessary parentheses in (mdev)->dev across
all dev_err/dev_warn calls
- Remove devm_kfree() calls from mtk_pci_probe() error
path and mtk_pci_remove(), devres handles cleanup
- Remove mtk_dev_alloc()/mtk_dev_free() wrappers, use
devm_kzalloc() directly in mtk_pci_probe()
- Convert ext_evt callbacks from devm_kzalloc/devm_kfree
to kzalloc/kfree for runtime-managed resources
- Patch 2 (Add control plane transaction layer):
- Remove mtk_dev_alloc()/mtk_dev_free() declarations and
implementations from mtk_dev.h and mtk_dev.c
- Remove empty module_init/module_exit stubs, defer to
Patch 4 where they have actual content
- Remove devm_kfree() and unused ctrl_blk variable in
mtk_ctrl_exit(), devres handles cleanup
- Patch 3 (Add control DMA interface):
- Remove inline keyword from mtk_cldma_clr_bd_dsc() in
.c file, let compiler decide inlining
- Replace dev_warn() with dev_warn_ratelimited() for SKB
alloc/map failure messages in data path
- Replace open-coded do/while polling loop with
read_poll_timeout() from <linux/iopoll.h> in
mtk_cldma_stop_queue()
- Remove ctrl_port_chl_mtu module_param, MODULE_PARM_DESC,
and mtk_ctrl_queue_info_update() with associated macros
- Remove unnecessary parentheses in (mdev)->dev across
mtk_cldma.c and mtk_trans_ctrl.c
- Convert CLDMA txq/rxq/cd from devm_kzalloc/devm_kfree
to kzalloc/kfree for runtime-managed resources
- Convert trb_srv/srv_que from devm_kzalloc/devm_kfree
to kzalloc/kfree for runtime-managed resources
- Remove devm_kfree() and unused variables from
mtk_cldma_exit() and mtk_trans_ctrl_exit(), devres
handles cleanup for device-lifetime resources
- Remove unnecessary NULL checks before kfree() for
bd_dsc_pool in txq_free/rxq_free
- Patch 4 (Add control port):
- Add module_init/module_exit with mtk_port_io_init/exit
content, moved from Patch 2
- Remove unnecessary parentheses in (mdev)->dev in
mtk_port.c
- Remove devm_kfree() from mtk_port_mngr_init() error
path and mtk_port_mngr_exit(), devres handles cleanup
- Simplify mtk_trans_ctrl_init() error path: replace goto
err_free_trans with direct return -ENOMEM
- Patch 5 (Add FSM thread):
- Remove unnecessary parentheses in (mdev)->dev across
mtk_fsm.c and mtk_ctrl_plane.c
- Convert FSM notifiers from devm_kzalloc/devm_kfree to
kzalloc/kfree for runtime-managed resources
- Convert CLDMA drv_info from devm_kzalloc/devm_kfree to
kzalloc/kfree for runtime-managed resources
- Remove devm_kfree() from mtk_fsm_init()/mtk_fsm_exit()
and mtk_ctrl_init()/mtk_ctrl_exit(), devres handles
cleanup for device-lifetime resources
- Link to v3: https://patch.msgid.link/[email protected]

Changes in v3:
- Address sashiko AI code review comments and fix sparse warnings
- Patch 1 (Add PCIe core):
- Move extern declaration of mtk_dev_cfg_0900 from mtk_pci.c to mtk_pci.h to fix sparse warning
- Remove mtk_pci_bar_exit(): pcim_iounmap_region() was called with bitmask instead of BAR index, and pcim_iomap_regions() is devres-managed so manual unmap is redundant [sashiko]
- Remove pci_disable_device() from probe error path and remove path: pcim_enable_device() registers devres cleanup, manual disable causes enable_cnt underflow [sashiko]
- Patch 3 (Add control DMA interface):
- Add #include "mtk_cldma.h" in mtk_cldma_drv_m9xx.c to fix sparse undeclared symbol warnings for mtk_cldma_regs_m9xx and cldma_drv_ops_m9xx
- Move extern declaration of mtk_ctrl_info_m9xx from mtk_trans_ctrl.c to mtk_trans_ctrl.h to fix sparse undeclared symbol warning
- Replace kcalloc + radix_tree_gang_lookup with radix_tree_for_each_slot() in mtk_ctrl_remove_radix_tree() to eliminate allocation in teardown path [sashiko]
- Add missing mtk_pci_dev_exit() call in mtk_pci_remove() to properly clean up FSM and trans_ctrl resources before device removal [sashiko]
- Patch 4 (Add control port):
- Replace kcalloc + radix_tree_gang_lookup with radix_tree_for_each_slot() and single-entry gang_lookup in mtk_port_tbl_destroy() to eliminate allocation failure in teardown path [sashiko]
- Add port = NULL after mtk_port_put_locked() in mtk_port_internal_open() error path to prevent returning un-refcounted pointer [sashiko]
- Restore skb_unlink + trb_complete for non-EAGAIN errors in mtk_ctrl_trb_handler() TX path to prevent infinite retry loop [sashiko]
- Patch 5 (Add FSM thread):
- Check mtk_pci_register_irq() return value in mtk_cldma_dev_init() and add err_destroy_wq error label to fix unreachable dead code [sashiko]
- Propagate specific error codes (ENOMEM/EIO/EINVAL) from mtk_cldma_dev_init() error paths instead of generic -EIO [sashiko]
- Free head SKB after detaching frag_list in mtk_cldma_rxq_free() scatter-gather mode to fix memory leak [sashiko]
- Patch 6 (Add AT & MBIM WWAN ports):
- Remove unused write_lock mutex from struct mtk_port and its mutex_init call [sashiko]
- Link to v2: https://patch.msgid.link/[email protected]

Changes in v2:
- Split series into control plane (this v2) and data plane (follow-up)
- Patch 1 (Add PCIe core):
- Rename BAR_NUM to MTK_PCI_BAR_NUM for driver prefix consistency
- Replace magic numbers in mtk_pci_setup_atr() with named defines
- Remove redundant ATR register comments, use blank line separators
- Add kernel-doc comments to all non-static functions
- Convert 4 MMIO wrapper functions to static inline in header [sashiko]
- Remove unnecessary unlikely() from IRQ validation paths
- Add irq_cnt == 0 and irq_id < 0 guards in mtk_pci_get_virq_id() [sashiko]
- Initialize hw_bits at declaration for consistency
- Merge same-type variable declarations into single lines
- Add #else/#endif comments for CONFIG_ACPI blocks
- Add newlines in mtk_pci_pldr() for readability
- Move return into default case in mtk_pci_dev_reset()
- Simplify mtk_mhccif_init() error path to use direct returns
- Change -EFAULT to -ENOLINK for PCIe link check failure
- Rename goto label "out" to "log_err" in mtk_pci_probe()
- Wrap long lines to stay within 80 columns
- Fix IRQ vector leak: add pci_free_irq_vectors() on error path [sashiko]
- Fix mtk_pci_remove() ordering: free IRQ before cancel_work_sync [sashiko]
- Fix mtk_pci_pldr() ACPI buffer leak: free first result before second call [sashiko]
- Replace msleep(500) with MTK_PLDR_POWER_OFF_DELAY_MS define
- Remove unused EXT_EVT_H2D_DRM_DISABLE_AP and related register define [sashiko]
- Increase MTK_IRQ_NAME_LEN from 20 to 32 to fix W=1 format-truncation warning [sashiko]
- Patch 2 (Add control plane transaction layer):
- Add kernel-doc comments to mtk_ctrl_init() and mtk_ctrl_exit()
- Change mtk_ctrl_exit() return type from int to void
- Set mdev->ctrl_blk to NULL after freeing in mtk_ctrl_exit() [sashiko]
- Change ctrl_blk from void* to typed struct mtk_ctrl_blk* [sashiko]
- Remove redundant "depends on MTK_T9XX" from MTK_T9XX_PCI Kconfig [sashiko]
- Use mtk_dev_free() instead of devm_kfree() in mtk_pci_probe() error path [sashiko]
- Patch 3 (Add control DMA interface):
- Add @ops kernel-doc parameter for mtk_ctrl_init()
- Rename 'err' to 'ret' consistently throughout the patch
- Reorder variable declarations to follow reverse Christmas tree style
- Change mtk_cldma_txq_free() return type from int to void
- Change mtk_cldma_rxq_free() return type from int to void
- Change mtk_cldma_exit() return type from int to void
- Remove unnecessary zero-initialization of ret in mtk_cldma_start_xfer()
- Remove unnecessary zero-initialization of ret in mtk_cldma_tx()
- Use direct return instead of goto out in mtk_cldma_submit_tx() error paths
- Move software state before HWO flag in mtk_cldma_submit_tx()
- Squash variable declarations in mtk_cldma_check_intr_status()
- Remove unlikely() from validation paths in mtk_cldma_check_ch_cfg()
- Clamp data_recv_len with min_t to prevent skb_over_panic in mtk_cldma_rx_skb_adjust() [sashiko]
- Use READ_ONCE() for HWO flag polling in mtk_cldma_check_rx_req() [sashiko]
- Fix mtk_cldma_rx_done_work() to always unmask interrupt on error path [sashiko]
- Add DMA address guard in mtk_cldma_txq_free() teardown loop [sashiko]
- Add IS_ERR() check for kthread_run() in mtk_ctrl_trb_srv_init() [sashiko]
- Fix queue_info memory leak on validation failure in mtk_pcie_hif_init() [sashiko]
- Handle non-EAGAIN errors in mtk_ctrl_trb_handler() TX path [sashiko]
- Fix 'err' typo to 'ret' in mtk_cldma_txbuf_set() error message
- Remove unused variable mdev in mtk_cldma_rx_check_again() [sashiko]
- Remove unused variables trans and ctrl_blk in mtk_cldma_txq_free() and mtk_cldma_rxq_free() [sashiko]
- Patch 4 (Add control port):
- Add @cfg kernel-doc parameter for mtk_ctrl_init()
- Update mtk_ctrl_init() return description to cover additional error codes
- Fix double list_del in mtk_port_stale_list_grp_cleanup() [sashiko]
- Fix direct mtk_port_trb_free() call to use kref_put() in mtk_port_ch_enable() error path [sashiko]
- Fix direct mtk_port_trb_free() call to use kref_put() in mtk_port_ch_disable() error path [sashiko]
- Add mtk_port_tbl_destroy() in mtk_port_mngr_init() error path to prevent port memory leak [sashiko]
- Change port_ops exit/reset/enable/disable callbacks from int to void
- Move -EIO dispatch comment to where the code was introduced
- Patch 5 (Add FSM thread):
- Add bounds check for rtft_entry in mtk_fsm_parse_hs2_msg() [sashiko]
- Add skb length validation before accessing ctrl_msg_header in mtk_fsm_sap_ctrl_msg_handler() [sashiko]
- Fix skb leak on CTRL_MSG_HS2 mismatch return in mtk_fsm_sap_ctrl_msg_handler() [sashiko]
- Add skb length validation before accessing ctrl_msg_header in mtk_fsm_md_ctrl_msg_handler() [sashiko]
- Replace devm_kzalloc/devm_kfree with kzalloc/kfree for FSM events [sashiko]
- Fix mtk_fsm_evt_submit() to return -ETIMEDOUT on blocking event timeout [sashiko]
- Change FSM kthread from TASK_INTERRUPTIBLE to TASK_UNINTERRUPTIBLE [sashiko]
- Remove unused variable hw_id in mtk_cldma_dev_exit() [sashiko]
- Patch 6 (Add AT & MBIM WWAN ports):
- Use imperative mode in commit message
- Remove unnecessary zero-initialization of ret in mtk_port_copy_data_from()
- Change copy_from_user() error code from -EFAULT to -EINVAL in mtk_port_copy_data_from()
- Return -EINVAL for zero-length write in mtk_port_common_write()
- Change mtk_port_wwan_exit/enable/disable() return type from int to void
- Fix packet_size to account for CCCI header reservation in mtk_port_common_write() [sashiko]
- Fix WWAN tx callbacks to consume skb and return 0 per wwan_port_ops contract [sashiko]
- Fix wwan_create_port() error path: clear ERR_PTR to NULL and call mtk_port_ch_disable() [sashiko]
- Patch 7 (Add maintainers entry): new patch
- Link to v1: https://patch.msgid.link/[email protected]

To: Loic Poulain <[email protected]>
To: Sergey Ryazanov <[email protected]>
To: Johannes Berg <[email protected]>
To: Andrew Lunn <[email protected]>
To: "David S. Miller" <[email protected]>
To: Eric Dumazet <[email protected]>
To: Jakub Kicinski <[email protected]>
To: Paolo Abeni <[email protected]>
To: Jack Wu <[email protected]>
To: Robert Yu <[email protected]>
To: Jeff Chang <[email protected]>
To: Wen-Zhi Huang <[email protected]>
To: Shi-Wei Yeh <[email protected]>
To: Minano Tseng <[email protected]>
To: Matthias Brugger <[email protected]>
To: AngeloGioacchino Del Regno <[email protected]>
To: Eric Dumazet <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]

---
Jack Wu (6):
net: wwan: t9xx: Add PCIe core
net: wwan: t9xx: Add control plane transaction layer framework
net: wwan: t9xx: Add control DMA interface
net: wwan: t9xx: Add control port
net: wwan: t9xx: Add FSM thread
net: wwan: t9xx: Add AT & MBIM WWAN ports

 MAINTAINERS                                 |   11 +
 drivers/net/wwan/Kconfig                    |   11 +
 drivers/net/wwan/Makefile                   |    1 +
 drivers/net/wwan/t9xx/Makefile              |   16 +
 drivers/net/wwan/t9xx/mtk_ctrl_plane.c      |  108 ++
 drivers/net/wwan/t9xx/mtk_ctrl_plane.h      |   85 ++
 drivers/net/wwan/t9xx/mtk_dev.h             |   43 +
 drivers/net/wwan/t9xx/mtk_fsm.c             | 1002 ++++++++++++++++
 drivers/net/wwan/t9xx/mtk_fsm.h             |  130 ++
 drivers/net/wwan/t9xx/mtk_port.c            |  719 ++++++++++++
 drivers/net/wwan/t9xx/mtk_port.h            |  149 +++
 drivers/net/wwan/t9xx/mtk_port_io.c         |  660 +++++++++++
 drivers/net/wwan/t9xx/mtk_port_io.h         |   37 +
 drivers/net/wwan/t9xx/pcie/mtk_cldma.c      | 1697 +++++++++++++++++++++++++++
 drivers/net/wwan/t9xx/pcie/mtk_cldma.h      |  128 ++
 drivers/net/wwan/t9xx/pcie/mtk_cldma_drv.c  |  513 ++++++++
 drivers/net/wwan/t9xx/pcie/mtk_cldma_drv.h  |  118 ++
 drivers/net/wwan/t9xx/pcie/mtk_pci.c        | 1093 +++++++++++++++++
 drivers/net/wwan/t9xx/pcie/mtk_pci.h        |  139 +++
 drivers/net/wwan/t9xx/pcie/mtk_pci_reg.h    |   35 +
 drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.c |  669 +++++++++++
 drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.h |   87 ++
 22 files changed, 7451 insertions(+)

---
base-commit: c88fd6989aea9237a60a4859139a265bfb7ddc0b
change-id: 20260529-t9xx_driver_v1-1744f8af7739

Best regards,

Signature · 1 line
Jack Wu <[email protected]>
author
#1 lore raw

PATCH v12 1/6 net: wwan: t9xx: Add PCIe core

Registers the T900 device driver with the kernel. Set up all the fundamental configurations for the device: PCIe layer, Modem Host Cross Core Interface (MHCCIF), modem common control operations, build infrastructure and MAINTAINERS entry. Besides the T900 itself (14c3:0900) the driver binds its HP-branded variant, the HP RMM-G4 (03f0:01ca); both IDs are exported via MODULE_DEVICE_TABLE for module autoloading.

* PCIe layer code implements driver probe and removal, MSI-X interrupt initialization and de-initialization, and the way of resetting the device.
* MHCCIF provides the interrupt channels used for the boot handshake and for the host-to-device reset doorbell.
* Modem common control operations provide the basic read/write functions of the device's hardware registers, mask/unmask/get/clear functions of the device's interrupt registers and inquiry functions of the device's status.
* Add MAINTAINERS entry for the MediaTek T9XX 5G WWAN modem device driver.

Removal resets the modem, because the next driver load has to redo the device handshake and status sync and cannot do that against firmware left running by the previous load. Shutdown runs the same teardown and reset when kexec_is_in_progress() says this is a kexec reboot: that gets no platform reset, and the next kernel would otherwise find that firmware still running. Any other reboot or power-off ends in a platform reset or power loss, so shutdown leaves the modem alone there and adds no delay. A crash kexec (kdump) skips .shutdown and is not covered: the modem stays unusable in the capture kernel until the next platform reset. Probe does not reset the modem or look for running firmware: it has no stronger reset than removal, and the firmware state is only known after the handshake added later in the series.
There are no power management callbacks, so system suspend is not
supported: suspend and resume have to be negotiated with the modem over MHCCIF, which this series does not implement. mtk_pci_remove() evaluates MRST._RST on the device's own ACPI
node: that is a platform-level reset and does not depend on the firmware's state. Where the platform has no MRST._RST, or the method fails, removal falls back to the MHCCIF DEV_EVT_H2D_DEVICE_RESET doorbell if the link is still up. The doorbell is a request to the firmware, so it is best effort and cannot recover firmware that has stopped responding - the case the reset exists for. Probe therefore does not require MRST._RST; without it the driver still binds and only removal is degraded.

---
 MAINTAINERS                              |   11 +
 drivers/net/wwan/Kconfig                 |   11 +
 drivers/net/wwan/Makefile                |    1 +
 drivers/net/wwan/t9xx/Makefile           |    9 +
 drivers/net/wwan/t9xx/mtk_dev.h          |   39 ++
 drivers/net/wwan/t9xx/pcie/mtk_pci.c     | 1034 ++++++++++++++++++++++++++++++
 drivers/net/wwan/t9xx/pcie/mtk_pci.h     |  139 ++++
 drivers/net/wwan/t9xx/pcie/mtk_pci_reg.h |   34 +
 8 files changed, 1278 insertions(+)
MAINTAINERS +11 -0
index 893b0670a7b6..6f14af98fa5f 100644
@@ -17250,6 +17250,17 @@ L:	[email protected]
 S:	Supported
 F:	drivers/net/wwan/t7xx/
 
+MEDIATEK T9XX 5G WWAN MODEM DRIVER
+M:	Jack Wu <[email protected]>
+M:	Robert Yu <[email protected]>
+M:	Jeff Chang <[email protected]>
+R:	Wen-Zhi Huang <[email protected]>
+R:	Shi-Wei Yeh <[email protected]>
+R:	Minano Tseng <[email protected]>
+L:	[email protected]
+S:	Supported
+F:	drivers/net/wwan/t9xx/
+
 MEDIATEK USB3 DRD IP DRIVER
 M:	Chunfeng Yun <[email protected]>
 L:	[email protected]
drivers/net/wwan/Kconfig +11 -0
index 958dbc7347fa..8290ba8e7252 100644
@@ -121,6 +121,17 @@ config MTK_T7XX
 
 	  If unsure, say N.
 
+config MTK_T9XX
+	tristate "MediaTek PCIe 5G WWAN modem T9xx device"
+	depends on PCI_MSI
+	help
+	  Enables MediaTek PCIe based 5G WWAN modem (T9xx series) device.
+
+	  To compile this driver as a module, choose M here: the module will be
+	  called mtk_t9xx.
+
+	  If unsure, say N.
+
 endif # WWAN
 
 endmenu
drivers/net/wwan/Makefile +1 -0
index 3960c0ae2445..7361eef4c472 100644
@@ -14,3 +14,4 @@ obj-$(CONFIG_QCOM_BAM_DMUX) += qcom_bam_dmux.o
 obj-$(CONFIG_RPMSG_WWAN_CTRL) += rpmsg_wwan_ctrl.o
 obj-$(CONFIG_IOSM) += iosm/
 obj-$(CONFIG_MTK_T7XX) += t7xx/
+obj-$(CONFIG_MTK_T9XX) += t9xx/
drivers/net/wwan/t9xx/Makefile new file +9 -0
new file mode 100644
index 000000000000..bd6063c85c2b
@@ -0,0 +1,9 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+ccflags-y += -I$(src)/pcie
+ccflags-y += -I$(src)
+
+obj-$(CONFIG_MTK_T9XX) += mtk_t9xx.o
+
+mtk_t9xx-y := \
+	pcie/mtk_pci.o
drivers/net/wwan/t9xx/mtk_dev.h new file +39 -0
new file mode 100644
index 000000000000..fc25418bb957
@@ -0,0 +1,39 @@
+/* SPDX-License-Identifier: GPL-2.0-only
+ *
+ * Copyright (c) 2022, MediaTek Inc.
+ */
+
+#ifndef __MTK_DEV_H__
+#define __MTK_DEV_H__
+
+#include <linux/bits.h>
+#include <linux/types.h>
+
+struct device;
+
+#define MTK_DEV_STR_LEN 16
+
+enum mtk_user_id {
+	MTK_USER_CTRL,
+	MTK_USER_MAX
+};
+
+enum mtk_dev_evt_h2d {
+	DEV_EVT_H2D_DEVICE_RESET	= BIT(2),
+};
+
+enum mtk_dev_evt_d2h {
+	DEV_EVT_D2H_BOOT_FLOW_SYNC	= BIT(4),
+	DEV_EVT_D2H_ASYNC_HS_NOTIFY_SAP = BIT(5),
+	DEV_EVT_D2H_ASYNC_HS_NOTIFY_MD	= BIT(6),
+};
+
+/* mtk_md_dev defines the structure of MTK modem device */
+struct mtk_md_dev {
+	struct device *dev;
+	void *hw_priv;
+	u32 hw_ver;
+	char dev_str[MTK_DEV_STR_LEN];
+};
+
+#endif /* __MTK_DEV_H__ */
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +1034 -0

1,034 lines not on this page · raw message

drivers/net/wwan/t9xx/pcie/mtk_pci.h new file +139 -0

139 lines not on this page · raw message

drivers/net/wwan/t9xx/pcie/mtk_pci_reg.h new file +34 -0
new file mode 100644
index 000000000000..a97ad6630dcf
@@ -0,0 +1,34 @@
+/* SPDX-License-Identifier: GPL-2.0-only
+ *
+ * Copyright (c) 2022, MediaTek Inc.
+ */
+
+#ifndef __MTK_PCI_REG_H__
+#define __MTK_PCI_REG_H__
+
+#define REG_ATR_PCIE_WIN0_T0_SRC_ADDR_LSB	0x0600
+#define REG_ATR_PCIE_WIN0_T0_SRC_ADDR_MSB	0x0604
+#define REG_ATR_PCIE_WIN0_T0_TRSL_ADDR_LSB	0x0608
+#define REG_ATR_PCIE_WIN0_T0_TRSL_ADDR_MSB	0x060C
+#define REG_ATR_PCIE_WIN0_T0_TRSL_PARAM		0x0610
+#define REG_PCIE_DEBUG_DUMMY_7			0x0D1C
+#define REG_MSIX_ISTATUS_HOST_GRP0_0		0x0F00
+#define REG_IMASK_HOST_MSIX_SET_GRP0_0		0x3000
+#define REG_IMASK_HOST_MSIX_CLR_GRP0_0		0x3080
+#define REG_IMASK_HOST_MSIX_GRP0_0		0x3100
+
+/* mhccif registers */
+#define MHCCIF_RC2EP_SW_BSY			0x4
+#define MHCCIF_RC2EP_SW_TCHNUM			0xC
+#define MHCCIF_RC2EP_EVT_DEVICE_RESET		BIT(13)
+
+#define MHCCIF_EP2RC_SW_INT_STS			0x10
+#define MHCCIF_EP2RC_SW_INT_ACK			0x14
+#define MHCCIF_EP2RC_SW_INT_EAP_MASK		0x20
+#define MHCCIF_EP2RC_SW_INT_EAP_MASK_SET	0x30
+#define MHCCIF_EP2RC_SW_INT_EAP_MASK_CLR	0x40
+#define MHCCIF_EP2RC_EVT_BOOT_FLOW_SYNC		BIT(5)
+#define MHCCIF_EP2RC_EVT_ASYNC_HS_NOTIFY_SAP	BIT(15)
+#define MHCCIF_EP2RC_EVT_ASYNC_HS_NOTIFY_MD	BIT(16)
+
+#endif /* __MTK_PCI_REG_H__ */
Signature · 1 line
2.34.1
maintainer
#2 lore raw

Re: [PATCH net-next v12 1/6] net: wwan: t9xx: Add PCIe core

Quoted 693 lines · On Tue, Nov 17, 2026 at 11:51 AM Jack Wu via B4 Relay…

From: Jack Wu <[email protected]>

Registers the T900 device driver with the kernel. Set up all the fundamental configurations for the device: PCIe layer, Modem Host Cross Core Interface (MHCCIF), modem common control operations, build infrastructure and MAINTAINERS entry. Besides the T900 itself (14c3:0900) the driver binds its HP-branded variant, the HP RMM-G4 (03f0:01ca); both IDs are exported via MODULE_DEVICE_TABLE for module autoloading.

* PCIe layer code implements driver probe and removal, MSI-X interrupt initialization and de-initialization, and the way of resetting the device.
* MHCCIF provides the interrupt channels used for the boot handshake and for the host-to-device reset doorbell.
* Modem common control operations provide the basic read/write functions of the device's hardware registers, mask/unmask/get/clear functions of the device's interrupt registers and inquiry functions of the device's status.
* Add MAINTAINERS entry for the MediaTek T9XX 5G WWAN modem device driver.

Removal resets the modem, because the next driver load has to redo the device handshake and status sync and cannot do that against firmware left running by the previous load. Shutdown runs the same teardown and reset when kexec_is_in_progress() says this is a kexec reboot: that gets no platform reset, and the next kernel would otherwise find that firmware still running. Any other reboot or power-off ends in a platform reset or power loss, so shutdown leaves the modem alone there and adds no delay. A crash kexec (kdump) skips .shutdown and is not covered: the modem stays unusable in the capture kernel until the next platform reset. Probe does not reset the modem or look for running firmware: it has no stronger reset than removal, and the firmware state is only known after the handshake added later in the series.
There are no power management callbacks, so system suspend is not
supported: suspend and resume have to be negotiated with the modem over MHCCIF, which this series does not implement. mtk_pci_remove() evaluates MRST._RST on the device's own ACPI
node: that is a platform-level reset and does not depend on the firmware's state. Where the platform has no MRST._RST, or the method fails, removal falls back to the MHCCIF DEV_EVT_H2D_DEVICE_RESET doorbell if the link is still up. The doorbell is a request to the firmware, so it is best effort and cannot recover firmware that has stopped responding - the case the reset exists for. Probe therefore does not require MRST._RST; without it the driver still binds and only removal is degraded.

---
 MAINTAINERS                              |   11 +
 drivers/net/wwan/Kconfig                 |   11 +
 drivers/net/wwan/Makefile                |    1 +
 drivers/net/wwan/t9xx/Makefile           |    9 +
 drivers/net/wwan/t9xx/mtk_dev.h          |   39 ++
 drivers/net/wwan/t9xx/pcie/mtk_pci.c     | 1034 ++++++++++++++++++++++++++++++
 drivers/net/wwan/t9xx/pcie/mtk_pci.h     |  139 ++++
 drivers/net/wwan/t9xx/pcie/mtk_pci_reg.h |   34 +
 8 files changed, 1278 insertions(+)
MAINTAINERS +11 -0
index 893b0670a7b6..6f14af98fa5f 100644
@@ -17250,6 +17250,17 @@ L:     [email protected]
 S:     Supported
 F:     drivers/net/wwan/t7xx/
 
+MEDIATEK T9XX 5G WWAN MODEM DRIVER
+M:     Jack Wu <[email protected]>
+M:     Robert Yu <[email protected]>
+M:     Jeff Chang <[email protected]>
+R:     Wen-Zhi Huang <[email protected]>
+R:     Shi-Wei Yeh <[email protected]>
+R:     Minano Tseng <[email protected]>
+L:     [email protected]
+S:     Supported
+F:     drivers/net/wwan/t9xx/
+
 MEDIATEK USB3 DRD IP DRIVER
 M:     Chunfeng Yun <[email protected]>
 L:     [email protected]
drivers/net/wwan/Kconfig +11 -0
index 958dbc7347fa..8290ba8e7252 100644
@@ -121,6 +121,17 @@ config MTK_T7XX
 
          If unsure, say N.
 
+config MTK_T9XX
+       tristate "MediaTek PCIe 5G WWAN modem T9xx device"
+       depends on PCI_MSI
+       help
+         Enables MediaTek PCIe based 5G WWAN modem (T9xx series) device.
+
+         To compile this driver as a module, choose M here: the module will be
+         called mtk_t9xx.
+
+         If unsure, say N.
+
 endif # WWAN
 
 endmenu
drivers/net/wwan/Makefile +1 -0
index 3960c0ae2445..7361eef4c472 100644
@@ -14,3 +14,4 @@ obj-$(CONFIG_QCOM_BAM_DMUX) += qcom_bam_dmux.o
 obj-$(CONFIG_RPMSG_WWAN_CTRL) += rpmsg_wwan_ctrl.o
 obj-$(CONFIG_IOSM) += iosm/
 obj-$(CONFIG_MTK_T7XX) += t7xx/
+obj-$(CONFIG_MTK_T9XX) += t9xx/
drivers/net/wwan/t9xx/Makefile new file +9 -0
new file mode 100644
index 000000000000..bd6063c85c2b
@@ -0,0 +1,9 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+ccflags-y += -I$(src)/pcie
+ccflags-y += -I$(src)
+
+obj-$(CONFIG_MTK_T9XX) += mtk_t9xx.o
+
+mtk_t9xx-y := \
+       pcie/mtk_pci.o
drivers/net/wwan/t9xx/mtk_dev.h new file +39 -0
new file mode 100644
index 000000000000..fc25418bb957
@@ -0,0 +1,39 @@
+/* SPDX-License-Identifier: GPL-2.0-only
+ *
+ * Copyright (c) 2022, MediaTek Inc.
+ */
+
+#ifndef __MTK_DEV_H__
+#define __MTK_DEV_H__
+
+#include <linux/bits.h>
+#include <linux/types.h>
+
+struct device;
+
+#define MTK_DEV_STR_LEN 16
+
+enum mtk_user_id {
+       MTK_USER_CTRL,
+       MTK_USER_MAX
+};
+
+enum mtk_dev_evt_h2d {
+       DEV_EVT_H2D_DEVICE_RESET        = BIT(2),
+};
+
+enum mtk_dev_evt_d2h {
+       DEV_EVT_D2H_BOOT_FLOW_SYNC      = BIT(4),
+       DEV_EVT_D2H_ASYNC_HS_NOTIFY_SAP = BIT(5),
+       DEV_EVT_D2H_ASYNC_HS_NOTIFY_MD  = BIT(6),
+};
+
+/* mtk_md_dev defines the structure of MTK modem device */
+struct mtk_md_dev {
+       struct device *dev;
+       void *hw_priv;
+       u32 hw_ver;
+       char dev_str[MTK_DEV_STR_LEN];
+};
+
+#endif /* __MTK_DEV_H__ */
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +512 -0
new file mode 100644
index 000000000000..cf59038f0906
@@ -0,0 +1,1034 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (c) 2022, MediaTek Inc.
+ */
+
+#include <linux/acpi.h>
+#include <linux/bitfield.h>
+#include <linux/delay.h>
+#include <linux/device.h>
+#include <linux/dma-mapping.h>
+#include <linux/kernel.h>
+#include <linux/kexec.h>
+#include <linux/module.h>
+
+#include "mtk_dev.h"
+#include "mtk_pci.h"
+#include "mtk_pci_reg.h"
+
+#define MTK_MHCCIF_RC_BASE_ADDR                0x1000A000
+
+#define MTK_MHCCIF_RESET_DELAY_MS      2000
+#define MTK_PLDR_READY_POLL_MS         20
+#define MTK_PLDR_READY_POLLS           50
+/* BAR0/1: end of the highest MAC register; BAR2/3: the ATR window */
+#define MTK_BAR_0_1_MIN_LEN            (REG_IMASK_HOST_MSIX_GRP0_0 + 4)
+#define MTK_BAR_2_3_MIN_LEN            ATR_PCIE_REG_SIZE
+
+static const int mtk_pci_irq_tbl[MTK_IRQ_SRC_MAX] = {
+       [MTK_IRQ_SRC_MHCCIF] = 28,
+       [MTK_IRQ_SRC_CLDMA0] = 27,
+       [MTK_IRQ_SRC_CLDMA1] = 26,
+};
+
+#define MTK_PCI_TRANSPARENT_ATR_SIZE   (0x3F)
+#define MTK_PCI_MINIMUM_ATR_SIZE       (0x1000)
+#define ATR_SIZE_LO32_MASK             GENMASK_ULL(31, 0)
+#define ATR_SIZE_HI32_MASK             GENMASK_ULL(63, 32)
+#define ATR_SIZE_BIAS_FROM_LO32                2
+#define ATR_ADDR_ALIGN_MASK            0xFFFFF000
+#define ATR_EN                         BIT(0)
+#define ATR_PARAM_OFFSET               16
+
+struct mtk_mhccif_cb {
+       struct list_head entry;
+       void (*evt_cb)(u32 status, void *data);
+       void *data;
+       u32 chs;
+};
+
+/**
+ * mtk_pci_setup_atr() - Configure a PCIe address translation rule
+ * @mdev: MTK MD device
+ * @cfg: ATR configuration parameters
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+static int mtk_pci_setup_atr(struct mtk_md_dev *mdev, struct mtk_atr_cfg *cfg)
+{
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+       u32 addr, val, size_h, size_l;
+       int atr_size, pos, offset;
+
+       if (cfg->transparent) {
+               /* No address conversion is performed */
+               atr_size = MTK_PCI_TRANSPARENT_ATR_SIZE;
+       } else {
+               if (cfg->size < MTK_PCI_MINIMUM_ATR_SIZE)
+                       cfg->size = MTK_PCI_MINIMUM_ATR_SIZE;
+
+               if (cfg->src_addr & (cfg->size - 1)) {
+                       dev_err(mdev->dev, "Invalid atr src addr is not aligned to size\n");
+                       return -EINVAL;
+               }
+
+               if (cfg->trsl_addr & (cfg->size - 1)) {
+                       dev_err(mdev->dev,
+                               "Invalid atr trsl addr is not aligned to size, %llx, %llx\n",
+                               cfg->trsl_addr, cfg->size - 1);
+                       return -EINVAL;
+               }
+
+               size_l = FIELD_GET(ATR_SIZE_LO32_MASK, cfg->size);
+               size_h = FIELD_GET(ATR_SIZE_HI32_MASK, cfg->size);
+               pos = ffs(size_l);
+               if (pos) {
+                       atr_size = pos - ATR_SIZE_BIAS_FROM_LO32;
+               } else {
+                       pos = ffs(size_h);
+                       atr_size = pos + 32 - ATR_SIZE_BIAS_FROM_LO32;
+               }
+       }
+
+       /* Calculate table offset */
+       offset = ATR_PORT_OFFSET * cfg->port + ATR_TABLE_OFFSET * cfg->table;
+
+       addr = REG_ATR_PCIE_WIN0_T0_SRC_ADDR_MSB + offset;
+       val = (u32)(cfg->src_addr >> 32);
+       mtk_pci_mac_write32(priv, addr, val);
+
+       addr = REG_ATR_PCIE_WIN0_T0_TRSL_ADDR_MSB + offset;
+       val = (u32)(cfg->trsl_addr >> 32);
+       mtk_pci_mac_write32(priv, addr, val);
+
+       addr = REG_ATR_PCIE_WIN0_T0_TRSL_ADDR_LSB + offset;
+       val = (u32)(cfg->trsl_addr & ATR_ADDR_ALIGN_MASK);
+       mtk_pci_mac_write32(priv, addr, val);
+
+       /* TRSL_PARAM */
+       addr = REG_ATR_PCIE_WIN0_T0_TRSL_PARAM + offset;
+       val = (cfg->trsl_param << ATR_PARAM_OFFSET) | cfg->trsl_id;
+       mtk_pci_mac_write32(priv, addr, val);
+
+       /* Enable ATR last, after translation target is fully programmed */
+       addr = REG_ATR_PCIE_WIN0_T0_SRC_ADDR_LSB + offset;
+       val = (u32)(cfg->src_addr & ATR_ADDR_ALIGN_MASK) | (atr_size << 1) | ATR_EN;
+       mtk_pci_mac_write32(priv, addr, val);
+
+       /* Ensure ATR is set */
+       mtk_pci_mac_read32(priv, addr);
+
+       return 0;
+}
+
+/**
+ * mtk_pci_atr_disable() - Disable all PCIe address translation rules
+ * @priv: MTK PCI private data
+ */
+static void mtk_pci_atr_disable(struct mtk_pci_priv *priv)
+{
+       int port, tbl, offset;
+       u32 val;
+
+       /* Disable all ATR table for all ports */
+       for (port = ATR_SRC_PCI_WIN0; port <= ATR_SRC_AXIS_3; port++)
+               for (tbl = 0; tbl < ATR_TABLE_NUM_PER_ATR; tbl++) {
+                       /* Calculate table offset */
+                       offset = ATR_PORT_OFFSET * port + ATR_TABLE_OFFSET * tbl;
+                       val = mtk_pci_mac_read32(priv, REG_ATR_PCIE_WIN0_T0_SRC_ADDR_LSB + offset);
+                       val = val & (~BIT(0));
+                       /* Disable table by SRC_ADDR_L */
+                       mtk_pci_mac_write32(priv, REG_ATR_PCIE_WIN0_T0_SRC_ADDR_LSB + offset, val);
+               }
+}
+
+/**
+ * mtk_pci_get_dev_state() - Read the device state from the modem
+ * @mdev: MTK MD device
+ *
+ * Return: Device state value.
+ */
+u32 mtk_pci_get_dev_state(struct mtk_md_dev *mdev)
+{
+       return mtk_pci_mac_read32(mdev->hw_priv, REG_PCIE_DEBUG_DUMMY_7);
+}
+
+/**
+ * mtk_pci_get_irq_id() - Map an IRQ source to its hardware IRQ ID
+ * @mdev: MTK MD device
+ * @irq_src: IRQ source enum
+ *
+ * Return: IRQ ID on success, -EINVAL on failure.
+ */
+int mtk_pci_get_irq_id(struct mtk_md_dev *mdev, enum mtk_irq_src irq_src)
+{
+       int irq_id = -EINVAL;
+
+       if (irq_src > MTK_IRQ_SRC_MIN && irq_src < MTK_IRQ_SRC_MAX) {
+               irq_id = mtk_pci_irq_tbl[irq_src];
+               if (irq_id < 0 || irq_id >= MTK_IRQ_CNT_MAX)
+                       irq_id = -EINVAL;
+       }
+
+       return irq_id;
+}
+
+/**
+ * mtk_pci_get_virq_id() - Get the Linux virtual IRQ for a hardware IRQ ID
+ * @mdev: MTK MD device
+ * @irq_id: Hardware IRQ ID
+ *
+ * Return: Virtual IRQ number on success, negative error code on failure.
+ */
+int mtk_pci_get_virq_id(struct mtk_md_dev *mdev, int irq_id)
+{
+       struct pci_dev *pdev = to_pci_dev(mdev->dev);
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+
+       if (irq_id < 0 || irq_id >= priv->irq_cnt)
+               return -EINVAL;
+
+       return pci_irq_vector(pdev, irq_id);
+}
+
+/**
+ * mtk_pci_register_irq() - Register a callback for a hardware IRQ
+ * @mdev: MTK MD device
+ * @irq_id: Hardware IRQ ID
+ * @irq_cb: Callback function
+ * @data: Private data passed to callback
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int mtk_pci_register_irq(struct mtk_md_dev *mdev, int irq_id,
+                        void (*irq_cb)(int irq_id, void *data), void *data)
+{
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+
+       if ((irq_id < 0 || irq_id >= MTK_IRQ_CNT_MAX) || !irq_cb)
+               return -EINVAL;
+
+       spin_lock(&priv->irq_cb_lock);
+       if (priv->irq_cb_list[irq_id]) {
+               spin_unlock(&priv->irq_cb_lock);
+               dev_err(mdev->dev,
+                       "Unable to register irq, irq_id=%d, it's already been register by %ps.\n",
+                       irq_id, priv->irq_cb_list[irq_id]);
+               return -EBUSY;
+       }
+       priv->irq_cb_data[irq_id] = data;
+       smp_wmb(); /* Ensure data is visible before callback */
+       WRITE_ONCE(priv->irq_cb_list[irq_id], irq_cb);
+       spin_unlock(&priv->irq_cb_lock);
+
+       return 0;
+}
+
+/**
+ * mtk_pci_unregister_irq() - Unregister a hardware IRQ callback
+ * @mdev: MTK MD device
+ * @irq_id: Hardware IRQ ID
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int mtk_pci_unregister_irq(struct mtk_md_dev *mdev, int irq_id)
+{
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+       int virq_id;
+
+       if (irq_id < 0 || irq_id >= MTK_IRQ_CNT_MAX)
+               return -EINVAL;
+
+       if (!READ_ONCE(priv->irq_cb_list[irq_id])) {
+               dev_err(mdev->dev, "irq_id=%d has not been registered\n", irq_id);
+               return -ENOENT;
+       }
+
+       /* mtk_pci_irq_handler() loads the callback and its data separately, so
+        * the data may only be cleared once no handler can still hold a live
+        * callback pointer.
+        */
+       mtk_pci_mask_irq(mdev, irq_id);
+
+       spin_lock(&priv->irq_cb_lock);
+       WRITE_ONCE(priv->irq_cb_list[irq_id], NULL);
+       spin_unlock(&priv->irq_cb_lock);
+
+       virq_id = mtk_pci_get_virq_id(mdev, irq_id);
+       if (virq_id >= 0)
+               synchronize_irq(virq_id);
+
+       priv->irq_cb_data[irq_id] = NULL;
+
+       return 0;
+}
+
+/**
+ * mtk_pci_mask_irq() - Mask (disable) a hardware IRQ
+ * @mdev: MTK MD device
+ * @irq_id: Hardware IRQ ID
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int mtk_pci_mask_irq(struct mtk_md_dev *mdev, int irq_id)
+{
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+
+       if (irq_id < 0 || irq_id >= MTK_IRQ_CNT_MAX) {
+               dev_err(mdev->dev, "Failed to mask irq: input irq_id=%d\n", irq_id);
+               return -EINVAL;
+       }
+
+       mtk_pci_mac_write32(priv, REG_IMASK_HOST_MSIX_CLR_GRP0_0, BIT(irq_id));
+
+       return 0;
+}
+
+/**
+ * mtk_pci_unmask_irq() - Unmask (enable) a hardware IRQ
+ * @mdev: MTK MD device
+ * @irq_id: Hardware IRQ ID
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int mtk_pci_unmask_irq(struct mtk_md_dev *mdev, int irq_id)
+{
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+
+       if (irq_id < 0 || irq_id >= MTK_IRQ_CNT_MAX) {
+               dev_err(mdev->dev, "Failed to unmask irq: input irq_id=%d\n", irq_id);
+               return -EINVAL;
+       }
+
+       mtk_pci_mac_write32(priv, REG_IMASK_HOST_MSIX_SET_GRP0_0, BIT(irq_id));
+
+       return 0;
+}
+
+/**
+ * mtk_pci_clear_irq() - Clear (acknowledge) a hardware IRQ
+ * @mdev: MTK MD device
+ * @irq_id: Hardware IRQ ID
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int mtk_pci_clear_irq(struct mtk_md_dev *mdev, int irq_id)
+{
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+
+       if (irq_id < 0 || irq_id >= MTK_IRQ_CNT_MAX) {
+               dev_err(mdev->dev, "Failed to clear irq: input irq_id=%d\n", irq_id);
+               return -EINVAL;
+       }
+
+       mtk_pci_mac_write32(priv, REG_MSIX_ISTATUS_HOST_GRP0_0, BIT(irq_id));
+
+       return 0;
+}
+
+static u32 mtk_pci_map_evt_bit(u32 val, u32 from, u32 to)
+{
+       return (val & from) ? to : 0;
+}
+
+static u32 mtk_pci_ext_d2h_evt_hw_bits(u32 chs)
+{
+       return mtk_pci_map_evt_bit(chs, DEV_EVT_D2H_BOOT_FLOW_SYNC,
+                                  MHCCIF_EP2RC_EVT_BOOT_FLOW_SYNC) |
+              mtk_pci_map_evt_bit(chs, DEV_EVT_D2H_ASYNC_HS_NOTIFY_SAP,
+                                  MHCCIF_EP2RC_EVT_ASYNC_HS_NOTIFY_SAP) |
+              mtk_pci_map_evt_bit(chs, DEV_EVT_D2H_ASYNC_HS_NOTIFY_MD,
+                                  MHCCIF_EP2RC_EVT_ASYNC_HS_NOTIFY_MD);
+}
+
+static u32 mtk_pci_ext_d2h_evt_chs(u32 hw_bits)
+{
+       return mtk_pci_map_evt_bit(hw_bits, MHCCIF_EP2RC_EVT_BOOT_FLOW_SYNC,
+                                  DEV_EVT_D2H_BOOT_FLOW_SYNC) |
+              mtk_pci_map_evt_bit(hw_bits, MHCCIF_EP2RC_EVT_ASYNC_HS_NOTIFY_SAP,
+                                  DEV_EVT_D2H_ASYNC_HS_NOTIFY_SAP) |
+              mtk_pci_map_evt_bit(hw_bits, MHCCIF_EP2RC_EVT_ASYNC_HS_NOTIFY_MD,
+                                  DEV_EVT_D2H_ASYNC_HS_NOTIFY_MD);
+}
+
+/**
+ * mtk_pci_register_ext_evt() - Register a callback for MHCCIF device events
+ * @mdev: MTK MD device
+ * @chs: Bitmask of event channels to register; must not overlap the
+ *      channels of a callback already registered
+ * @evt_cb: Callback function, called from a work item with mhccif_lock
+ *         held: it must not (un)register MHCCIF callbacks
+ * @data: Private data passed to callback
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+int mtk_pci_register_ext_evt(struct mtk_md_dev *mdev, u32 chs,
+                            void (*evt_cb)(u32 status, void *data), void *data)
+{
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+       struct mtk_mhccif_cb *cb;
+       int ret = 0;
+
+       if (!chs || !evt_cb)
+               return -EINVAL;
+
+       mutex_lock(&priv->mhccif_lock);
+       list_for_each_entry(cb, &priv->mhccif_cb_list, entry) {
+               if (cb->chs & chs) {
+                       ret = -EBUSY;
+                       dev_err(mdev->dev,
+                               "Unable to register evt, intersection: chs=0x%08x&0x%08x cb=%ps\n",
+                               chs, cb->chs, cb->evt_cb);
+                       goto err_unlock;
+               }
+       }
+       cb = kzalloc(sizeof(*cb), GFP_KERNEL);
+       if (!cb) {
+               ret = -ENOMEM;
+               goto err_unlock;
+       }
+       cb->evt_cb = evt_cb;
+       cb->data = data;
+       cb->chs = chs;
+       list_add_tail(&cb->entry, &priv->mhccif_cb_list);
+err_unlock:
+       mutex_unlock(&priv->mhccif_lock);
+
+       return ret;
+}
+
+/**
+ * mtk_pci_unregister_ext_evt() - Unregister an MHCCIF device event callback
+ * @mdev: MTK MD device
+ * @chs: Bitmask of event channels to unregister, exactly as registered
+ */
+void mtk_pci_unregister_ext_evt(struct mtk_md_dev *mdev, u32 chs)
+{
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+       struct mtk_mhccif_cb *cb, *next;
+
+       if (!chs)
+               return;
+
+       mutex_lock(&priv->mhccif_lock);
+       list_for_each_entry_safe(cb, next, &priv->mhccif_cb_list, entry) {
+               if (cb->chs == chs) {
+                       list_del(&cb->entry);
+                       kfree(cb);
+                       goto out;
+               }
+       }
+       dev_warn(mdev->dev,
+                "Unable to unregister evt, no chs=0x%08x has been registered.\n", chs);
+out:
+       mutex_unlock(&priv->mhccif_lock);
+}
+
+/**
+ * mtk_pci_mask_ext_evt() - Mask (disable) MHCCIF device events
+ * @mdev: MTK MD device
+ * @chs: Bitmask of event channels to mask
+ */
+void mtk_pci_mask_ext_evt(struct mtk_md_dev *mdev, u32 chs)
+{
+       u32 hw_bits = mtk_pci_ext_d2h_evt_hw_bits(chs);
+
+       mtk_pci_write32(mdev, MTK_MHCCIF_RC_BASE_ADDR +
+                       MHCCIF_EP2RC_SW_INT_EAP_MASK_SET, hw_bits);
+}
+
+/**
+ * mtk_pci_unmask_ext_evt() - Unmask (enable) MHCCIF device events
+ * @mdev: MTK MD device
+ * @chs: Bitmask of event channels to unmask
+ */
+void mtk_pci_unmask_ext_evt(struct mtk_md_dev *mdev, u32 chs)
+{
+       u32 hw_bits = mtk_pci_ext_d2h_evt_hw_bits(chs);
+
+       mtk_pci_write32(mdev, MTK_MHCCIF_RC_BASE_ADDR +
+                       MHCCIF_EP2RC_SW_INT_EAP_MASK_CLR, hw_bits);
+}
+
+static u32 mtk_pci_ext_h2d_evt_hw_bits(u32 chs)
+{
+       return mtk_pci_map_evt_bit(chs, DEV_EVT_H2D_DEVICE_RESET,
+                                  MHCCIF_RC2EP_EVT_DEVICE_RESET);
+}
+
+/**
+ * mtk_pci_send_ext_evt() - Send an MHCCIF event to the modem
+ * @mdev: MTK MD device
+ * @ch: Event channel to trigger (must be a single bit)
+ *
+ * Return: 0 on success, negative error code on failure.
+ */
+static int mtk_pci_send_ext_evt(struct mtk_md_dev *mdev, u32 ch)
+{
+       u32 rc_base = MTK_MHCCIF_RC_BASE_ADDR;
+       u32 hw_bits;
+
+       /* Only allow one ch to be triggered at a time */
+       if (!is_power_of_2(ch)) {
+               dev_err(mdev->dev, "Unsupported ext evt ch=0x%08x\n", ch);
+               return -EINVAL;
+       }
+
+       hw_bits = mtk_pci_ext_h2d_evt_hw_bits(ch);
+       if (!hw_bits) {
+               dev_err(mdev->dev, "Unmapped ext evt ch=0x%08x\n", ch);
+               return -EINVAL;
+       }
+
+       mtk_pci_write32(mdev, rc_base + MHCCIF_RC2EP_SW_BSY, hw_bits);
+       mtk_pci_write32(mdev, rc_base + MHCCIF_RC2EP_SW_TCHNUM, ffs(hw_bits) - 1);
+       return 0;
+}
+
+static u32 mtk_pci_get_ext_evt_hw_status(struct mtk_md_dev *mdev)
+{
+       return mtk_pci_read32(mdev, MTK_MHCCIF_RC_BASE_ADDR +
+                             MHCCIF_EP2RC_SW_INT_STS);
+}
+
+static void mtk_pci_ack_ext_evt_hw(struct mtk_md_dev *mdev, u32 hw_bits)
+{
+       mtk_pci_write32(mdev, MTK_MHCCIF_RC_BASE_ADDR +
+                       MHCCIF_EP2RC_SW_INT_ACK, hw_bits);
+       /* Flush the ack before the callbacks run: one landing late would
+        * erase an event they make the device raise.
+        */
+       mtk_pci_read32(mdev, MTK_MHCCIF_RC_BASE_ADDR +
+                      MHCCIF_EP2RC_SW_INT_STS);
+}
+
+/**
+ * mtk_pci_pldr() - Reset the modem via its ACPI MRST._RST method
+ * @mdev: MTK MD device
+ *
+ * Return:
+ * * 0       - Success, device was reset.
+ * * -ENODEV - No ACPI, no handle or no MRST._RST method.  Device
+ *             untouched.

drivers/net/wwan/t9xx/pcie/mtk_pci.c line 522

Quoted 10 lines
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +10 -0
+ * * -EIO    - MRST._RST failed.  Device untouched, still running;
+ *             a different reset may be attempted.
+ */
+static int mtk_pci_pldr(struct mtk_md_dev *mdev)
+{
+       acpi_status acpi_ret;
+       acpi_handle handle;
+
+       if (acpi_disabled) {
+               dev_dbg(mdev->dev, "Unsupported, acpi function isn't enable\n");

Go straight to the point: "ACPI is disabled\n"

drivers/net/wwan/t9xx/pcie/mtk_pci.c line 532

Quoted 10 lines
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +10 -0
+               return -ENODEV;
+       }
+
+       handle = ACPI_HANDLE(mdev->dev);
+       if (!handle) {
+               dev_dbg(mdev->dev, "Unsupported, acpi handle isn't found\n");
+               return -ENODEV;
+       }
+       if (!acpi_has_method(handle, "MRST._RST")) {
+               dev_dbg(mdev->dev, "Unsupported, pldr method isn't supported\n");

"ACPI handle not found"

Quoted 334 lines
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +334 -0
+               return -ENODEV;
+       }
+       acpi_ret = acpi_evaluate_object(handle, "MRST._RST", NULL, NULL);
+       if (ACPI_FAILURE(acpi_ret)) {
+               dev_err(mdev->dev, "Failed to execute MRST._RST method: %s\n",
+                       acpi_format_exception(acpi_ret));
+               return -EIO;
+       }
+
+       return 0;
+}
+
+/**
+ * mtk_pci_link_check() - Check if the PCIe link to the modem is active
+ * @mdev: MTK MD device
+ *
+ * Return: true if the device is present, false otherwise.
+ */
+static bool mtk_pci_link_check(struct mtk_md_dev *mdev)
+{
+       return pci_device_is_present(to_pci_dev(mdev->dev));
+}
+
+static void mtk_mhccif_isr_work(struct work_struct *work)
+{
+       struct mtk_pci_priv *priv =
+               container_of(work, struct mtk_pci_priv, mhccif_work);
+       struct mtk_md_dev *mdev = priv->mdev;
+       struct mtk_mhccif_cb *cb;
+       u32 stat, mask, chs;
+
+       /* Clear level 1 before reading level 2: an event raised after the
+        * clear latches level 1 again and fires on the unmask below, one
+        * raised before it is in the read.
+        */
+       mtk_pci_clear_irq(mdev, priv->mhccif_irq_id);
+       stat = mtk_pci_get_ext_evt_hw_status(mdev);
+       mask = mtk_pci_read32(mdev, MTK_MHCCIF_RC_BASE_ADDR
+               + MHCCIF_EP2RC_SW_INT_EAP_MASK);
+       if (unlikely(stat == U32_MAX && !(mtk_pci_link_check(mdev)))) {
+               /* When link failed, we don't need to unmask. */
+               dev_err(mdev->dev, "Failed to check link in MHCCIF handler.\n");
+               return;
+       }
+
+       stat &= ~mask;
+       /* Acknowledge level 2 before dispatch: an event that re-asserts
+        * while a callback runs must survive as a new status bit.
+        */
+       if (stat)
+               mtk_pci_ack_ext_evt_hw(mdev, stat);
+
+       chs = mtk_pci_ext_d2h_evt_chs(stat);
+       /* Callbacks must not modify mhccif_cb_list */
+       mutex_lock(&priv->mhccif_lock);
+       list_for_each_entry(cb, &priv->mhccif_cb_list, entry) {
+               if (cb->chs & chs)
+                       cb->evt_cb(cb->chs & chs, cb->data);
+       }
+       mutex_unlock(&priv->mhccif_lock);
+
+       mtk_pci_unmask_irq(mdev, priv->mhccif_irq_id);
+}
+
+static const struct pci_device_id t9xx_pci_table[] = {
+       { PCI_DEVICE(PCI_VENDOR_ID_MEDIATEK, 0x0900),
+         .class = MTK_PCI_CLASS, .class_mask = ~0 },
+       { PCI_DEVICE(0x03f0, 0x01ca),  /* HP RMM-G4 */
+         .class = MTK_PCI_CLASS, .class_mask = ~0 },
+       {/* end: all zeroes */}
+};
+
+MODULE_DEVICE_TABLE(pci, t9xx_pci_table);
+
+static int mtk_pci_atr_init(struct mtk_md_dev *mdev)
+{
+       struct pci_dev *pdev = to_pci_dev(mdev->dev);
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+       struct mtk_atr_cfg cfg;
+       int port, ret;
+
+       mtk_pci_atr_disable(priv);
+
+       /* Config ATR for RC to access device's register */
+       cfg.src_addr = pci_bus_address(pdev, MTK_BAR_2_3_IDX);
+       cfg.size = ATR_PCIE_REG_SIZE;
+       cfg.trsl_addr = ATR_PCIE_REG_TRSL_ADDR;
+       cfg.port = ATR_PCIE_REG_PORT;
+       cfg.table = ATR_PCIE_REG_TABLE_NUM;
+       cfg.trsl_id = ATR_PCIE_REG_TRSL_PORT;
+       cfg.trsl_param = 0x0;
+       cfg.transparent = 0x0;
+       ret = mtk_pci_setup_atr(mdev, &cfg);
+       if (ret)
+               return ret;
+
+       /* Config ATR for EP to access RC's memory */
+       for (port = ATR_SRC_AXIS_0; port <= ATR_SRC_AXIS_3; port++) {
+               cfg.src_addr = ATR_PCIE_DEV_DMA_SRC_ADDR;
+               cfg.size = ATR_PCIE_DEV_DMA_SIZE;
+               cfg.trsl_addr = ATR_PCIE_DEV_DMA_TRSL_ADDR;
+               cfg.port = port;
+               cfg.table = ATR_PCIE_DEV_DMA_TABLE_NUM;
+               cfg.trsl_id = ATR_DST_PCI_TRX;
+               cfg.trsl_param = 0x0;
+               /* Enable transparent translation */
+               cfg.transparent = ATR_PCIE_DEV_DMA_TRANSPARENT;
+               ret = mtk_pci_setup_atr(mdev, &cfg);
+               if (ret)
+                       return ret;
+       }
+
+       return 0;
+}
+
+static int mtk_pci_bar_init(struct mtk_md_dev *mdev)
+{
+       struct pci_dev *pdev = to_pci_dev(mdev->dev);
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+
+       if (pci_resource_len(pdev, MTK_BAR_0_1_IDX) < MTK_BAR_0_1_MIN_LEN ||
+           pci_resource_len(pdev, MTK_BAR_2_3_IDX) < MTK_BAR_2_3_MIN_LEN) {
+               dev_err(mdev->dev, "BARs too small for the register map\n");
+               return -ENODEV;
+       }
+
+       priv->mac_reg_base = pcim_iomap_region(pdev, MTK_BAR_0_1_IDX,
+                                              KBUILD_MODNAME);
+       if (IS_ERR(priv->mac_reg_base)) {
+               dev_err(mdev->dev, "Failed to map BAR0/1\n");
+               return PTR_ERR(priv->mac_reg_base);
+       }
+
+       priv->bar23_addr = pcim_iomap_region(pdev, MTK_BAR_2_3_IDX,
+                                            KBUILD_MODNAME);
+       if (IS_ERR(priv->bar23_addr)) {
+               dev_err(mdev->dev, "Failed to map BAR2/3\n");
+               return PTR_ERR(priv->bar23_addr);
+       }
+
+       /* We use MD view base address "0" to observe registers */
+       priv->ext_reg_base = priv->bar23_addr - ATR_PCIE_REG_TRSL_ADDR;
+
+       return 0;
+}
+
+static void mtk_mhccif_irq_cb(int irq_id, void *data)
+{
+       struct mtk_md_dev *mdev = data;
+       struct mtk_pci_priv *priv;
+
+       priv = mdev->hw_priv;
+       queue_work(system_highpri_wq, &priv->mhccif_work);
+}
+
+static int mtk_mhccif_init(struct mtk_md_dev *mdev)
+{
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+       int ret;
+
+       INIT_LIST_HEAD(&priv->mhccif_cb_list);
+       mutex_init(&priv->mhccif_lock);
+       INIT_WORK(&priv->mhccif_work, mtk_mhccif_isr_work);
+
+       /* The write below goes through the BAR 2/3 ATR window, so this
+        * function must run after mtk_pci_atr_init().
+        * Mask every channel; consumers unmask the channels they need.
+        * Do NOT ack here: EP2RC status bits are latched one-shot
+        * notifications (e.g. BOOT_FLOW_SYNC raised before the driver
+        * loads) that the device never re-sends.  Masking blocks
+        * delivery but preserves the bit for delivery on unmask; an
+        * ack would erase it and the boot flow would hang silently.
+        */
+       mtk_pci_write32(mdev, MTK_MHCCIF_RC_BASE_ADDR +
+                       MHCCIF_EP2RC_SW_INT_EAP_MASK_SET, U32_MAX);
+
+       ret = mtk_pci_get_irq_id(mdev, MTK_IRQ_SRC_MHCCIF);
+       if (ret < 0) {
+               dev_err(mdev->dev, "Failed to get mhccif_irq_id. ret=%d\n", ret);
+               return ret;
+       }
+       priv->mhccif_irq_id = ret;
+
+       ret = mtk_pci_register_irq(mdev, priv->mhccif_irq_id, mtk_mhccif_irq_cb, mdev);
+       if (ret) {
+               dev_err(mdev->dev, "Failed to register mhccif_irq callback\n");
+               return ret;
+       }
+
+       return 0;
+}
+
+static void mtk_mhccif_exit(struct mtk_md_dev *mdev)
+{
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+       struct mtk_mhccif_cb *cb, *tmp;
+
+       mtk_pci_unregister_irq(mdev, priv->mhccif_irq_id);
+       cancel_work_sync(&priv->mhccif_work);
+       /* The work unmasks the source on its way out, so leave it masked. */
+       mtk_pci_mask_irq(mdev, priv->mhccif_irq_id);
+
+       list_for_each_entry_safe(cb, tmp, &priv->mhccif_cb_list, entry) {
+               list_del(&cb->entry);
+               kfree(cb);
+       }
+}
+
+static irqreturn_t mtk_pci_irq_handler(struct mtk_md_dev *mdev, u32 irq_state)
+{
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+       int irq_id;
+
+       /* Check whether each set bit has a callback, if has, call it */
+       do {
+               void (*cb)(int irq_id, void *data);
+
+               irq_id = fls(irq_state) - 1;
+               irq_state &= ~BIT(irq_id);
+               cb = READ_ONCE(priv->irq_cb_list[irq_id]);
+               if (likely(cb)) {
+                       smp_rmb(); /* Ensure data is read after callback */
+                       cb(irq_id, priv->irq_cb_data[irq_id]);
+               } else {
+                       dev_err_ratelimited(mdev->dev,
+                                           "Unhandled irq_id=%d, no callback for it.\n",
+                                           irq_id);
+                       mtk_pci_clear_irq(mdev, irq_id);
+               }
+       } while (irq_state);
+
+       return IRQ_HANDLED;
+}
+
+static irqreturn_t mtk_pci_irq_msix(int irq, void *data)
+{
+       struct mtk_pci_irq_desc *irq_desc = data;
+       struct mtk_md_dev *mdev = irq_desc->mdev;
+       struct mtk_pci_priv *priv;
+       u32 irq_state, irq_enable;
+
+       priv = mdev->hw_priv;
+       irq_state = mtk_pci_mac_read32(priv, REG_MSIX_ISTATUS_HOST_GRP0_0);
+       irq_enable = mtk_pci_mac_read32(priv, REG_IMASK_HOST_MSIX_GRP0_0);
+       irq_state &= irq_enable;
+
+       if (unlikely(irq_state == U32_MAX && irq_enable == U32_MAX))
+               return IRQ_NONE; /* device gone */
+
+       irq_state &= irq_desc->msix_bits; /* scope to this vector */
+       if (unlikely(!irq_state))
+               return IRQ_NONE;
+
+       /* Mask the bit; the consumer unmasks it when it is done */
+       mtk_pci_mac_write32(priv, REG_IMASK_HOST_MSIX_CLR_GRP0_0, irq_state);
+
+       return mtk_pci_irq_handler(mdev, irq_state);
+}
+
+static int mtk_pci_request_irq_msix(struct mtk_md_dev *mdev)
+{
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+       struct mtk_pci_irq_desc *irq_desc;
+       struct pci_dev *pdev;
+       int ret, i;
+
+       pdev = to_pci_dev(mdev->dev);
+       irq_desc = priv->irq_desc;
+
+       priv->irq_cnt = MTK_IRQ_CNT_MAX;
+
+       for (i = 0; i < MTK_IRQ_CNT_MAX; i++) {
+               irq_desc[i].mdev = mdev;
+               irq_desc[i].msix_bits = BIT(i);
+               snprintf(irq_desc[i].name, MTK_IRQ_NAME_LEN, "msix%d-%s", i, mdev->dev_str);
+               ret = pci_request_irq(pdev, i, mtk_pci_irq_msix, NULL,
+                                     &irq_desc[i], "%s", irq_desc[i].name);
+               if (ret) {
+                       dev_err(mdev->dev, "Failed to request %s: ret=%d\n",
+                               irq_desc[i].name, ret);
+                       for (i--; i >= 0; i--)
+                               pci_free_irq(pdev, i, &irq_desc[i]);
+                       return ret;
+               }
+       }
+
+       return 0;
+}
+
+static int mtk_pci_request_irq(struct mtk_md_dev *mdev)
+{
+       struct pci_dev *pdev = to_pci_dev(mdev->dev);
+       int ret;
+
+       /* 32 vectors map 1:1 at the MAC's power-on default and the driver
+        * never merges them, so the MSI-X config register is left alone.
+        */
+       ret = pci_alloc_irq_vectors(pdev, MTK_IRQ_CNT_MAX,
+                                   MTK_IRQ_CNT_MAX, PCI_IRQ_MSIX);
+       if (ret < 0) {
+               dev_err(mdev->dev,
+                       "Unable to alloc %d MSI-X vectors: ret=%d\n",
+                       MTK_IRQ_CNT_MAX, ret);
+               return ret;
+       }
+
+       return mtk_pci_request_irq_msix(mdev);
+}
+
+static void mtk_pci_free_irq(struct mtk_md_dev *mdev)
+{
+       struct pci_dev *pdev = to_pci_dev(mdev->dev);
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+       int i;
+
+       for (i = 0; i < priv->irq_cnt; i++)
+               pci_free_irq(pdev, i, &priv->irq_desc[i]);
+}
+
+static int mtk_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
+{
+       struct device *dev = &pdev->dev;
+       struct mtk_pci_priv *priv;
+       struct mtk_md_dev *mdev;
+       int ret;
+
+       mdev = devm_kzalloc(dev, sizeof(*mdev), GFP_KERNEL);
+       if (!mdev) {
+               ret = -ENOMEM;
+               goto log_err;
+       }
+       mdev->dev = dev;
+
+       priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL);

drivers/net/wwan/t9xx/pcie/mtk_pci.c line 876

Quoted 10 lines
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +10 -0
+       if (!priv) {
+               ret = -ENOMEM;
+               goto log_err;
+       }
+
+       pci_set_drvdata(pdev, mdev);
+       priv->mdev = mdev;
+       mdev->hw_ver  = pdev->device;
+       mdev->hw_priv = priv;
+       strscpy(mdev->dev_str, pci_name(pdev), MTK_DEV_STR_LEN);

Do we really need this buffer to exist solely for IRQ names, can't we simply use dev_name()?

Quoted 348 lines
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +158 -0
+
+       ret = pcim_enable_device(pdev);
+       if (ret) {
+               dev_err(mdev->dev, "Failed to enable pci device.\n");
+               goto log_err;
+       }
+
+       ret = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
+       if (ret) {
+               dev_err(mdev->dev, "Failed to set DMA Mask and Coherent. (ret=%d)\n", ret);
+               goto log_err;
+       }
+
+       ret = mtk_pci_bar_init(mdev);
+       if (ret)
+               goto log_err;
+
+       ret = mtk_pci_atr_init(mdev);
+       if (ret)
+               goto disable_atr;
+
+       spin_lock_init(&priv->irq_cb_lock);
+
+       ret = mtk_mhccif_init(mdev);
+       if (ret)
+               goto disable_atr;
+
+       /* Mask every source before the handlers go in, so a source
+        * left enabled by firmware or a previous bind cannot fire
+        * into a half-initialised driver.
+        */
+       mtk_pci_mac_write32(priv, REG_IMASK_HOST_MSIX_CLR_GRP0_0, U32_MAX);
+
+       ret = mtk_pci_request_irq(mdev);
+       if (ret)
+               goto free_mhccif;
+
+       if (!mtk_pci_link_check(mdev)) {
+               ret = -ENOLINK;
+               goto free_irq;
+       }
+
+       pci_set_master(pdev);
+       mtk_pci_unmask_irq(mdev, priv->mhccif_irq_id);
+
+       return 0;
+
+free_irq:
+       mtk_pci_free_irq(mdev);
+free_mhccif:
+       mtk_mhccif_exit(mdev);
+       pci_free_irq_vectors(pdev);
+       priv->irq_cnt = 0;
+disable_atr:
+       mtk_pci_atr_disable(priv);
+log_err:
+       dev_err(dev, "Failed to probe device, ret=%d\n", ret);
+
+       return ret;
+}
+
+static void mtk_pci_remove(struct pci_dev *pdev)
+{
+       struct mtk_md_dev *mdev = pci_get_drvdata(pdev);
+       struct mtk_pci_priv *priv = mdev->hw_priv;
+       struct device *dev = &pdev->dev;
+       int i, ret;
+
+       /* Silence every source before tearing anything down. */
+       mtk_pci_mac_write32(priv, REG_IMASK_HOST_MSIX_CLR_GRP0_0, U32_MAX);
+
+       /* Free the handlers before mtk_mhccif_exit() and the vectors after
+        * it: MSI-X, and so INTx disable, stays on until the work is gone.
+        */
+       mtk_pci_free_irq(mdev);
+       mtk_mhccif_exit(mdev);
+       pci_free_irq_vectors(pdev);
+       priv->irq_cnt = 0;
+       pci_clear_master(pdev);
+       /* A dead link reads all-ones: keep the copy saved while it was up. */
+       if (mtk_pci_link_check(mdev))
+               pci_save_state(pdev);
+
+       /* Reset last: the endpoint comes back at power-on defaults, so no MMIO
+        * and no MSI-X teardown may follow it.
+        */
+       ret = mtk_pci_pldr(mdev);
+       if (!ret) {
+               /* MRST._RST may return before the link has retrained, and a
+                * config write the device does not take is simply lost.
+                */
+               for (i = 0; i < MTK_PLDR_READY_POLLS && !mtk_pci_link_check(mdev); i++)
+                       msleep(MTK_PLDR_READY_POLL_MS);
+               if (!mtk_pci_link_check(mdev))
+                       dev_warn(dev, "device not back %d ms after reset, its config space may not be restored\n",
+                                MTK_PLDR_READY_POLLS * MTK_PLDR_READY_POLL_MS);
+       } else if (!mtk_pci_link_check(mdev)) {
+               dev_warn(dev, "PLDR failed (%d) and link is down, modem not reset\n", ret);
+       } else {
+               dev_warn(dev, "PLDR failed (%d), trying MHCCIF reset\n", ret);
+               if (mtk_pci_send_ext_evt(mdev, DEV_EVT_H2D_DEVICE_RESET)) {
+                       dev_err(dev, "MHCCIF reset failed\n");
+               } else {
+                       /* Unlike MRST._RST the doorbell returns before the device
+                        * has reset, and whether the link drops is up to the
+                        * firmware: wait a fixed time, then for a link that is
+                        * still down to come back, before the restore below.
+                        */
+                       msleep(MTK_MHCCIF_RESET_DELAY_MS);
+                       for (i = 0; i < MTK_PLDR_READY_POLLS && !mtk_pci_link_check(mdev); i++)
+                               msleep(MTK_PLDR_READY_POLL_MS);
+               }
+       }
+
+       /* The reset returned the endpoint to its power-on defaults: put back
+        * the saved config space for the next driver that binds.
+        */
+       pci_restore_state(pdev);
+}
+
+/* A kexec reboot neither resets nor powers down the slot, and the boot
+ * notification the next kernel waits for is one-shot, so reset the modem
+ * on the way down the same way remove() does.
+ */
+static void mtk_pci_shutdown(struct pci_dev *pdev)
+{
+       if (kexec_is_in_progress())
+               mtk_pci_remove(pdev);
+}
+
+static pci_ers_result_t mtk_pci_error_detected(struct pci_dev *pdev,
+                                              pci_channel_state_t state)
+{
+       struct mtk_md_dev *mdev = pci_get_drvdata(pdev);
+
+       dev_err(mdev->dev, "AER detected: pci_channel_state_t=%u\n", state);
+
+       /* AER recovery not supported, disconnect the device */
+       return PCI_ERS_RESULT_DISCONNECT;
+}
+
+static const struct pci_error_handlers mtk_pci_err_handler = {
+       .error_detected = mtk_pci_error_detected,
+};
+
+static struct pci_driver mtk_pci_drv = {
+       .name = KBUILD_MODNAME,
+       .id_table = t9xx_pci_table,
+       .probe = mtk_pci_probe,
+       .remove = mtk_pci_remove,
+       .shutdown = mtk_pci_shutdown,
+       .err_handler = &mtk_pci_err_handler
+};
+
+module_pci_driver(mtk_pci_drv);
+
+MODULE_DESCRIPTION("MediaTek T9xx PCIe WWAN driver");
+MODULE_LICENSE("GPL");
drivers/net/wwan/t9xx/pcie/mtk_pci.h new file +139 -0
new file mode 100644
index 000000000000..36ab9d85417c
@@ -0,0 +1,139 @@
+/* SPDX-License-Identifier: GPL-2.0-only
+ *
+ * Copyright (c) 2022, MediaTek Inc.
+ */
+
+#ifndef __MTK_PCI_H__
+#define __MTK_PCI_H__
+
+#include <linux/mutex.h>
+#include <linux/pci.h>
+
+#include "mtk_dev.h"
+
+enum mtk_irq_src {
+       MTK_IRQ_SRC_MIN,
+       MTK_IRQ_SRC_MHCCIF,
+       MTK_IRQ_SRC_CLDMA0,
+       MTK_IRQ_SRC_CLDMA1,
+       MTK_IRQ_SRC_MAX
+};
+
+enum mtk_atr_src_port {
+       ATR_SRC_PCI_WIN0 = 0,
+       ATR_SRC_PCI_WIN1,
+       ATR_SRC_AXIS_0,
+       ATR_SRC_AXIS_1,
+       ATR_SRC_AXIS_2,
+       ATR_SRC_AXIS_3,
+};
+
+enum mtk_atr_dst_port {
+       ATR_DST_PCI_TRX = 0,
+       ATR_DST_AXIM_0 = 4,
+};
+
+#define MTK_PCI_CLASS                 0x0D4000
+
+#define MTK_BAR_0_1_IDX                 0
+#define MTK_BAR_2_3_IDX                 2
+
+#define MTK_IRQ_CNT_MAX                                32
+#define MTK_IRQ_NAME_LEN                       32
+
+#define ATR_PORT_OFFSET                                0x100
+#define ATR_TABLE_OFFSET                       0x20
+#define ATR_TABLE_NUM_PER_ATR                  8
+#define ATR_PCIE_REG_TRSL_ADDR                 0x10000000
+#define ATR_PCIE_REG_SIZE                      0x00400000
+#define ATR_PCIE_REG_PORT                      ATR_SRC_PCI_WIN0
+#define ATR_PCIE_REG_TABLE_NUM                 1
+#define ATR_PCIE_REG_TRSL_PORT                 ATR_DST_AXIM_0
+#define ATR_PCIE_DEV_DMA_SRC_ADDR              0x00000000
+#define ATR_PCIE_DEV_DMA_TRANSPARENT           1
+#define ATR_PCIE_DEV_DMA_SIZE                  0
+#define ATR_PCIE_DEV_DMA_TABLE_NUM             0
+#define ATR_PCIE_DEV_DMA_TRSL_ADDR             0x00000000
+
+struct mtk_pci_irq_desc {
+       struct mtk_md_dev *mdev;
+       u32 msix_bits;
+       char name[MTK_IRQ_NAME_LEN];
+};
+
+struct mtk_pci_priv {
+       struct mtk_md_dev *mdev;
+       void __iomem *bar23_addr;
+       void __iomem *mac_reg_base;
+       void __iomem *ext_reg_base;
+       int irq_cnt;
+       /* irq_cb_lock: protects irq_cb_list[] and, on the register side,
+        * irq_cb_data[].  mtk_pci_unregister_irq() clears irq_cb_data[]
+        * after synchronize_irq() and outside the lock, because a handler
+        * past its READ_ONCE() of irq_cb_list[] still needs the data.
+        * Callers must not register and unregister one irq_id concurrently.
+        */
+       spinlock_t irq_cb_lock;
+       void *irq_cb_data[MTK_IRQ_CNT_MAX];
+
+       void (*irq_cb_list[MTK_IRQ_CNT_MAX])(int irq_id, void *data);
+       struct mtk_pci_irq_desc irq_desc[MTK_IRQ_CNT_MAX];
+       struct list_head mhccif_cb_list;
+       /* mhccif_lock: lock to protect mhccif_cb_list */
+       struct mutex mhccif_lock;
+       struct work_struct mhccif_work;
+       int mhccif_irq_id;
+};
+
+struct mtk_atr_cfg {
+       u64 src_addr;
+       u64 trsl_addr;
+       u64 size;
+       u32 port;      /* Port number */
+       u32 table;     /* Table number (8 tables for each port) */
+       u32 trsl_id;
+       u32 trsl_param;
+       u32 transparent;
+};
+
+/* BAR 0/1 MMIO access */
+static inline u32 mtk_pci_mac_read32(struct mtk_pci_priv *priv, u64 addr)
+{
+       return ioread32(priv->mac_reg_base + addr);
+}
+
+static inline void mtk_pci_mac_write32(struct mtk_pci_priv *priv, u64 addr, u32 val)
+{
+       iowrite32(val, priv->mac_reg_base + addr);
+}
+
+/* BAR 2/3 MMIO access */
+static inline u32 mtk_pci_read32(struct mtk_md_dev *mdev, u64 addr)
+{
+       return ioread32(((struct mtk_pci_priv *)mdev->hw_priv)->ext_reg_base + addr);
+}
+
+static inline void mtk_pci_write32(struct mtk_md_dev *mdev, u64 addr, u32 val)
+{
+       iowrite32(val, ((struct mtk_pci_priv *)mdev->hw_priv)->ext_reg_base + addr);
+}
+
+/* Device operations */
+u32 mtk_pci_get_dev_state(struct mtk_md_dev *mdev);
+/* IRQ Related operations */
+int mtk_pci_get_irq_id(struct mtk_md_dev *mdev, enum mtk_irq_src irq_src);
+int mtk_pci_get_virq_id(struct mtk_md_dev *mdev, int irq_id);
+int mtk_pci_register_irq(struct mtk_md_dev *mdev, int irq_id,
+                        void (*irq_cb)(int irq_id, void *data), void *data);
+int mtk_pci_unregister_irq(struct mtk_md_dev *mdev, int irq_id);
+int mtk_pci_mask_irq(struct mtk_md_dev *mdev, int irq_id);
+int mtk_pci_unmask_irq(struct mtk_md_dev *mdev, int irq_id);
+int mtk_pci_clear_irq(struct mtk_md_dev *mdev, int irq_id);
+/* External event related */
+int mtk_pci_register_ext_evt(struct mtk_md_dev *mdev, u32 chs,
+                            void (*evt_cb)(u32 status, void *data), void *data);
+void mtk_pci_unregister_ext_evt(struct mtk_md_dev *mdev, u32 chs);
+void mtk_pci_mask_ext_evt(struct mtk_md_dev *mdev, u32 chs);
+void mtk_pci_unmask_ext_evt(struct mtk_md_dev *mdev, u32 chs);
+
+#endif /* __MTK_PCI_H__ */
drivers/net/wwan/t9xx/pcie/mtk_pci_reg.h new file +34 -1
new file mode 100644
index 000000000000..a97ad6630dcf
@@ -0,0 +1,34 @@
+/* SPDX-License-Identifier: GPL-2.0-only
+ *
+ * Copyright (c) 2022, MediaTek Inc.
+ */
+
+#ifndef __MTK_PCI_REG_H__
+#define __MTK_PCI_REG_H__
+
+#define REG_ATR_PCIE_WIN0_T0_SRC_ADDR_LSB      0x0600
+#define REG_ATR_PCIE_WIN0_T0_SRC_ADDR_MSB      0x0604
+#define REG_ATR_PCIE_WIN0_T0_TRSL_ADDR_LSB     0x0608
+#define REG_ATR_PCIE_WIN0_T0_TRSL_ADDR_MSB     0x060C
+#define REG_ATR_PCIE_WIN0_T0_TRSL_PARAM                0x0610
+#define REG_PCIE_DEBUG_DUMMY_7                 0x0D1C
+#define REG_MSIX_ISTATUS_HOST_GRP0_0           0x0F00
+#define REG_IMASK_HOST_MSIX_SET_GRP0_0         0x3000
+#define REG_IMASK_HOST_MSIX_CLR_GRP0_0         0x3080
+#define REG_IMASK_HOST_MSIX_GRP0_0             0x3100
+
+/* mhccif registers */
+#define MHCCIF_RC2EP_SW_BSY                    0x4
+#define MHCCIF_RC2EP_SW_TCHNUM                 0xC
+#define MHCCIF_RC2EP_EVT_DEVICE_RESET          BIT(13)
+
+#define MHCCIF_EP2RC_SW_INT_STS                        0x10
+#define MHCCIF_EP2RC_SW_INT_ACK                        0x14
+#define MHCCIF_EP2RC_SW_INT_EAP_MASK           0x20
+#define MHCCIF_EP2RC_SW_INT_EAP_MASK_SET       0x30
+#define MHCCIF_EP2RC_SW_INT_EAP_MASK_CLR       0x40
+#define MHCCIF_EP2RC_EVT_BOOT_FLOW_SYNC                BIT(5)
+#define MHCCIF_EP2RC_EVT_ASYNC_HS_NOTIFY_SAP   BIT(15)
+#define MHCCIF_EP2RC_EVT_ASYNC_HS_NOTIFY_MD    BIT(16)
+
+#endif /* __MTK_PCI_REG_H__ */
 
--

2.34.1

#3 lore raw

RE: [External Mail] Re: [PATCH net-next v12 1/6] net: wwan: t9xx: Add PCIe core

Hi Loic,

Thanks for the review.

Quoted 4 lines · Loic Poulain

drivers/net/wwan/t9xx/pcie/mtk_pci.c line 522

Quoted 2 lines
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +2 -0
+       if (acpi_disabled) {
+               dev_dbg(mdev->dev, "Unsupported, acpi function isn't enable\n");

Go straight to the point: "ACPI is disabled\n"

Will fix in v13, with that wording.

Quoted 9 lines

drivers/net/wwan/t9xx/pcie/mtk_pci.c line 532

Quoted 7 lines
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +7 -0
+       handle = ACPI_HANDLE(mdev->dev);
+       if (!handle) {
+               dev_dbg(mdev->dev, "Unsupported, acpi handle isn't found\n");
+               return -ENODEV;
+       }
+       if (!acpi_has_method(handle, "MRST._RST")) {
+               dev_dbg(mdev->dev, "Unsupported, pldr method isn't supported\n");

"ACPI handle not found"

Will fix in v13: "ACPI handle not found" for the missing handle, and "MRST._RST method not found" for the missing method.

Quoted 4 lines
Quoted 1 line

+ strscpy(mdev->dev_str, pci_name(pdev), MTK_DEV_STR_LEN);

Do we really need this buffer to exist solely for IRQ names, can't we simply use dev_name()?

Will fix in v13: dev_str goes away and every name is built from dev_name(). pci_request_irq() gets the format directly, so the per-IRQ name buffer goes away as well.

Thanks,
Jack

#4 lore raw

Re: [PATCH net-next v12 1/6] net: wwan: t9xx: Add PCIe core

In reply to Jack Wu
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 1 · Low: 1

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] mtk_pci_remove() resets the modem itself after pci_save_state(), and mtk_pci_shutdown() reuses it on a kexec reboot.
- [Low] mtk_pci_probe() enables the device with pcim_enable_device(), which sets pdev->is_managed.

--

net: wwan: t9xx: Add PCIe core

This commit adds the PCIe core for the MediaTek T9xx 5G WWAN modem driver. It covers probe/remove, MSI-X setup, the MHCCIF event channels and the register accessors. On removal, and on shutdown during a kexec reboot, the modem is reset through ACPI MRST._RST, falling back to the MHCCIF DEV_EVT_H2D_DEVICE_RESET doorbell.

Quoted 6 lines
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +0 -0
new file mode 100644
index 0000000000000..cf59038f09067
@@ -0,0 +1,1034 @@

[ ... ]

Quoted 2 lines
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +2 -0
+static int mtk_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
+{

[ ... ]

Quoted 5 lines
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +5 -0
+	ret = pcim_enable_device(pdev);
+	if (ret) {
+		dev_err(mdev->dev, "Failed to enable pci device.\n");
+		goto log_err;
+	}

[ ... ]

drivers/net/wwan/t9xx/pcie/mtk_pci.c line 928

Quoted 5 lines
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +5 -0
+free_irq:
+	mtk_pci_free_irq(mdev);
+free_mhccif:
+	mtk_mhccif_exit(mdev);
+	pci_free_irq_vectors(pdev);

[Severity: Low]
Is it safe to call pci_free_irq_vectors() here and in mtk_pci_remove() when the device was enabled with pcim_enable_device()?

pcim_enable_device() sets pdev->is_managed. Because of that, pci_alloc_irq_vectors() in mtk_pci_request_irq() goes through pci_setup_msi_context()->pcim_setup_msi_release(), which registers pcim_msi_release() as a devres action.

The kernel-doc of pci_free_irq_vectors() in drivers/pci/msi/api.c says:

* WARNING: Do not call this function if the device has been enabled
* with pcim_enable_device(). In that case, IRQ vectors are automatically
* managed via pcim_msi_release() and calling pci_free_irq_vectors() can
* lead to double-free issues.

After a failed probe, or once mtk_pci_remove() returns, devres calls pci_free_irq_vectors() a second time. Today that does nothing, because pci_disable_msix() returns early when !dev->msix_enabled. The TODO in drivers/pci/msi/msi.c says this implicit managed behaviour is going to change, though, so the driver would then be relying on an idempotence that may go away.

This is still the same at the end of the series.

Quoted 3 lines
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +3 -0
+	priv->irq_cnt = 0;
+disable_atr:
+	mtk_pci_atr_disable(priv);

[ ... ]

Quoted 2 lines
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +2 -0
+static void mtk_pci_remove(struct pci_dev *pdev)
+{

[ ... ]

drivers/net/wwan/t9xx/pcie/mtk_pci.c line 963

Quoted 13 lines
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +13 -0
+	mtk_pci_free_irq(mdev);
+	mtk_mhccif_exit(mdev);
+	pci_free_irq_vectors(pdev);
+	priv->irq_cnt = 0;
+	pci_clear_master(pdev);
+	/* A dead link reads all-ones: keep the copy saved while it was up. */
+	if (mtk_pci_link_check(mdev))
+		pci_save_state(pdev);
+
+	/* Reset last: the endpoint comes back at power-on defaults, so no MMIO
+	 * and no MSI-X teardown may follow it.
+	 */
+	ret = mtk_pci_pldr(mdev);

[Severity: Medium]
Could pciehp treat this reset as a surprise removal of the modem?

MRST._RST in mtk_pci_pldr() is a platform reset that drops and retrains the link. The MHCCIF DEV_EVT_H2D_DEVICE_RESET fallback below may drop the link too, depending on the firmware.

Neither path is wrapped in pci_hp_ignore_link_change() and pci_hp_unignore_link_change() on pdev->bus->self. Their kernel-doc covers this case:

* Mark the beginning of a code section causing spurious link changes on the
* Secondary Bus of @pdev, e.g. as a side effect of a Secondary Bus Reset,
* D3cold transition, firmware update or FPGA reconfiguration.
...
* Must be paired with pci_hp_unignore_link_change(). May be called both
* from the PCI core and from Endpoint drivers.

pciehp_ist() ignores the link events only when that bracket is set:

drivers/pci/hotplug/pciehp_hpc.c:pciehp_ist() {
    ...
	if ((events & (PCI_EXP_SLTSTA_PDC | PCI_EXP_SLTSTA_DLLSC)) &&
	    (pci_dpc_recovered(pdev) || pci_hp_spurious_link_change(pdev)) &&
	    ctrl->state == ON_STATE) {
    ...
}

Without the bracket, on a hotplug-capable upstream port, pciehp_handle_presence_or_link_change() would disable the slot, mark the device disconnected and re-enumerate it.

Once the device is marked disconnected, pci_device_is_present() returns false. The 50 x 20 ms poll on mtk_pci_link_check() then runs to the end and the "device not back" warning fires. pci_restore_state() is then sent to a device the core has already given up on.

The core's own pciehp_reset_slot() brackets its link-dropping bus reset with these helpers. Would it make sense to do the same around both reset paths here? mtk_pci_shutdown() runs this same code during a kexec reboot.

This is still the same at the end of the series.

Quoted 14 lines
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +14 -0
+	if (!ret) {
+		/* MRST._RST may return before the link has retrained, and a
+		 * config write the device does not take is simply lost.
+		 */
+		for (i = 0; i < MTK_PLDR_READY_POLLS && !mtk_pci_link_check(mdev); i++)
+			msleep(MTK_PLDR_READY_POLL_MS);
+		if (!mtk_pci_link_check(mdev))
+			dev_warn(dev, "device not back %d ms after reset, its config space may not be restored\n",
+				 MTK_PLDR_READY_POLLS * MTK_PLDR_READY_POLL_MS);
+	} else if (!mtk_pci_link_check(mdev)) {
+		dev_warn(dev, "PLDR failed (%d) and link is down, modem not reset\n", ret);
+	} else {
+		dev_warn(dev, "PLDR failed (%d), trying MHCCIF reset\n", ret);
+		if (mtk_pci_send_ext_evt(mdev, DEV_EVT_H2D_DEVICE_RESET)) {

[ ... ]

Quoted 5 lines
drivers/net/wwan/t9xx/pcie/mtk_pci.c new file +5 -0
+	/* The reset returned the endpoint to its power-on defaults: put back
+	 * the saved config space for the next driver that binds.
+	 */
+	pci_restore_state(pdev);
+}

[ ... ]

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261117-t9xx_driver_v1-v12-0-e181b616b820%40compal.com
#5 lore raw

Re: [PATCH net-next v12 1/6] net: wwan: t9xx: Add PCIe core

Thanks for the review.

Quoted 15 lines

Is it safe to call pci_free_irq_vectors() here and in mtk_pci_remove() when the device was enabled with pcim_enable_device()?

pcim_enable_device() sets pdev->is_managed. Because of that, pci_alloc_irq_vectors() in mtk_pci_request_irq() goes through pci_setup_msi_context()->pcim_setup_msi_release(), which registers pcim_msi_release() as a devres action.

The kernel-doc of pci_free_irq_vectors() in drivers/pci/msi/api.c says:

* WARNING: Do not call this function if the device has been enabled
* with pcim_enable_device(). In that case, IRQ vectors are automatically
* managed via pcim_msi_release() and calling pci_free_irq_vectors() can
* lead to double-free issues.

Quoted 8 lines

After a failed probe, or once mtk_pci_remove() returns, devres calls pci_free_irq_vectors() a second time. Today that does nothing, because pci_disable_msix() returns early when !dev->msix_enabled. The TODO in drivers/pci/msi/msi.c says this implicit managed behaviour is going to change, though, so the driver would then be relying on an idempotence that may go away.

This is still the same at the end of the series.

No change. The vectors have to be freed after mtk_mhccif_exit() and before the reset, and devres only runs once remove() has returned, that is after the reset and after pci_restore_state(); on the kexec shutdown path it does not run at all. The later pcim_msi_release() finds msix_enabled clear and returns, and if the implicit managed behaviour is removed, as the TODO says, the explicit call is what remains, so nothing here depends on it. t7xx enables with pcim_enable_device() and frees its vectors the same way.

Quoted 36 lines

Could pciehp treat this reset as a surprise removal of the modem?

MRST._RST in mtk_pci_pldr() is a platform reset that drops and retrains the link. The MHCCIF DEV_EVT_H2D_DEVICE_RESET fallback below may drop the link too, depending on the firmware.

Neither path is wrapped in pci_hp_ignore_link_change() and pci_hp_unignore_link_change() on pdev->bus->self. Their kernel-doc covers this case:

* Mark the beginning of a code section causing spurious link changes on the
* Secondary Bus of @pdev, e.g. as a side effect of a Secondary Bus Reset,
* D3cold transition, firmware update or FPGA reconfiguration.
...
* Must be paired with pci_hp_unignore_link_change(). May be called both
* from the PCI core and from Endpoint drivers.

pciehp_ist() ignores the link events only when that bracket is set:

drivers/pci/hotplug/pciehp_hpc.c:pciehp_ist() {
    ...
        if ((events & (PCI_EXP_SLTSTA_PDC | PCI_EXP_SLTSTA_DLLSC)) &&
            (pci_dpc_recovered(pdev) || pci_hp_spurious_link_change(pdev)) &&
            ctrl->state == ON_STATE) {
    ...
}

Without the bracket, on a hotplug-capable upstream port, pciehp_handle_presence_or_link_change() would disable the slot, mark the device disconnected and re-enumerate it.

Once the device is marked disconnected, pci_device_is_present() returns false. The 50 x 20 ms poll on mtk_pci_link_check() then runs to the end and the "device not back" warning fires. pci_restore_state() is then sent to a device the core has already given up on.

Quoted 5 lines

The core's own pciehp_reset_slot() brackets its link-dropping bus reset with these helpers. Would it make sense to do the same around both reset paths here? mtk_pci_shutdown() runs this same code during a kexec reboot.

This is still the same at the end of the series.

No change for the bracket in this series: pci_hp_ignore_link_change() and pci_hp_unignore_link_change() are not exported to modules, and this driver can be built as one. Their only caller is pciehp_reset_slot(); pci_dev_acpi_reset() and the MRST._RST reset in t7xx are not bracketed either. On a hotplug-capable port the result is what you describe: the poll runs out, the warning is printed, and pciehp removes and re-enumerates the modem, which leaves it with valid config space. I will state this in the commit message, and add the bracket once the helpers can be called from a module.

Will fix in v13 the kexec case that follows from it: there pciehp can unbind the device after .shutdown has already run the teardown, so mtk_pci_dev_exit() will return early when it has already run.

Thanks,
Jack

pw-bot: cr

author
#6 lore raw

PATCH v12 2/6 net: wwan: t9xx: Add control plane transaction layer framework

In reply to Jack Wu

Introduce the control plane and transaction layer framework for the T9XX WWAN driver. This patch adds the core data structures (mtk_ctrl_blk, mtk_ctrl_trans) and initialization entry points that subsequent patches build upon.

The control plane block (ctrl_blk) starts out with only the device back-pointer and an opaque pointer to the transport context; later patches add the port layer and FSM hooks to it. The actual DMA engine and TX/RX service implementations are added in subsequent patches, and mtk_ctrl_init() and mtk_ctrl_exit() get their first callers there, in pcie/mtk_trans_ctrl.c.

---
 drivers/net/wwan/t9xx/Makefile              |  1 +
 drivers/net/wwan/t9xx/mtk_ctrl_plane.c      | 45 +++++++++++++++++++++++++++++
 drivers/net/wwan/t9xx/mtk_ctrl_plane.h      | 21 ++++++++++++++
 drivers/net/wwan/t9xx/mtk_dev.h             |  3 ++
 drivers/net/wwan/t9xx/pcie/mtk_pci.c        |  1 +
 drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.h | 19 ++++++++++++
 6 files changed, 90 insertions(+)
drivers/net/wwan/t9xx/Makefile +1 -0
index bd6063c85c2b..0a07507f1ddf 100644
@@ -6,4 +6,5 @@ ccflags-y += -I$(src)
 obj-$(CONFIG_MTK_T9XX) += mtk_t9xx.o
 
 mtk_t9xx-y := \
+	mtk_ctrl_plane.o \
 	pcie/mtk_pci.o
drivers/net/wwan/t9xx/mtk_ctrl_plane.c new file +45 -0

45 lines not on this page · raw message

drivers/net/wwan/t9xx/mtk_ctrl_plane.h new file +21 -0
new file mode 100644
index 000000000000..46f1ab9f0551
@@ -0,0 +1,21 @@
+/* SPDX-License-Identifier: GPL-2.0-only
+ *
+ * Copyright (c) 2022, MediaTek Inc.
+ */
+
+#ifndef __MTK_CTRL_PLANE_H__
+#define __MTK_CTRL_PLANE_H__
+
+#include <linux/skbuff.h>
+
+#include "mtk_dev.h"
+
+struct mtk_ctrl_blk {
+	struct mtk_md_dev *mdev;
+	void *ctrl_hw_priv;
+};
+
+int mtk_ctrl_init(struct mtk_md_dev *mdev);
+void mtk_ctrl_exit(struct mtk_md_dev *mdev);
+
+#endif /* __MTK_CTRL_PLANE_H__ */
drivers/net/wwan/t9xx/mtk_dev.h +3 -0
index fc25418bb957..ff3cbaa4329e 100644
@@ -28,12 +28,15 @@ enum mtk_dev_evt_d2h {
 	DEV_EVT_D2H_ASYNC_HS_NOTIFY_MD	= BIT(6),
 };
 
+struct mtk_ctrl_blk;
+
 /* mtk_md_dev defines the structure of MTK modem device */
 struct mtk_md_dev {
 	struct device *dev;
 	void *hw_priv;
 	u32 hw_ver;
 	char dev_str[MTK_DEV_STR_LEN];
+	struct mtk_ctrl_blk *ctrl_blk;
 };
 
 #endif /* __MTK_DEV_H__ */
drivers/net/wwan/t9xx/pcie/mtk_pci.c +1 -0
index cf59038f0906..3dd8efa374ff 100644
@@ -13,6 +13,7 @@
 #include <linux/module.h>
 
 #include "mtk_dev.h"
+#include "mtk_trans_ctrl.h"
 #include "mtk_pci.h"
 #include "mtk_pci_reg.h"
 
drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.h new file +19 -0
new file mode 100644
index 000000000000..9b42f33bd008
@@ -0,0 +1,19 @@
+/* SPDX-License-Identifier: GPL-2.0-only
+ *
+ * Copyright (c) 2022, MediaTek Inc.
+ */
+
+#ifndef __MTK_TRANS_CTRL_H__
+#define __MTK_TRANS_CTRL_H__
+
+#include <linux/list.h>
+#include <linux/skbuff.h>
+#include <linux/types.h>
+
+#include "mtk_dev.h"
+
+struct mtk_ctrl_trans {
+	struct mtk_md_dev *mdev;
+};
+
+#endif
Signature · 1 line
2.34.1
maintainer
#7 lore raw

Re: [PATCH net-next v12 2/6] net: wwan: t9xx: Add control plane transaction layer framework

Quoted 93 lines · On Tue, Nov 17, 2026 at 11:51 AM Jack Wu via B4 Relay…

From: Jack Wu <[email protected]>

Introduce the control plane and transaction layer framework for the T9XX WWAN driver. This patch adds the core data structures (mtk_ctrl_blk, mtk_ctrl_trans) and initialization entry points that subsequent patches build upon.

The control plane block (ctrl_blk) starts out with only the device back-pointer and an opaque pointer to the transport context; later patches add the port layer and FSM hooks to it. The actual DMA engine and TX/RX service implementations are added in subsequent patches, and mtk_ctrl_init() and mtk_ctrl_exit() get their first callers there, in pcie/mtk_trans_ctrl.c.

---
 drivers/net/wwan/t9xx/Makefile              |  1 +
 drivers/net/wwan/t9xx/mtk_ctrl_plane.c      | 45 +++++++++++++++++++++++++++++
 drivers/net/wwan/t9xx/mtk_ctrl_plane.h      | 21 ++++++++++++++
 drivers/net/wwan/t9xx/mtk_dev.h             |  3 ++
 drivers/net/wwan/t9xx/pcie/mtk_pci.c        |  1 +
 drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.h | 19 ++++++++++++
 6 files changed, 90 insertions(+)
drivers/net/wwan/t9xx/Makefile +1 -0
index bd6063c85c2b..0a07507f1ddf 100644
@@ -6,4 +6,5 @@ ccflags-y += -I$(src)
 obj-$(CONFIG_MTK_T9XX) += mtk_t9xx.o
 
 mtk_t9xx-y := \
+       mtk_ctrl_plane.o \
        pcie/mtk_pci.o
drivers/net/wwan/t9xx/mtk_ctrl_plane.c new file +45 -0
new file mode 100644
index 000000000000..18f0573ac653
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (c) 2022, MediaTek Inc.
+ */
+
+#include <linux/device.h>
+
+#include "mtk_ctrl_plane.h"
+
+/**
+ * mtk_ctrl_init() - Initialize the control plane block.
+ * @mdev: Pointer to the MTK modem device.
+ *
+ * Allocates and initializes the control plane block
+ * associated with @mdev.  Runs once per bind; the allocation is
+ * devres managed and is released at unbind, not by
+ * mtk_ctrl_exit().
+ *
+ * Return: 0 on success, -ENOMEM on allocation failure.
+ */
+int mtk_ctrl_init(struct mtk_md_dev *mdev)
+{
+       struct mtk_ctrl_blk *ctrl_blk;
+
+       ctrl_blk = devm_kzalloc(mdev->dev, sizeof(*ctrl_blk), GFP_KERNEL);
+       if (!ctrl_blk)
+               return -ENOMEM;
+
+       ctrl_blk->mdev = mdev;
+       mdev->ctrl_blk = ctrl_blk;
+
+       return 0;
+}
+
+/**
+ * mtk_ctrl_exit() - Clean up the control plane block.
+ * @mdev: Pointer to the MTK modem device.
+ *
+ * Clears the control plane block pointer. The allocation
+ * itself is managed by devres and freed on driver detach.
+ */
+void mtk_ctrl_exit(struct mtk_md_dev *mdev)
+{
+       mdev->ctrl_blk = NULL;
+}
drivers/net/wwan/t9xx/mtk_ctrl_plane.h new file +0 -0
new file mode 100644
index 000000000000..46f1ab9f0551

drivers/net/wwan/t9xx/mtk_ctrl_plane.h line 9

Quoted 9 lines
drivers/net/wwan/t9xx/mtk_ctrl_plane.h new file +9 -0
@@ -0,0 +1,21 @@
+/* SPDX-License-Identifier: GPL-2.0-only
+ *
+ * Copyright (c) 2022, MediaTek Inc.
+ */
+
+#ifndef __MTK_CTRL_PLANE_H__
+#define __MTK_CTRL_PLANE_H__
+
+#include <linux/skbuff.h>

Is it actually unused here?

Quoted 51 lines
drivers/net/wwan/t9xx/mtk_ctrl_plane.h new file +12 -0
+
+#include "mtk_dev.h"
+
+struct mtk_ctrl_blk {
+       struct mtk_md_dev *mdev;
+       void *ctrl_hw_priv;
+};
+
+int mtk_ctrl_init(struct mtk_md_dev *mdev);
+void mtk_ctrl_exit(struct mtk_md_dev *mdev);
+
+#endif /* __MTK_CTRL_PLANE_H__ */
drivers/net/wwan/t9xx/mtk_dev.h +3 -0
index fc25418bb957..ff3cbaa4329e 100644
@@ -28,12 +28,15 @@ enum mtk_dev_evt_d2h {
        DEV_EVT_D2H_ASYNC_HS_NOTIFY_MD  = BIT(6),
 };
 
+struct mtk_ctrl_blk;
+
 /* mtk_md_dev defines the structure of MTK modem device */
 struct mtk_md_dev {
        struct device *dev;
        void *hw_priv;
        u32 hw_ver;
        char dev_str[MTK_DEV_STR_LEN];
+       struct mtk_ctrl_blk *ctrl_blk;
 };
 
 #endif /* __MTK_DEV_H__ */
drivers/net/wwan/t9xx/pcie/mtk_pci.c +1 -0
index cf59038f0906..3dd8efa374ff 100644
@@ -13,6 +13,7 @@
 #include <linux/module.h>
 
 #include "mtk_dev.h"
+#include "mtk_trans_ctrl.h"
 #include "mtk_pci.h"
 #include "mtk_pci_reg.h"
 
drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.h new file +1 -0
new file mode 100644
index 000000000000..9b42f33bd008
@@ -0,0 +1,19 @@
+/* SPDX-License-Identifier: GPL-2.0-only

drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.h line 11

Quoted 10 lines
drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.h new file +10 -0
+ *
+ * Copyright (c) 2022, MediaTek Inc.
+ */
+
+#ifndef __MTK_TRANS_CTRL_H__
+#define __MTK_TRANS_CTRL_H__
+
+#include <linux/list.h>
+#include <linux/skbuff.h>
+#include <linux/types.h>

Same question.

Quoted 13 lines
drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.h new file +8 -1
+
+#include "mtk_dev.h"
+
+struct mtk_ctrl_trans {
+       struct mtk_md_dev *mdev;
+};
+
+#endif
 
--

2.34.1

#8 lore raw

Re: [PATCH net-next v12 2/6] net: wwan: t9xx: Add control plane transaction layer framework

Hi Loic,

Thanks for the review.

Quoted 3 lines · Loic Poulain
Quoted 1 line

+#include <linux/skbuff.h>

Is it actually unused here?

Yes, it is unused in this patch. Will fix in v13: the include moves to the control DMA patch, which adds the first sk_buff user to this header.

Quoted 5 lines

drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.h line 11

Quoted 3 lines
drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.h new file +3 -0
+#include <linux/list.h>
+#include <linux/skbuff.h>
+#include <linux/types.h>

Same question.

All three are first needed by the next patch and will move there in v13. I went through the includes of the whole series for the same problem and v13 will also drop the ones no patch uses.

Thanks,
Jack

author
#9 lore raw

PATCH v12 3/6 net: wwan: t9xx: Add control DMA interface

In reply to Jack Wu

Cross Layer Direct Memory Access(CLDMA) is the hardware interface used by the control plane and designated to translate data between the host and the device. It supports 8 hardware queues for the device AP and modem respectively.

CLDMA driver uses General Purpose Descriptor (GPD) to describe transaction information that can be recognized by CLDMA hardware. Once CLDMA hardware transaction is started, it would fetch and parse GPD to transfer data correctly. To facilitate the CLDMA transaction, a GPD ring for each queue is used. Once the transaction is started, CLDMA hardware will traverse the GPD ring to transfer data between the host and the device until no GPD is available.

CLDMA TX flow:
Once a TX service receives the TX data from the port layer, it uses APIs exported by the CLDMA driver to configure GPD with the DMA address of TX data. After that, the service triggers CLDMA to fetch the first available GPD to transfer data.

CLDMA RX flow:
When there is RX data from the MD, CLDMA hardware asserts an interrupt to notify the host to fetch data and dispatch it to FSM (for handshake messages) or the port layer. After CLDMA opening is finished, All RX GPDs are fulfilled and ready to receive data from the device.

A queue that does not stop within the poll escalates to a reset of its CLDMA instance, which also cuts the instance's other queues. The re-arm restarts each of them from the first descriptor the device still owns, so a cut transfer is sent again in full.

With this commit, probe registers the transport plane through new mtk_pci_dev_init()/mtk_pci_dev_exit() hooks: the transaction context, which points at the static queue info table for the AP and modem control channels, is attached to the control plane. Nothing is brought up yet - the FSM listener that calls mtk_pcie_hif_init(), which builds the per-channel queue table, the CLDMA device context and the TRB service thread, arrives with the later
"Add FSM thread" patch, together with the per-instance CLDMA setup (DMA pools, workqueue, IRQ) the queue code here runs on; the userspace-visible port interfaces arrive with "Add control port".

---
 drivers/net/wwan/t9xx/Makefile              |    5 +-
 drivers/net/wwan/t9xx/mtk_ctrl_plane.h      |   49 ++
 drivers/net/wwan/t9xx/pcie/mtk_cldma.c      | 1207 +++++++++++++++++++++++++++
 drivers/net/wwan/t9xx/pcie/mtk_cldma.h      |  118 +++
 drivers/net/wwan/t9xx/pcie/mtk_cldma_drv.c  |  513 ++++++++++++
 drivers/net/wwan/t9xx/pcie/mtk_cldma_drv.h  |  109 +++
 drivers/net/wwan/t9xx/pcie/mtk_pci.c        |   28 +-
 drivers/net/wwan/t9xx/pcie/mtk_pci_reg.h    |    1 +
 drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.c |  614 ++++++++++++++
 drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.h |   65 ++
 10 files changed, 2707 insertions(+), 2 deletions(-)
drivers/net/wwan/t9xx/Makefile +4 -1
index 0a07507f1ddf..74bef150e3a1 100644
@@ -7,4 +7,7 @@ obj-$(CONFIG_MTK_T9XX) += mtk_t9xx.o
 
 mtk_t9xx-y := \
 	mtk_ctrl_plane.o \
-	pcie/mtk_pci.o
+	pcie/mtk_pci.o \
+	pcie/mtk_trans_ctrl.o \
+	pcie/mtk_cldma.o \
+	pcie/mtk_cldma_drv.o
drivers/net/wwan/t9xx/mtk_ctrl_plane.h +49 -0

55 lines not on this page · raw message

drivers/net/wwan/t9xx/pcie/mtk_cldma.c new file +1207 -0

1,207 lines not on this page · raw message

drivers/net/wwan/t9xx/pcie/mtk_cldma.h new file +118 -0

118 lines not on this page · raw message

drivers/net/wwan/t9xx/pcie/mtk_cldma_drv.c new file +513 -0

513 lines not on this page · raw message

drivers/net/wwan/t9xx/pcie/mtk_cldma_drv.h new file +109 -0

109 lines not on this page · raw message

drivers/net/wwan/t9xx/pcie/mtk_pci.c +27 -1
index 3dd8efa374ff..9d089a0fa1ec 100644
@@ -850,6 +850,24 @@ static void mtk_pci_free_irq(struct mtk_md_dev *mdev)
 		pci_free_irq(pdev, i, &priv->irq_desc[i]);
 }
 
+static int mtk_pci_dev_init(struct mtk_md_dev *mdev)
+{
+	int ret;
+
+	ret = mtk_trans_ctrl_init(mdev);
+	if (ret) {
+		dev_err(mdev->dev, "Failed to initialize control plane: %d\n", ret);
+		return ret;
+	}
+
+	return 0;
+}
+
+static void mtk_pci_dev_exit(struct mtk_md_dev *mdev)
+{
+	mtk_trans_ctrl_exit(mdev);
+}
+
 static int mtk_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
 {
 	struct device *dev = &pdev->dev;
@@ -912,9 +930,13 @@ static int mtk_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
 	if (ret)
 		goto free_mhccif;
 
+	ret = mtk_pci_dev_init(mdev);
+	if (ret)
+		goto free_irq;
+
 	if (!mtk_pci_link_check(mdev)) {
 		ret = -ENOLINK;
-		goto free_irq;
+		goto dev_exit;
 	}
 
 	pci_set_master(pdev);
@@ -922,6 +944,8 @@ static int mtk_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
 
 	return 0;
 
+dev_exit:
+	mtk_pci_dev_exit(mdev);
 free_irq:
 	mtk_pci_free_irq(mdev);
 free_mhccif:
@@ -943,6 +967,8 @@ static void mtk_pci_remove(struct pci_dev *pdev)
 	struct device *dev = &pdev->dev;
 	int i, ret;
 
+	mtk_pci_dev_exit(mdev);
+
 	/* Silence every source before tearing anything down. */
 	mtk_pci_mac_write32(priv, REG_IMASK_HOST_MSIX_CLR_GRP0_0, U32_MAX);
 
drivers/net/wwan/t9xx/pcie/mtk_pci_reg.h +1 -0
index a97ad6630dcf..f65a8065d945 100644
@@ -16,6 +16,7 @@
 #define REG_IMASK_HOST_MSIX_SET_GRP0_0		0x3000
 #define REG_IMASK_HOST_MSIX_CLR_GRP0_0		0x3080
 #define REG_IMASK_HOST_MSIX_GRP0_0		0x3100
+#define REG_DEV_INFRA_BASE			0x10001000
 
 /* mhccif registers */
 #define MHCCIF_RC2EP_SW_BSY			0x4
drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.c new file +614 -0

614 lines not on this page · raw message

drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.h +65 -0

78 lines not on this page · raw message

Signature · 1 line
2.34.1
#10 lore raw

Re: [PATCH net-next v12 3/6] net: wwan: t9xx: Add control DMA interface

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 3 · Low: 1

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] In mtk_cldma_rxq_free() (drivers/net/wwan/t9xx/pcie/mtk_cldma.c), the final ring-drain loop…
- [Medium] mtk_cldma_hw_recovery() runs from mtk_cldma_start_xfer() when one TX queue's UL start-address register reads 0.
- [Medium] The driver says the CLDMA 'can lose its queue state, which leaves zero addresses' (comment in mtk_cldma_drv_init()).
- [Low] The patch adds TRB_CMD_STOP and TRB_CMD_RECOVER to the shared enum mtk_trb_cmd_type in mtk_ctrl_plane.h, but nothing implements them.

--

net: wwan: t9xx: Add control DMA interface

This adds the CLDMA (Cross Layer DMA) control-plane transport for the t9xx WWAN driver. It covers the GPD ring handling for the TX and RX queues, the reset and re-arm logic for an instance, and a TRB service layer. Probe now attaches the transport context through the new mtk_pci_dev_init()/mtk_pci_dev_exit() hooks.

Quoted 6 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma.c new file +0 -0
new file mode 100644
index 0000000000000..c0bafb39e4f5a
@@ -0,0 +1,1207 @@

[ ... ]

Quoted 2 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma.c new file +2 -0
+static void mtk_cldma_rx_done_work(struct work_struct *work)
+{

[ ... ]

Quoted 14 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma.c new file +14 -0
+	ret = mtk_cldma_check_rx_req(drv_info, rxq);
+	if (!ret)
+		goto again;
+
+	/* -ENXIO means the queue has no start address programmed, which is
+	 * exactly what a restart installs, so consume need_restart first.
+	 * Only the resume below is skipped in that case.
+	 */
+	mutex_lock(&drv_info->rearm_lock);
+	if (!atomic_read(&rxq->need_exit)) {
+		if (atomic_xchg(&rxq->need_restart, 0)) {
+			if (!mtk_cldma_rxq_restart(drv_info, rxq)) {
+				atomic_set(&rxq->need_restart, 1);
+				mutex_unlock(&drv_info->rearm_lock);

drivers/net/wwan/t9xx/pcie/mtk_cldma.c line 332

Quoted 10 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma.c new file +10 -0
+				goto again;
+			}
+		} else if (ret != -ENXIO) {
+			mtk_cldma_resume_queue(drv_info, DIR_RX, rxq->rxqno);
+		}
+	}
+	mutex_unlock(&drv_info->rearm_lock);
+
+	if (ret == -ENXIO)
+		goto out;

[Severity: Medium]
What brings this RX queue back when mtk_cldma_check_rx_req() returns -ENXIO and need_restart is clear?

mtk_cldma_check_rx_req() treats a zero SO_CUR_ADDR as lost state:

    curr_addr = mtk_cldma_get_rx_curr_addr(drv_info, rxq->rxqno);
    if (unlikely(!curr_addr))
        return -ENXIO;

The comment in mtk_cldma_drv_init() also says the device "can lose its queue state, which leaves zero addresses".

In that case this worker skips the resume and goes to out. That path unmasks XFER_DONE and returns. It does not set need_restart, restart the queue or schedule any recovery.

An RX engine with no address should not raise another XFER_DONE, so nothing reruns this worker. The only lost-state recovery is in the TX submit path:

    mtk_cldma_start_xfer()
        if (unlikely(!val))
            mtk_cldma_hw_recovery()

Could RX on this CLDMA instance stay stuck until the host happens to submit a TX on the same instance? On CLDMA0 (the SAP control channel), host TX may be rare after the handshake. Unsolicited device-to-host control messages could then sit there indefinitely.

This depends on SO_CUR_ADDR reading 0 after the state is lost, which the driver's own comments say can happen.

[ ... ]

Quoted 2 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma.c new file +2 -0
+static void mtk_cldma_rxq_free(struct cldma_drv_info *drv_info, u32 rxqno)
+{

[ ... ]

drivers/net/wwan/t9xx/pcie/mtk_cldma.c line 761

Quoted 10 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma.c new file +10 -0
+	/* free rx req resource */
+	for (i = 0; i < rxq->nr_gpds; i++) {
+		req = rxq->req_pool + rxq->free_idx;
+		if (!(req->gpd->rx_gpd.gpd_flags & CLDMA_GPD_FLAG_HWO) &&
+		    le16_to_cpu(req->gpd->rx_gpd.data_recv_len)) {
+			if (!mtk_cldma_rx_skb_adjust(mdev, req)) {
+				rxq->rx_done(req->skb, rxq->arg);
+				req->skb = NULL;
+			}
+		}

[Severity: Medium]
Can req->skb be NULL when this loop reaches mtk_cldma_rx_skb_adjust()?

In mtk_cldma_rx_done_work(), if both the reload and the recycle dma_map_single() fail, the slot is left empty:

    dev_kfree_skb_any(rx_skb);
    req->skb = NULL;
    req->data_dma_addr = 0;
    goto out_retry;

The leading refill for an empty slot (the !req->skb branch) can also fail and jump to out_retry. The cancel_work_sync() earlier in mtk_cldma_rxq_free() can then cancel the requeued retry before the slot is refilled.

mtk_cldma_rx_skb_adjust() dereferences req->skb unconditionally:

    req->skb->len = 0;
    skb_reset_tail_pointer(req->skb);
    skb_put(req->skb, recv_len);

mtk_cldma_rx_skb_adjust() already zeroed data_recv_len for that slot. To get here, the device would have to write a non-zero data_recv_len into a GPD with HWO clear, which it does not own. The driver already treats data_recv_len as device-controlled and clamps it against mtu.

If that happens, would closing the channel oops on a NULL skb? Would a req->skb check here, like the one at the top of the loop in mtk_cldma_rx_done_work(), be enough?

[ ... ]

drivers/net/wwan/t9xx/pcie/mtk_cldma.c line 786

Quoted 10 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma.c new file +10 -0
+/* The device reported a zero TX start address: it lost its queue state. */
+static int mtk_cldma_hw_recovery(struct cldma_drv_info *drv_info, u32 qno)
+{
+	u64 val;
+
+	dev_err(drv_info->mdev->dev,
+		"CLDMA%d lost its queue state, re-initializing\n",
+		drv_info->hw_id);
+
+	mtk_cldma_rearm_queues(drv_info);

[Severity: Medium]
Is it safe to re-arm the whole instance here without a stop or a mtk_cldma_drv_reset() first?

mtk_cldma_txq_free() and mtk_cldma_rxq_free() both reset the IP before they call mtk_cldma_rearm_queues(). Here, the only evidence is that one TX queue's UL start address read back as zero.

mtk_cldma_rearm_queues() then does three things:

- mtk_cldma_drv_init() read-modify-writes UL_CFG and SO_CFG (the GPD format bits) and other IP-global registers.

- On every published TX queue with tx_started set, it reprograms the start address and issues UL_START.

- On every published RX queue, it sets need_restart, so mtk_cldma_rx_done_work() later reprograms SO_START_ADDR and issues SO_START.

What if a zero read on one queue does not mean the whole instance was reset? Sibling TX and RX engines could still be running when they get these CFG writes and START commands.

On TX, a START at the GPD currently being sent could resend or cut that control message. On RX, a restart could lose or corrupt the frame being written.

If the hardware only reads zero after a full IP reset, the other engines are already idle and this does not apply. For comparison, the t7xx driver re-initializes in a similar way without a stop, but only reprograms the affected queue.

[ ... ]

Quoted 6 lines
drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.c new file +0 -0
new file mode 100644
index 0000000000000..3650878128a27
@@ -0,0 +1,614 @@

[ ... ]

Quoted 5 lines
drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.c new file +5 -0
+int mtk_pcie_hif_submit_skb(struct mtk_md_dev *mdev, struct sk_buff *skb, bool force_send)
+{
+	struct mtk_ctrl_blk *ctrl_blk = mdev->ctrl_blk;
+	struct mtk_ctrl_trans *trans;
+	struct queue_info *que;

drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.c line 493

Quoted 10 lines
drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.c new file +10 -0
+	struct trb *trb;
+	int ret;
+
+	trans = ctrl_blk->ctrl_hw_priv;
+	trb = (struct trb *)skb->cb;
+
+	if (trb->cmd == TRB_CMD_STOP || trb->cmd == TRB_CMD_RECOVER) {
+		trb->trb_complete(skb);
+		return 0;
+	}

[Severity: Low]
TRB_CMD_STOP and TRB_CMD_RECOVER are added to enum mtk_trb_cmd_type in mtk_ctrl_plane.h, but nothing implements them. The commit message does not mention them either.

Here they complete immediately and never set trb->status. They also skip the trans->available check and submit_lock. mtk_cldma_trb_process() rejects them in any case:

    if (!(trb->cmd > TRB_CMD_MIN && trb->cmd < TRB_CMD_STOP))
        return -EINVAL;

A caller trying to stop or recover a queue would get a successful completion, with whatever status was left in skb->cb, while the queue keeps running.

No caller in the series issues these commands yet. Could they be dropped, or rejected with something like -EOPNOTSUPP until they are implemented?

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261117-t9xx_driver_v1-v12-0-e181b616b820%40compal.com
#11 lore raw

Re: [PATCH net-next v12 3/6] net: wwan: t9xx: Add control DMA interface

Thanks for the review.

Quoted 24 lines

What brings this RX queue back when mtk_cldma_check_rx_req() returns -ENXIO and need_restart is clear?

mtk_cldma_check_rx_req() treats a zero SO_CUR_ADDR as lost state:

    curr_addr = mtk_cldma_get_rx_curr_addr(drv_info, rxq->rxqno);
    if (unlikely(!curr_addr))
        return -ENXIO;

The comment in mtk_cldma_drv_init() also says the device "can lose its queue state, which leaves zero addresses".

In that case this worker skips the resume and goes to out. That path unmasks XFER_DONE and returns. It does not set need_restart, restart the queue or schedule any recovery.

An RX engine with no address should not raise another XFER_DONE, so nothing reruns this worker. The only lost-state recovery is in the TX submit path:

    mtk_cldma_start_xfer()
        if (unlikely(!val))
            mtk_cldma_hw_recovery()
Quoted 7 lines

Could RX on this CLDMA instance stay stuck until the host happens to submit a TX on the same instance? On CLDMA0 (the SAP control channel), host TX may be rare after the handshake. Unsolicited device-to-host control messages could then sit there indefinitely.

This depends on SO_CUR_ADDR reading 0 after the state is lost, which the driver's own comments say can happen.

The code is right here, but the comment in mtk_cldma_drv_init() is
wrong: it says the device can lose its queue state, which suggests an RX queue can lose its address on its own. v13 rewords it to say what actually happens: a TX start address reads zero after the device has powered the block down.

In this series a zero SO_CUR_ADDR with need_restart clear means the link is dead: every host-side reset sets need_restart under rearm_lock before this worker can take that lock. t7xx detects lost state on TX submission only, in the same way.

Quoted 21 lines

Can req->skb be NULL when this loop reaches mtk_cldma_rx_skb_adjust()?

In mtk_cldma_rx_done_work(), if both the reload and the recycle dma_map_single() fail, the slot is left empty:

    dev_kfree_skb_any(rx_skb);
    req->skb = NULL;
    req->data_dma_addr = 0;
    goto out_retry;

The leading refill for an empty slot (the !req->skb branch) can also fail and jump to out_retry. The cancel_work_sync() earlier in mtk_cldma_rxq_free() can then cancel the requeued retry before the slot is refilled.

mtk_cldma_rx_skb_adjust() dereferences req->skb unconditionally:

    req->skb->len = 0;
    skb_reset_tail_pointer(req->skb);
    skb_put(req->skb, recv_len);
Quoted 8 lines

mtk_cldma_rx_skb_adjust() already zeroed data_recv_len for that slot. To get here, the device would have to write a non-zero data_recv_len into a GPD with HWO clear, which it does not own. The driver already treats data_recv_len as device-controlled and clamps it against mtu.

If that happens, would closing the channel oops on a NULL skb? Would a req->skb check here, like the one at the top of the loop in mtk_cldma_rx_done_work(), be enough?

Will fix in v13: the drain loop in mtk_cldma_rxq_free() checks req->skb first, as the loop in mtk_cldma_rx_done_work() does. A well-behaved device cannot get there, since the host zeroes data_recv_len when it reaps the slot and the device stops at the unarmed descriptor before it, but the field is device-writable.

Quoted 23 lines

Is it safe to re-arm the whole instance here without a stop or a mtk_cldma_drv_reset() first?

mtk_cldma_txq_free() and mtk_cldma_rxq_free() both reset the IP before they call mtk_cldma_rearm_queues(). Here, the only evidence is that one TX queue's UL start address read back as zero.

mtk_cldma_rearm_queues() then does three things:

- mtk_cldma_drv_init() read-modify-writes UL_CFG and SO_CFG (the GPD format bits) and other IP-global registers.

- On every published TX queue with tx_started set, it reprograms the start address and issues UL_START.

- On every published RX queue, it sets need_restart, so mtk_cldma_rx_done_work() later reprograms SO_START_ADDR and issues SO_START.

What if a zero read on one queue does not mean the whole instance was reset? Sibling TX and RX engines could still be running when they get these CFG writes and START commands.

Quoted 8 lines

On TX, a START at the GPD currently being sent could resend or cut that control message. On RX, a restart could lose or corrupt the frame being written.

If the hardware only reads zero after a full IP reset, the other engines are already idle and this does not apply. For comparison, the t7xx driver re-initializes in a similar way without a stop, but only reprograms the affected queue.

No functional change; the comment above mtk_cldma_hw_recovery() will say what a zero start address means.

The host never leaves a published TX queue without a start address, so a zero is read only after the device has powered the block down. That clears the configuration and the start addresses of all its TX queues together and leaves no TX engine running. Re-arming only the affected queue, as t7xx does, would leave the descriptors already submitted on the other queues waiting for their next submission. An RX queue is restarted from its own worker, which stops it first later in the series.

Quoted 11 lines

TRB_CMD_STOP and TRB_CMD_RECOVER are added to enum mtk_trb_cmd_type in mtk_ctrl_plane.h, but nothing implements them. The commit message does not mention them either.

Here they complete immediately and never set trb->status. They also skip the trans->available check and submit_lock. mtk_cldma_trb_process() rejects them in any case:

    if (!(trb->cmd > TRB_CMD_MIN && trb->cmd < TRB_CMD_STOP))
        return -EINVAL;
Quoted 7 lines

A caller trying to stop or recover a queue would get a successful completion, with whatever status was left in skb->cb, while the queue keeps running.

No caller in the series issues these commands yet. Could they be dropped, or rejected with something like -EOPNOTSUPP until they are implemented?

Will fix in v13: TRB_CMD_STOP and TRB_CMD_RECOVER are removed, together with the early completion in mtk_pcie_hif_submit_skb(). Nothing in the series issues them.

Thanks,
Jack

pw-bot: cr

author
#12 lore raw

PATCH v12 4/6 net: wwan: t9xx: Add control port

In reply to Jack Wu

The control port consists of port I/O and port manager. Port I/O provides a common operation as defined by "struct mtk_port_ops", and the operation is managed by the "port manager". It provides interfaces to internal users, the implemented internal interfaces are open, close, write and recv_register.

The port manager defines and implements port management interfaces and structures. It is responsible for port creation, destroying, and managing port states. It sends data from port I/O to CLDMA via TRB ( Transaction Request Block ), and dispatches received data from CLDMA to port I/O.

A TRB lives in the control buffer of the skb it describes, so it is freed together with that skb. This patch therefore gives struct trb a
kref: the port layer initialises it in mtk_port_trb_init() and owns the release function mtk_port_trb_free(). mtk_ctrl_trb_handler() holds a reference for the duration of a dispatch, including on the -EAGAIN early return, so a completion running concurrently cannot free the skb underneath the handler.

The TX sequence number is written into the header when the trb thread hands the packet to CLDMA, and only advanced once CLDMA has put it on the ring, so a packet refused before that takes no number. A packet already on the ring keeps its number even if the queue then fails to start or is flushed: it may have reached the modem by then, so the number is not reused.

At this commit probe and remove only build and tear down the port
table: ->init() runs for each port, and ->disable() and ->exit() find no port enabled. Nothing calls ->enable(), ->recv() or the internal port interface yet, and no TRB is processed: the port-state, RX dispatch and TRB kref paths become live with "Add FSM thread". That patch also provides the teardown order these paths rely on - the CLDMA queues are quiesced and the trb services stopped before the port manager frees the ports - so neither a TRB completion nor an armed RX queue outlives the port it points to.

---
 drivers/net/wwan/t9xx/Makefile              |   2 +
 drivers/net/wwan/t9xx/mtk_ctrl_plane.c      |  24 +-
 drivers/net/wwan/t9xx/mtk_ctrl_plane.h      |  12 +-
 drivers/net/wwan/t9xx/mtk_port.c            | 641 ++++++++++++++++++++++++++++
 drivers/net/wwan/t9xx/mtk_port.h            | 130 ++++++
 drivers/net/wwan/t9xx/mtk_port_io.c         | 236 ++++++++++
 drivers/net/wwan/t9xx/mtk_port_io.h         |  32 ++
 drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.c |  27 +-
 8 files changed, 1097 insertions(+), 7 deletions(-)
drivers/net/wwan/t9xx/Makefile +2 -0
index 74bef150e3a1..d44266009362 100644
@@ -7,6 +7,8 @@ obj-$(CONFIG_MTK_T9XX) += mtk_t9xx.o
 
 mtk_t9xx-y := \
 	mtk_ctrl_plane.o \
+	mtk_port.o \
+	mtk_port_io.o \
 	pcie/mtk_pci.o \
 	pcie/mtk_trans_ctrl.o \
 	pcie/mtk_cldma.o \
drivers/net/wwan/t9xx/mtk_ctrl_plane.c +20 -4
index 18f0573ac653..1d0eba4e18b3 100644
@@ -6,21 +6,24 @@
 #include <linux/device.h>
 
 #include "mtk_ctrl_plane.h"
+#include "mtk_port.h"
 
 /**
  * mtk_ctrl_init() - Initialize the control plane block.
  * @mdev: Pointer to the MTK modem device.
+ * @port_layer_cfg: Port layer configuration.
  *
  * Allocates and initializes the control plane block
  * associated with @mdev.  Runs once per bind; the allocation is
  * devres managed and is released at unbind, not by
  * mtk_ctrl_exit().
  *
- * Return: 0 on success, -ENOMEM on allocation failure.
+ * Return: 0 on success, negative error code on failure.
  */
-int mtk_ctrl_init(struct mtk_md_dev *mdev)
+int mtk_ctrl_init(struct mtk_md_dev *mdev, struct mtk_port_layer_cfg *port_layer_cfg)
 {
 	struct mtk_ctrl_blk *ctrl_blk;
+	int err;
 
 	ctrl_blk = devm_kzalloc(mdev->dev, sizeof(*ctrl_blk), GFP_KERNEL);
 	if (!ctrl_blk)
@@ -29,6 +32,13 @@ int mtk_ctrl_init(struct mtk_md_dev *mdev)
 	ctrl_blk->mdev = mdev;
 	mdev->ctrl_blk = ctrl_blk;
 
+	err = mtk_port_mngr_init(ctrl_blk, port_layer_cfg->port_cfg,
+				 port_layer_cfg->port_cnt);
+	if (err) {
+		mdev->ctrl_blk = NULL;
+		return err;
+	}
+
 	return 0;
 }
 
@@ -36,10 +46,16 @@ int mtk_ctrl_init(struct mtk_md_dev *mdev)
  * mtk_ctrl_exit() - Clean up the control plane block.
  * @mdev: Pointer to the MTK modem device.
  *
- * Clears the control plane block pointer. The allocation
- * itself is managed by devres and freed on driver detach.
+ * Tears down what mtk_ctrl_init() set up and clears the control plane
+ * block pointer.  The allocation itself is managed by devres and freed
+ * on driver detach.
+ *
+ * Context: Process context; may sleep.
  */
 void mtk_ctrl_exit(struct mtk_md_dev *mdev)
 {
+	struct mtk_ctrl_blk *ctrl_blk = mdev->ctrl_blk;
+
+	mtk_port_mngr_exit(ctrl_blk);
 	mdev->ctrl_blk = NULL;
 }
drivers/net/wwan/t9xx/mtk_ctrl_plane.h +11 -1
index 42c387652788..0c53712e9cbe 100644
@@ -6,6 +6,7 @@
 #ifndef __MTK_CTRL_PLANE_H__
 #define __MTK_CTRL_PLANE_H__
 
+#include <linux/kref.h>
 #include <linux/skbuff.h>
 
 #include "mtk_dev.h"
@@ -49,6 +50,11 @@ struct trb {
 	u32 channel_id;
 	enum mtk_trb_cmd_type cmd;
 	int status;
+	/* Store-release by the completion callback, load-acquire by the
+	 * waiter: seeing it set means seeing everything the callback wrote.
+	 */
+	bool done;
+	struct kref kref;
 	void *priv;
 	int (*trb_complete)(struct sk_buff *skb);
 };
@@ -59,12 +65,16 @@ union ctrl_hif_cmd_data {
 	u32 rx_ch;
 };
 
+struct mtk_port_layer_cfg;
+struct mtk_port_mngr;
+
 struct mtk_ctrl_blk {
 	struct mtk_md_dev *mdev;
+	struct mtk_port_mngr *port_mngr;
 	void *ctrl_hw_priv;
 };
 
-int mtk_ctrl_init(struct mtk_md_dev *mdev);
+int mtk_ctrl_init(struct mtk_md_dev *mdev, struct mtk_port_layer_cfg *port_layer_cfg);
 void mtk_ctrl_exit(struct mtk_md_dev *mdev);
 
 #endif /* __MTK_CTRL_PLANE_H__ */
drivers/net/wwan/t9xx/mtk_port.c new file +641 -0

641 lines not on this page · raw message

drivers/net/wwan/t9xx/mtk_port.h new file +130 -0

130 lines not on this page · raw message

drivers/net/wwan/t9xx/mtk_port_io.c new file +236 -0

236 lines not on this page · raw message

drivers/net/wwan/t9xx/mtk_port_io.h new file +32 -0
new file mode 100644
index 000000000000..db1d9ae52d9a
@@ -0,0 +1,32 @@
+/* SPDX-License-Identifier: GPL-2.0-only
+ *
+ * Copyright (c) 2022, MediaTek Inc.
+ */
+
+#ifndef __MTK_PORT_IO_H__
+#define __MTK_PORT_IO_H__
+
+#include <linux/skbuff.h>
+
+#include "mtk_port.h"
+
+extern struct mutex mtk_port_mngr_grp_mtx;
+
+struct mtk_port_ops {
+	int (*init)(struct mtk_port *port);
+	void (*exit)(struct mtk_port *port);
+	void (*enable)(struct mtk_port *port);
+	void (*disable)(struct mtk_port *port);
+	int (*recv)(struct mtk_port *port, struct sk_buff *skb);
+};
+
+const struct mtk_port_ops *mtk_port_get_ops(enum mtk_port_type type);
+
+void *mtk_port_internal_open(struct mtk_md_dev *mdev, char *name, int flag);
+int mtk_port_internal_close(void *i_port);
+int mtk_port_internal_write(void *i_port, struct sk_buff *skb);
+void mtk_port_internal_recv_register(void *i_port,
+				     int (*cb)(void *priv, struct sk_buff *skb),
+				     void *arg);
+
+#endif /* __MTK_PORT_IO_H__ */
drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.c +25 -2
index 3650878128a2..61b2428beb83 100644
@@ -13,6 +13,7 @@
 #include "mtk_ctrl_plane.h"
 #include "mtk_dev.h"
 #include "mtk_pci.h"
+#include "mtk_port.h"
 #include "mtk_trans_ctrl.h"
 
 #define QUEUE_CHL_MASK	0xFFFF
@@ -26,6 +27,18 @@ static const struct queue_info mtk_queue_info[] = {
 	 Q_MTU_3_5K, Q_MTU_3_5K, TX_GPD_NUM, RX_GPD_NUM, 0},
 };
 
+static const struct mtk_port_cfg mtk_port_cfg_tbl[] = {
+	{CCCI_CONTROL_TX, CCCI_CONTROL_RX, PORT_TYPE_INTERNAL, "MDCTRL",
+		PORT_F_DFLT},
+	{CCCI_SAP_CONTROL_TX, CCCI_SAP_CONTROL_RX, PORT_TYPE_INTERNAL, "SAPCTRL",
+		PORT_F_DFLT},
+};
+
+static struct mtk_port_layer_cfg mtk_port_layer_cfg = {
+	.port_cfg = mtk_port_cfg_tbl,
+	.port_cnt = ARRAY_SIZE(mtk_port_cfg_tbl),
+};
+
 static bool mtk_queue_list_is_full(struct mtk_ctrl_trans *trans, struct queue_info *que)
 {
 	return skb_queue_len_lockless(&trans->trans_list[que->hif_id].skb_list[que->txqno]) >=
@@ -170,6 +183,7 @@ static void mtk_ctrl_trb_handler(struct trb_srv *srv, struct trans_list *trans_l
 			break;
 		}
 		trb = (struct trb *)skb->cb;
+		kref_get(&trb->kref);
 
 		switch (trb->cmd) {
 		case TRB_CMD_ENABLE:
@@ -185,14 +199,17 @@ static void mtk_ctrl_trb_handler(struct trb_srv *srv, struct trans_list *trans_l
 			break;
 		case TRB_CMD_TX:
 			spin_unlock_irqrestore(&skb_list->lock, flags);
+			mtk_port_tx_seq_stamp(skb);
 			err = mtk_cldma_submit_tx(trans->dev, skb);
 			if (err) {
 				if (trans_list->tx_burst_cnt[qno]) {
 					kick = true;
 					break;
 				}
-				if (err == -EAGAIN)
+				if (err == -EAGAIN) {
+					kref_put(&trb->kref, mtk_port_trb_free);
 					return;
+				}
 
 				skb_unlink(skb, skb_list);
 				trb->status = err;
@@ -200,6 +217,7 @@ static void mtk_ctrl_trb_handler(struct trb_srv *srv, struct trans_list *trans_l
 				break;
 			}
 
+			mtk_port_tx_seq_advance(skb);
 			trans_list->tx_burst_cnt[qno]++;
 			spin_lock_irqsave(&skb_list->lock, flags);
 			if (trans_list->tx_burst_cnt[qno] >= TX_BURST_MAX_CNT ||
@@ -233,6 +251,8 @@ static void mtk_ctrl_trb_handler(struct trb_srv *srv, struct trans_list *trans_l
 			kick = false;
 		}
 
+		kref_put(&trb->kref, mtk_port_trb_free);
+
 		loop++;
 	} while (loop < TRB_NUM_PER_ROUND);
 }
@@ -476,6 +496,9 @@ int mtk_pcie_hif_exit(struct mtk_md_dev *mdev)
 	return 0;
 }
 
+/* skb->cb holds a trb set up by mtk_port_trb_init(); a TX skb starts with
+ * its CCCI header and has the sending port as trb->priv.
+ */
 int mtk_pcie_hif_submit_skb(struct mtk_md_dev *mdev, struct sk_buff *skb, bool force_send)
 {
 	struct mtk_ctrl_blk *ctrl_blk = mdev->ctrl_blk;
@@ -596,7 +619,7 @@ int mtk_trans_ctrl_init(struct mtk_md_dev *mdev)
 	trans->queue_info_num = ARRAY_SIZE(mtk_queue_info);
 	trans->trb_srv_num = TRB_SRV_NUM;
 
-	err = mtk_ctrl_init(mdev);
+	err = mtk_ctrl_init(mdev, &mtk_port_layer_cfg);
 	if (err)
 		return err;
 
Signature · 1 line
2.34.1
#13 lore raw

Re: [PATCH net-next v12 4/6] net: wwan: t9xx: Add control port

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

Low priority / nit picks for your consideration:

- [Low] Two comments added in this patch give conflicting meanings for -EBUSY, and neither matches mtk_ch_status_check().
- [Low] The struct mtk_port comment (drivers/net/wwan/t9xx/mtk_port.h) says tx_seq and rx_seq "are reset while the channel is disabled, so…
- [Low] mtk_port_rx_dispatch() (drivers/net/wwan/t9xx/mtk_port.c) picks the target port from the channel field of the received CCCI header,…

--

net: wwan: t9xx: Add control port

This patch adds the port I/O layer and the port manager to the t9xx WWAN driver. The port table is built from a static config, TRBs are sent to CLDMA, and received data is dispatched to ports. struct trb gets a kref, and TX sequence numbers are stamped when a TRB is handed to CLDMA.

Quoted 6 lines
drivers/net/wwan/t9xx/mtk_port.c new file +0 -0
new file mode 100644
index 0000000000000..eb5ea6741ed7f
@@ -0,0 +1,641 @@

[ ... ]

Quoted 2 lines
drivers/net/wwan/t9xx/mtk_port.c new file +2 -0
+static int mtk_port_rx_dispatch(struct sk_buff *skb, void *priv)
+{

[ ... ]

Quoted 8 lines
drivers/net/wwan/t9xx/mtk_port.c new file +8 -0
+	channel = FIELD_GET(MTK_HDR_FLD_CHN, le32_to_cpu(ccci_h->status));
+	/* A CLDMA instance carries the channels of one peer only (sAP or MD),
+	 * the peer of the port that armed this queue.
+	 */
+	if (MTK_PEER_ID(channel) == MTK_PEER_ID(port->info.rx_ch))
+		port = mtk_port_search_by_id(port_mngr, channel);
+	else
+		port = NULL;

drivers/net/wwan/t9xx/mtk_port.c line 387

Quoted 10 lines
drivers/net/wwan/t9xx/mtk_port.c new file +10 -0
+	if (unlikely(!port)) {
+		dev_warn_ratelimited(port_mngr->ctrl_blk->mdev->dev,
+				     "Failed to find port by channel:%d\n", channel);
+		goto drop_data;
+	}
+
+	mtk_port_check_rx_seq(port, ccci_h);
+	port->rx_seq = FIELD_GET(MTK_HDR_FLD_SEQ, le32_to_cpu(ccci_h->status));
+
+	ret = mtk_port_get_ops(port->info.type)->recv(port, skb);

[Severity: Low]
Can two RX workers update the same port->rx_seq at the same time here?

The target port comes from the channel in the CCCI header. The only filter is the peer ID. The queue that delivered the packet (the port passed in as priv, i.e. rxq->arg) is not used for the lookup.

Each RX queue has its own rx_done_work. mtk_cldma_dev_init() creates drv_info->wq like this:

    flag = WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_HIGHPRI;
    drv_info->wq = alloc_workqueue("cldma%d_workq_%s", flag, 0, hw_id, mdev->dev_str);

So work items for different RX queues of the same CLDMA are not ordered. Later in the series CLDMA1 serves RXQ(0) for MDCTRL, RXQ(2) for MBIM and RXQ(5) for AT.

Suppose the device puts a packet whose header names channel B on queue A's ring. Queue A's worker then runs mtk_port_check_rx_seq(), does the plain store to port B's rx_seq, and calls port B's ->recv(). Queue B's worker may be doing the same thing at that moment.

That seems to conflict with the comment in struct mtk_port:

rx_seq only from the rx_done
callback of the one queue serving this channel.

Should dispatch reject packets whose channel does not belong to the delivering queue? Or should rx_seq be protected some other way?

[ ... ]

drivers/net/wwan/t9xx/mtk_port.c line 511

Quoted 13 lines
drivers/net/wwan/t9xx/mtk_port.c new file +13 -0
+int mtk_port_ch_enable(struct mtk_port *port)
+{
+	struct mtk_port_mngr *port_mngr = port->port_mngr;
+	struct trb_open_priv *trb_open_priv;
+	struct sk_buff *skb;
+	struct trb *trb;
+	int ret;
+
+	/* The modem restarts its sequence numbering with the channel, and
+	 * the first packet after it is not checked.
+	 */
+	port->tx_seq = 0;
+	port->rx_seq = MTK_INVALID_RX_SEQ;

[Severity: Low]
Is the struct mtk_port comment right about when these counters are reset?

Both are reset
while the channel is disabled, so neither needs a lock.

The reset happens at the start of mtk_port_ch_enable(), before the ENABLE trb is submitted. The channel is not always disabled at that point.

The ENABLE can complete with -EBUSY in two places:

- mtk_ch_status_check(), when usr_cnt is already >= 1
- mtk_cldma_open(), when the queues already exist

In either case the RX queue is already armed with rxq->arg == port. mtk_port_rx_dispatch() may be running this store at the same time:

    port->rx_seq = FIELD_GET(MTK_HDR_FLD_SEQ, le32_to_cpu(ccci_h->status));

There is also a second case. An earlier ENABLE that timed out may still be queued, along with its compensating DISABLE. That pair can arm the queue for a short time while a new ->enable() resets the counters.

These are plain unsigned short accesses with no READ_ONCE() or WRITE_ONCE(). A late store from RX dispatch could undo the reset. The first packet of the new session would then be checked against a stale rx_seq and log a spurious "seq num out-of-order" warning.

Likewise, a TX left in flight from an earlier session could be stamped with a tx_seq while the reset is happening.

[ ... ]

Quoted 6 lines
drivers/net/wwan/t9xx/mtk_port_io.c new file +0 -0
new file mode 100644
index 0000000000000..48fdadf96f00f
@@ -0,0 +1,236 @@

[ ... ]

Quoted 9 lines
drivers/net/wwan/t9xx/mtk_port_io.c new file +9 -0
+static void mtk_port_internal_enable(struct mtk_port *port)
+{
+	int ret;
+
+	if (test_bit(PORT_S_ENABLE, &port->status))
+		return;
+
+	ret = mtk_port_ch_enable(port);
+	if (ret && ret != -EBUSY) {

[ ... ]

Quoted 6 lines
drivers/net/wwan/t9xx/mtk_port_io.c new file +6 -0
+	set_bit(PORT_S_WR, &port->status);
+	set_bit(PORT_S_ENABLE, &port->status);
+}
+
+static void mtk_port_internal_disable(struct mtk_port *port)
+{

[ ... ]

drivers/net/wwan/t9xx/mtk_port_io.c line 78

Quoted 4 lines
drivers/net/wwan/t9xx/mtk_port_io.c new file +4 -0
+	ret = mtk_port_ch_disable(port);
+	/* -EBUSY is reported too: every queue has a single port, so a refused
+	 * DISABLE means its user count was already zero.
+	 */

[Severity: Low]
Does this comment match what mtk_ch_status_check() does? The DISABLE path there is:

	case TRB_CMD_DISABLE:
		if (trans->usr_cnt[que->hif_id][que->txqno] > 0) {
			trans->usr_cnt[que->hif_id][que->txqno]--;
			if (!trans->usr_cnt[que->hif_id][que->txqno])
				break;
		}
		trb->status = -EBUSY;

So -EBUSY comes back in two cases: when the count was zero, and when the count was decremented but is still above zero.

mtk_port_ch_enable() has its own comment about -EBUSY:

    /* -EBUSY means another user already owns the queue, and the
     * geometry it reports is that queue's - also valid here.
     */

This assumes a queue can have more than one owner, which conflicts with the "single port" claim above. Following that comment, mtk_port_internal_enable() treats an ENABLE that returns -EBUSY (usr_cnt 1->2) as success and sets PORT_S_WR and PORT_S_ENABLE.

The later DISABLE then takes usr_cnt from 2 to 1 and gets -EBUSY. mtk_cldma_close() never runs, and the RX queue stays armed with rxq->arg pointing at the port.

Even with one port per queue, a leftover count can come from either of two failures:

- An ENABLE times out and the compensating mtk_port_ch_disable() fails in __dev_alloc_skb(). The ENABLE is still queued and later raises usr_cnt to 1.
- mtk_port_internal_disable() clears PORT_S_ENABLE, but the DISABLE skb cannot be allocated, so usr_cnt stays at 1.

If one owner per queue is meant to be an invariant, should an ENABLE that returns -EBUSY be treated as success? If not, should this comment and the one in mtk_port_ch_enable() be reconciled?

Quoted 5 lines
drivers/net/wwan/t9xx/mtk_port_io.c new file +5 -0
+	if (ret)
+		dev_warn(port->port_mngr->ctrl_blk->mdev->dev,
+			 "Failed to disable channel for port(%s): %d\n",
+			 port->info.name, ret);
+}
Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261117-t9xx_driver_v1-v12-0-e181b616b820%40compal.com
#14 lore raw

Re: [PATCH net-next v12 4/6] net: wwan: t9xx: Add control port

Thanks for the review.

Quoted 22 lines

Can two RX workers update the same port->rx_seq at the same time here?

The target port comes from the channel in the CCCI header. The only filter is the peer ID. The queue that delivered the packet (the port passed in as priv, i.e. rxq->arg) is not used for the lookup.

Each RX queue has its own rx_done_work. mtk_cldma_dev_init() creates drv_info->wq like this:

    flag = WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_HIGHPRI;
    drv_info->wq = alloc_workqueue("cldma%d_workq_%s", flag, 0, hw_id,

mdev->dev_str);

So work items for different RX queues of the same CLDMA are not ordered. Later in the series CLDMA1 serves RXQ(0) for MDCTRL, RXQ(2) for MBIM and RXQ(5) for AT.

Suppose the device puts a packet whose header names channel B on queue A's ring. Queue A's worker then runs mtk_port_check_rx_seq(), does the plain store to port B's rx_seq, and calls port B's ->recv(). Queue B's worker may be doing the same thing at that moment.

Quoted 7 lines

That seems to conflict with the comment in struct mtk_port:

rx_seq only from the rx_done
callback of the one queue serving this channel.

Should dispatch reject packets whose channel does not belong to the delivering queue? Or should rx_seq be protected some other way?

No code change: t7xx matches path and channel in the same way, both ->recv() paths tolerate concurrent calls, and rx_seq only feeds a rate-limited warning. A check against the delivering queue would drop frames on queues that several channels share. The struct mtk_port comment you quote will be reworded so that it no longer reads as a rule about which queue may write rx_seq.

Quoted 22 lines

Is the struct mtk_port comment right about when these counters are reset?

Both are reset
while the channel is disabled, so neither needs a lock.

The reset happens at the start of mtk_port_ch_enable(), before the ENABLE trb is submitted. The channel is not always disabled at that point.

The ENABLE can complete with -EBUSY in two places:

- mtk_ch_status_check(), when usr_cnt is already >= 1
- mtk_cldma_open(), when the queues already exist

In either case the RX queue is already armed with rxq->arg == port. mtk_port_rx_dispatch() may be running this store at the same time:

    port->rx_seq = FIELD_GET(MTK_HDR_FLD_SEQ, le32_to_cpu(ccci_h->status));

There is also a second case. An earlier ENABLE that timed out may still be queued, along with its compensating DISABLE. That pair can arm the queue for a short time while a new ->enable() resets the counters.

Quoted 7 lines

These are plain unsigned short accesses with no READ_ONCE() or WRITE_ONCE(). A late store from RX dispatch could undo the reset. The first packet of the new session would then be checked against a stale rx_seq and log a spurious "seq num out-of-order" warning.

Likewise, a TX left in flight from an earlier session could be stamped with a tx_seq while the reset is happening.

Will fix the comment in v13: it will say who writes each counter and that rx_seq only feeds the out-of-order warning, and will no longer state when they are reset. The code stays as it is: the reset only runs with PORT_S_ENABLE clear, which is either after every queue was closed or after an enable that never got as far as opening the port.

Quoted 38 lines

Does this comment match what mtk_ch_status_check() does? The DISABLE path there is:

        case TRB_CMD_DISABLE:
                if (trans->usr_cnt[que->hif_id][que->txqno] > 0) {
                        trans->usr_cnt[que->hif_id][que->txqno]--;
                        if (!trans->usr_cnt[que->hif_id][que->txqno])
                                break;
                }
                trb->status = -EBUSY;

So -EBUSY comes back in two cases: when the count was zero, and when the count was decremented but is still above zero.

mtk_port_ch_enable() has its own comment about -EBUSY:

    /* -EBUSY means another user already owns the queue, and the
     * geometry it reports is that queue's - also valid here.
     */

This assumes a queue can have more than one owner, which conflicts with the "single port" claim above. Following that comment, mtk_port_internal_enable() treats an ENABLE that returns -EBUSY (usr_cnt 1->2) as success and sets PORT_S_WR and PORT_S_ENABLE.

The later DISABLE then takes usr_cnt from 2 to 1 and gets -EBUSY. mtk_cldma_close() never runs, and the RX queue stays armed with rxq->arg pointing at the port.

Even with one port per queue, a leftover count can come from either of two failures:

- An ENABLE times out and the compensating mtk_port_ch_disable() fails in __dev_alloc_skb(). The ENABLE is still queued and later raises usr_cnt to 1.
- mtk_port_internal_disable() clears PORT_S_ENABLE, but the DISABLE skb cannot be allocated, so usr_cnt stays at 1.

Quoted 3 lines

If one owner per queue is meant to be an invariant, should an ENABLE that returns -EBUSY be treated as success? If not, should this comment and the one in mtk_port_ch_enable() be reconciled?

Will fix in v13: you are right that the comment in mtk_port_internal_disable() claims more than the code guarantees. It will only say that a DISABLE refused with -EBUSY did not close the queue, which holds for both cases in mtk_ch_status_check(). The one in mtk_port_ch_enable() will say that -EBUSY means the queue is already open, without naming another user.

-EBUSY stays a successful ENABLE. With one port per queue the open queue can only have been armed by this port's own earlier ENABLE, with the same rx callback and argument.

No change for the two leftover-count cases. A count left by a failed DISABLE does not outlive the HIF: ->disable() runs only on the way to OFF or at unbind, and mtk_pcie_hif_exit() there frees every queue while the ports are still alive; the next HIF init starts the counts at zero.

Thanks,
Jack

pw-bot: cr

author
#15 lore raw

PATCH v12 5/6 net: wwan: t9xx: Add FSM thread

In reply to Jack Wu

The FSM (Finite-state Machine) thread is responsible for synchronizing the actions of different modules. The asynchronous events from the device or the OS will trigger a state transition.

The FSM thread will append it to the event queue when an event arrives. It handles the events sequentially. After processing the event, the FSM thread notifies other modules of the state transition.

Five FSM states are defined. They can transition from one state to another, and self-transition in some states.

Also wire the HS1/HS2/HS3 runtime feature handshake into the FSM: the host opens a control port on device readiness, sends HS1 with the supported feature set, parses the HS2 reply, and confirms with HS3. MD and SAP each run this sequence independently; the FSM advances to READY only after both complete (MD alone on an MD-only device). A transport init that fails leaves the control port that depends on it unopenable, so that handshake cannot complete. The device sends HS1 once per boot and does not retry a failed handshake; it starts again only after a modem reset, which removal performs. A modem that reboots on its own after READY is not
recovered: its new handshake is refused until the device is rebound.

The port manager follows the same transitions: it enables the handshaking side's control port on BOOTUP and disables every port on OFF.

CLDMA hardware bring-up and teardown are driven by FSM state transitions: mtk_cldma_dev_init() on FSM_STATE_BOOTUP allocates DMA pools, creates a workqueue and registers the MSI-X IRQ, and mtk_cldma_dev_exit() tears them down on FSM_STATE_OFF.

Registering that IRQ is what first makes the completion path built by the earlier patches run: mtk_cldma_isr() dispatches tx_done_work and rx_done_work, and queues err_work on a QUEUE_ERROR interrupt. err_work owns the recovery policy: on a TX error it stops the offending queue and completes every outstanding request with -EPIPE rather than retrying it; a queue whose stop times out keeps its requests and refuses new ones. An RX error is handed to rx_done_work instead, which is the only context that programs an RX queue, so a stop/restart pair cannot race the worker's own resume.

A queue that will not stop within the timeout is still a live DMA target, so its ring is deliberately leaked instead of being unmapped and freed. The DMA pools are destroyed
regardless: dma_pool_destroy() does not free the pages of a pool that still has blocks outstanding, so the leaked descriptors stay allocated and only the pool bookkeeping is released. The leak is bounded by the device instance and is reported with dev_err().

Teardown is ordered to match. mtk_pcie_hif_exit() first calls mtk_cldma_quiesce(), which silences each CLDMA instance's interrupt output, masks the vector, waits out an in-flight handler, drops the handler and drains the workqueue. A quiesced instance is never re-armed, and the trb service threads cannot queue CLDMA work through a recovery once it is, so nothing is queued again before the threads are joined and mtk_cldma_exit() frees what they dereference.
Joining the kthreads is not sufficient on its own, because the IRQ handler and the workqueue read trans->trb_srv[] too.

---
 drivers/net/wwan/t9xx/Makefile              |    1 +
 drivers/net/wwan/t9xx/mtk_ctrl_plane.c      |   47 ++
 drivers/net/wwan/t9xx/mtk_ctrl_plane.h      |    1 +
 drivers/net/wwan/t9xx/mtk_dev.h             |    1 +
 drivers/net/wwan/t9xx/mtk_fsm.c             | 1002 +++++++++++++++++++++++++++
 drivers/net/wwan/t9xx/mtk_fsm.h             |  130 ++++
 drivers/net/wwan/t9xx/mtk_port.c            |   58 +-
 drivers/net/wwan/t9xx/mtk_port.h            |    2 +
 drivers/net/wwan/t9xx/pcie/mtk_cldma.c      |  574 +++++++++++++--
 drivers/net/wwan/t9xx/pcie/mtk_cldma.h      |   10 +
 drivers/net/wwan/t9xx/pcie/mtk_cldma_drv.h  |   11 +-
 drivers/net/wwan/t9xx/pcie/mtk_pci.c        |   36 +-
 drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.c |   34 +-
 drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.h |    3 +
 14 files changed, 1859 insertions(+), 51 deletions(-)
drivers/net/wwan/t9xx/Makefile +1 -0
index d44266009362..fcfddf2e5147 100644
@@ -9,6 +9,7 @@ mtk_t9xx-y := \
 	mtk_ctrl_plane.o \
 	mtk_port.o \
 	mtk_port_io.o \
+	mtk_fsm.o \
 	pcie/mtk_pci.o \
 	pcie/mtk_trans_ctrl.o \
 	pcie/mtk_cldma.o \
drivers/net/wwan/t9xx/mtk_ctrl_plane.c +47 -0

66 lines not on this page · raw message

drivers/net/wwan/t9xx/mtk_ctrl_plane.h +1 -0
index 0c53712e9cbe..98969ce38d31 100644
@@ -10,6 +10,7 @@
 #include <linux/skbuff.h>
 
 #include "mtk_dev.h"
+#include "mtk_fsm.h"
 
 #define Q_MTU_3_5K	(0xE00)
 
drivers/net/wwan/t9xx/mtk_dev.h +1 -0
index ff3cbaa4329e..fe876a8edbe1 100644
@@ -37,6 +37,7 @@ struct mtk_md_dev {
 	u32 hw_ver;
 	char dev_str[MTK_DEV_STR_LEN];
 	struct mtk_ctrl_blk *ctrl_blk;
+	struct mtk_md_fsm *fsm;
 };
 
 #endif /* __MTK_DEV_H__ */
drivers/net/wwan/t9xx/mtk_fsm.c new file +1002 -0

1,002 lines not on this page · raw message

drivers/net/wwan/t9xx/mtk_fsm.h new file +130 -0

130 lines not on this page · raw message

drivers/net/wwan/t9xx/mtk_port.c +57 -1

77 lines not on this page · raw message

drivers/net/wwan/t9xx/mtk_port.h +2 -0
index 377323954f13..5246014f85cf 100644
@@ -122,6 +122,8 @@ int mtk_port_send_data(struct mtk_port *port, void *data, bool blocking, bool fo
 int mtk_port_status_update(struct mtk_md_dev *mdev, void *data, u32 data_len);
 int mtk_port_ch_enable(struct mtk_port *port);
 int mtk_port_ch_disable(struct mtk_port *port);
+void mtk_port_mngr_fsm_state_handler(struct mtk_fsm_param *fsm_param, void *arg);
+void mtk_port_mngr_fsm_state_handler_late(struct mtk_fsm_param *fsm_param, void *arg);
 int mtk_port_mngr_init(struct mtk_ctrl_blk *ctrl_blk, const struct mtk_port_cfg *port_cfg,
 		       int port_cnt);
 void mtk_port_mngr_exit(struct mtk_ctrl_blk *ctrl_blk);
drivers/net/wwan/t9xx/pcie/mtk_cldma.c +532 -42

822 lines not on this page · raw message

drivers/net/wwan/t9xx/pcie/mtk_cldma.h +10 -0
index 375b57f67218..f6d26b80589f 100644
@@ -16,6 +16,8 @@
 #include "mtk_ctrl_plane.h"
 #include "mtk_trans_ctrl.h"
 
+struct mtk_fsm_param;
+
 #define TXQ(N)					(N)
 #define RXQ(N)					(N)
 
@@ -101,6 +103,12 @@ struct txq {
 	u32 wr_idx;
 	u32 free_idx;
 	bool tx_started;
+	/* Set by err_work while it stops this queue, and left set if the
+	 * stop failed: the device may still be walking the ring, so new
+	 * requests are refused with -EPIPE and the ones already queued are
+	 * kept.  Read under ring_lock by the producer.
+	 */
+	bool is_stopping;
 };
 
 struct cldma_dev {
@@ -109,10 +117,12 @@ struct cldma_dev {
 };
 
 int mtk_cldma_init(struct mtk_ctrl_trans *trans);
+void mtk_cldma_quiesce(struct mtk_ctrl_trans *trans);
 void mtk_cldma_exit(struct mtk_ctrl_trans *trans);
 int mtk_cldma_submit_tx(void *dev, struct sk_buff *skb);
 int mtk_cldma_get_tx_budget(void *dev, enum mtk_hif_id hif_id, u32 qno);
 int mtk_cldma_trb_process(void *dev, struct sk_buff *skb);
+void mtk_cldma_fsm_state_listener(struct mtk_fsm_param *param, struct mtk_ctrl_trans *trans);
 int mtk_cldma_check_ch_cfg(void *dev, struct queue_info *que);
 
 #endif
drivers/net/wwan/t9xx/pcie/mtk_cldma_drv.h +10 -1
index f7b5018d3a73..b32301b0240a 100644
@@ -78,8 +78,17 @@ struct cldma_drv_info {
 	struct dma_pool *gpd_dma_pool;
 	struct workqueue_struct *wq;
 	const struct cldma_hw_regs *hw_regs;
+	struct work_struct err_work;
+	atomic_t tx_err_qs;
+	atomic_t rx_err_qs;
+	/* a ring could not be stopped and was leaked on free */
+	bool ring_leaked;
+	/* this instance's interrupt and workers have already been retired;
+	 * makes the quiesce safe to repeat on the teardown path
+	 */
+	bool quiesced;
 	/* serialises the instance reset and re-arm against queue kicks and
-	 * RX resume/restart: no queue is kicked while it has no address
+	 * RX resume/restart, and re-arming against setting quiesced
 	 */
 	struct mutex rearm_lock;
 };
drivers/net/wwan/t9xx/pcie/mtk_pci.c +34 -2
index 9d089a0fa1ec..ca45b5650fa9 100644
@@ -13,6 +13,7 @@
 #include <linux/module.h>
 
 #include "mtk_dev.h"
+#include "mtk_fsm.h"
 #include "mtk_trans_ctrl.h"
 #include "mtk_pci.h"
 #include "mtk_pci_reg.h"
@@ -854,18 +855,41 @@ static int mtk_pci_dev_init(struct mtk_md_dev *mdev)
 {
 	int ret;
 
-	ret = mtk_trans_ctrl_init(mdev);
+	ret = mtk_fsm_init(mdev);
 	if (ret) {
-		dev_err(mdev->dev, "Failed to initialize control plane: %d\n", ret);
+		dev_err(mdev->dev, "Failed to initialize FSM: %d\n", ret);
 		return ret;
 	}
 
+	ret = mtk_trans_ctrl_init(mdev);
+	if (ret)
+		goto free_fsm;
+
 	return 0;
+free_fsm:
+	mtk_fsm_exit(mdev);
+	return ret;
 }
 
 static void mtk_pci_dev_exit(struct mtk_md_dev *mdev)
 {
+	int ret;
+
+	ret = mtk_fsm_evt_submit(mdev, FSM_EVT_DEV_RM, 0, NULL,
+				 EVT_MODE_BLOCKING | EVT_MODE_TOHEAD);
+	if (ret < 0)
+		dev_err(mdev->dev, "FSM DEV_RM failed: %d, forcing cleanup\n", ret);
+	/* Close the event gate and stop the FSM thread before the transport
+	 * plane it drives is torn down.
+	 */
+	mtk_fsm_stop(mdev);
 	mtk_trans_ctrl_exit(mdev);
+	mtk_fsm_exit(mdev);
+}
+
+static int mtk_pci_dev_start(struct mtk_md_dev *mdev)
+{
+	return mtk_fsm_evt_submit(mdev, FSM_EVT_DEV_ADD, 0, NULL, 0);
 }
 
 static int mtk_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
@@ -942,8 +966,16 @@ static int mtk_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id)
 	pci_set_master(pdev);
 	mtk_pci_unmask_irq(mdev, priv->mhccif_irq_id);
 
+	ret = mtk_pci_dev_start(mdev);
+	if (ret) {
+		dev_err(mdev->dev, "Failed to start dev.\n");
+		goto clear_master;
+	}
+
 	return 0;
 
+clear_master:
+	pci_clear_master(pdev);
 dev_exit:
 	mtk_pci_dev_exit(mdev);
 free_irq:
drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.c +29 -5
index 61b2428beb83..334418f5b886 100644
@@ -477,19 +477,27 @@ int mtk_pcie_hif_exit(struct mtk_md_dev *mdev)
 
 	trans = ctrl_blk->ctrl_hw_priv;
 
+	/* Hold submit_lock across the whole teardown: late submitters either
+	 * see available and finish before the teardown starts, or block here
+	 * and then bail out on !available. Also makes this exit idempotent,
+	 * so both the FSM listener and device removal may call it.
+	 */
 	mutex_lock(&trans->submit_lock);
+	if (!trans->available) {
+		mutex_unlock(&trans->submit_lock);
+		return 0;
+	}
 	trans->available = false;
-	mutex_unlock(&trans->submit_lock);
-
+	/* The CLDMA interrupt and its workers read trans->trb_srv[] too, so
+	 * joining the service threads below does not cover them.
+	 */
+	mtk_cldma_quiesce(trans);
 	/* Join the service threads before freeing what they dereference: they
 	 * read trans->dev without a lock, so clearing it cannot stop a
 	 * consumer that has already loaded the pointer.
 	 */
 	mtk_ctrl_trb_srv_exit(trans);
 	mtk_cldma_exit(trans);
-
-	/* Late submitters may still hold the lock and walk the tree. */
-	mutex_lock(&trans->submit_lock);
 	mtk_ctrl_remove_queue_tbl(trans);
 	mutex_unlock(&trans->submit_lock);
 
@@ -570,6 +578,15 @@ int mtk_pcie_hif_submit_skb(struct mtk_md_dev *mdev, struct sk_buff *skb, bool f
 	return ret;
 }
 
+void mtk_pcie_hif_fsm_indication(struct mtk_md_dev *mdev, struct mtk_fsm_param *param)
+{
+	struct mtk_ctrl_blk *ctrl_blk = mdev->ctrl_blk;
+	struct mtk_ctrl_trans *trans;
+
+	trans = ctrl_blk->ctrl_hw_priv;
+	mtk_cldma_fsm_state_listener(param, trans);
+}
+
 int mtk_pcie_hif_cmd_func(struct mtk_md_dev *mdev, int cmd, void *data)
 {
 	struct mtk_ctrl_blk *ctrl_blk = mdev->ctrl_blk;
@@ -631,6 +648,13 @@ int mtk_trans_ctrl_init(struct mtk_md_dev *mdev)
 
 int mtk_trans_ctrl_exit(struct mtk_md_dev *mdev)
 {
+	/* FSM_STATE_OFF normally tears the HIF down. If that never ran, the
+	 * trb kthreads and the CLDMA irq callback would outlive the devm
+	 * allocations they point at, so do it here. mtk_pcie_hif_exit() is
+	 * idempotent under trans->submit_lock, so calling it again is safe.
+	 */
+	mtk_pcie_hif_exit(mdev);
+
 	mtk_ctrl_exit(mdev);
 
 	return 0;
drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.h +3 -0
index 41f6cffec6b5..bf237c1e6e60 100644
@@ -74,9 +74,12 @@ struct trb_srv {
 	struct task_struct *trb_thread;
 };
 
+struct mtk_fsm_param;
+
 int mtk_pcie_hif_init(struct mtk_md_dev *mdev);
 int mtk_pcie_hif_exit(struct mtk_md_dev *mdev);
 int mtk_pcie_hif_submit_skb(struct mtk_md_dev *mdev, struct sk_buff *skb, bool force_send);
+void mtk_pcie_hif_fsm_indication(struct mtk_md_dev *mdev, struct mtk_fsm_param *param);
 int mtk_pcie_hif_cmd_func(struct mtk_md_dev *mdev, int cmd, void *data);
 int mtk_trans_ctrl_init(struct mtk_md_dev *mdev);
 int mtk_trans_ctrl_exit(struct mtk_md_dev *mdev);
Signature · 1 line
2.34.1
#16 lore raw

Re: [PATCH net-next v12 5/6] net: wwan: t9xx: Add FSM thread

Thank you for your contribution! Sashiko AI review found 9 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 9 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 3 · Low: 6

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] If the modem reboots during the handshake, the FSM can report READY falsely.
- [Medium] mtk_cldma_rxq_restart() now calls mtk_cldma_stop_queue(DIR_RX) before every restart.
- [Medium] net: wwan: t9xx: mtk_cldma_start_xfer() returns -EIO on concurrent stop
- [Low] The subject "net: wwan: t9xx: Add FSM thread" understates the patch.
- [Low] When a TX or RX ring could not be stopped (drv_info->ring_leaked), mtk_cldma_dev_exit() still calls…
- [Low] The comment on the new field struct txq::is_stopping (mtk_cldma.h) says it is "Set by err_work while it stops this queue,…
- [Low] The comment on cldma_drv_info::quiesced (mtk_cldma_drv.h) says the instance's "interrupt and workers have already been retired".
- [Low] mtk_cldma_drv_quiesce() masks the CLDMA interrupt output by writing LINK_ERROR_VAL to reg_cldma_int_mask…
- [Low] mtk_fsm_feature_set_match() treats host-required features inconsistently.

--

net: wwan: t9xx: Add FSM thread

This commit adds an FSM kthread to the t9xx WWAN driver. The thread serialises device and OS events and notifies registered listeners of state transitions. It also wires the HS1/HS2/HS3 runtime feature handshake into the FSM, drives CLDMA instance init/exit from FSM states, registers the CLDMA IRQ, and adds ISR, error-recovery and quiesce logic.

Quoted 1 line

net: wwan: t9xx: Add FSM thread

[Severity: Low]
This isn't a bug, but the subject covers only part of what this patch does. Besides the FSM core, it adds:

- the HS1/HS2/HS3 handshake
- CLDMA dev_init/dev_exit driven by FSM states, including the IRQ registration
- the new mtk_cldma_isr(), mtk_cldma_err_work(), txq->is_stopping and mtk_cldma_drv_quiesce() recovery and teardown design

It also changes code from earlier patches in the series:

- mtk_cldma_rxq_restart() now stops the queue before every restart
- mtk_pcie_hif_exit() holds submit_lock across the whole teardown and returns early on !available
- mtk_trans_ctrl_exit() now calls mtk_pcie_hif_exit()
- mtk_cldma_txq_free() and mtk_cldma_rxq_free() reorder their masks and flushes

The commit message does describe most of this. Would splitting it make a regression in one part easier to bisect or revert on its own?

Quoted 6 lines
drivers/net/wwan/t9xx/mtk_fsm.c new file +0 -0
new file mode 100644
index 0000000000000..227dc31ed2773
@@ -0,0 +1,1002 @@

[ ... ]

Quoted 18 lines
drivers/net/wwan/t9xx/mtk_fsm.c new file +18 -0
+static int mtk_fsm_feature_set_match(enum runtime_feature_support_type *cur_ft_spt,
+				     struct runtime_feature_info rtft_info_st,
+				     struct runtime_feature_info rtft_info_cfg)
+{
+	int ret = 0;
+
+	switch (FIELD_GET(FEATURE_TYPE, rtft_info_st.feature)) {
+	case RTFT_TYPE_NOT_EXIST:
+		fallthrough;
+	case RTFT_TYPE_NOT_SUPPORT:
+		/* A feature the device refuses fails the handshake only if
+		 * the host requires it.
+		 */
+		if (FIELD_GET(FEATURE_TYPE, rtft_info_cfg.feature) == RTFT_TYPE_MUST_SUPPORT)
+			ret = -EPROTO;
+		else
+			*cur_ft_spt = RTFT_TYPE_NOT_EXIST;
+		break;

[ ... ]

drivers/net/wwan/t9xx/mtk_fsm.c line 156

Quoted 12 lines
drivers/net/wwan/t9xx/mtk_fsm.c new file +12 -0
+	case RTFT_TYPE_OPTIONAL_SUPPORT:
+		if (FIELD_GET(FEATURE_TYPE, rtft_info_cfg.feature) == RTFT_TYPE_NOT_EXIST ||
+		    FIELD_GET(FEATURE_TYPE, rtft_info_cfg.feature) == RTFT_TYPE_NOT_SUPPORT) {
+			*cur_ft_spt = RTFT_TYPE_NOT_SUPPORT;
+		} else {
+			if (FIELD_GET(FEATURE_VER, rtft_info_st.feature) ==
+			    FIELD_GET(FEATURE_VER, rtft_info_cfg.feature))
+				*cur_ft_spt = RTFT_TYPE_MUST_SUPPORT;
+			else
+				*cur_ft_spt = RTFT_TYPE_NOT_SUPPORT;
+		}
+		break;

[Severity: Low]
Should a host MUST_SUPPORT feature fail the handshake here too?

The host marks QUERY_RTFT_ID_MD_PORT_ENUM and QUERY_RTFT_ID_SAP_PORT_ENUM as RTFT_TYPE_MUST_SUPPORT, version 0. If the device answers NOT_EXIST/NOT_SUPPORT, the branch above returns -EPROTO.

If the device instead answers OPTIONAL_SUPPORT with a different FEATURE_VER, this sets NOT_SUPPORT and returns 0. Then mtk_fsm_parse_hs2_msg() skips the port enumeration:

	if (cur_ft_spt == RTFT_TYPE_MUST_SUPPORT && query_rtft_action[ft_id]) {

HS3 is sent and HS2_DONE is set. The FSM can then reach READY with no ports enumerated and no error logged.

[ ... ]

Quoted 2 lines
drivers/net/wwan/t9xx/mtk_fsm.c new file +2 -0
+static int mtk_fsm_startup_act(struct mtk_md_fsm *fsm, struct mtk_fsm_evt *event)
+{

[ ... ]

Quoted 10 lines
drivers/net/wwan/t9xx/mtk_fsm.c new file +10 -0
+	} else if (event->fsm_flag & FSM_HS2_DONE_MASK) {
+		if (fsm->fsm_flag & event->fsm_flag) {
+			dev_warn(mdev->dev, "Duplicate HS2 (hs%d), dropping\n", hs_info->id);
+			dev_kfree_skb(skb);
+			return 0;
+		}
+		ret = mtk_fsm_parse_hs2_msg(fsm, hs_info, skb);
+		if (!ret)
+			ret = mtk_fsm_send_hs3_msg(hs_info, skb);
+		dev_kfree_skb(skb);

drivers/net/wwan/t9xx/mtk_fsm.c line 537

Quoted 10 lines
drivers/net/wwan/t9xx/mtk_fsm.c new file +10 -0
+		if (ret)
+			goto hs_err;
+		mtk_fsm_switch_state(fsm, to_state, event);
+	}
+
+	hs_done_flag = READ_ONCE(fsm->hs_done_flag);
+	if (((fsm->fsm_flag | event->fsm_flag) & hs_done_flag) == hs_done_flag) {
+		to_state = FSM_STATE_READY;
+		mtk_fsm_switch_state(fsm, to_state, NULL);
+	}

[Severity: Medium]
Can mtk_cldma_start_xfer() return -EIO for a queue that err_work is already stopping? The first is_stopping check here is made under ring_lock, and ring_lock is then dropped while rearm_lock stays held. mtk_cldma_err_tx_one() sets is_stopping under ring_lock alone, without rearm_lock, so the write can land just after this check:

trb service thread err_work
mtk_cldma_start_xfer()
takes rearm_lock
reads is_stopping == false
mtk_cldma_err_tx_one()
sets is_stopping mtk_cldma_stop_queue()
tx start address reads 0 mtk_cldma_hw_recovery()
mtk_cldma_rearm_queues()
skips the start address
for this txq, is_stopping
start address still 0
returns -EIO
goto out, before the second
is_stopping check

mtk_cldma_tx() then gets -EIO rather than -EPIPE, so its early return for a stopping queue is bypassed. It goes on to call mtk_cldma_stop_queue() and mtk_cldma_txq_flush() on the same queue while err_work is stopping and flushing it.

The per-slot ring_lock keeps the two flushes from double-unmapping, but nothing orders the two stops. Suppose err_work's stop succeeds; it then flushes and clears is_stopping. If the stop in mtk_cldma_tx() times out after that, mtk_cldma_tx() sets is_stopping again. The queue then refuses every new request with -EPIPE until the channel is closed. Also, requests that the error path meant to complete with -EPIPE can instead be completed with -EIO by the other flush.

The window needs a zero start address read. That is the lost queue state case mtk_cldma_hw_recovery() exists to handle.

Should mtk_cldma_err_tx_one() set is_stopping under rearm_lock as well, so it cannot change while start_xfer holds that lock? Or should start_xfer re-check is_stopping under ring_lock before it turns a recovery failure into -EIO?

[Severity: Medium]
Can the FSM reach READY falsely if the modem reboots partway through the handshake? Nothing ever clears bits in fsm->fsm_flag.

Suppose MD has finished HS2/HS3 and SAP has not, and then the device reboots:

fsm->fsm_flag has MD_HS_START | MD_HS2_DONE, state is BOOTUP device reboots and goes back through its boot stages mtk_fsm_early_bootup_handler() sees a new IDLE dev_state

    mtk_fsm_idle_evt_handler() re-opens both HS channels:

	for (hs_id = 0; hs_id < HS_ID_MAX; hs_id++)
		mtk_fsm_unmask_ext_evt(fsm, fsm->hs_info[hs_id].mhccif_ch);

new MD HS1 is accepted in BOOTUP, and the host sends HS1 again new MD HS2 matches "fsm->fsm_flag & event->fsm_flag" and is dropped
as a duplicate, so no HS3 is sent
SAP completes; the stale MD_HS2_DONE bit satisfies hs_done_flag
and the FSM switches to READY

With later patches in the series, READY enables the MD ports even though the rebooted MD side never got HS3. The commit message only covers a reboot after READY.

Should a new HS1 for a side clear that side's done bits?

[ ... ]

Quoted 4 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma.c +0 -0
index c0bafb39e4f5a..aca2484c13681 100644

[ ... ]

Quoted 1 line
drivers/net/wwan/t9xx/pcie/mtk_cldma.c +0 -0
@@ -214,21 +376,37 @@ static bool mtk_cldma_rx_check_again(struct rxq *rxq)

[ ... ]

Quoted 6 lines

static bool mtk_cldma_rxq_restart(struct cldma_drv_info *drv_info, struct rxq *rxq) {

drivers/net/wwan/t9xx/pcie/mtk_cldma.c +3 -0
 	struct rx_req *req = rxq->req_pool + rxq->free_idx;
+	int ret;
+
+	ret = mtk_cldma_stop_queue(drv_info, DIR_RX, rxq->rxqno);

drivers/net/wwan/t9xx/pcie/mtk_cldma.c static bool mtk_cldma_rx_check_again(struct rxq *rxq) · line 401

Quoted 10 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma.c +10 -0
+	if (ret) {
+		/* Do not restart it; QUEUE_ERROR stays masked: TRB_CMD_DISABLE
+		 * tears the queue down and has the leak-the-ring handling for
+		 * a stop that timed out.
+		 */
+		dev_err(drv_info->mdev->dev,
+			"RX queue %u stop failed (%d), not restarting it\n",
+			rxq->rxqno, ret);
+		return true;
+	}

[Severity: Medium]
What brings this RX queue back after the stop fails? The caller in mtk_cldma_rx_done_work() has already consumed need_restart:

	if (atomic_xchg(&rxq->need_restart, 0)) {
		if (!mtk_cldma_rxq_restart(drv_info, rxq)) {

Returning true means the restart is never retried. On the error path, the ISR left QUEUE_ERROR masked, and rx_done_work only unmasks QUEUE_XFER_DONE on exit. RX also has no equivalent of txq->is_stopping to record the state.

If the stop completes late, the queue ends up stopped. No XFER_DONE arrives to run the worker again, so the RX channel stays dead while the port still looks open.

If the hardware ignores the stop, the queue keeps running with its error interrupt masked.

The comment points to TRB_CMD_DISABLE, but nothing issues one in this case. The reset-recovery path in mtk_cldma_rearm_queues() also goes through this function.

[ ... ]

Quoted 13 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma.c +9 -0
@@ -792,9 +1024,110 @@ static int mtk_cldma_hw_recovery(struct cldma_drv_info *drv_info, u32 qno)
 	return 0;
 }
 
+/* Silence the IP's interrupt output as well as the vector: a handler already
+ * past the mask unmasks it again on its way out.  Repeated calls are no-ops,
+ * so the teardown path can run it again without unregistering twice.
+ */
+static void mtk_cldma_drv_quiesce(struct cldma_drv_info *drv_info)
+{
+	struct mtk_md_dev *mdev = drv_info->mdev;
+
+	mutex_lock(&drv_info->rearm_lock);

drivers/net/wwan/t9xx/pcie/mtk_cldma.c static int mtk_cldma_hw_recovery(struct cldma_drv_info *drv_info, u32 qno) · line 1045

Quoted 10 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma.c +10 -0
+	if (drv_info->quiesced) {
+		mutex_unlock(&drv_info->rearm_lock);
+		return;
+	}
+	/* also read by the RX worker: no refill retry outlives the drain */
+	WRITE_ONCE(drv_info->quiesced, true);
+	mutex_unlock(&drv_info->rearm_lock);
+
+	mtk_pci_write32(mdev, drv_info->base_addr + drv_info->hw_regs->reg_cldma_int_mask,
+			LINK_ERROR_VAL);

[Severity: Low]
This isn't a bug, but LINK_ERROR_VAL is otherwise used only as the all-ones read-back value for a dead link. See mtk_cldma_check_intr_status(), mtk_cldma_stop_queue() and mtk_cldma_tx_done_work().

mtk_cldma_drv_init() writes 0 to the same register to enable it. Would a dedicated "mask all" constant be clearer here?

[ ... ]

Quoted 2 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma.c +2 -0
+static int mtk_cldma_dev_exit(struct cldma_dev *cd, int hif_id)
+{

[ ... ]

drivers/net/wwan/t9xx/pcie/mtk_cldma.c static int mtk_cldma_hw_recovery(struct cldma_drv_info *drv_info, u32 qno) · line 1120

Quoted 7 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma.c +7 -0
+	if (drv_info->ring_leaked)
+		dev_err(mdev->dev, "CLDMA%d rings leaked\n", drv_info->hw_id);
+	/* The leaked rings keep the pool busy: it keeps its pages and only its
+	 * bookkeeping is freed.  Not destroying it would leak the same pages
+	 * and the pool.
+	 */
+	dma_pool_destroy(drv_info->gpd_dma_pool);

[Severity: Low]
Is it safe to rely on this? The kernel-doc for dma_pool_destroy() in mm/dmapool.c says:

Caller guarantees that no more memory from the pool is in use, and that nothing will try to use the pool after this call.

When ring_leaked is set, descriptors from this pool are still allocated and may still be a live DMA target. They survive only because of the current pool->nr_active busy branch. That branch prints "busy", skips dma_free_coherent(), and frees only the bookkeeping.

Every bind cycle where a stop times out also leaks more coherent pages that nothing tracks.

[ ... ]

Quoted 4 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma.h +0 -0
index 375b57f672188..f6d26b80589f5 100644

[ ... ]

drivers/net/wwan/t9xx/pcie/mtk_cldma.h struct txq { · line 112

Quoted 11 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma.h +6 -0
@@ -101,6 +103,12 @@ struct txq {
 	u32 wr_idx;
 	u32 free_idx;
 	bool tx_started;
+	/* Set by err_work while it stops this queue, and left set if the
+	 * stop failed: the device may still be walking the ring, so new
+	 * requests are refused with -EPIPE and the ones already queued are
+	 * kept.  Read under ring_lock by the producer.
+	 */
+	bool is_stopping;
 };

[Severity: Low]
This isn't a bug, but err_work is not the only writer. mtk_cldma_tx() sets it from the trb service thread when mtk_cldma_start_xfer() fails and the follow-up stop also fails:

	spin_lock(&txq->ring_lock);
	txq->is_stopping = true;
	spin_unlock(&txq->ring_lock);

mtk_cldma_err_tx_one() then clears it unconditionally after its own stop and flush succeed, whoever set it. mtk_cldma_rearm_queues() and mtk_cldma_start_xfer() also read it.

Could the comment describe both writers?

[ ... ]

Quoted 5 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma_drv.h +0 -0
index f7b5018d3a737..b32301b0240ad 100644
@@ -78,8 +78,17 @@ struct cldma_drv_info {

[ ... ]

drivers/net/wwan/t9xx/pcie/mtk_cldma_drv.h struct cldma_drv_info { · line 89

Quoted 4 lines
drivers/net/wwan/t9xx/pcie/mtk_cldma_drv.h +4 -0
+	/* this instance's interrupt and workers have already been retired;
+	 * makes the quiesce safe to repeat on the teardown path
+	 */
+	bool quiesced;

[Severity: Low]
This isn't a bug, but mtk_cldma_drv_quiesce() sets quiesced before any retirement step runs. It sets the flag under rearm_lock, and only then:

- writes int_mask
- masks the vector
- calls synchronize_irq()
- unregisters the handler
- calls drain_workqueue()

mtk_cldma_rx_done_work() and mtk_cldma_rearm_queues() read the flag while that is still in progress. So the flag really means retirement has started and no more work should be queued.

Could the comment say that instead of "already been retired"?

[ ... ]

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261117-t9xx_driver_v1-v12-0-e181b616b820%40compal.com
#17 lore raw

Re: [PATCH net-next v12 5/6] net: wwan: t9xx: Add FSM thread

Thanks for the review.

Quoted 18 lines

This isn't a bug, but the subject covers only part of what this patch does. Besides the FSM core, it adds:

- the HS1/HS2/HS3 handshake
- CLDMA dev_init/dev_exit driven by FSM states, including the IRQ registration
- the new mtk_cldma_isr(), mtk_cldma_err_work(), txq->is_stopping and mtk_cldma_drv_quiesce() recovery and teardown design

It also changes code from earlier patches in the series:

- mtk_cldma_rxq_restart() now stops the queue before every restart
- mtk_pcie_hif_exit() holds submit_lock across the whole teardown and returns early on !available
- mtk_trans_ctrl_exit() now calls mtk_pcie_hif_exit()
- mtk_cldma_txq_free() and mtk_cldma_rxq_free() reorder their masks and flushes

Quoted 2 lines

The commit message does describe most of this. Would splitting it make a regression in one part easier to bisect or revert on its own?

No change. The CLDMA interrupt, error recovery and teardown are reachable only once the FSM listener added here registers the interrupt, so moving them earlier adds unreachable code and moving them later leaves this patch bringing CLDMA up without interrupt handling. The commit message describes each part, as you note.

Quoted 6 lines

Should a host MUST_SUPPORT feature fail the handshake here too?

The host marks QUERY_RTFT_ID_MD_PORT_ENUM and QUERY_RTFT_ID_SAP_PORT_ENUM as RTFT_TYPE_MUST_SUPPORT, version 0. If the device answers NOT_EXIST/NOT_SUPPORT, the branch above returns -EPROTO.

Quoted 8 lines

If the device instead answers OPTIONAL_SUPPORT with a different FEATURE_VER, this sets NOT_SUPPORT and returns 0. Then mtk_fsm_parse_hs2_msg() skips the port enumeration:

        if (cur_ft_spt == RTFT_TYPE_MUST_SUPPORT && query_rtft_action[ft_id]) {

HS3 is sent and HS2_DONE is set. The FSM can then reach READY with no ports enumerated and no error logged.

Will fix in v13: an OPTIONAL_SUPPORT reply whose version does not match fails the handshake with -EPROTO when the host marked the feature MUST_SUPPORT, like a NOT_EXIST or NOT_SUPPORT reply does.

Quoted 36 lines

Can mtk_cldma_start_xfer() return -EIO for a queue that err_work is already stopping? The first is_stopping check here is made under ring_lock, and ring_lock is then dropped while rearm_lock stays held. mtk_cldma_err_tx_one() sets is_stopping under ring_lock alone, without rearm_lock, so the write can land just after this check:

trb service thread err_work
mtk_cldma_start_xfer()
takes rearm_lock
reads is_stopping == false
mtk_cldma_err_tx_one()
sets is_stopping mtk_cldma_stop_queue()
tx start address reads 0 mtk_cldma_hw_recovery()
mtk_cldma_rearm_queues()
skips the start address
for this txq, is_stopping
start address still 0
returns -EIO
goto out, before the second
is_stopping check

mtk_cldma_tx() then gets -EIO rather than -EPIPE, so its early return for a stopping queue is bypassed. It goes on to call mtk_cldma_stop_queue() and mtk_cldma_txq_flush() on the same queue while err_work is stopping and flushing it.

The per-slot ring_lock keeps the two flushes from double-unmapping, but nothing orders the two stops. Suppose err_work's stop succeeds; it then flushes and clears is_stopping. If the stop in mtk_cldma_tx() times out after that, mtk_cldma_tx() sets is_stopping again. The queue then refuses every new request with -EPIPE until the channel is closed. Also, requests that the error path meant to complete with -EPIPE can instead be completed with -EIO by the other flush.

Quoted 7 lines

The window needs a zero start address read. That is the lost queue state case mtk_cldma_hw_recovery() exists to handle.

Should mtk_cldma_err_tx_one() set is_stopping under rearm_lock as well, so it cannot change while start_xfer holds that lock? Or should start_xfer re-check is_stopping under ring_lock before it turns a recovery failure into -EIO?

Will fix in v13, as you suggest: mtk_cldma_err_tx_one() sets is_stopping under rearm_lock as well, so the flag cannot change between the check in mtk_cldma_start_xfer() and its kick. The second check there then cannot trigger any more and is removed.

The race costs an error code and a stuck queue, not a DMA problem: the two flushes claim each request once under ring_lock, and each side unmaps only after its own stop succeeded.

Quoted 20 lines

Can the FSM reach READY falsely if the modem reboots partway through the handshake? Nothing ever clears bits in fsm->fsm_flag.

Suppose MD has finished HS2/HS3 and SAP has not, and then the device reboots:

fsm->fsm_flag has MD_HS_START | MD_HS2_DONE, state is BOOTUP device reboots and goes back through its boot stages mtk_fsm_early_bootup_handler() sees a new IDLE dev_state

    mtk_fsm_idle_evt_handler() re-opens both HS channels:

        for (hs_id = 0; hs_id < HS_ID_MAX; hs_id++)
                mtk_fsm_unmask_ext_evt(fsm, fsm->hs_info[hs_id].mhccif_ch);

new MD HS1 is accepted in BOOTUP, and the host sends HS1 again new MD HS2 matches "fsm->fsm_flag & event->fsm_flag" and is dropped
as a duplicate, so no HS3 is sent
SAP completes; the stale MD_HS2_DONE bit satisfies hs_done_flag
and the FSM switches to READY

Quoted 5 lines

With later patches in the series, READY enables the MD ports even though the rebooted MD side never got HS3. The commit message only covers a reboot after READY.

Should a new HS1 for a side clear that side's done bits?

Will fix in v13, as you suggest: an HS1 from a side clears that side's HS2-done bit before the handshake is restarted, so the new HS2 is parsed and answered with HS3 instead of being dropped as a duplicate, and READY waits for it. An HS2 repeated without a new HS1 is still dropped.

Quoted 15 lines

What brings this RX queue back after the stop fails? The caller in mtk_cldma_rx_done_work() has already consumed need_restart:

        if (atomic_xchg(&rxq->need_restart, 0)) {
                if (!mtk_cldma_rxq_restart(drv_info, rxq)) {

Returning true means the restart is never retried. On the error path, the ISR left QUEUE_ERROR masked, and rx_done_work only unmasks QUEUE_XFER_DONE on exit. RX also has no equivalent of txq->is_stopping to record the state.

If the stop completes late, the queue ends up stopped. No XFER_DONE arrives to run the worker again, so the RX channel stays dead while the port still looks open.

Quoted 6 lines

If the hardware ignores the stop, the queue keeps running with its error interrupt masked.

The comment points to TRB_CMD_DISABLE, but nothing issues one in this case. The reset-recovery path in mtk_cldma_rearm_queues() also goes through this function.

No functional change; v13 rewords the comment and adds a sentence to the commit message.

When the stop times out the engine may still be walking the ring, so it is given no new start address and its error interrupt is not re-armed. Nothing restarts that queue by itself: it is recovered when the channel is closed, where a stop that still times out resets the instance. The TX side behaves the same way after a failed stop. The comment named TRB_CMD_DISABLE as if something issued it at that point, which it does not.

Quoted 6 lines

This isn't a bug, but LINK_ERROR_VAL is otherwise used only as the all-ones read-back value for a dead link. See mtk_cldma_check_intr_status(), mtk_cldma_stop_queue() and mtk_cldma_tx_done_work().

mtk_cldma_drv_init() writes 0 to the same register to enable it. Would a dedicated "mask all" constant be clearer here?

Will fix in v13: the write uses a dedicated mask-all constant instead of LINK_ERROR_VAL.

Quoted 6 lines

Is it safe to rely on this? The kernel-doc for dma_pool_destroy() in mm/dmapool.c says:

Caller guarantees that no more memory from the pool is in use, and that nothing will try to use the pool after this call.

Quoted 7 lines

When ring_leaked is set, descriptors from this pool are still allocated and may still be a live DMA target. They survive only because of the current pool->nr_active busy branch. That branch prints "busy", skips dma_free_coherent(), and frees only the bookkeeping.

Every bind cycle where a stop times out also leaks more coherent pages that nothing tracks.

No change. Skipping dma_pool_destroy() would leak the same pages plus the pool object and its sysfs entry. The descriptors cannot be returned while the device may still be using them, so the pages are left to the pool's busy handling on purpose. This only happens after a queue failed to stop, and it is reported.

Quoted 8 lines

This isn't a bug, but err_work is not the only writer. mtk_cldma_tx() sets it from the trb service thread when mtk_cldma_start_xfer() fails and the follow-up stop also fails:

        spin_lock(&txq->ring_lock);
        txq->is_stopping = true;
        spin_unlock(&txq->ring_lock);
Quoted 5 lines

mtk_cldma_err_tx_one() then clears it unconditionally after its own stop and flush succeed, whoever set it. mtk_cldma_rearm_queues() and mtk_cldma_start_xfer() also read it.

Could the comment describe both writers?

Will fix in v13: the comment will describe both cases in which the flag is set, while a queue error is being handled and after any stop of the queue failed, and say that it is protected by ring_lock.

Quoted 9 lines

This isn't a bug, but mtk_cldma_drv_quiesce() sets quiesced before any retirement step runs. It sets the flag under rearm_lock, and only then:

- writes int_mask
- masks the vector
- calls synchronize_irq()
- unregisters the handler
- calls drain_workqueue()

Quoted 5 lines

mtk_cldma_rx_done_work() and mtk_cldma_rearm_queues() read the flag while that is still in progress. So the flag really means retirement has started and no more work should be queued.

Could the comment say that instead of "already been retired"?

Will fix in v13: the comment will say that the flag marks that the quiesce has started, so that no more work is queued for the instance and a repeated quiesce returns early.

Thanks,
Jack

pw-bot: cr

author
#18 lore raw

PATCH v12 6/6 net: wwan: t9xx: Add AT & MBIM WWAN ports

In reply to Jack Wu

Add AT & MBIM ports to the port infrastructure.

mtk_port_wwan_init() only prepares the port object; wwan_create_port() is called from mtk_port_wwan_enable(). enable() runs on FSM_STATE_READY through the new mtk_port_enable_by_type(PORT_TBL_MD) hook, which enables every MD-table port the device marked enabled, internal ports included. CCCI_UART2 and CCCI_MBIM get CLDMA1 TXQ(5)/RXQ(5) and TXQ(2)/RXQ(2) in mtk_queue_info[].

The implemented WWAN port operations are start, stop, tx and tx_blocking. The tx path copies with skb_copy_bits(), handling the non-linear skb the WWAN core supplies for writes larger than one fragment. One write() is capped at MTK_PORT_MAX_TX_PKT CCCI packets (SKB_LIST_MAX_LEN, the HIF queue depth) and anything larger is rejected with -EMSGSIZE: every packet after the first is submitted with force_send, which bypasses the depth check, so without a cap a single write could queue an unbounded number of skbs. The same cap bounds the second copy of the message the tx path holds and the number of times skb_copy_bits() re-walks the source fragment chain.

The first packet of every write() is depth checked. A blocking write waits on the port's trb wait queue for the HIF queue to drop below its depth before it submits anything, rather than bypassing the check, so blocking writers whose waits are cut short by signals cannot grow the queue either. Like the t7xx .tx path, this wait sleeps interruptibly under the WWAN core's ops_lock, with no timeout. A blocking write then also waits, the same way, for each of its packets to complete, so that it returns the modem's TX status.

start() publishes the wwan_port under w_priv.w_lock together with PORT_S_OPEN, so the receive path can never see an open port with a NULL wwan_port and drop the reply to a command that open made possible.

TX back-pressure is reported through wwan_port_txon()/txoff() rather than a .tx_poll operation: a queue-full submit failure pauses the port and a per-port tx_complete hook resumes it from TRB completion, so poll() sleeps on the WWAN core's own waitqueue - whose lifetime is pinned by the open file - instead of a driver waitqueue that wwan_remove_port() can outlive. The pause path drops w_lock before querying the HIF for queue occupancy, because HIF teardown holds trans->submit_lock while the TRB completions it flushes call back into the port under w_lock.

---
 drivers/net/wwan/t9xx/mtk_ctrl_plane.h      |   4 +
 drivers/net/wwan/t9xx/mtk_port.c            |  22 ++
 drivers/net/wwan/t9xx/mtk_port.h            |  21 +-
 drivers/net/wwan/t9xx/mtk_port_io.c         | 424 ++++++++++++++++++++++++++++
 drivers/net/wwan/t9xx/mtk_port_io.h         |   5 +
 drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.c |   8 +
 6 files changed, 482 insertions(+), 2 deletions(-)
drivers/net/wwan/t9xx/mtk_ctrl_plane.h +4 -0
index 98969ce38d31..a64d4de97ae2 100644
@@ -21,6 +21,10 @@ enum mtk_ccci_ch {
 	/* to MD */
 	CCCI_CONTROL_RX = 0x2000,
 	CCCI_CONTROL_TX = 0x2001,
+	CCCI_UART2_RX = 0x200A,
+	CCCI_UART2_TX = 0x200C,
+	CCCI_MBIM_RX = 0x20D0,
+	CCCI_MBIM_TX = 0x20D1,
 };
 
 enum mtk_trb_cmd_type {
drivers/net/wwan/t9xx/mtk_port.c +22 -0
index 649b1458a58b..1436b872dc32 100644
@@ -267,6 +267,10 @@ static int mtk_port_tx_complete(struct sk_buff *skb)
 				     "Failed to send data: status:%d, port:%s\n",
 				     trb->status, port->info.name);
 
+	/* Locking rule: see struct mtk_port_ops. */
+	if (mtk_port_get_ops(port->info.type)->tx_complete)
+		mtk_port_get_ops(port->info.type)->tx_complete(port);
+
 	return mtk_port_ch_trb_complete(skb);
 }
 
@@ -612,6 +616,21 @@ int mtk_port_ch_disable(struct mtk_port *port)
 	return ret;
 }
 
+static void mtk_port_enable_by_type(struct mtk_port_mngr *port_mngr, int tbl_type)
+{
+	struct mtk_port *port;
+	unsigned long index;
+
+	/* READY is reached at most once per bind and FSM_STATE_OFF is
+	 * terminal, so port->enable never carries over from an earlier port
+	 * enumeration.
+	 */
+	xa_for_each(&port_mngr->port_tbl[tbl_type], index, port) {
+		if (port->enable)
+			mtk_port_get_ops(port->info.type)->enable(port);
+	}
+}
+
 void mtk_port_mngr_fsm_state_handler(struct mtk_fsm_param *fsm_param, void *arg)
 {
 	struct mtk_port_mngr *port_mngr;
@@ -625,6 +644,9 @@ void mtk_port_mngr_fsm_state_handler(struct mtk_fsm_param *fsm_param, void *arg)
 	case FSM_STATE_OFF:
 		mtk_port_disable(port_mngr);
 		break;
+	case FSM_STATE_READY:
+		mtk_port_enable_by_type(port_mngr, PORT_TBL_MD);
+		break;
 	default:
 		break;
 	}
drivers/net/wwan/t9xx/mtk_port.h +19 -2
index 5246014f85cf..4075cf69a787 100644
@@ -10,6 +10,7 @@
 #include <linux/device.h>
 #include <linux/skbuff.h>
 #include <linux/types.h>
+#include <linux/wwan.h>
 #include <linux/xarray.h>
 
 #include "mtk_ctrl_plane.h"
@@ -35,8 +36,10 @@
 #define MTK_INFO_FLD_EN		((u16)BIT(15))
 #define MTK_INFO_FLD_CHID	GENMASK(14, 0)
 
-/* State bits, not locks: callers serialise ->enable(), ->disable() and
- * open of a port.  The atomic bitops only make a repeated call a no-op.
+/* State bits, not locks: callers serialise ->enable(), ->disable() and the
+ * open of an internal port.  A WWAN open comes from userspace: its node
+ * exists only after ->enable(), and w_priv.w_lock orders it against
+ * ->disable().  The atomic bitops only make a repeated call a no-op.
  */
 enum mtk_port_status {
 	PORT_S_ENABLE,
@@ -58,6 +61,7 @@ enum mtk_port_tbl {
 
 enum mtk_port_type {
 	PORT_TYPE_INTERNAL,
+	PORT_TYPE_WWAN,
 	PORT_TYPE_MAX
 };
 
@@ -66,6 +70,18 @@ struct mtk_internal_port {
 	int (*recv_cb)(void *arg, struct sk_buff *skb);
 };
 
+struct mtk_wwan_port {
+	/* w_lock serialises w_port and PORT_S_OPEN against the receive path,
+	 * and txoff/txon against TX completion.  It is a leaf: the receive
+	 * path and TX completion can both take it with trans->submit_lock
+	 * held, during HIF teardown, so it is never held across a call into
+	 * the HIF.
+	 */
+	struct mutex w_lock;
+	enum wwan_port_type w_type;
+	struct wwan_port *w_port;
+};
+
 struct mtk_port_cfg {
 	enum mtk_ccci_ch tx_ch;
 	enum mtk_ccci_ch rx_ch;
@@ -90,6 +106,7 @@ struct mtk_port {
 	wait_queue_head_t trb_wq;
 	struct mtk_port_mngr *port_mngr;
 	struct mtk_internal_port i_priv;
+	struct mtk_wwan_port w_priv;
 };
 
 struct mtk_port_mngr {
drivers/net/wwan/t9xx/mtk_port_io.c +424 -0

446 lines not on this page · raw message

drivers/net/wwan/t9xx/mtk_port_io.h +5 -0
index db1d9ae52d9a..3e3acf93411c 100644
@@ -17,7 +17,12 @@ struct mtk_port_ops {
 	void (*exit)(struct mtk_port *port);
 	void (*enable)(struct mtk_port *port);
 	void (*disable)(struct mtk_port *port);
+	/* recv and tx_complete may sleep, but also run from HIF teardown with
+	 * trans->submit_lock held: they must not take a lock that is ever held
+	 * across a call into the HIF.
+	 */
 	int (*recv)(struct mtk_port *port, struct sk_buff *skb);
+	void (*tx_complete)(struct mtk_port *port);
 };
 
 const struct mtk_port_ops *mtk_port_get_ops(enum mtk_port_type type);
drivers/net/wwan/t9xx/pcie/mtk_trans_ctrl.c +8 -0
index 334418f5b886..d773af12bcb7 100644
@@ -21,6 +21,10 @@
 
 /* the number of RX GPDs should be at least two */
 static const struct queue_info mtk_queue_info[] = {
+	{CCCI_UART2_TX, CCCI_UART2_RX, CLDMA1, TXQ(5), RXQ(5),
+	 Q_MTU_3_5K, Q_MTU_3_5K, TX_GPD_NUM, RX_GPD_NUM, 0},
+	{CCCI_MBIM_TX, CCCI_MBIM_RX, CLDMA1, TXQ(2), RXQ(2),
+	 Q_MTU_3_5K, Q_MTU_3_5K, TX_GPD_NUM, RX_GPD_NUM, 0},
 	{CCCI_CONTROL_TX, CCCI_CONTROL_RX, CLDMA1, TXQ(0), RXQ(0),
 	 Q_MTU_3_5K, Q_MTU_3_5K, TX_GPD_NUM, RX_GPD_NUM, 0},
 	{CCCI_SAP_CONTROL_TX, CCCI_SAP_CONTROL_RX, CLDMA0, TXQ(0), RXQ(0),
@@ -28,6 +32,10 @@ static const struct queue_info mtk_queue_info[] = {
 };
 
 static const struct mtk_port_cfg mtk_port_cfg_tbl[] = {
+	{CCCI_UART2_TX, CCCI_UART2_RX, PORT_TYPE_WWAN, "AT",
+		PORT_F_DFLT},
+	{CCCI_MBIM_TX, CCCI_MBIM_RX, PORT_TYPE_WWAN, "MBIM",
+		PORT_F_DFLT},
 	{CCCI_CONTROL_TX, CCCI_CONTROL_RX, PORT_TYPE_INTERNAL, "MDCTRL",
 		PORT_F_DFLT},
 	{CCCI_SAP_CONTROL_TX, CCCI_SAP_CONTROL_RX, PORT_TYPE_INTERNAL, "SAPCTRL",
Signature · 1 line
2.34.1