2023-10-17 20:04:44

by Wesley Cheng

[permalink] [raw]
Subject: [PATCH v9 00/34] Introduce QC USB SND audio offloading support

Several Qualcomm based chipsets can support USB audio offloading to a
dedicated audio DSP, which can take over issuing transfers to the USB
host controller. The intention is to reduce the load on the main
processors in the SoC, and allow them to be placed into lower power modes.
There are several parts to this design:
1. Adding ASoC binding layer
2. Create a USB backend for Q6DSP
3. Introduce XHCI interrupter support
4. Create vendor ops for the USB SND driver

USB | ASoC
--------------------------------------------------------------------
| _________________________
| |sm8250 platform card |
| |_________________________|
| | |
| ___V____ ____V____
| |Q6USB | |Q6AFE |
| |"codec" | |"cpu" |
| |________| |_________|
| ^ ^ ^
| | |________|
| ___V____ |
| |SOC-USB | |
________ ________ | | |
|USB SND |<--->|QC offld|<------------>|________| |
|(card.c)| | |<---------- |
|________| |________|___ | | |
^ ^ | | | ____________V_________
| | | | | |APR/GLINK |
__ V_______________V_____ | | | |______________________|
|USB SND (endpoint.c) | | | | ^
|_________________________| | | | |
^ | | | ___________V___________
| | | |->|audio DSP |
___________V_____________ | | |_______________________|
|XHCI HCD |<- |
|_________________________| |


Adding ASoC binding layer:
soc-usb: Intention is to treat a USB port similar to a headphone jack.
The port is always present on the device, but cable/pin status can be
enabled/disabled. Expose mechanisms for USB backend ASoC drivers to
communicate with USB SND.

Create a USB backend for Q6DSP:
q6usb: Basic backend driver that will be responsible for maintaining the
resources needed to initiate a playback stream using the Q6DSP. Will
be the entity that checks to make sure the connected USB audio device
supports the requested PCM format. If it does not, the PCM open call will
fail, and userpsace ALSA can take action accordingly.

Introduce XHCI interrupter support:
XHCI HCD supports multiple interrupters, which allows for events to be routed
to different event rings. This is determined by "Interrupter Target" field
specified in Section "6.4.1.1 Normal TRB" of the XHCI specification.

Events in the offloading case will be routed to an event ring that is assigned
to the audio DSP.

Create vendor ops for the USB SND driver:
qc_audio_offload: This particular driver has several components associated
with it:
- QMI stream request handler
- XHCI interrupter and resource management
- audio DSP memory management

When the audio DSP wants to enable a playback stream, the request is first
received by the ASoC platform sound card. Depending on the selected route,
ASoC will bring up the individual DAIs in the path. The Q6USB backend DAI
will send an AFE port start command (with enabling the USB playback path), and
the audio DSP will handle the request accordingly.

Part of the AFE USB port start handling will have an exchange of control
messages using the QMI protocol. The qc_audio_offload driver will populate the
buffer information:
- Event ring base address
- EP transfer ring base address

and pass it along to the audio DSP. All endpoint management will now be handed
over to the DSP, and the main processor is not involved in transfers.

Overall, implementing this feature will still expose separate sound card and PCM
devices for both the platorm card and USB audio device:
0 [SM8250MTPWCD938]: sm8250 - SM8250-MTP-WCD9380-WSA8810-VA-D
SM8250-MTP-WCD9380-WSA8810-VA-DMIC
1 [Audio ]: USB-Audio - USB Audio
Generic USB Audio at usb-xhci-hcd.1.auto-1.4, high speed

This is to ensure that userspace ALSA entities can decide which route to take
when executing the audio playback. In the above, if card#1 is selected, then
USB audio data will take the legacy path over the USB PCM drivers, etc...

This feature was validated using:
- tinymix: set/enable the multimedia path to route to USB backend
- tinyplay: issue playback on platform card

Changelog
--------------------------------------------
Changes in v9:
- Fixed the dt binding check issue with regards to num-hc-interrupters.

Changes in v8:
- Cleaned up snd_soc_usb_find_priv_data() based on Mark's feedback. Removed some of
the duplicate looping code that was present on previous patches. Also renamed the API.
- Integrated Mathias' suggestions on his new sideband changes:
https://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git/log/?h=feature_interrupters
- Addressed some of Mathias' fixme tags, such as:
- Resetting transfer ring dequeue/enqueue pointers
- Issuing stop endpoint command during ep removal
- Reset ERDP properly to first segment ring during interrupter removal. (this is currently
just being cleared to 0, but should be pointing to a valid segment if controller is still
running.

Changes in v7:
- Fixed dt check error for q6usb bindings
- Updated q6usb property from qcom,usb-audio-intr-num --> qcom,usb-audio-intr-idx
- Removed separate DWC3 HC interrupters num property, and place limits to XHCI one.
- Modified xhci_ring_to_sgtable() to use assigned IOVA/DMA address to fetch pages, as
it is not ensured event ring allocated is always done in the vmalloc range.

Changes in v6:
- Fixed limits and description on several DT bindings (XHCI and Q6USB)
- Fixed patch subjects to follow other ALSA/ASoC notations.

USB SND
- Addressed devices which expose multiple audio (UAC) interfaces. These devices will
create a single USB sound card with multiple audio streams, and receive multiple
interface probe routines. QC offload was not properly considering cases with multiple
probe calls.
- Renamed offload module name and kconfig to fit within the SND domain.
- Renamed attach/detach endpoint API to keep the hw_params notation.

Changes in v5:
- Removed some unnescessary files that were included
- Fixed some typos mentioned
- Addressed dt-binding issues and added hc-interrupters definition to usb-xhci.yaml

XHCI:
- Moved secondary skip events API to xhci-ring and updated implementation
- Utilized existing XHCI APIs, such as inc_deq and xhci_update_erst_dequeue()

USB SND
- Renamed and reworked the APIs in "sound: usb: Export USB SND APIs for modules" patch to
include suggestions to utilize snd_usb_hw_params/free and to avoid generic naming.
- Added a resume_cb() op for completion sake.
- Addressed some locking concerns with regards to when registering for platform hooks.
- Added routine to disconnect all offloaded devices during module unbind.

ASoC
- Replaced individual PCM parameter arguments in snd_soc_usb_connect() with new
snd_soc_usb_device structure to pass along PCM info.
- Modified snd_jack set report to notify HEADPHONE event, as we do not support record path.

Changes in v4:
- Rebased to xhci/for-usb-next
- Addressed some dt-bindings comments

XHCI:
- Pulled in latest changes from Mathias' feature_interrupters branch:
https://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git/log/?h=feature_interrupters

- Fixed commit text and signage for the XHCI sideband/interrupter related changes
- Added some logic to address the FIXME tags mentioned throughout the commits, such
as handling multi segment rings and building the SGT, locking concerns, and ep
cleanup operations.
- Removed some fixme tags for conditions that may not be needed/addressed.
- Repurposed the new endpoint stop sync API to be utilized in other places.
- Fixed potential compile issue if XHCI sideband config is not defined.

ASoC:
- Added sound jack control into the Q6USB driver. Allows for userpsace to know when
an offload capable device is connected.

USB SND:
- Avoided exporting _snd_pcm_hw_param_set based on Takashi's recommendation.
- Split USB QMI packet header definitions into a separate commit. This is used to
properly allow the QMI interface driver to parse and route QMI packets accordingly
- Added a "depends on" entry when enabling QC audio offload to avoid compile time
issues.

Changes in v3:
- Changed prefix from RFC to PATCH
- Rebased entire series to usb-next
- Updated copyright years

XHCI:
- Rebased changes on top of XHCI changes merged into usb-next, and only added
changes that were still under discussion.
- Added change to read in the "num-hc-interrupters" device property.

ASoC:
- qusb6 USB backend
- Incorporated suggestions to fetch iommu information with existing APIs
- Added two new sound kcontrols to fetch offload status and offload device
selection.
- offload status - will return the card and pcm device in use
tinymix -D 0 get 1 --> 1, 0 (offload in progress on card#1 pcm#0)

- device selection - set the card and pcm device to enable offload on. Ex.:
tinymix -D 0 set 1 2 0 --> sets offload on card#2 pcm#0
(this should be the USB card)

USB SND:
- Fixed up some locking related concerns for registering platform ops.
- Moved callbacks under the register_mutex, so that
- Modified APIs to properly pass more information about the USB SND device, so
that the Q6USB backend can build a device list/map, in order to monitor offload
status and device selection.

Changes in v2:

XHCI:
- Replaced XHCI and HCD changes with Mathias' XHCI interrupter changes
in his tree:
https://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git/log/?h=feature_interrupters

Adjustments made to Mathias' changes:
- Created xhci-intr.h to export/expose interrupter APIs versus exposing xhci.h.
Moved dependent structures to this file as well. (so clients can parse out
information from "struct xhci_interrupter")
- Added some basic locking when requesting interrupters.
- Fixed up some sanity checks.
- Removed clearing of the ERSTBA during freeing of the interrupter. (pending
issue where SMMU fault occurs if DMA addr returned is 64b - TODO)

- Clean up pending events in the XHCI secondary interrupter. While testing USB
bus suspend, it was seen that on bus resume, the xHCI HC would run into a command
timeout.
- Added offloading APIs to xHCI to fetch transfer and event ring information.

ASoC:
- Modified soc-usb to allow for multiple USB port additions. For this to work,
the USB offload driver has to have a reference to the USB backend by adding
a "usb-soc-be" DT entry to the device saved into XHCI sysdev.
- Created separate dt-bindings for defining USB_RX port.
- Increased APR timeout to accommodate the situation where the AFE port start
command could be delayed due to having to issue a USB bus resume while
handling the QMI stream start command.

USB SND:
- Added a platform ops during usb_audio_suspend(). This allows for the USB
offload driver to halt the audio stream when system enters PM suspend. This
ensures the audio DSP is not issuing transfers on the USB bus.
- Do not override platform ops if they are already populated.
- Introduce a shared status variable between the USB offload and USB SND layers,
to ensure that only one path is active at a time. If the USB bus is occupied,
then userspace is notified that the path is busy.

Mathias Nyman (4):
xhci: split free interrupter into separate remove and free parts
xhci: add support to allocate several interrupters
xhci: add helper to stop endpoint and wait for completion
xhci: sideband: add initial api to register a sideband entity

Wesley Cheng (30):
usb: host: xhci-mem: Cleanup pending secondary event ring events
usb: host: xhci-mem: Allow for interrupter clients to choose specific
index
ASoC: Add SOC USB APIs for adding an USB backend
ASoC: dt-bindings: qcom,q6dsp-lpass-ports: Add USB_RX port
ASoC: qcom: qdsp6: Introduce USB AFE port to q6dsp
ASoC: qdsp6: q6afe: Increase APR timeout
ASoC: qcom: qdsp6: Add USB backend ASoC driver for Q6
ALSA: usb-audio: Introduce USB SND platform op callbacks
ALSA: usb-audio: Export USB SND APIs for modules
dt-bindings: usb: xhci: Add num-hc-interrupters definition
dt-bindings: usb: dwc3: Limit num-hc-interrupters definition
usb: dwc3: Specify maximum number of XHCI interrupters
usb: host: xhci-plat: Set XHCI max interrupters if property is present
ALSA: usb-audio: qcom: Add USB QMI definitions
ALSA: usb-audio: qcom: Introduce QC USB SND offloading support
ALSA: usb-audio: Check for support for requested audio format
ASoC: usb: Add PCM format check API for USB backend
ASoC: qcom: qdsp6: Ensure PCM format is supported by USB audio device
ALSA: usb-audio: Prevent starting of audio stream if in use
ASoC: dt-bindings: Add Q6USB backend
ASoC: dt-bindings: Update example for enabling USB offload on SM8250
ASoC: qcom: qdsp6: q6afe: Split USB AFE dev_token param into separate
API
ALSA: usb-audio: qcom: Populate PCM and USB chip information
ASoC: qcom: qdsp6: Add support to track available USB PCM devices
ASoC: qcom: qdsp6: Add SND kcontrol to select offload device
ASoC: qcom: qdsp6: Add SND kcontrol for fetching offload status
ASoC: qcom: qdsp6: Add headphone jack for offload connection status
ALSA: usb-audio: qcom: Use card and PCM index from QMI request
ALSA: usb-audio: Allow for rediscovery of connected USB SND devices
ASoC: usb: Rediscover USB SND devices on USB port add

.../devicetree/bindings/sound/qcom,q6usb.yaml | 55 +
.../bindings/sound/qcom,sm8250.yaml | 15 +
.../devicetree/bindings/usb/snps,dwc3.yaml | 4 +
.../devicetree/bindings/usb/usb-xhci.yaml | 6 +
drivers/usb/dwc3/core.c | 12 +
drivers/usb/dwc3/core.h | 2 +
drivers/usb/dwc3/host.c | 5 +-
drivers/usb/host/Kconfig | 9 +
drivers/usb/host/Makefile | 4 +
drivers/usb/host/xhci-debugfs.c | 2 +-
drivers/usb/host/xhci-mem.c | 136 +-
drivers/usb/host/xhci-plat.c | 2 +
drivers/usb/host/xhci-ring.c | 53 +-
drivers/usb/host/xhci-sideband.c | 372 ++++
drivers/usb/host/xhci.c | 114 +-
drivers/usb/host/xhci.h | 18 +-
.../sound/qcom,q6dsp-lpass-ports.h | 1 +
include/linux/usb/xhci-sideband.h | 67 +
include/sound/q6usboffload.h | 20 +
include/sound/soc-usb.h | 51 +
sound/soc/Makefile | 2 +-
sound/soc/qcom/Kconfig | 4 +
sound/soc/qcom/qdsp6/Makefile | 1 +
sound/soc/qcom/qdsp6/q6afe-dai.c | 56 +
sound/soc/qcom/qdsp6/q6afe.c | 206 +-
sound/soc/qcom/qdsp6/q6afe.h | 36 +-
sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c | 23 +
sound/soc/qcom/qdsp6/q6dsp-lpass-ports.h | 1 +
sound/soc/qcom/qdsp6/q6routing.c | 9 +
sound/soc/qcom/qdsp6/q6usb.c | 450 ++++
sound/soc/soc-usb.c | 201 ++
sound/usb/Kconfig | 15 +
sound/usb/Makefile | 2 +-
sound/usb/card.c | 123 ++
sound/usb/card.h | 23 +
sound/usb/endpoint.c | 1 +
sound/usb/helper.c | 1 +
sound/usb/pcm.c | 94 +-
sound/usb/pcm.h | 11 +
sound/usb/qcom/Makefile | 2 +
sound/usb/qcom/qc_audio_offload.c | 1867 +++++++++++++++++
sound/usb/qcom/usb_audio_qmi_v01.c | 892 ++++++++
sound/usb/qcom/usb_audio_qmi_v01.h | 162 ++
43 files changed, 5041 insertions(+), 89 deletions(-)
create mode 100644 Documentation/devicetree/bindings/sound/qcom,q6usb.yaml
create mode 100644 drivers/usb/host/xhci-sideband.c
create mode 100644 include/linux/usb/xhci-sideband.h
create mode 100644 include/sound/q6usboffload.h
create mode 100644 include/sound/soc-usb.h
create mode 100644 sound/soc/qcom/qdsp6/q6usb.c
create mode 100644 sound/soc/soc-usb.c
create mode 100644 sound/usb/qcom/Makefile
create mode 100644 sound/usb/qcom/qc_audio_offload.c
create mode 100644 sound/usb/qcom/usb_audio_qmi_v01.c
create mode 100644 sound/usb/qcom/usb_audio_qmi_v01.h


2023-10-17 20:04:50

by Wesley Cheng

[permalink] [raw]
Subject: [PATCH v9 34/34] ASoC: usb: Rediscover USB SND devices on USB port add

In case the USB backend device has not been initialized/probed, USB SND
device connections can still occur. When the USB backend is eventually
made available, previous USB SND device connections are not communicated to
the USB backend. Call snd_usb_rediscover_devices() to generate the connect
callbacks for all USB SND devices connected. This will allow for the USB
backend to be updated with the current set of devices available.

The chip array entries are all populated and removed while under the
register_mutex, so going over potential race conditions:

Thread#1:
q6usb_component_probe()
--> snd_soc_usb_add_port()
--> snd_usb_rediscover_devices()
--> mutex_lock(register_mutex)

Thread#2
--> usb_audio_disconnect()
--> mutex_lock(register_mutex)

So either thread#1 or thread#2 will complete first. If

Thread#1 completes before thread#2:
SOC USB will notify DPCM backend of the device connection. Shortly
after, once thread#2 runs, we will get a disconnect event for the
connected device.

Thread#2 completes before thread#1:
Then during snd_usb_rediscover_devices() it won't notify of any
connection for that particular chip index.

Signed-off-by: Wesley Cheng <[email protected]>
---
sound/soc/soc-usb.c | 2 ++
1 file changed, 2 insertions(+)

diff --git a/sound/soc/soc-usb.c b/sound/soc/soc-usb.c
index 7407678a993e..60aafbe87c36 100644
--- a/sound/soc/soc-usb.c
+++ b/sound/soc/soc-usb.c
@@ -104,6 +104,8 @@ struct snd_soc_usb *snd_soc_usb_add_port(struct device *dev, void *priv,
list_add_tail(&usb->list, &usb_ctx_list);
mutex_unlock(&ctx_mutex);

+ snd_usb_rediscover_devices();
+
return usb;
}
EXPORT_SYMBOL_GPL(snd_soc_usb_add_port);

2023-10-17 20:04:50

by Wesley Cheng

[permalink] [raw]
Subject: [PATCH v9 20/34] ALSA: usb-audio: Check for support for requested audio format

Allow for checks on a specific USB audio device to see if a requested PCM
format is supported. This is needed for support for when playback is
initiated by the ASoC USB backend path.

Signed-off-by: Wesley Cheng <[email protected]>
---
sound/usb/card.c | 40 ++++++++++++++++++++++++++++++++++++++++
sound/usb/card.h | 11 +++++++++++
2 files changed, 51 insertions(+)

diff --git a/sound/usb/card.c b/sound/usb/card.c
index c0b312e264bf..88f431917c15 100644
--- a/sound/usb/card.c
+++ b/sound/usb/card.c
@@ -162,6 +162,46 @@ int snd_usb_unregister_platform_ops(void)
}
EXPORT_SYMBOL_GPL(snd_usb_unregister_platform_ops);

+/*
+ * Checks to see if requested audio profile, i.e sample rate, # of
+ * channels, etc... is supported by the substream associated to the
+ * USB audio device.
+ */
+struct snd_usb_stream *snd_usb_find_suppported_substream(int card_idx,
+ struct snd_pcm_hw_params *params, int direction)
+{
+ struct snd_usb_audio *chip;
+ struct snd_usb_substream *subs = NULL;
+ struct snd_usb_stream *as;
+ const struct audioformat *fmt;
+
+ /*
+ * Register mutex is held when populating and clearing usb_chip
+ * array.
+ */
+ mutex_lock(&register_mutex);
+ chip = usb_chip[card_idx];
+ if (!chip) {
+ mutex_unlock(&register_mutex);
+ return NULL;
+ }
+
+ if (enable[card_idx]) {
+ list_for_each_entry(as, &chip->pcm_list, list) {
+ subs = &as->substream[direction];
+ fmt = snd_usb_find_substream_format(subs, params);
+ if (fmt) {
+ mutex_unlock(&register_mutex);
+ return as;
+ }
+ }
+ }
+ mutex_unlock(&register_mutex);
+
+ return NULL;
+}
+EXPORT_SYMBOL_GPL(snd_usb_find_suppported_substream);
+
/*
* disconnect streams
* called from usb_audio_disconnect()
diff --git a/sound/usb/card.h b/sound/usb/card.h
index 2884912adc96..e26292363cf0 100644
--- a/sound/usb/card.h
+++ b/sound/usb/card.h
@@ -216,4 +216,15 @@ struct snd_usb_platform_ops {

int snd_usb_register_platform_ops(struct snd_usb_platform_ops *ops);
int snd_usb_unregister_platform_ops(void);
+
+#if IS_ENABLED(CONFIG_SND_USB_AUDIO)
+struct snd_usb_stream *snd_usb_find_suppported_substream(int card_idx,
+ struct snd_pcm_hw_params *params, int direction);
+#else
+static struct snd_usb_stream *snd_usb_find_suppported_substream(int card_idx,
+ struct snd_pcm_hw_params *params, int direction)
+{
+ return NULL;
+}
+#endif /* IS_ENABLED(CONFIG_SND_USB_AUDIO) */
#endif /* __USBAUDIO_CARD_H */

2023-10-17 20:04:50

by Wesley Cheng

[permalink] [raw]
Subject: [PATCH v9 19/34] ALSA: usb-audio: qcom: Introduce QC USB SND offloading support

Several Qualcomm SoCs have a dedicated audio DSP, which has the ability to
support USB sound devices. This vendor driver will implement the required
handshaking with the DSP, in order to pass along required resources that
will be utilized by the DSP's USB SW. The communication channel used for
this handshaking will be using the QMI protocol. Required resources
include:
- Allocated secondary event ring address
- EP transfer ring address
- Interrupter number

The above information will allow for the audio DSP to execute USB transfers
over the USB bus. It will also be able to support devices that have an
implicit feedback and sync endpoint as well. Offloading these data
transfers will allow the main/applications processor to enter lower CPU
power modes, and sustain a longer duration in those modes.

Audio offloading is initiated with the following sequence:
1. Userspace configures to route audio playback to USB backend and starts
playback on the platform soundcard.
2. The Q6DSP AFE will communicate to the audio DSP to start the USB AFE
port.
3. This results in a QMI packet with a STREAM enable command.
4. The QC audio offload driver will fetch the required resources, and pass
this information as part of the QMI response to the STREAM enable command.
5. Once the QMI response is received the audio DSP will start queuing data
on the USB bus.

Signed-off-by: Wesley Cheng <[email protected]>
---
include/sound/soc-usb.h | 2 +-
sound/usb/Kconfig | 15 +
sound/usb/Makefile | 2 +-
sound/usb/qcom/Makefile | 2 +
sound/usb/qcom/qc_audio_offload.c | 1843 +++++++++++++++++++++++++++++
5 files changed, 1862 insertions(+), 2 deletions(-)
create mode 100644 sound/usb/qcom/Makefile
create mode 100644 sound/usb/qcom/qc_audio_offload.c

diff --git a/include/sound/soc-usb.h b/include/sound/soc-usb.h
index 1fa671924018..58c686f4f7ba 100644
--- a/include/sound/soc-usb.h
+++ b/include/sound/soc-usb.h
@@ -39,7 +39,7 @@ struct snd_soc_usb {

int snd_soc_usb_connect(struct device *usbdev, struct snd_soc_usb_device *sdev);
int snd_soc_usb_disconnect(struct device *usbdev, struct snd_soc_usb_device *sdev);
-void *snd_soc_usb_get_priv_data(struct device *usbdev);
+void *snd_soc_usb_find_priv_data(struct device *usbdev);

struct snd_soc_usb *snd_soc_usb_add_port(struct device *dev, void *priv,
int (*connection_cb)(struct snd_soc_usb *usb,
diff --git a/sound/usb/Kconfig b/sound/usb/Kconfig
index 4a9569a3a39a..4c842fbe6365 100644
--- a/sound/usb/Kconfig
+++ b/sound/usb/Kconfig
@@ -176,6 +176,21 @@ config SND_BCD2000
To compile this driver as a module, choose M here: the module
will be called snd-bcd2000.

+config SND_USB_AUDIO_QMI
+ tristate "Qualcomm Audio Offload driver"
+ depends on QCOM_QMI_HELPERS && SND_USB_AUDIO && USB_XHCI_SIDEBAND
+ select SND_PCM
+ help
+ Say Y here to enable the Qualcomm USB audio offloading feature.
+
+ This module sets up the required QMI stream enable/disable
+ responses to requests generated by the audio DSP. It passes the
+ USB transfer resource references, so that the audio DSP can issue
+ USB transfers to the host controller.
+
+ To compile this driver as a module, choose M here: the module
+ will be called snd-usb-audio-qmi.
+
source "sound/usb/line6/Kconfig"

endif # SND_USB
diff --git a/sound/usb/Makefile b/sound/usb/Makefile
index db5ff76d0e61..fa624a4052ae 100644
--- a/sound/usb/Makefile
+++ b/sound/usb/Makefile
@@ -34,5 +34,5 @@ obj-$(CONFIG_SND_USB_UA101) += snd-usbmidi-lib.o
obj-$(CONFIG_SND_USB_USX2Y) += snd-usbmidi-lib.o
obj-$(CONFIG_SND_USB_US122L) += snd-usbmidi-lib.o

-obj-$(CONFIG_SND) += misc/ usx2y/ caiaq/ 6fire/ hiface/ bcd2000/
+obj-$(CONFIG_SND) += misc/ usx2y/ caiaq/ 6fire/ hiface/ bcd2000/ qcom/
obj-$(CONFIG_SND_USB_LINE6) += line6/
diff --git a/sound/usb/qcom/Makefile b/sound/usb/qcom/Makefile
new file mode 100644
index 000000000000..a81c9b28d484
--- /dev/null
+++ b/sound/usb/qcom/Makefile
@@ -0,0 +1,2 @@
+snd-usb-audio-qmi-objs := usb_audio_qmi_v01.o qc_audio_offload.o
+obj-$(CONFIG_SND_USB_AUDIO_QMI) += snd-usb-audio-qmi.o
\ No newline at end of file
diff --git a/sound/usb/qcom/qc_audio_offload.c b/sound/usb/qcom/qc_audio_offload.c
new file mode 100644
index 000000000000..320ce3a6688f
--- /dev/null
+++ b/sound/usb/qcom/qc_audio_offload.c
@@ -0,0 +1,1843 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (c) 2022-2023 Qualcomm Innovation Center, Inc. All rights reserved.
+ */
+
+#include <linux/ctype.h>
+#include <linux/moduleparam.h>
+#include <linux/module.h>
+#include <linux/usb.h>
+#include <linux/init.h>
+#include <linux/usb/hcd.h>
+#include <linux/usb/xhci-sideband.h>
+#include <linux/usb/quirks.h>
+#include <linux/usb/audio.h>
+#include <linux/usb/audio-v2.h>
+#include <linux/usb/audio-v3.h>
+#include <linux/soc/qcom/qmi.h>
+#include <linux/iommu.h>
+#include <linux/dma-mapping.h>
+#include <linux/dma-map-ops.h>
+#include <sound/q6usboffload.h>
+
+#include <sound/control.h>
+#include <sound/core.h>
+#include <sound/info.h>
+#include <sound/pcm.h>
+#include <sound/pcm_params.h>
+#include <sound/initval.h>
+
+#include <sound/soc.h>
+#include <sound/soc-usb.h>
+#include "../usbaudio.h"
+#include "../card.h"
+#include "../endpoint.h"
+#include "../helper.h"
+#include "../pcm.h"
+#include "../format.h"
+#include "../power.h"
+#include "usb_audio_qmi_v01.h"
+
+/* Stream disable request timeout during USB device disconnect */
+#define DEV_RELEASE_WAIT_TIMEOUT 10000 /* in ms */
+
+/* Data interval calculation parameters */
+#define BUS_INTERVAL_FULL_SPEED 1000 /* in us */
+#define BUS_INTERVAL_HIGHSPEED_AND_ABOVE 125 /* in us */
+#define MAX_BINTERVAL_ISOC_EP 16
+
+#define QMI_STREAM_REQ_CARD_NUM_MASK 0xffff0000
+#define QMI_STREAM_REQ_DEV_NUM_MASK 0xff00
+#define QMI_STREAM_REQ_DIRECTION 0xff
+
+/* iommu resource parameters and management */
+#define PREPEND_SID_TO_IOVA(iova, sid) ((u64)(((u64)(iova)) | \
+ (((u64)sid) << 32)))
+#define IOVA_BASE 0x1000
+#define IOVA_XFER_RING_BASE (IOVA_BASE + PAGE_SIZE * (SNDRV_CARDS + 1))
+#define IOVA_XFER_BUF_BASE (IOVA_XFER_RING_BASE + PAGE_SIZE * SNDRV_CARDS * 32)
+#define IOVA_XFER_RING_MAX (IOVA_XFER_BUF_BASE - PAGE_SIZE)
+#define IOVA_XFER_BUF_MAX (0xfffff000 - PAGE_SIZE)
+
+#define MAX_XFER_BUFF_LEN (24 * PAGE_SIZE)
+
+struct iova_info {
+ struct list_head list;
+ unsigned long start_iova;
+ size_t size;
+ bool in_use;
+};
+
+struct intf_info {
+ unsigned long data_xfer_ring_va;
+ size_t data_xfer_ring_size;
+ unsigned long sync_xfer_ring_va;
+ size_t sync_xfer_ring_size;
+ unsigned long xfer_buf_va;
+ size_t xfer_buf_size;
+ phys_addr_t xfer_buf_pa;
+ unsigned int data_ep_pipe;
+ unsigned int sync_ep_pipe;
+ u8 *xfer_buf;
+ u8 intf_num;
+ u8 pcm_card_num;
+ u8 pcm_dev_num;
+ u8 direction;
+ bool in_use;
+};
+
+struct uaudio_qmi_dev {
+ struct device *dev;
+ u32 sid;
+ u32 intr_num;
+ struct xhci_ring *sec_ring;
+ struct iommu_domain *domain;
+
+ /* list to keep track of available iova */
+ struct list_head xfer_ring_list;
+ size_t xfer_ring_iova_size;
+ unsigned long curr_xfer_ring_iova;
+ struct list_head xfer_buf_list;
+ size_t xfer_buf_iova_size;
+ unsigned long curr_xfer_buf_iova;
+
+ /* bit fields representing pcm card enabled */
+ unsigned long card_slot;
+ /* indicate event ring mapped or not */
+ bool er_mapped;
+ /* reference count to number of possible consumers */
+ atomic_t qdev_in_use;
+ /* idx to last udev card number plugged in */
+ unsigned int last_card_num;
+};
+
+struct uaudio_dev {
+ struct usb_device *udev;
+ /* audio control interface */
+ struct usb_host_interface *ctrl_intf;
+ unsigned int usb_core_id;
+ atomic_t in_use;
+ struct kref kref;
+ wait_queue_head_t disconnect_wq;
+
+ /* interface specific */
+ int num_intf;
+ struct intf_info *info;
+ struct snd_usb_audio *chip;
+
+ /* xhci sideband */
+ struct xhci_sideband *sb;
+
+ /* SoC USB device */
+ struct snd_soc_usb_device *sdev;
+};
+
+static struct uaudio_dev uadev[SNDRV_CARDS];
+static struct uaudio_qmi_dev *uaudio_qdev;
+static struct uaudio_qmi_svc *uaudio_svc;
+static DEFINE_MUTEX(qdev_mutex);
+
+struct uaudio_qmi_svc {
+ struct qmi_handle *uaudio_svc_hdl;
+ struct work_struct qmi_disconnect_work;
+ struct workqueue_struct *uaudio_wq;
+ struct sockaddr_qrtr client_sq;
+ bool client_connected;
+};
+
+enum mem_type {
+ MEM_EVENT_RING,
+ MEM_XFER_RING,
+ MEM_XFER_BUF,
+};
+
+/* Supported audio formats */
+enum usb_qmi_audio_format {
+ USB_QMI_PCM_FORMAT_S8 = 0,
+ USB_QMI_PCM_FORMAT_U8,
+ USB_QMI_PCM_FORMAT_S16_LE,
+ USB_QMI_PCM_FORMAT_S16_BE,
+ USB_QMI_PCM_FORMAT_U16_LE,
+ USB_QMI_PCM_FORMAT_U16_BE,
+ USB_QMI_PCM_FORMAT_S24_LE,
+ USB_QMI_PCM_FORMAT_S24_BE,
+ USB_QMI_PCM_FORMAT_U24_LE,
+ USB_QMI_PCM_FORMAT_U24_BE,
+ USB_QMI_PCM_FORMAT_S24_3LE,
+ USB_QMI_PCM_FORMAT_S24_3BE,
+ USB_QMI_PCM_FORMAT_U24_3LE,
+ USB_QMI_PCM_FORMAT_U24_3BE,
+ USB_QMI_PCM_FORMAT_S32_LE,
+ USB_QMI_PCM_FORMAT_S32_BE,
+ USB_QMI_PCM_FORMAT_U32_LE,
+ USB_QMI_PCM_FORMAT_U32_BE,
+};
+
+static enum usb_qmi_audio_device_speed_enum_v01
+get_speed_info(enum usb_device_speed udev_speed)
+{
+ switch (udev_speed) {
+ case USB_SPEED_LOW:
+ return USB_QMI_DEVICE_SPEED_LOW_V01;
+ case USB_SPEED_FULL:
+ return USB_QMI_DEVICE_SPEED_FULL_V01;
+ case USB_SPEED_HIGH:
+ return USB_QMI_DEVICE_SPEED_HIGH_V01;
+ case USB_SPEED_SUPER:
+ return USB_QMI_DEVICE_SPEED_SUPER_V01;
+ case USB_SPEED_SUPER_PLUS:
+ return USB_QMI_DEVICE_SPEED_SUPER_PLUS_V01;
+ default:
+ return USB_QMI_DEVICE_SPEED_INVALID_V01;
+ }
+}
+
+static struct snd_usb_substream *find_substream(unsigned int card_num,
+ unsigned int pcm_idx, unsigned int direction)
+{
+ struct snd_usb_stream *as;
+ struct snd_usb_substream *subs = NULL;
+ struct snd_usb_audio *chip;
+
+ chip = uadev[card_num].chip;
+ if (!chip || atomic_read(&chip->shutdown))
+ goto done;
+
+ if (pcm_idx >= chip->pcm_devs)
+ goto done;
+
+ if (direction > SNDRV_PCM_STREAM_CAPTURE)
+ goto done;
+
+ list_for_each_entry(as, &chip->pcm_list, list) {
+ if (as->pcm_index == pcm_idx) {
+ subs = &as->substream[direction];
+ goto done;
+ }
+ }
+
+done:
+ return subs;
+}
+
+static int info_idx_from_ifnum(int card_num, int intf_num, bool enable)
+{
+ int i;
+
+ /*
+ * default index 0 is used when info is allocated upon
+ * first enable audio stream req for a pcm device
+ */
+ if (enable && !uadev[card_num].info)
+ return 0;
+
+ for (i = 0; i < uadev[card_num].num_intf; i++) {
+ if (enable && !uadev[card_num].info[i].in_use)
+ return i;
+ else if (!enable &&
+ uadev[card_num].info[i].intf_num == intf_num)
+ return i;
+ }
+
+ return -EINVAL;
+}
+
+static int get_data_interval_from_si(struct snd_usb_substream *subs,
+ u32 service_interval)
+{
+ unsigned int bus_intval, bus_intval_mult, binterval;
+
+ if (subs->dev->speed >= USB_SPEED_HIGH)
+ bus_intval = BUS_INTERVAL_HIGHSPEED_AND_ABOVE;
+ else
+ bus_intval = BUS_INTERVAL_FULL_SPEED;
+
+ if (service_interval % bus_intval)
+ return -EINVAL;
+
+ bus_intval_mult = service_interval / bus_intval;
+ binterval = ffs(bus_intval_mult);
+ if (!binterval || binterval > MAX_BINTERVAL_ISOC_EP)
+ return -EINVAL;
+
+ /* check if another bit is set then bail out */
+ bus_intval_mult = bus_intval_mult >> binterval;
+ if (bus_intval_mult)
+ return -EINVAL;
+
+ return (binterval - 1);
+}
+
+/* maps audio format received over QMI to asound.h based pcm format */
+static snd_pcm_format_t map_pcm_format(enum usb_qmi_audio_format fmt_received)
+{
+ switch (fmt_received) {
+ case USB_QMI_PCM_FORMAT_S8:
+ return SNDRV_PCM_FORMAT_S8;
+ case USB_QMI_PCM_FORMAT_U8:
+ return SNDRV_PCM_FORMAT_U8;
+ case USB_QMI_PCM_FORMAT_S16_LE:
+ return SNDRV_PCM_FORMAT_S16_LE;
+ case USB_QMI_PCM_FORMAT_S16_BE:
+ return SNDRV_PCM_FORMAT_S16_BE;
+ case USB_QMI_PCM_FORMAT_U16_LE:
+ return SNDRV_PCM_FORMAT_U16_LE;
+ case USB_QMI_PCM_FORMAT_U16_BE:
+ return SNDRV_PCM_FORMAT_U16_BE;
+ case USB_QMI_PCM_FORMAT_S24_LE:
+ return SNDRV_PCM_FORMAT_S24_LE;
+ case USB_QMI_PCM_FORMAT_S24_BE:
+ return SNDRV_PCM_FORMAT_S24_BE;
+ case USB_QMI_PCM_FORMAT_U24_LE:
+ return SNDRV_PCM_FORMAT_U24_LE;
+ case USB_QMI_PCM_FORMAT_U24_BE:
+ return SNDRV_PCM_FORMAT_U24_BE;
+ case USB_QMI_PCM_FORMAT_S24_3LE:
+ return SNDRV_PCM_FORMAT_S24_3LE;
+ case USB_QMI_PCM_FORMAT_S24_3BE:
+ return SNDRV_PCM_FORMAT_S24_3BE;
+ case USB_QMI_PCM_FORMAT_U24_3LE:
+ return SNDRV_PCM_FORMAT_U24_3LE;
+ case USB_QMI_PCM_FORMAT_U24_3BE:
+ return SNDRV_PCM_FORMAT_U24_3BE;
+ case USB_QMI_PCM_FORMAT_S32_LE:
+ return SNDRV_PCM_FORMAT_S32_LE;
+ case USB_QMI_PCM_FORMAT_S32_BE:
+ return SNDRV_PCM_FORMAT_S32_BE;
+ case USB_QMI_PCM_FORMAT_U32_LE:
+ return SNDRV_PCM_FORMAT_U32_LE;
+ case USB_QMI_PCM_FORMAT_U32_BE:
+ return SNDRV_PCM_FORMAT_U32_BE;
+ default:
+ /*
+ * We expect the caller to do input validation so we should
+ * never hit this. But we do have to return a proper
+ * snd_pcm_format_t value due to the __bitwise attribute; so
+ * just return the equivalent of 0 in case of bad input.
+ */
+ return SNDRV_PCM_FORMAT_S8;
+ }
+}
+
+/* Offloading IOMMU management */
+static unsigned long uaudio_get_iova(unsigned long *curr_iova,
+ size_t *curr_iova_size, struct list_head *head, size_t size)
+{
+ struct iova_info *info, *new_info = NULL;
+ struct list_head *curr_head;
+ unsigned long va = 0;
+ size_t tmp_size = size;
+ bool found = false;
+
+ if (size % PAGE_SIZE) {
+ dev_dbg(uaudio_qdev->dev, "size %zu is not page size multiple\n",
+ size);
+ goto done;
+ }
+
+ if (size > *curr_iova_size) {
+ dev_dbg(uaudio_qdev->dev, "size %zu > curr size %zu\n",
+ size, *curr_iova_size);
+ goto done;
+ }
+ if (*curr_iova_size == 0) {
+ dev_dbg(uaudio_qdev->dev, "iova mapping is full\n");
+ goto done;
+ }
+
+ list_for_each_entry(info, head, list) {
+ /* exact size iova_info */
+ if (!info->in_use && info->size == size) {
+ info->in_use = true;
+ va = info->start_iova;
+ *curr_iova_size -= size;
+ found = true;
+ dev_dbg(uaudio_qdev->dev, "exact size: %zu found\n", size);
+ goto done;
+ } else if (!info->in_use && tmp_size >= info->size) {
+ if (!new_info)
+ new_info = info;
+ dev_dbg(uaudio_qdev->dev, "partial size: %zu found\n",
+ info->size);
+ tmp_size -= info->size;
+ if (tmp_size)
+ continue;
+
+ va = new_info->start_iova;
+ for (curr_head = &new_info->list; curr_head !=
+ &info->list; curr_head = curr_head->next) {
+ new_info = list_entry(curr_head, struct
+ iova_info, list);
+ new_info->in_use = true;
+ }
+ info->in_use = true;
+ *curr_iova_size -= size;
+ found = true;
+ goto done;
+ } else {
+ /* iova region in use */
+ new_info = NULL;
+ tmp_size = size;
+ }
+ }
+
+ info = kzalloc(sizeof(struct iova_info), GFP_KERNEL);
+ if (!info) {
+ va = 0;
+ goto done;
+ }
+
+ va = info->start_iova = *curr_iova;
+ info->size = size;
+ info->in_use = true;
+ *curr_iova += size;
+ *curr_iova_size -= size;
+ found = true;
+ list_add_tail(&info->list, head);
+
+done:
+ if (!found)
+ dev_err(uaudio_qdev->dev, "unable to find %zu size iova\n",
+ size);
+ else
+ dev_dbg(uaudio_qdev->dev,
+ "va:0x%08lx curr_iova:0x%08lx curr_iova_size:%zu\n",
+ va, *curr_iova, *curr_iova_size);
+
+ return va;
+}
+
+static void uaudio_put_iova(unsigned long va, size_t size, struct list_head
+ *head, size_t *curr_iova_size)
+{
+ struct iova_info *info;
+ size_t tmp_size = size;
+ bool found = false;
+
+ list_for_each_entry(info, head, list) {
+ if (info->start_iova == va) {
+ if (!info->in_use) {
+ dev_err(uaudio_qdev->dev, "va %lu is not in use\n",
+ va);
+ return;
+ }
+ found = true;
+ info->in_use = false;
+ if (info->size == size)
+ goto done;
+ }
+
+ if (found && tmp_size >= info->size) {
+ info->in_use = false;
+ tmp_size -= info->size;
+ if (!tmp_size)
+ goto done;
+ }
+ }
+
+ if (!found) {
+ dev_err(uaudio_qdev->dev, "unable to find the va %lu\n", va);
+ return;
+ }
+done:
+ *curr_iova_size += size;
+ dev_dbg(uaudio_qdev->dev, "curr_iova_size %zu\n", *curr_iova_size);
+}
+
+/**
+ * uaudio_iommu_unmap() - unmaps iommu memory for adsp
+ * @mtype: ring type
+ * @va: virtual address to unmap
+ * @iova_size: region size
+ * @mapped_iova_size: mapped region size
+ *
+ * Unmaps the memory region that was previously assigned to the adsp.
+ *
+ */
+static void uaudio_iommu_unmap(enum mem_type mtype, unsigned long va,
+ size_t iova_size, size_t mapped_iova_size)
+{
+ size_t umap_size;
+ bool unmap = true;
+
+ if (!va || !iova_size)
+ return;
+
+ switch (mtype) {
+ case MEM_EVENT_RING:
+ if (uaudio_qdev->er_mapped)
+ uaudio_qdev->er_mapped = false;
+ else
+ unmap = false;
+ break;
+
+ case MEM_XFER_RING:
+ uaudio_put_iova(va, iova_size, &uaudio_qdev->xfer_ring_list,
+ &uaudio_qdev->xfer_ring_iova_size);
+ break;
+ case MEM_XFER_BUF:
+ uaudio_put_iova(va, iova_size, &uaudio_qdev->xfer_buf_list,
+ &uaudio_qdev->xfer_buf_iova_size);
+ break;
+ default:
+ dev_err(uaudio_qdev->dev, "unknown mem type %d\n", mtype);
+ unmap = false;
+ }
+
+ if (!unmap || !mapped_iova_size)
+ return;
+
+ dev_dbg(uaudio_qdev->dev, "type %d: unmap iova 0x%08lx size %zu\n",
+ mtype, va, mapped_iova_size);
+
+ umap_size = iommu_unmap(uaudio_qdev->domain, va, mapped_iova_size);
+ if (umap_size != mapped_iova_size)
+ dev_err(uaudio_qdev->dev,
+ "unmapped size %zu for iova 0x%08lx of mapped size %zu\n",
+ umap_size, va, mapped_iova_size);
+}
+
+/**
+ * uaudio_iommu_map() - maps iommu memory for adsp
+ * @mtype: ring type
+ * @dma_coherent: dma coherent
+ * @pa: physical address for ring/buffer
+ * @size: size of memory region
+ * @sgt: sg table for memory region
+ *
+ * Maps the XHCI related resources to a memory region that is assigned to be
+ * used by the adsp. This will be mapped to the domain, which is created by
+ * the ASoC USB backend driver.
+ *
+ */
+static unsigned long uaudio_iommu_map(enum mem_type mtype, bool dma_coherent,
+ phys_addr_t pa, size_t size, struct sg_table *sgt)
+{
+ unsigned long va_sg, va = 0;
+ bool map = true;
+ int i, ret;
+ size_t sg_len, total_len = 0;
+ struct scatterlist *sg;
+ phys_addr_t pa_sg;
+ int prot = IOMMU_READ | IOMMU_WRITE;
+
+ if (dma_coherent)
+ prot |= IOMMU_CACHE;
+
+ switch (mtype) {
+ case MEM_EVENT_RING:
+ va = IOVA_BASE;
+ /* er already mapped */
+ if (uaudio_qdev->er_mapped)
+ map = false;
+ break;
+ case MEM_XFER_RING:
+ va = uaudio_get_iova(&uaudio_qdev->curr_xfer_ring_iova,
+ &uaudio_qdev->xfer_ring_iova_size, &uaudio_qdev->xfer_ring_list,
+ size);
+ break;
+ case MEM_XFER_BUF:
+ va = uaudio_get_iova(&uaudio_qdev->curr_xfer_buf_iova,
+ &uaudio_qdev->xfer_buf_iova_size, &uaudio_qdev->xfer_buf_list,
+ size);
+ break;
+ default:
+ dev_err(uaudio_qdev->dev, "unknown mem type %d\n", mtype);
+ }
+
+ if (!va || !map)
+ goto done;
+
+ if (!sgt)
+ goto skip_sgt_map;
+
+ va_sg = va;
+ for_each_sg(sgt->sgl, sg, sgt->nents, i) {
+ sg_len = PAGE_ALIGN(sg->offset + sg->length);
+ pa_sg = page_to_phys(sg_page(sg));
+ ret = iommu_map(uaudio_qdev->domain, va_sg, pa_sg, sg_len,
+ prot, GFP_KERNEL);
+ if (ret) {
+ dev_err(uaudio_qdev->dev, "mapping failed ret%d\n", ret);
+ dev_err(uaudio_qdev->dev,
+ "type:%d, pa:%pa iova:0x%08lx sg_len:%zu\n",
+ mtype, &pa_sg, va_sg, sg_len);
+ uaudio_iommu_unmap(MEM_XFER_BUF, va, size, total_len);
+ va = 0;
+ goto done;
+ }
+ dev_dbg(uaudio_qdev->dev,
+ "type:%d map pa:%pa to iova:0x%08lx len:%zu offset:%u\n",
+ mtype, &pa_sg, va_sg, sg_len, sg->offset);
+ va_sg += sg_len;
+ total_len += sg_len;
+ }
+
+ if (size != total_len) {
+ dev_err(uaudio_qdev->dev, "iova size %zu != mapped iova size %zu\n",
+ size, total_len);
+ uaudio_iommu_unmap(MEM_XFER_BUF, va, size, total_len);
+ va = 0;
+ }
+ return va;
+
+skip_sgt_map:
+ dev_dbg(uaudio_qdev->dev, "type:%d map pa:%pa to iova:0x%08lx size:%zu\n",
+ mtype, &pa, va, size);
+
+ ret = iommu_map(uaudio_qdev->domain, va, pa, size, prot, GFP_KERNEL);
+ if (ret)
+ dev_err(uaudio_qdev->dev,
+ "failed to map pa:%pa iova:0x%lx type:%d ret:%d\n",
+ &pa, va, mtype, ret);
+done:
+ return va;
+}
+
+/* looks up alias, if any, for controller DT node and returns the index */
+static int usb_get_controller_id(struct usb_device *udev)
+{
+ if (udev->bus->sysdev && udev->bus->sysdev->of_node)
+ return of_alias_get_id(udev->bus->sysdev->of_node, "usb");
+
+ return -ENODEV;
+}
+
+/**
+ * uaudio_dev_intf_cleanup() - cleanup transfer resources
+ * @udev: usb device
+ * @info: usb offloading interface
+ *
+ * Cleans up the transfer ring related resources which are assigned per
+ * endpoint from XHCI. This is invoked when the USB endpoints are no
+ * longer in use by the adsp.
+ *
+ */
+static void uaudio_dev_intf_cleanup(struct usb_device *udev,
+ struct intf_info *info)
+{
+ uaudio_iommu_unmap(MEM_XFER_RING, info->data_xfer_ring_va,
+ info->data_xfer_ring_size, info->data_xfer_ring_size);
+ info->data_xfer_ring_va = 0;
+ info->data_xfer_ring_size = 0;
+
+ uaudio_iommu_unmap(MEM_XFER_RING, info->sync_xfer_ring_va,
+ info->sync_xfer_ring_size, info->sync_xfer_ring_size);
+ info->sync_xfer_ring_va = 0;
+ info->sync_xfer_ring_size = 0;
+
+ uaudio_iommu_unmap(MEM_XFER_BUF, info->xfer_buf_va,
+ info->xfer_buf_size, info->xfer_buf_size);
+ info->xfer_buf_va = 0;
+
+ usb_free_coherent(udev, info->xfer_buf_size,
+ info->xfer_buf, info->xfer_buf_pa);
+ info->xfer_buf_size = 0;
+ info->xfer_buf = NULL;
+ info->xfer_buf_pa = 0;
+
+ info->in_use = false;
+}
+
+/**
+ * uaudio_event_ring_cleanup_free() - cleanup secondary event ring
+ * @dev: usb offload device
+ *
+ * Cleans up the secondary event ring that was requested. This will
+ * occur when the adsp is no longer transferring data on the USB bus
+ * across all endpoints.
+ *
+ */
+static void uaudio_event_ring_cleanup_free(struct uaudio_dev *dev)
+{
+ clear_bit(dev->chip->card->number, &uaudio_qdev->card_slot);
+ /* all audio devices are disconnected */
+ if (!uaudio_qdev->card_slot) {
+ uaudio_iommu_unmap(MEM_EVENT_RING, IOVA_BASE, PAGE_SIZE,
+ PAGE_SIZE);
+ xhci_sideband_remove_interrupter(uadev[dev->chip->card->number].sb);
+ }
+}
+
+static void uaudio_dev_cleanup(struct uaudio_dev *dev)
+{
+ int if_idx;
+
+ if (!dev->udev)
+ return;
+
+ /* free xfer buffer and unmap xfer ring and buf per interface */
+ for (if_idx = 0; if_idx < dev->num_intf; if_idx++) {
+ if (!dev->info[if_idx].in_use)
+ continue;
+ uaudio_dev_intf_cleanup(dev->udev, &dev->info[if_idx]);
+ dev_dbg(uaudio_qdev->dev, "release resources: intf# %d card# %d\n",
+ dev->info[if_idx].intf_num, dev->chip->card->number);
+ }
+
+ dev->num_intf = 0;
+
+ /* free interface info */
+ kfree(dev->info);
+ dev->info = NULL;
+ uaudio_event_ring_cleanup_free(dev);
+ dev->udev = NULL;
+}
+
+/**
+ * disable_audio_stream() - disable usb snd endpoints
+ * @subs: usb substream
+ *
+ * Closes the USB SND endpoints associated with the current audio stream
+ * used. This will decrement the USB SND endpoint opened reference count.
+ *
+ */
+static void disable_audio_stream(struct snd_usb_substream *subs)
+{
+ struct snd_usb_audio *chip = subs->stream->chip;
+
+ snd_usb_hw_free(subs);
+ snd_usb_autosuspend(chip);
+}
+
+/* QMI service disconnect handlers */
+static void qmi_disconnect_work(struct work_struct *w)
+{
+ struct intf_info *info;
+ int idx, if_idx;
+ struct snd_usb_substream *subs;
+ struct snd_usb_audio *chip;
+
+ mutex_lock(&qdev_mutex);
+ /* find all active intf for set alt 0 and cleanup usb audio dev */
+ for (idx = 0; idx < SNDRV_CARDS; idx++) {
+ if (!atomic_read(&uadev[idx].in_use))
+ continue;
+
+ chip = uadev[idx].chip;
+ for (if_idx = 0; if_idx < uadev[idx].num_intf; if_idx++) {
+ if (!uadev[idx].info || !uadev[idx].info[if_idx].in_use)
+ continue;
+ info = &uadev[idx].info[if_idx];
+ subs = find_substream(info->pcm_card_num,
+ info->pcm_dev_num,
+ info->direction);
+ if (!subs || !chip || atomic_read(&chip->shutdown)) {
+ dev_err(&subs->dev->dev,
+ "no sub for c#%u dev#%u dir%u\n",
+ info->pcm_card_num,
+ info->pcm_dev_num,
+ info->direction);
+ continue;
+ }
+ disable_audio_stream(subs);
+ }
+ atomic_set(&uadev[idx].in_use, 0);
+ mutex_lock(&chip->mutex);
+ uaudio_dev_cleanup(&uadev[idx]);
+ mutex_unlock(&chip->mutex);
+ }
+ mutex_unlock(&qdev_mutex);
+}
+
+/**
+ * qmi_bye_cb() - qmi bye message callback
+ * @handle: QMI handle
+ * @node: id of the dying node
+ *
+ * This callback is invoked when the QMI bye control message is received
+ * from the QMI client. Handle the message accordingly by ensuring that
+ * the USB offload path is disabled and cleaned up. At this point, ADSP
+ * is not utilizing the USB bus.
+ *
+ */
+static void qmi_bye_cb(struct qmi_handle *handle, unsigned int node)
+{
+ struct uaudio_qmi_svc *svc = uaudio_svc;
+
+ if (svc->uaudio_svc_hdl != handle)
+ return;
+
+ if (svc->client_connected && svc->client_sq.sq_node == node) {
+ queue_work(svc->uaudio_wq, &svc->qmi_disconnect_work);
+ svc->client_sq.sq_node = 0;
+ svc->client_sq.sq_port = 0;
+ svc->client_sq.sq_family = 0;
+ svc->client_connected = false;
+ }
+}
+
+/**
+ * qmi_svc_disconnect_cb() - qmi client disconnected
+ * @handle: QMI handle
+ * @node: id of the dying node
+ * @port: port of the dying client
+ *
+ * Invoked when the remote QMI client is disconnected. Handle this event
+ * the same way as when the QMI bye message is received. This will ensure
+ * the USB offloading path is disabled and cleaned up.
+ *
+ */
+static void qmi_svc_disconnect_cb(struct qmi_handle *handle,
+ unsigned int node, unsigned int port)
+{
+ struct uaudio_qmi_svc *svc;
+
+ if (uaudio_svc == NULL)
+ return;
+
+ svc = uaudio_svc;
+ if (svc->uaudio_svc_hdl != handle)
+ return;
+
+ if (svc->client_connected && svc->client_sq.sq_node == node &&
+ svc->client_sq.sq_port == port) {
+ queue_work(svc->uaudio_wq, &svc->qmi_disconnect_work);
+ svc->client_sq.sq_node = 0;
+ svc->client_sq.sq_port = 0;
+ svc->client_sq.sq_family = 0;
+ svc->client_connected = false;
+ }
+}
+
+/* QMI client callback handlers from QMI interface */
+static struct qmi_ops uaudio_svc_ops_options = {
+ .bye = qmi_bye_cb,
+ .del_client = qmi_svc_disconnect_cb,
+};
+
+/* kref release callback when all streams are disabled */
+static void uaudio_dev_release(struct kref *kref)
+{
+ struct uaudio_dev *dev = container_of(kref, struct uaudio_dev, kref);
+
+ uaudio_event_ring_cleanup_free(dev);
+ atomic_set(&dev->in_use, 0);
+ wake_up(&dev->disconnect_wq);
+}
+
+/**
+ * enable_audio_stream() - enable usb snd endpoints
+ * @subs: usb substream
+ * @pcm_format: pcm format requested
+ * @channels: number of channels
+ * @cur_rate: sample rate
+ * @datainterval: interval
+ *
+ * Opens all USB SND endpoints used for the data interface. This will increment
+ * the USB SND endpoint's opened count. Requests to keep the interface resumed
+ * until the audio stream is stopped. Will issue the USB set interface control
+ * message to enable the data interface.
+ *
+ */
+static int enable_audio_stream(struct snd_usb_substream *subs,
+ snd_pcm_format_t pcm_format,
+ unsigned int channels, unsigned int cur_rate,
+ int datainterval)
+{
+ struct snd_usb_audio *chip = subs->stream->chip;
+ struct snd_pcm_hw_params params;
+ struct snd_mask *m;
+ struct snd_interval *i;
+ int ret;
+
+ _snd_pcm_hw_params_any(&params);
+
+ m = hw_param_mask(&params, SNDRV_PCM_HW_PARAM_FORMAT);
+ snd_mask_leave(m, pcm_format);
+
+ i = hw_param_interval(&params, SNDRV_PCM_HW_PARAM_CHANNELS);
+ snd_interval_setinteger(i);
+ i->min = i->max = channels;
+
+ i = hw_param_interval(&params, SNDRV_PCM_HW_PARAM_RATE);
+ snd_interval_setinteger(i);
+ i->min = i->max = cur_rate;
+
+ pm_runtime_barrier(&chip->intf[0]->dev);
+ snd_usb_autoresume(chip);
+
+ ret = snd_usb_hw_params(subs, &params);
+ if (ret < 0)
+ goto put_suspend;
+
+ if (!atomic_read(&chip->shutdown)) {
+ ret = snd_usb_lock_shutdown(chip);
+ if (ret < 0)
+ goto detach_ep;
+
+ if (subs->sync_endpoint) {
+ ret = snd_usb_endpoint_prepare(chip, subs->sync_endpoint);
+ if (ret < 0)
+ goto unlock;
+ }
+
+ ret = snd_usb_endpoint_prepare(chip, subs->data_endpoint);
+ if (ret < 0)
+ goto unlock;
+
+ snd_usb_unlock_shutdown(chip);
+
+ dev_dbg(uaudio_qdev->dev,
+ "selected %s iface:%d altsetting:%d datainterval:%dus\n",
+ subs->direction ? "capture" : "playback",
+ subs->cur_audiofmt->iface, subs->cur_audiofmt->altsetting,
+ (1 << subs->cur_audiofmt->datainterval) *
+ (subs->dev->speed >= USB_SPEED_HIGH ?
+ BUS_INTERVAL_HIGHSPEED_AND_ABOVE :
+ BUS_INTERVAL_FULL_SPEED));
+ }
+
+ return 0;
+
+unlock:
+ snd_usb_unlock_shutdown(chip);
+
+detach_ep:
+ snd_usb_hw_free(subs);
+
+put_suspend:
+ snd_usb_autosuspend(chip);
+
+ return ret;
+}
+
+/* returns usb hcd sysdev */
+static struct device *usb_get_usb_backend(struct usb_device *udev)
+{
+ if (udev->bus->sysdev && udev->bus->sysdev->of_node)
+ return udev->bus->sysdev;
+
+ return NULL;
+}
+
+/**
+ * prepare_qmi_response() - prepare stream enable response
+ * @subs: usb substream
+ * @req_msg: QMI request message
+ * @resp: QMI response buffer
+ * @info_idx: usb interface array index
+ *
+ * Prepares the QMI response for a USB QMI stream enable request. Will parse
+ * out the parameters within the stream enable request, in order to match
+ * requested audio profile to the ones exposed by the USB device connected.
+ *
+ * In addition, will fetch the XHCI transfer resources needed for the handoff to
+ * happen. This includes, transfer ring and buffer addresses and secondary event
+ * ring address. These parameters will be communicated as part of the USB QMI
+ * stream enable response.
+ *
+ */
+static int prepare_qmi_response(struct snd_usb_substream *subs,
+ struct qmi_uaudio_stream_req_msg_v01 *req_msg,
+ struct qmi_uaudio_stream_resp_msg_v01 *resp, int info_idx)
+{
+ struct usb_interface *iface;
+ struct usb_host_interface *alts;
+ struct usb_interface_descriptor *altsd;
+ struct usb_interface_assoc_descriptor *assoc;
+ struct usb_host_endpoint *ep;
+ struct uac_format_type_i_continuous_descriptor *fmt;
+ struct uac_format_type_i_discrete_descriptor *fmt_v1;
+ struct uac_format_type_i_ext_descriptor *fmt_v2;
+ struct uac1_as_header_descriptor *as;
+ struct q6usb_offload *data;
+ int ret;
+ int protocol, card_num, pcm_dev_num;
+ void *hdr_ptr;
+ u8 *xfer_buf;
+ unsigned int data_ep_pipe = 0, sync_ep_pipe = 0;
+ u32 len, mult, remainder, xfer_buf_len;
+ unsigned long va, tr_data_va = 0, tr_sync_va = 0;
+ phys_addr_t xhci_pa, xfer_buf_pa, tr_data_pa = 0, tr_sync_pa = 0;
+ struct sg_table *sgt;
+ struct sg_table xfer_buf_sgt;
+ struct page *pg;
+ bool dma_coherent;
+
+ iface = usb_ifnum_to_if(subs->dev, subs->cur_audiofmt->iface);
+ if (!iface) {
+ dev_err(uaudio_qdev->dev, "interface # %d does not exist\n",
+ subs->cur_audiofmt->iface);
+ ret = -ENODEV;
+ goto err;
+ }
+
+ assoc = iface->intf_assoc;
+ pcm_dev_num = (req_msg->usb_token & QMI_STREAM_REQ_DEV_NUM_MASK) >> 8;
+ xfer_buf_len = req_msg->xfer_buff_size;
+ card_num = uaudio_qdev->last_card_num;
+
+ alts = &iface->altsetting[subs->cur_audiofmt->altset_idx];
+ altsd = get_iface_desc(alts);
+ protocol = altsd->bInterfaceProtocol;
+
+ /* get format type */
+ if (protocol != UAC_VERSION_3) {
+ fmt = snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL,
+ UAC_FORMAT_TYPE);
+ if (!fmt) {
+ dev_err(uaudio_qdev->dev,
+ "%u:%d : no UAC_FORMAT_TYPE desc\n",
+ subs->cur_audiofmt->iface,
+ subs->cur_audiofmt->altset_idx);
+ ret = -ENODEV;
+ goto err;
+ }
+ }
+
+ if (!uadev[card_num].ctrl_intf) {
+ dev_err(uaudio_qdev->dev, "audio ctrl intf info not cached\n");
+ ret = -ENODEV;
+ goto err;
+ }
+
+ if (protocol != UAC_VERSION_3) {
+ hdr_ptr = snd_usb_find_csint_desc(uadev[card_num].ctrl_intf->extra,
+ uadev[card_num].ctrl_intf->extralen, NULL,
+ UAC_HEADER);
+ if (!hdr_ptr) {
+ dev_err(uaudio_qdev->dev, "no UAC_HEADER desc\n");
+ ret = -ENODEV;
+ goto err;
+ }
+ }
+
+ if (protocol == UAC_VERSION_1) {
+ struct uac1_ac_header_descriptor *uac1_hdr = hdr_ptr;
+
+ as = snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL,
+ UAC_AS_GENERAL);
+ if (!as) {
+ dev_err(uaudio_qdev->dev,
+ "%u:%d : no UAC_AS_GENERAL desc\n",
+ subs->cur_audiofmt->iface,
+ subs->cur_audiofmt->altset_idx);
+ ret = -ENODEV;
+ goto err;
+ }
+ resp->data_path_delay = as->bDelay;
+ resp->data_path_delay_valid = 1;
+ fmt_v1 = (struct uac_format_type_i_discrete_descriptor *)fmt;
+ resp->usb_audio_subslot_size = fmt_v1->bSubframeSize;
+ resp->usb_audio_subslot_size_valid = 1;
+
+ resp->usb_audio_spec_revision = le16_to_cpu(uac1_hdr->bcdADC);
+ resp->usb_audio_spec_revision_valid = 1;
+ } else if (protocol == UAC_VERSION_2) {
+ struct uac2_ac_header_descriptor *uac2_hdr = hdr_ptr;
+
+ fmt_v2 = (struct uac_format_type_i_ext_descriptor *)fmt;
+ resp->usb_audio_subslot_size = fmt_v2->bSubslotSize;
+ resp->usb_audio_subslot_size_valid = 1;
+
+ resp->usb_audio_spec_revision = le16_to_cpu(uac2_hdr->bcdADC);
+ resp->usb_audio_spec_revision_valid = 1;
+ } else if (protocol == UAC_VERSION_3) {
+ if (assoc->bFunctionSubClass ==
+ UAC3_FUNCTION_SUBCLASS_FULL_ADC_3_0) {
+ dev_err(uaudio_qdev->dev, "full adc is not supported\n");
+ ret = -EINVAL;
+ }
+
+ switch (le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize)) {
+ case UAC3_BADD_EP_MAXPSIZE_SYNC_MONO_16:
+ case UAC3_BADD_EP_MAXPSIZE_SYNC_STEREO_16:
+ case UAC3_BADD_EP_MAXPSIZE_ASYNC_MONO_16:
+ case UAC3_BADD_EP_MAXPSIZE_ASYNC_STEREO_16: {
+ resp->usb_audio_subslot_size = 0x2;
+ break;
+ }
+
+ case UAC3_BADD_EP_MAXPSIZE_SYNC_MONO_24:
+ case UAC3_BADD_EP_MAXPSIZE_SYNC_STEREO_24:
+ case UAC3_BADD_EP_MAXPSIZE_ASYNC_MONO_24:
+ case UAC3_BADD_EP_MAXPSIZE_ASYNC_STEREO_24: {
+ resp->usb_audio_subslot_size = 0x3;
+ break;
+ }
+
+ default:
+ dev_err(uaudio_qdev->dev,
+ "%d: %u: Invalid wMaxPacketSize\n",
+ subs->cur_audiofmt->iface,
+ subs->cur_audiofmt->altset_idx);
+ ret = -EINVAL;
+ goto err;
+ }
+ resp->usb_audio_subslot_size_valid = 1;
+ } else {
+ dev_err(uaudio_qdev->dev, "unknown protocol version %x\n",
+ protocol);
+ ret = -ENODEV;
+ goto err;
+ }
+
+ resp->slot_id = subs->dev->slot_id;
+ resp->slot_id_valid = 1;
+
+ memcpy(&resp->std_as_opr_intf_desc, &alts->desc, sizeof(alts->desc));
+ resp->std_as_opr_intf_desc_valid = 1;
+
+ ep = usb_pipe_endpoint(subs->dev, subs->data_endpoint->pipe);
+ if (!ep) {
+ dev_err(uaudio_qdev->dev, "data ep # %d context is null\n",
+ subs->data_endpoint->ep_num);
+ ret = -ENODEV;
+ goto err;
+ }
+ data_ep_pipe = subs->data_endpoint->pipe;
+ memcpy(&resp->std_as_data_ep_desc, &ep->desc, sizeof(ep->desc));
+ resp->std_as_data_ep_desc_valid = 1;
+
+ ret = xhci_sideband_add_endpoint(uadev[card_num].sb, ep);
+ if (ret < 0) {
+ dev_err(uaudio_qdev->dev, "failed to add data ep to sideband\n");
+ ret = -ENODEV;
+ goto err;
+ }
+
+ sgt = xhci_sideband_get_endpoint_buffer(uadev[card_num].sb, ep);
+ if (!sgt) {
+ dev_err(uaudio_qdev->dev, "failed to get data ep ring address\n");
+ ret = -ENODEV;
+ goto drop_data_ep;
+ }
+
+ pg = sg_page(sgt->sgl);
+ tr_data_pa = page_to_phys(pg);
+ resp->xhci_mem_info.tr_data.pa = sg_dma_address(sgt->sgl);
+ sg_free_table(sgt);
+
+ if (subs->sync_endpoint) {
+ ep = usb_pipe_endpoint(subs->dev, subs->sync_endpoint->pipe);
+ if (!ep) {
+ dev_err(uaudio_qdev->dev, "implicit fb on data ep\n");
+ goto skip_sync_ep;
+ }
+ sync_ep_pipe = subs->sync_endpoint->pipe;
+ memcpy(&resp->std_as_sync_ep_desc, &ep->desc, sizeof(ep->desc));
+ resp->std_as_sync_ep_desc_valid = 1;
+
+ ret = xhci_sideband_add_endpoint(uadev[card_num].sb, ep);
+ if (ret < 0) {
+ dev_err(uaudio_qdev->dev,
+ "failed to add sync ep to sideband\n");
+ ret = -ENODEV;
+ goto drop_data_ep;
+ }
+
+ sgt = xhci_sideband_get_endpoint_buffer(uadev[card_num].sb, ep);
+ if (!sgt) {
+ dev_err(uaudio_qdev->dev, "failed to get sync ep ring address\n");
+ ret = -ENODEV;
+ goto drop_sync_ep;
+ }
+
+ pg = sg_page(sgt->sgl);
+ tr_sync_pa = page_to_phys(pg);
+ resp->xhci_mem_info.tr_sync.pa = sg_dma_address(sgt->sgl);
+ sg_free_table(sgt);
+ }
+
+skip_sync_ep:
+ data = snd_soc_usb_find_priv_data(usb_get_usb_backend(subs->dev));
+ if (!data)
+ goto drop_sync_ep;
+
+ uaudio_qdev->domain = data->domain;
+ uaudio_qdev->sid = data->sid;
+ uaudio_qdev->intr_num = data->intr_num;
+ uaudio_qdev->dev = data->dev;
+
+ resp->interrupter_num_valid = 1;
+ resp->controller_num_valid = 0;
+ ret = usb_get_controller_id(subs->dev);
+ if (ret >= 0) {
+ resp->controller_num = ret;
+ resp->controller_num_valid = 1;
+ }
+ /* map xhci data structures PA memory to iova */
+ dma_coherent = dev_is_dma_coherent(subs->dev->bus->sysdev);
+
+ /* event ring */
+ ret = xhci_sideband_create_interrupter(uadev[card_num].sb, uaudio_qdev->intr_num);
+ if (ret < 0) {
+ dev_err(uaudio_qdev->dev, "failed to fetch interrupter\n");
+ ret = -ENODEV;
+ goto drop_sync_ep;
+ }
+
+ sgt = xhci_sideband_get_event_buffer(uadev[card_num].sb);
+ if (!sgt) {
+ dev_err(uaudio_qdev->dev, "failed to get event ring address\n");
+ ret = -ENODEV;
+ goto free_sec_ring;
+ }
+
+ xhci_pa = page_to_phys(sg_page(sgt->sgl));
+ resp->xhci_mem_info.evt_ring.pa = sg_dma_address(sgt->sgl);
+ sg_free_table(sgt);
+ if (!xhci_pa) {
+ dev_err(uaudio_qdev->dev,
+ "failed to get sec event ring address\n");
+ ret = -ENODEV;
+ goto free_sec_ring;
+ }
+
+ resp->interrupter_num = xhci_sideband_interrupter_id(uadev[card_num].sb);
+
+ va = uaudio_iommu_map(MEM_EVENT_RING, dma_coherent, xhci_pa, PAGE_SIZE,
+ NULL);
+ if (!va) {
+ ret = -ENOMEM;
+ goto free_sec_ring;
+ }
+
+ resp->xhci_mem_info.evt_ring.va = PREPEND_SID_TO_IOVA(va,
+ uaudio_qdev->sid);
+ resp->xhci_mem_info.evt_ring.size = PAGE_SIZE;
+ uaudio_qdev->er_mapped = true;
+
+ resp->speed_info = get_speed_info(subs->dev->speed);
+ if (resp->speed_info == USB_QMI_DEVICE_SPEED_INVALID_V01) {
+ ret = -ENODEV;
+ goto unmap_er;
+ }
+
+ resp->speed_info_valid = 1;
+
+ /* data transfer ring */
+ va = uaudio_iommu_map(MEM_XFER_RING, dma_coherent, tr_data_pa,
+ PAGE_SIZE, NULL);
+ if (!va) {
+ ret = -ENOMEM;
+ goto unmap_er;
+ }
+
+ tr_data_va = va;
+ resp->xhci_mem_info.tr_data.va = PREPEND_SID_TO_IOVA(va,
+ uaudio_qdev->sid);
+ resp->xhci_mem_info.tr_data.size = PAGE_SIZE;
+
+ /* sync transfer ring */
+ if (!resp->xhci_mem_info.tr_sync.pa)
+ goto skip_sync;
+
+ xhci_pa = resp->xhci_mem_info.tr_sync.pa;
+ va = uaudio_iommu_map(MEM_XFER_RING, dma_coherent, tr_sync_pa,
+ PAGE_SIZE, NULL);
+ if (!va) {
+ ret = -ENOMEM;
+ goto unmap_data;
+ }
+
+ tr_sync_va = va;
+ resp->xhci_mem_info.tr_sync.va = PREPEND_SID_TO_IOVA(va,
+ uaudio_qdev->sid);
+ resp->xhci_mem_info.tr_sync.size = PAGE_SIZE;
+
+skip_sync:
+ /* xfer buffer, multiple of 4K only */
+ if (!xfer_buf_len)
+ xfer_buf_len = PAGE_SIZE;
+
+ mult = xfer_buf_len / PAGE_SIZE;
+ remainder = xfer_buf_len % PAGE_SIZE;
+ len = mult * PAGE_SIZE;
+ len += remainder ? PAGE_SIZE : 0;
+
+ if (len > MAX_XFER_BUFF_LEN) {
+ dev_err(uaudio_qdev->dev,
+ "req buf len %d > max buf len %lu, setting %lu\n",
+ len, MAX_XFER_BUFF_LEN, MAX_XFER_BUFF_LEN);
+ len = MAX_XFER_BUFF_LEN;
+ }
+
+ xfer_buf = usb_alloc_coherent(subs->dev, len, GFP_KERNEL, &xfer_buf_pa);
+ if (!xfer_buf) {
+ ret = -ENOMEM;
+ goto unmap_sync;
+ }
+
+ dma_get_sgtable(subs->dev->bus->sysdev, &xfer_buf_sgt, xfer_buf, xfer_buf_pa,
+ len);
+ va = uaudio_iommu_map(MEM_XFER_BUF, dma_coherent, xfer_buf_pa, len,
+ &xfer_buf_sgt);
+ if (!va) {
+ ret = -ENOMEM;
+ goto unmap_sync;
+ }
+
+ resp->xhci_mem_info.xfer_buff.pa = xfer_buf_pa;
+ resp->xhci_mem_info.xfer_buff.size = len;
+
+ resp->xhci_mem_info.xfer_buff.va = PREPEND_SID_TO_IOVA(va,
+ uaudio_qdev->sid);
+
+ resp->xhci_mem_info_valid = 1;
+
+ sg_free_table(&xfer_buf_sgt);
+
+ if (!atomic_read(&uadev[card_num].in_use)) {
+ kref_init(&uadev[card_num].kref);
+ init_waitqueue_head(&uadev[card_num].disconnect_wq);
+ uadev[card_num].num_intf =
+ subs->dev->config->desc.bNumInterfaces;
+ uadev[card_num].info = kcalloc(uadev[card_num].num_intf,
+ sizeof(struct intf_info), GFP_KERNEL);
+ if (!uadev[card_num].info) {
+ ret = -ENOMEM;
+ goto unmap_sync;
+ }
+ uadev[card_num].udev = subs->dev;
+ atomic_set(&uadev[card_num].in_use, 1);
+ } else {
+ kref_get(&uadev[card_num].kref);
+ }
+
+ uadev[card_num].usb_core_id = resp->controller_num;
+
+ /* cache intf specific info to use it for unmap and free xfer buf */
+ uadev[card_num].info[info_idx].data_xfer_ring_va = tr_data_va;
+ uadev[card_num].info[info_idx].data_xfer_ring_size = PAGE_SIZE;
+ uadev[card_num].info[info_idx].sync_xfer_ring_va = tr_sync_va;
+ uadev[card_num].info[info_idx].sync_xfer_ring_size = PAGE_SIZE;
+ uadev[card_num].info[info_idx].xfer_buf_va = va;
+ uadev[card_num].info[info_idx].xfer_buf_pa = xfer_buf_pa;
+ uadev[card_num].info[info_idx].xfer_buf_size = len;
+ uadev[card_num].info[info_idx].data_ep_pipe = data_ep_pipe;
+ uadev[card_num].info[info_idx].sync_ep_pipe = sync_ep_pipe;
+ uadev[card_num].info[info_idx].xfer_buf = xfer_buf;
+ uadev[card_num].info[info_idx].pcm_card_num = card_num;
+ uadev[card_num].info[info_idx].pcm_dev_num = pcm_dev_num;
+ uadev[card_num].info[info_idx].direction = subs->direction;
+ uadev[card_num].info[info_idx].intf_num = subs->cur_audiofmt->iface;
+ uadev[card_num].info[info_idx].in_use = true;
+
+ set_bit(card_num, &uaudio_qdev->card_slot);
+
+ return 0;
+
+unmap_sync:
+ usb_free_coherent(subs->dev, len, xfer_buf, xfer_buf_pa);
+ uaudio_iommu_unmap(MEM_XFER_RING, tr_sync_va, PAGE_SIZE, PAGE_SIZE);
+unmap_data:
+ uaudio_iommu_unmap(MEM_XFER_RING, tr_data_va, PAGE_SIZE, PAGE_SIZE);
+unmap_er:
+ uaudio_iommu_unmap(MEM_EVENT_RING, IOVA_BASE, PAGE_SIZE, PAGE_SIZE);
+free_sec_ring:
+ xhci_sideband_remove_interrupter(uadev[card_num].sb);
+drop_sync_ep:
+ if (subs->sync_endpoint)
+ xhci_sideband_remove_endpoint(uadev[card_num].sb,
+ usb_pipe_endpoint(subs->dev, subs->sync_endpoint->pipe));
+drop_data_ep:
+ xhci_sideband_remove_endpoint(uadev[card_num].sb,
+ usb_pipe_endpoint(subs->dev, subs->data_endpoint->pipe));
+
+err:
+ return ret;
+}
+
+/**
+ * handle_uaudio_stream_req() - handle stream enable/disable request
+ * @handle: QMI client handle
+ * @sq: qrtr socket
+ * @txn: QMI transaction context
+ * @decoded_msg: decoded QMI message
+ *
+ * Main handler for the QMI stream enable/disable requests. This executes the
+ * corresponding enable/disable stream apis, respectively.
+ *
+ */
+static void handle_uaudio_stream_req(struct qmi_handle *handle,
+ struct sockaddr_qrtr *sq,
+ struct qmi_txn *txn,
+ const void *decoded_msg)
+{
+ struct qmi_uaudio_stream_req_msg_v01 *req_msg;
+ struct qmi_uaudio_stream_resp_msg_v01 resp = {{0}, 0};
+ struct snd_usb_substream *subs;
+ struct snd_usb_audio *chip = NULL;
+ struct uaudio_qmi_svc *svc = uaudio_svc;
+ struct intf_info *info;
+ struct usb_host_endpoint *ep;
+ u8 pcm_card_num, pcm_dev_num, direction;
+ int info_idx = -EINVAL, datainterval = -EINVAL, ret = 0;
+
+ if (!svc->client_connected) {
+ svc->client_sq = *sq;
+ svc->client_connected = true;
+ }
+
+ mutex_lock(&qdev_mutex);
+ req_msg = (struct qmi_uaudio_stream_req_msg_v01 *)decoded_msg;
+ if (!req_msg->audio_format_valid || !req_msg->bit_rate_valid ||
+ !req_msg->number_of_ch_valid || !req_msg->xfer_buff_size_valid) {
+ ret = -EINVAL;
+ goto response;
+ }
+
+ if (!uaudio_qdev) {
+ ret = -EINVAL;
+ goto response;
+ }
+
+ direction = (req_msg->usb_token & QMI_STREAM_REQ_DIRECTION);
+ pcm_dev_num = (req_msg->usb_token & QMI_STREAM_REQ_DEV_NUM_MASK) >> 8;
+ pcm_card_num = req_msg->enable ? uaudio_qdev->last_card_num :
+ ffs(uaudio_qdev->card_slot) - 1;
+ if (pcm_card_num >= SNDRV_CARDS) {
+ ret = -EINVAL;
+ goto response;
+ }
+
+ if (req_msg->audio_format > USB_QMI_PCM_FORMAT_U32_BE) {
+ ret = -EINVAL;
+ goto response;
+ }
+
+ subs = find_substream(pcm_card_num, pcm_dev_num, direction);
+ chip = uadev[pcm_card_num].chip;
+ if (!subs || !chip || atomic_read(&chip->shutdown)) {
+ ret = -ENODEV;
+ goto response;
+ }
+
+ info_idx = info_idx_from_ifnum(pcm_card_num, subs->cur_audiofmt ?
+ subs->cur_audiofmt->iface : -1, req_msg->enable);
+ if (atomic_read(&chip->shutdown) || !subs->stream || !subs->stream->pcm
+ || !subs->stream->chip) {
+ ret = -ENODEV;
+ goto response;
+ }
+
+ if (req_msg->enable) {
+ if (info_idx < 0 || chip->system_suspend) {
+ ret = -EBUSY;
+ goto response;
+ }
+ }
+
+ if (req_msg->service_interval_valid) {
+ ret = get_data_interval_from_si(subs,
+ req_msg->service_interval);
+ if (ret == -EINVAL)
+ goto response;
+
+ datainterval = ret;
+ }
+
+ uadev[pcm_card_num].ctrl_intf = chip->ctrl_intf;
+
+ if (req_msg->enable) {
+ ret = enable_audio_stream(subs,
+ map_pcm_format(req_msg->audio_format),
+ req_msg->number_of_ch, req_msg->bit_rate,
+ datainterval);
+
+ if (!ret)
+ ret = prepare_qmi_response(subs, req_msg, &resp,
+ info_idx);
+ } else {
+ info = &uadev[pcm_card_num].info[info_idx];
+ if (info->data_ep_pipe) {
+ ep = usb_pipe_endpoint(uadev[pcm_card_num].udev,
+ info->data_ep_pipe);
+ if (ep)
+ xhci_sideband_stop_endpoint(uadev[pcm_card_num].sb,
+ ep);
+ xhci_sideband_remove_endpoint(uadev[pcm_card_num].sb, ep);
+ info->data_ep_pipe = 0;
+ }
+
+ if (info->sync_ep_pipe) {
+ ep = usb_pipe_endpoint(uadev[pcm_card_num].udev,
+ info->sync_ep_pipe);
+ if (ep)
+ xhci_sideband_stop_endpoint(uadev[pcm_card_num].sb,
+ ep);
+ xhci_sideband_remove_endpoint(uadev[pcm_card_num].sb, ep);
+ info->sync_ep_pipe = 0;
+ }
+
+ disable_audio_stream(subs);
+ }
+
+response:
+ if (!req_msg->enable && ret != -EINVAL && ret != -ENODEV) {
+ mutex_lock(&chip->mutex);
+ if (info_idx >= 0) {
+ info = &uadev[pcm_card_num].info[info_idx];
+ uaudio_dev_intf_cleanup(
+ uadev[pcm_card_num].udev,
+ info);
+ }
+ if (atomic_read(&uadev[pcm_card_num].in_use))
+ kref_put(&uadev[pcm_card_num].kref,
+ uaudio_dev_release);
+ mutex_unlock(&chip->mutex);
+ }
+ mutex_unlock(&qdev_mutex);
+
+ resp.usb_token = req_msg->usb_token;
+ resp.usb_token_valid = 1;
+ resp.internal_status = ret;
+ resp.internal_status_valid = 1;
+ resp.status = ret ? USB_QMI_STREAM_REQ_FAILURE_V01 : ret;
+ resp.status_valid = 1;
+ ret = qmi_send_response(svc->uaudio_svc_hdl, sq, txn,
+ QMI_UAUDIO_STREAM_RESP_V01,
+ QMI_UAUDIO_STREAM_RESP_MSG_V01_MAX_MSG_LEN,
+ qmi_uaudio_stream_resp_msg_v01_ei, &resp);
+}
+
+static struct qmi_msg_handler uaudio_stream_req_handlers = {
+ .type = QMI_REQUEST,
+ .msg_id = QMI_UAUDIO_STREAM_REQ_V01,
+ .ei = qmi_uaudio_stream_req_msg_v01_ei,
+ .decoded_size = QMI_UAUDIO_STREAM_REQ_MSG_V01_MAX_MSG_LEN,
+ .fn = handle_uaudio_stream_req,
+};
+
+/**
+ * qc_usb_audio_offload_init_qmi_dev() - initializes qmi dev
+ *
+ * Initializes the USB qdev, which is used to carry information pertaining to
+ * the offloading resources. This device is freed only when there are no longer
+ * any offloading candidates. (i.e, when all audio devices are disconnected)
+ *
+ */
+static int qc_usb_audio_offload_init_qmi_dev(struct usb_device *udev)
+{
+ uaudio_qdev = kzalloc(sizeof(struct uaudio_qmi_dev),
+ GFP_KERNEL);
+ if (!uaudio_qdev)
+ return -ENOMEM;
+
+ /* initialize xfer ring and xfer buf iova list */
+ INIT_LIST_HEAD(&uaudio_qdev->xfer_ring_list);
+ uaudio_qdev->curr_xfer_ring_iova = IOVA_XFER_RING_BASE;
+ uaudio_qdev->xfer_ring_iova_size =
+ IOVA_XFER_RING_MAX - IOVA_XFER_RING_BASE;
+
+ INIT_LIST_HEAD(&uaudio_qdev->xfer_buf_list);
+ uaudio_qdev->curr_xfer_buf_iova = IOVA_XFER_BUF_BASE;
+ uaudio_qdev->xfer_buf_iova_size =
+ IOVA_XFER_BUF_MAX - IOVA_XFER_BUF_BASE;
+
+ return 0;
+}
+
+/**
+ * qc_usb_audio_offload_probe() - platform op connect handler
+ * @chip: USB SND device
+ *
+ * Platform connect handler when a USB SND device is detected. Will
+ * notify SOC USB about the connection to enable the USB ASoC backend
+ * and populate internal USB chip array.
+ *
+ */
+static void qc_usb_audio_offload_probe(struct snd_usb_audio *chip)
+{
+ struct usb_device *udev = chip->dev;
+ struct xhci_sideband *sb;
+ struct snd_soc_usb_device *sdev;
+
+ /*
+ * If there is no priv_data, the connected device is on a USB bus
+ * that doesn't support offloading. Avoid populating entries for
+ * this device.
+ */
+ if (!snd_soc_usb_find_priv_data(usb_get_usb_backend(udev)))
+ return;
+
+ mutex_lock(&chip->mutex);
+ if (!uadev[chip->card->number].chip) {
+ sdev = kzalloc(sizeof(*sdev), GFP_KERNEL);
+ if (!sdev)
+ goto exit;
+
+ sb = xhci_sideband_register(udev);
+ if (!sb)
+ goto free_sdev;
+ } else {
+ sb = uadev[chip->card->number].sb;
+ sdev = uadev[chip->card->number].sdev;
+ }
+
+ mutex_lock(&qdev_mutex);
+ if (!uaudio_qdev)
+ qc_usb_audio_offload_init_qmi_dev(udev);
+
+ atomic_inc(&uaudio_qdev->qdev_in_use);
+ mutex_unlock(&qdev_mutex);
+
+ uadev[chip->card->number].sb = sb;
+ uadev[chip->card->number].chip = chip;
+
+ sdev->card_idx = chip->card->number;
+ sdev->chip_idx = chip->index;
+ uadev[chip->card->number].sdev = sdev;
+
+ uaudio_qdev->last_card_num = chip->card->number;
+ snd_soc_usb_connect(usb_get_usb_backend(udev), sdev);
+ mutex_unlock(&chip->mutex);
+
+ return;
+
+free_sdev:
+ kfree(sdev);
+exit:
+ mutex_unlock(&chip->mutex);
+}
+
+/**
+ * qc_usb_audio_cleanup_qmi_dev() - release qmi device
+ *
+ * Frees the USB qdev. Only occurs when there are no longer any potential
+ * devices that can utilize USB audio offloading.
+ *
+ */
+static void qc_usb_audio_cleanup_qmi_dev(void)
+{
+ kfree(uaudio_qdev);
+ uaudio_qdev = NULL;
+}
+
+/**
+ * qc_usb_audio_offload_disconnect() - platform op disconnect handler
+ * @chip: USB SND device
+ *
+ * Platform disconnect handler. Will ensure that any pending stream is
+ * halted by issuing a QMI disconnect indication packet to the adsp.
+ *
+ */
+static void qc_usb_audio_offload_disconnect(struct snd_usb_audio *chip)
+{
+ struct qmi_uaudio_stream_ind_msg_v01 disconnect_ind = {0};
+ struct uaudio_qmi_svc *svc = uaudio_svc;
+ struct uaudio_dev *dev;
+ int card_num;
+ int ret;
+
+ if (!chip)
+ return;
+
+ card_num = chip->card->number;
+ if (card_num >= SNDRV_CARDS)
+ return;
+
+ mutex_lock(&qdev_mutex);
+ mutex_lock(&chip->mutex);
+ dev = &uadev[card_num];
+
+ /* Device has already been cleaned up, or never populated */
+ if (!dev->chip) {
+ mutex_unlock(&qdev_mutex);
+ mutex_unlock(&chip->mutex);
+ return;
+ }
+
+ /* clean up */
+ if (!dev->udev)
+ goto done;
+
+ if (atomic_read(&dev->in_use)) {
+ mutex_unlock(&chip->mutex);
+ mutex_unlock(&qdev_mutex);
+ dev_dbg(uaudio_qdev->dev, "sending qmi indication disconnect\n");
+ disconnect_ind.dev_event = USB_QMI_DEV_DISCONNECT_V01;
+ disconnect_ind.slot_id = dev->udev->slot_id;
+ disconnect_ind.controller_num = dev->usb_core_id;
+ disconnect_ind.controller_num_valid = 1;
+ ret = qmi_send_indication(svc->uaudio_svc_hdl, &svc->client_sq,
+ QMI_UAUDIO_STREAM_IND_V01,
+ QMI_UAUDIO_STREAM_IND_MSG_V01_MAX_MSG_LEN,
+ qmi_uaudio_stream_ind_msg_v01_ei,
+ &disconnect_ind);
+ if (ret < 0)
+ dev_err(uaudio_qdev->dev,
+ "qmi send failed with err: %d\n", ret);
+
+ ret = wait_event_interruptible_timeout(dev->disconnect_wq,
+ !atomic_read(&dev->in_use),
+ msecs_to_jiffies(DEV_RELEASE_WAIT_TIMEOUT));
+ if (!ret) {
+ dev_err(uaudio_qdev->dev,
+ "timeout while waiting for dev_release\n");
+ atomic_set(&dev->in_use, 0);
+ } else if (ret < 0) {
+ dev_err(uaudio_qdev->dev, "failed with ret %d\n", ret);
+ atomic_set(&dev->in_use, 0);
+ }
+ mutex_lock(&qdev_mutex);
+ mutex_lock(&chip->mutex);
+ }
+
+ uaudio_dev_cleanup(dev);
+done:
+ snd_soc_usb_disconnect(usb_get_usb_backend(chip->dev), dev->sdev);
+
+ /*
+ * If num_interfaces == 1, the last USB SND interface is being removed.
+ * This is to accommodate for devices w/ multiple UAC functions.
+ */
+ if (chip->num_interfaces == 1) {
+ xhci_sideband_unregister(dev->sb);
+ dev->chip = NULL;
+ kfree(dev->sdev);
+ dev->sdev = NULL;
+ }
+ mutex_unlock(&chip->mutex);
+
+ atomic_dec(&uaudio_qdev->qdev_in_use);
+ if (!atomic_read(&uaudio_qdev->qdev_in_use)) {
+ snd_soc_usb_disconnect(usb_get_usb_backend(udev));
+ qc_usb_audio_cleanup_qmi_dev();
+ }
+ mutex_unlock(&qdev_mutex);
+}
+
+/**
+ * qc_usb_audio_offload_suspend() - USB offload PM suspend handler
+ * @intf: USB interface
+ * @message: suspend type
+ *
+ * PM suspend handler to ensure that the USB offloading driver is able to stop
+ * any pending traffic, so that the bus can be suspended.
+ *
+ */
+static void qc_usb_audio_offload_suspend(struct usb_interface *intf, pm_message_t message)
+{
+ struct snd_usb_audio *chip = usb_get_intfdata(intf);
+ struct qmi_uaudio_stream_ind_msg_v01 disconnect_ind = {0};
+ struct uaudio_qmi_svc *svc = uaudio_svc;
+ struct uaudio_dev *dev;
+ int card_num;
+ int ret;
+
+ if (!chip)
+ return;
+
+ card_num = chip->card->number;
+ if (card_num >= SNDRV_CARDS)
+ return;
+
+
+ mutex_lock(&chip->mutex);
+ dev = &uadev[card_num];
+
+ if (atomic_read(&dev->in_use)) {
+ mutex_unlock(&chip->mutex);
+ dev_dbg(uaudio_qdev->dev, "sending qmi indication suspend\n");
+ disconnect_ind.dev_event = USB_QMI_DEV_DISCONNECT_V01;
+ disconnect_ind.slot_id = dev->udev->slot_id;
+ disconnect_ind.controller_num = dev->usb_core_id;
+ disconnect_ind.controller_num_valid = 1;
+ ret = qmi_send_indication(svc->uaudio_svc_hdl, &svc->client_sq,
+ QMI_UAUDIO_STREAM_IND_V01,
+ QMI_UAUDIO_STREAM_IND_MSG_V01_MAX_MSG_LEN,
+ qmi_uaudio_stream_ind_msg_v01_ei,
+ &disconnect_ind);
+ if (ret < 0)
+ dev_err(uaudio_qdev->dev,
+ "qmi send failed with err: %d\n", ret);
+
+ ret = wait_event_interruptible_timeout(dev->disconnect_wq,
+ !atomic_read(&dev->in_use),
+ msecs_to_jiffies(DEV_RELEASE_WAIT_TIMEOUT));
+ if (!ret) {
+ dev_err(uaudio_qdev->dev,
+ "timeout while waiting for dev_release\n");
+ atomic_set(&dev->in_use, 0);
+ } else if (ret < 0) {
+ dev_err(uaudio_qdev->dev, "failed with ret %d\n", ret);
+ atomic_set(&dev->in_use, 0);
+ }
+ mutex_lock(&chip->mutex);
+ }
+ mutex_unlock(&chip->mutex);
+}
+
+static struct snd_usb_platform_ops offload_ops = {
+ .connect_cb = qc_usb_audio_offload_probe,
+ .disconnect_cb = qc_usb_audio_offload_disconnect,
+ .suspend_cb = qc_usb_audio_offload_suspend,
+};
+
+static int __init qc_usb_audio_offload_init(void)
+{
+ struct uaudio_qmi_svc *svc;
+ int ret;
+
+ svc = kzalloc(sizeof(struct uaudio_qmi_svc), GFP_KERNEL);
+ if (!svc)
+ return -ENOMEM;
+
+ svc->uaudio_wq = create_singlethread_workqueue("uaudio_svc");
+ if (!svc->uaudio_wq) {
+ ret = -ENOMEM;
+ goto free_svc;
+ }
+
+ svc->uaudio_svc_hdl = kzalloc(sizeof(struct qmi_handle), GFP_KERNEL);
+ if (!svc->uaudio_svc_hdl) {
+ ret = -ENOMEM;
+ goto free_wq;
+ }
+
+ ret = qmi_handle_init(svc->uaudio_svc_hdl,
+ QMI_UAUDIO_STREAM_REQ_MSG_V01_MAX_MSG_LEN,
+ &uaudio_svc_ops_options,
+ &uaudio_stream_req_handlers);
+ ret = qmi_add_server(svc->uaudio_svc_hdl, UAUDIO_STREAM_SERVICE_ID_V01,
+ UAUDIO_STREAM_SERVICE_VERS_V01, 0);
+
+ INIT_WORK(&svc->qmi_disconnect_work, qmi_disconnect_work);
+ uaudio_svc = svc;
+
+ ret = snd_usb_register_platform_ops(&offload_ops);
+ if (ret < 0)
+ goto release_qmi;
+
+ return 0;
+
+release_qmi:
+ qmi_handle_release(svc->uaudio_svc_hdl);
+free_wq:
+ destroy_workqueue(svc->uaudio_wq);
+free_svc:
+ kfree(svc);
+
+ return ret;
+}
+
+static void __exit qc_usb_audio_offload_exit(void)
+{
+ struct uaudio_qmi_svc *svc = uaudio_svc;
+ int idx;
+
+ /*
+ * Remove all connected devices after unregistering ops, to ensure
+ * that no further connect events will occur. The disconnect routine
+ * will issue the QMI disconnect indication, which results in the
+ * external DSP to stop issuing transfers.
+ */
+ snd_usb_unregister_platform_ops();
+ for (idx = 0; idx < SNDRV_CARDS; idx++)
+ qc_usb_audio_offload_disconnect(uadev[idx].chip);
+
+ qmi_handle_release(svc->uaudio_svc_hdl);
+ flush_workqueue(svc->uaudio_wq);
+ destroy_workqueue(svc->uaudio_wq);
+ kfree(svc);
+ uaudio_svc = NULL;
+}
+
+module_init(qc_usb_audio_offload_init);
+module_exit(qc_usb_audio_offload_exit);
+
+MODULE_DESCRIPTION("QC USB Audio Offloading");
+MODULE_LICENSE("GPL");

2023-10-17 20:04:57

by Wesley Cheng

[permalink] [raw]
Subject: [PATCH v9 02/34] xhci: add support to allocate several interrupters

From: Mathias Nyman <[email protected]>

Modify the XHCI drivers to accommodate for handling multiple event rings in
case there are multiple interrupters. Add the required APIs so clients are
able to allocate/request for an interrupter ring, and pass this information
back to the client driver. This allows for users to handle the resource
accordingly, such as passing the event ring base address to an audio DSP.
There is no actual support for multiple MSI/MSI-X vectors.

Signed-off-by: Mathias Nyman <[email protected]>
Signed-off-by: Wesley Cheng <[email protected]>
---
drivers/usb/host/xhci-debugfs.c | 2 +-
drivers/usb/host/xhci-mem.c | 99 ++++++++++++++++++++++++++++++---
drivers/usb/host/xhci-ring.c | 2 +-
drivers/usb/host/xhci.c | 51 +++++++++++------
drivers/usb/host/xhci.h | 5 +-
5 files changed, 130 insertions(+), 29 deletions(-)

diff --git a/drivers/usb/host/xhci-debugfs.c b/drivers/usb/host/xhci-debugfs.c
index 99baa60ef50f..15a8402ee8a1 100644
--- a/drivers/usb/host/xhci-debugfs.c
+++ b/drivers/usb/host/xhci-debugfs.c
@@ -693,7 +693,7 @@ void xhci_debugfs_init(struct xhci_hcd *xhci)
"command-ring",
xhci->debugfs_root);

- xhci_debugfs_create_ring_dir(xhci, &xhci->interrupter->event_ring,
+ xhci_debugfs_create_ring_dir(xhci, &xhci->interrupters[0]->event_ring,
"event-ring",
xhci->debugfs_root);

diff --git a/drivers/usb/host/xhci-mem.c b/drivers/usb/host/xhci-mem.c
index 0994ca9fba44..ded105a23cce 100644
--- a/drivers/usb/host/xhci-mem.c
+++ b/drivers/usb/host/xhci-mem.c
@@ -1846,6 +1846,31 @@ xhci_free_interrupter(struct xhci_hcd *xhci, struct xhci_interrupter *ir)
kfree(ir);
}

+void xhci_remove_secondary_interrupter(struct usb_hcd *hcd, struct xhci_interrupter *ir)
+{
+ struct xhci_hcd *xhci = hcd_to_xhci(hcd);
+ unsigned int intr_num;
+
+ /* interrupter 0 is primary interrupter, don't touch it */
+ if (!ir || !ir->intr_num || ir->intr_num >= xhci->max_interrupters)
+ xhci_dbg(xhci, "Invalid secondary interrupter, can't remove\n");
+
+ /* fixme, should we check xhci->interrupter[intr_num] == ir */
+ /* fixme locking */
+
+ spin_lock_irq(&xhci->lock);
+
+ intr_num = ir->intr_num;
+
+ xhci_remove_interrupter(xhci, ir);
+ xhci->interrupters[intr_num] = NULL;
+
+ spin_unlock_irq(&xhci->lock);
+
+ xhci_free_interrupter(xhci, ir);
+}
+EXPORT_SYMBOL_GPL(xhci_remove_secondary_interrupter);
+
void xhci_mem_cleanup(struct xhci_hcd *xhci)
{
struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
@@ -1853,10 +1878,14 @@ void xhci_mem_cleanup(struct xhci_hcd *xhci)

cancel_delayed_work_sync(&xhci->cmd_timer);

- xhci_remove_interrupter(xhci, xhci->interrupter);
- xhci_free_interrupter(xhci, xhci->interrupter);
- xhci->interrupter = NULL;
- xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Freed primary event ring");
+ for (i = 0; i < xhci->max_interrupters; i++) {
+ if (xhci->interrupters[i]) {
+ xhci_remove_interrupter(xhci, xhci->interrupters[i]);
+ xhci_free_interrupter(xhci, xhci->interrupters[i]);
+ xhci->interrupters[i] = NULL;
+ }
+ }
+ xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Freed interrupters");

if (xhci->cmd_ring)
xhci_ring_free(xhci, xhci->cmd_ring);
@@ -1926,6 +1955,7 @@ void xhci_mem_cleanup(struct xhci_hcd *xhci)
for (i = 0; i < xhci->num_port_caps; i++)
kfree(xhci->port_caps[i].psi);
kfree(xhci->port_caps);
+ kfree(xhci->interrupters);
xhci->num_port_caps = 0;

xhci->usb2_rhub.ports = NULL;
@@ -1934,6 +1964,7 @@ void xhci_mem_cleanup(struct xhci_hcd *xhci)
xhci->rh_bw = NULL;
xhci->ext_caps = NULL;
xhci->port_caps = NULL;
+ xhci->interrupters = NULL;

xhci->page_size = 0;
xhci->page_shift = 0;
@@ -2286,6 +2317,13 @@ xhci_add_interrupter(struct xhci_hcd *xhci, struct xhci_interrupter *ir,
return -EINVAL;
}

+ if (xhci->interrupters[intr_num]) {
+ xhci_warn(xhci, "Interrupter %d\n already set up", intr_num);
+ return -EINVAL;
+ }
+
+ xhci->interrupters[intr_num] = ir;
+ ir->intr_num = intr_num;
ir->ir_set = &xhci->run_regs->ir_set[intr_num];

/* set ERST count with the number of entries in the segment table */
@@ -2305,10 +2343,52 @@ xhci_add_interrupter(struct xhci_hcd *xhci, struct xhci_interrupter *ir,
return 0;
}

+struct xhci_interrupter *
+xhci_create_secondary_interrupter(struct usb_hcd *hcd)
+{
+ struct xhci_hcd *xhci = hcd_to_xhci(hcd);
+ struct xhci_interrupter *ir;
+ unsigned int i;
+ int err = -ENOSPC;
+
+ if (!xhci->interrupters)
+ return NULL;
+
+ ir = xhci_alloc_interrupter(xhci, GFP_KERNEL);
+ if (!ir)
+ return NULL;
+
+ spin_lock_irq(&xhci->lock);
+
+ /* Find available secondary interrupter, interrupter 0 is reserved for primary */
+ for (i = 1; i < xhci->max_interrupters; i++) {
+ if (xhci->interrupters[i] == NULL) {
+ err = xhci_add_interrupter(xhci, ir, i);
+ break;
+ }
+ }
+
+ spin_unlock_irq(&xhci->lock);
+
+ if (err) {
+ xhci_warn(xhci, "Failed to add secondary interrupter, max interrupters %d\n",
+ xhci->max_interrupters);
+ xhci_free_interrupter(xhci, ir);
+ return NULL;
+ }
+
+ xhci_dbg(xhci, "Add secondary interrupter %d, max interrupters %d\n",
+ i, xhci->max_interrupters);
+
+ return ir;
+}
+EXPORT_SYMBOL_GPL(xhci_create_secondary_interrupter);
+
int xhci_mem_init(struct xhci_hcd *xhci, gfp_t flags)
{
- dma_addr_t dma;
+ struct xhci_interrupter *ir;
struct device *dev = xhci_to_hcd(xhci)->self.sysdev;
+ dma_addr_t dma;
unsigned int val, val2;
u64 val_64;
u32 page_size, temp;
@@ -2432,11 +2512,14 @@ int xhci_mem_init(struct xhci_hcd *xhci, gfp_t flags)
/* Allocate and set up primary interrupter 0 with an event ring. */
xhci_dbg_trace(xhci, trace_xhci_dbg_init,
"Allocating primary event ring");
- xhci->interrupter = xhci_alloc_interrupter(xhci, flags);
- if (!xhci->interrupter)
+ xhci->interrupters = kcalloc_node(xhci->max_interrupters, sizeof(*xhci->interrupters),
+ flags, dev_to_node(dev));
+
+ ir = xhci_alloc_interrupter(xhci, flags);
+ if (!ir)
goto fail;

- if (xhci_add_interrupter(xhci, xhci->interrupter, 0))
+ if (xhci_add_interrupter(xhci, ir, 0))
goto fail;

xhci->isoc_bei_interval = AVOID_BEI_INTERVAL_MAX;
diff --git a/drivers/usb/host/xhci-ring.c b/drivers/usb/host/xhci-ring.c
index 3e5dc0723a8f..d6fd1588cb67 100644
--- a/drivers/usb/host/xhci-ring.c
+++ b/drivers/usb/host/xhci-ring.c
@@ -3076,7 +3076,7 @@ irqreturn_t xhci_irq(struct usb_hcd *hcd)
writel(status, &xhci->op_regs->status);

/* This is the handler of the primary interrupter */
- ir = xhci->interrupter;
+ ir = xhci->interrupters[0];
if (!hcd->msi_enabled) {
u32 irq_pending;
irq_pending = readl(&ir->ir_set->irq_pending);
diff --git a/drivers/usb/host/xhci.c b/drivers/usb/host/xhci.c
index e1b1b64a0723..2c7b888d44fc 100644
--- a/drivers/usb/host/xhci.c
+++ b/drivers/usb/host/xhci.c
@@ -456,7 +456,7 @@ static int xhci_init(struct usb_hcd *hcd)

static int xhci_run_finished(struct xhci_hcd *xhci)
{
- struct xhci_interrupter *ir = xhci->interrupter;
+ struct xhci_interrupter *ir = xhci->interrupters[0];
unsigned long flags;
u32 temp;

@@ -508,7 +508,7 @@ int xhci_run(struct usb_hcd *hcd)
u64 temp_64;
int ret;
struct xhci_hcd *xhci = hcd_to_xhci(hcd);
- struct xhci_interrupter *ir = xhci->interrupter;
+ struct xhci_interrupter *ir = xhci->interrupters[0];
/* Start the xHCI host controller running only after the USB 2.0 roothub
* is setup.
*/
@@ -572,7 +572,7 @@ void xhci_stop(struct usb_hcd *hcd)
{
u32 temp;
struct xhci_hcd *xhci = hcd_to_xhci(hcd);
- struct xhci_interrupter *ir = xhci->interrupter;
+ struct xhci_interrupter *ir = xhci->interrupters[0];

mutex_lock(&xhci->mutex);

@@ -668,36 +668,51 @@ EXPORT_SYMBOL_GPL(xhci_shutdown);
#ifdef CONFIG_PM
static void xhci_save_registers(struct xhci_hcd *xhci)
{
- struct xhci_interrupter *ir = xhci->interrupter;
+ struct xhci_interrupter *ir;
+ unsigned int i;

xhci->s3.command = readl(&xhci->op_regs->command);
xhci->s3.dev_nt = readl(&xhci->op_regs->dev_notification);
xhci->s3.dcbaa_ptr = xhci_read_64(xhci, &xhci->op_regs->dcbaa_ptr);
xhci->s3.config_reg = readl(&xhci->op_regs->config_reg);

- if (!ir)
- return;
+ /* save both primary and all secondary interrupters */
+ /* fixme, shold we lock to prevent race with remove secondary interrupter? */
+ for (i = 0; i < xhci->max_interrupters; i++) {
+ ir = xhci->interrupters[i];
+ if (!ir)
+ continue;

- ir->s3_erst_size = readl(&ir->ir_set->erst_size);
- ir->s3_erst_base = xhci_read_64(xhci, &ir->ir_set->erst_base);
- ir->s3_erst_dequeue = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
- ir->s3_irq_pending = readl(&ir->ir_set->irq_pending);
- ir->s3_irq_control = readl(&ir->ir_set->irq_control);
+ ir->s3_erst_size = readl(&ir->ir_set->erst_size);
+ ir->s3_erst_base = xhci_read_64(xhci, &ir->ir_set->erst_base);
+ ir->s3_erst_dequeue = xhci_read_64(xhci, &ir->ir_set->erst_dequeue);
+ ir->s3_irq_pending = readl(&ir->ir_set->irq_pending);
+ ir->s3_irq_control = readl(&ir->ir_set->irq_control);
+ }
}

static void xhci_restore_registers(struct xhci_hcd *xhci)
{
- struct xhci_interrupter *ir = xhci->interrupter;
+ struct xhci_interrupter *ir;
+ unsigned int i;

writel(xhci->s3.command, &xhci->op_regs->command);
writel(xhci->s3.dev_nt, &xhci->op_regs->dev_notification);
xhci_write_64(xhci, xhci->s3.dcbaa_ptr, &xhci->op_regs->dcbaa_ptr);
writel(xhci->s3.config_reg, &xhci->op_regs->config_reg);
- writel(ir->s3_erst_size, &ir->ir_set->erst_size);
- xhci_write_64(xhci, ir->s3_erst_base, &ir->ir_set->erst_base);
- xhci_write_64(xhci, ir->s3_erst_dequeue, &ir->ir_set->erst_dequeue);
- writel(ir->s3_irq_pending, &ir->ir_set->irq_pending);
- writel(ir->s3_irq_control, &ir->ir_set->irq_control);
+
+ /* FIXME should we lock to protect against freeing of interrupters */
+ for (i = 0; i < xhci->max_interrupters; i++) {
+ ir = xhci->interrupters[i];
+ if (!ir)
+ continue;
+
+ writel(ir->s3_erst_size, &ir->ir_set->erst_size);
+ xhci_write_64(xhci, ir->s3_erst_base, &ir->ir_set->erst_base);
+ xhci_write_64(xhci, ir->s3_erst_dequeue, &ir->ir_set->erst_dequeue);
+ writel(ir->s3_irq_pending, &ir->ir_set->irq_pending);
+ writel(ir->s3_irq_control, &ir->ir_set->irq_control);
+ }
}

static void xhci_set_cmd_ring_deq(struct xhci_hcd *xhci)
@@ -1059,7 +1074,7 @@ int xhci_resume(struct xhci_hcd *xhci, pm_message_t msg)
xhci_dbg(xhci, "// Disabling event ring interrupts\n");
temp = readl(&xhci->op_regs->status);
writel((temp & ~0x1fff) | STS_EINT, &xhci->op_regs->status);
- xhci_disable_interrupter(xhci->interrupter);
+ xhci_disable_interrupter(xhci->interrupters[0]);

xhci_dbg(xhci, "cleaning up memory\n");
xhci_mem_cleanup(xhci);
diff --git a/drivers/usb/host/xhci.h b/drivers/usb/host/xhci.h
index 8342076cb309..97e313d8a03c 100644
--- a/drivers/usb/host/xhci.h
+++ b/drivers/usb/host/xhci.h
@@ -1772,7 +1772,7 @@ struct xhci_hcd {
struct reset_control *reset;
/* data structures */
struct xhci_device_context_array *dcbaa;
- struct xhci_interrupter *interrupter;
+ struct xhci_interrupter **interrupters;
struct xhci_ring *cmd_ring;
unsigned int cmd_ring_state;
#define CMD_RING_STATE_RUNNING (1 << 0)
@@ -2088,6 +2088,9 @@ struct xhci_container_ctx *xhci_alloc_container_ctx(struct xhci_hcd *xhci,
int type, gfp_t flags);
void xhci_free_container_ctx(struct xhci_hcd *xhci,
struct xhci_container_ctx *ctx);
+struct xhci_interrupter *xhci_create_secondary_interrupter(struct usb_hcd *hcd);
+void xhci_remove_secondary_interrupter(struct usb_hcd
+ *hcd, struct xhci_interrupter *ir);

/* xHCI host controller glue */
typedef void (*xhci_get_quirks_t)(struct device *, struct xhci_hcd *);

2023-10-17 20:05:06

by Wesley Cheng

[permalink] [raw]
Subject: [PATCH v9 04/34] xhci: sideband: add initial api to register a sideband entity

From: Mathias Nyman <[email protected]>

Introduce XHCI sideband, which manages the USB endpoints being requested by
a client driver. This is used for when client drivers are attempting to
offload USB endpoints to another entity for handling USB transfers. XHCI
sideband will allow for drivers to fetch the required information about the
transfer ring, so the user can submit transfers independently. Expose the
required APIs for drivers to register and request for a USB endpoint and to
manage XHCI secondary interrupters.

Multiple ring segment page linking and proper endpoint clean up added by
Wesley Cheng to complete original concept code by Mathias Nyman.

Signed-off-by: Mathias Nyman <[email protected]>
Co-developed-by: Wesley Cheng <[email protected]>
Signed-off-by: Wesley Cheng <[email protected]>
---
drivers/usb/host/Kconfig | 9 +
drivers/usb/host/Makefile | 4 +
drivers/usb/host/xhci-sideband.c | 371 ++++++++++++++++++++++++++++++
drivers/usb/host/xhci.h | 4 +
include/linux/usb/xhci-sideband.h | 66 ++++++
5 files changed, 454 insertions(+)
create mode 100644 drivers/usb/host/xhci-sideband.c
create mode 100644 include/linux/usb/xhci-sideband.h

diff --git a/drivers/usb/host/Kconfig b/drivers/usb/host/Kconfig
index 4448d0ab06f0..923af11c1982 100644
--- a/drivers/usb/host/Kconfig
+++ b/drivers/usb/host/Kconfig
@@ -104,6 +104,15 @@ config USB_XHCI_RZV2M
Say 'Y' to enable the support for the xHCI host controller
found in Renesas RZ/V2M SoC.

+config USB_XHCI_SIDEBAND
+ bool "xHCI support for sideband"
+ help
+ Say 'Y' to enable the support for the xHCI sideband capability.
+ provide a mechanism for a sideband datapath for payload associated
+ with audio class endpoints. This allows for an audio DSP to use
+ xHCI USB endpoints directly, allowing CPU to sleep while playing
+ audio
+
config USB_XHCI_TEGRA
tristate "xHCI support for NVIDIA Tegra SoCs"
depends on PHY_TEGRA_XUSB
diff --git a/drivers/usb/host/Makefile b/drivers/usb/host/Makefile
index be4e5245c52f..4df946c05ba0 100644
--- a/drivers/usb/host/Makefile
+++ b/drivers/usb/host/Makefile
@@ -32,6 +32,10 @@ endif
xhci-rcar-hcd-y += xhci-rcar.o
xhci-rcar-hcd-$(CONFIG_USB_XHCI_RZV2M) += xhci-rzv2m.o

+ifneq ($(CONFIG_USB_XHCI_SIDEBAND),)
+ xhci-hcd-y += xhci-sideband.o
+endif
+
obj-$(CONFIG_USB_PCI) += pci-quirks.o

obj-$(CONFIG_USB_EHCI_HCD) += ehci-hcd.o
diff --git a/drivers/usb/host/xhci-sideband.c b/drivers/usb/host/xhci-sideband.c
new file mode 100644
index 000000000000..cc4f90375e00
--- /dev/null
+++ b/drivers/usb/host/xhci-sideband.c
@@ -0,0 +1,371 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/*
+ * xHCI host controller sideband support
+ *
+ * Copyright (c) 2023, Intel Corporation.
+ *
+ * Author: Mathias Nyman
+ */
+
+#include <linux/usb/xhci-sideband.h>
+#include <linux/dma-direct.h>
+
+#include "xhci.h"
+
+/* sideband internal helpers */
+static struct sg_table *
+xhci_ring_to_sgtable(struct xhci_sideband *sb, struct xhci_ring *ring)
+{
+ struct xhci_segment *seg;
+ struct sg_table *sgt;
+ unsigned int n_pages;
+ struct page **pages;
+ struct device *dev;
+ size_t sz;
+ int i;
+
+ dev = xhci_to_hcd(sb->xhci)->self.sysdev;
+ sz = ring->num_segs * TRB_SEGMENT_SIZE;
+ n_pages = PAGE_ALIGN(sz) >> PAGE_SHIFT;
+ pages = kvmalloc_array(n_pages, sizeof(struct page *), GFP_KERNEL);
+ if (!pages)
+ return NULL;
+
+ sgt = kzalloc(sizeof(struct sg_table), GFP_KERNEL);
+ if (!sgt) {
+ kvfree(pages);
+ return NULL;
+ }
+
+ seg = ring->first_seg;
+ /*
+ * Rings can potentially have multiple segments, create an array that
+ * carries page references to allocated segments. Utilize the
+ * sg_alloc_table_from_pages() to create the sg table, and to ensure
+ * that page links are created.
+ */
+ for (i = 0; i < ring->num_segs; i++) {
+ dma_get_sgtable(dev, sgt, seg->trbs, seg->dma,
+ TRB_SEGMENT_SIZE);
+ pages[i] = sg_page(sgt->sgl);
+ sg_free_table(sgt);
+ seg = seg->next;
+ }
+
+ if (sg_alloc_table_from_pages(sgt, pages, n_pages, 0, sz, GFP_KERNEL)) {
+ kvfree(pages);
+ kfree(sgt);
+
+ return NULL;
+ }
+ /*
+ * Save first segment dma address to sg dma_address field for the sideband
+ * client to have access to the IOVA of the ring.
+ */
+ sg_dma_address(sgt->sgl) = ring->first_seg->dma;
+
+ return sgt;
+}
+
+static void
+__xhci_sideband_remove_endpoint(struct xhci_sideband *sb, struct xhci_virt_ep *ep)
+{
+ /*
+ * Issue a stop endpoint command when an endpoint is removed.
+ * The stop ep cmd handler will handle the ring cleanup.
+ */
+ xhci_stop_endpoint_sync(sb->xhci, ep, 0, GFP_KERNEL);
+
+ ep->sideband = NULL;
+ sb->eps[ep->ep_index] = NULL;
+}
+
+/* sideband api functions */
+
+/**
+ * xhci_sideband_add_endpoint - add endpoint to sideband access list
+ * @sb: sideband instance for this usb device
+ * @host_ep: usb host endpoint
+ *
+ * Adds an endpoint to the list of sideband accessed endpoints for this usb
+ * device.
+ * After an endpoint is added the sideband client can get the endpoint transfer
+ * ring buffer by calling xhci_sideband_endpoint_buffer()
+ *
+ * Return: 0 on success, negative error otherwise.
+ */
+int
+xhci_sideband_add_endpoint(struct xhci_sideband *sb,
+ struct usb_host_endpoint *host_ep)
+{
+ struct xhci_virt_ep *ep;
+ unsigned int ep_index;
+
+ ep_index = xhci_get_endpoint_index(&host_ep->desc);
+ ep = &sb->vdev->eps[ep_index];
+
+ if (ep->ep_state & EP_HAS_STREAMS)
+ return -EINVAL;
+
+ /*
+ * Note, we don't know the DMA mask of the audio DSP device, if its
+ * smaller than for xhci it won't be able to access the endpoint ring
+ * buffer. This could be solved by not allowing the audio class driver
+ * to add the endpoint the normal way, but instead offload it immediately,
+ * and let this function add the endpoint and allocate the ring buffer
+ * with the smallest common DMA mask
+ */
+
+ if (sb->eps[ep_index] || ep->sideband)
+ return -EBUSY;
+
+ ep->sideband = sb;
+ sb->eps[ep_index] = ep;
+
+ return 0;
+}
+EXPORT_SYMBOL_GPL(xhci_sideband_add_endpoint);
+
+/**
+ * xhci_sideband_remove_endpoint - remove endpoint from sideband access list
+ * @sb: sideband instance for this usb device
+ * @host_ep: usb host endpoint
+ *
+ * Removes an endpoint from the list of sideband accessed endpoints for this usb
+ * device.
+ * sideband client should no longer touch the endpoint transfer buffer after
+ * calling this.
+ *
+ * Return: 0 on success, negative error otherwise.
+ */
+int
+xhci_sideband_remove_endpoint(struct xhci_sideband *sb,
+ struct usb_host_endpoint *host_ep)
+{
+ struct xhci_virt_ep *ep;
+ unsigned int ep_index;
+
+ ep_index = xhci_get_endpoint_index(&host_ep->desc);
+ ep = sb->eps[ep_index];
+
+ if (!ep || !ep->sideband)
+ return -ENODEV;
+
+ __xhci_sideband_remove_endpoint(sb, ep);
+ xhci_initialize_ring_info(ep->ring, 1);
+
+ return 0;
+}
+EXPORT_SYMBOL_GPL(xhci_sideband_remove_endpoint);
+
+int
+xhci_sideband_stop_endpoint(struct xhci_sideband *sb,
+ struct usb_host_endpoint *host_ep)
+{
+ struct xhci_virt_ep *ep;
+ unsigned int ep_index;
+
+ ep_index = xhci_get_endpoint_index(&host_ep->desc);
+ ep = sb->eps[ep_index];
+
+ if (!ep || ep->sideband != sb)
+ return -EINVAL;
+
+ return xhci_stop_endpoint_sync(sb->xhci, ep, 0);
+}
+EXPORT_SYMBOL_GPL(xhci_sideband_stop_endpoint);
+
+/**
+ * xhci_sideband_get_endpoint_buffer - gets the endpoint transfer buffer address
+ * @sb: sideband instance for this usb device
+ * @host_ep: usb host endpoint
+ *
+ * Returns the address of the endpoint buffer where xHC controller reads queued
+ * transfer TRBs from. This is the starting address of the ringbuffer where the
+ * sidband cliend should write TRBs to.
+ *
+ * Caller needs to free the returned sg_table
+ *
+ * Return: struct sg_table * if successful. NULL otherwise.
+ */
+struct sg_table *
+xhci_sideband_get_endpoint_buffer(struct xhci_sideband *sb,
+ struct usb_host_endpoint *host_ep)
+{
+ struct xhci_virt_ep *ep;
+ unsigned int ep_index;
+
+ ep_index = xhci_get_endpoint_index(&host_ep->desc);
+ ep = sb->eps[ep_index];
+
+ if (!ep)
+ return NULL;
+
+ return xhci_ring_to_sgtable(sb, ep->ring);
+}
+EXPORT_SYMBOL_GPL(xhci_sideband_get_endpoint_buffer);
+
+/**
+ * xhci_sideband_get_event_buffer - return the event buffer for this device
+ * @sb: sideband instance for this usb device
+ *
+ * If a secondary xhci interupter is set up for this usb device then this
+ * function returns the address of the event buffer where xHC writes
+ * the transfer completion events.
+ *
+ * Caller needs to free the returned sg_table
+ *
+ * Return: struct sg_table * if successful. NULL otherwise.
+ */
+struct sg_table *
+xhci_sideband_get_event_buffer(struct xhci_sideband *sb)
+{
+ if (!sb->ir)
+ return NULL;
+
+ return xhci_ring_to_sgtable(sb, sb->ir->event_ring);
+}
+EXPORT_SYMBOL_GPL(xhci_sideband_get_event_buffer);
+
+/**
+ * xhci_sideband_create_interrupter - creates a new interrupter for this sideband
+ * @sb: sideband instance for this usb device
+ *
+ * Sets up a xhci interrupter that can be used for this sideband accessed usb
+ * device. Transfer events for this device can be routed to this interrupters
+ * event ring by setting the 'Interrupter Target' field correctly when queueing
+ * the transfer TRBs.
+ * Once this interrupter is created the interrupter target ID can be obtained
+ * by calling xhci_sideband_interrupter_id()
+ *
+ * Returns 0 on success, negative error otherwise
+ */
+int
+xhci_sideband_create_interrupter(struct xhci_sideband *sb)
+{
+ if (sb->ir)
+ return -EBUSY;
+
+ sb->ir = xhci_create_secondary_interrupter(xhci_to_hcd(sb->xhci));
+ if (!sb->ir)
+ return -ENOMEM;
+
+ return 0;
+}
+EXPORT_SYMBOL_GPL(xhci_sideband_create_interrupter);
+
+/**
+ * xhci_sideband_remove_interrupter - remove the interrupter from a sideband
+ * @sb: sideband instance for this usb device
+ *
+ * Removes a registered interrupt for a sideband. This would allow for other
+ * sideband users to utilize this interrupter.
+ */
+void
+xhci_sideband_remove_interrupter(struct xhci_sideband *sb)
+{
+ if (!sb || !sb->ir)
+ return;
+
+ xhci_remove_secondary_interrupter(xhci_to_hcd(sb->xhci), sb->ir);
+
+ sb->ir = NULL;
+}
+EXPORT_SYMBOL_GPL(xhci_sideband_remove_interrupter);
+
+/**
+ * xhci_sideband_interrupter_id - return the interrupter target id
+ * @sb: sideband instance for this usb device
+ *
+ * If a secondary xhci interrupter is set up for this usb device then this
+ * function returns the ID used by the interrupter. The sideband client
+ * needs to write this ID to the 'Interrupter Target' field of the transfer TRBs
+ * it queues on the endpoints transfer ring to ensure transfer completion event
+ * are written by xHC to the correct interrupter event ring.
+ *
+ * Returns interrupter id on success, negative error othgerwise
+ */
+int
+xhci_sideband_interrupter_id(struct xhci_sideband *sb)
+{
+ if (!sb || !sb->ir)
+ return -ENODEV;
+
+ return sb->ir->intr_num;
+}
+EXPORT_SYMBOL_GPL(xhci_sideband_interrupter_id);
+
+/**
+ * xhci_sideband_register - register a sideband for a usb device
+ * @udev: usb device to be accessed via sideband
+ *
+ * Allows for clients to utilize XHCI interrupters and fetch transfer and event
+ * ring parameters for executing data transfers.
+ *
+ * Return: pointer to a new xhci_sideband instance if successful. NULL otherwise.
+ */
+struct xhci_sideband *
+xhci_sideband_register(struct usb_device *udev)
+{
+ struct usb_hcd *hcd = bus_to_hcd(udev->bus);
+ struct xhci_hcd *xhci = hcd_to_xhci(hcd);
+ struct xhci_virt_device *vdev;
+ struct xhci_sideband *sb;
+
+ /* make sure the usb device is connected to a xhci controller */
+ if (!udev->slot_id)
+ return NULL;
+
+ sb = kzalloc_node(sizeof(*sb), GFP_KERNEL, dev_to_node(hcd->self.sysdev));
+ if (!sb)
+ return NULL;
+
+ /* check this device isn't already controlled via sideband */
+ spin_lock_irq(&xhci->lock);
+
+ vdev = xhci->devs[udev->slot_id];
+
+ if (!vdev || vdev->sideband) {
+ xhci_warn(xhci, "XHCI sideband for slot %d already in use\n",
+ udev->slot_id);
+ spin_unlock_irq(&xhci->lock);
+ kfree(sb);
+ return NULL;
+ }
+
+ sb->xhci = xhci;
+ sb->vdev = vdev;
+ vdev->sideband = sb;
+
+ spin_unlock_irq(&xhci->lock);
+
+ return sb;
+}
+EXPORT_SYMBOL_GPL(xhci_sideband_register);
+
+/**
+ * xhci_sideband_unregister - unregister sideband access to a usb device
+ * @sb: sideband instance to be unregistered
+ *
+ * Unregisters sideband access to a usb device and frees the sideband
+ * instance.
+ * After this the endpoint and interrupter event buffers should no longer
+ * be accessed via sideband. The xhci driver can now take over handling
+ * the buffers.
+ */
+void
+xhci_sideband_unregister(struct xhci_sideband *sb)
+{
+ int i;
+
+ for (i = 0; i < EP_CTX_PER_DEV; i++)
+ if (sb->eps[i])
+ __xhci_sideband_remove_endpoint(sb, sb->eps[i]);
+
+ xhci_sideband_remove_interrupter(sb);
+
+ sb->vdev->sideband = NULL;
+ kfree(sb);
+}
+EXPORT_SYMBOL_GPL(xhci_sideband_unregister);
diff --git a/drivers/usb/host/xhci.h b/drivers/usb/host/xhci.h
index 4b8caaed6f95..339d37c3a3d9 100644
--- a/drivers/usb/host/xhci.h
+++ b/drivers/usb/host/xhci.h
@@ -947,6 +947,8 @@ struct xhci_virt_ep {
int next_frame_id;
/* Use new Isoch TRB layout needed for extended TBC support */
bool use_extended_tbc;
+ /* set if this endpoint is controlled via sideband access*/
+ struct xhci_sideband *sideband;
};

enum xhci_overhead_type {
@@ -1010,6 +1012,8 @@ struct xhci_virt_device {
u16 current_mel;
/* Used for the debugfs interfaces. */
void *debugfs_private;
+ /* set if this device is registered for sideband access */
+ struct xhci_sideband *sideband;
};

/*
diff --git a/include/linux/usb/xhci-sideband.h b/include/linux/usb/xhci-sideband.h
new file mode 100644
index 000000000000..c1457d1800f4
--- /dev/null
+++ b/include/linux/usb/xhci-sideband.h
@@ -0,0 +1,66 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * xHCI host controller sideband support
+ *
+ * Copyright (c) 2023, Intel Corporation.
+ *
+ * Author: Mathias Nyman <[email protected]>
+ */
+
+#ifndef __LINUX_XHCI_SIDEBAND_H
+#define __LINUX_XHCI_SIDEBAND_H
+
+#include <linux/scatterlist.h>
+#include <linux/usb.h>
+
+#define EP_CTX_PER_DEV 31 /* FIMXME defined twice, from xhci.h */
+
+struct xhci_sideband;
+
+/**
+ * struct xhci_sideband - representation of a sideband accessed usb device.
+ * @xhci: The xhci host controller the usb device is connected to
+ * @vdev: the usb device accessed via sideband
+ * @eps: array of endpoints controlled via sideband
+ * @ir: event handling and buffer for sideband accessed device
+ *
+ * FIXME usb device accessed via sideband Keeping track of sideband accessed usb devices.
+ */
+
+struct xhci_sideband {
+ struct xhci_hcd *xhci;
+ struct xhci_virt_device *vdev;
+ struct xhci_virt_ep *eps[EP_CTX_PER_DEV];
+ struct xhci_interrupter *ir;
+};
+
+struct xhci_sideband *
+xhci_sideband_register(struct usb_device *udev);
+void
+xhci_sideband_unregister(struct xhci_sideband *sb);
+int
+xhci_sideband_add_endpoint(struct xhci_sideband *sb,
+ struct usb_host_endpoint *host_ep);
+int
+xhci_sideband_remove_endpoint(struct xhci_sideband *sb,
+ struct usb_host_endpoint *host_ep);
+int
+xhci_sideband_stop_endpoint(struct xhci_sideband *sb,
+ struct usb_host_endpoint *host_ep);
+struct sg_table *
+xhci_sideband_get_endpoint_buffer(struct xhci_sideband *sb,
+ struct usb_host_endpoint *host_ep);
+struct sg_table *
+xhci_sideband_get_event_buffer(struct xhci_sideband *sb);
+
+int
+xhci_sideband_create_interrupter(struct xhci_sideband *sb);
+
+void
+xhci_sideband_remove_interrupter(struct xhci_sideband *sb);
+
+int
+xhci_sideband_interrupter_id(struct xhci_sideband *sb);
+
+#endif /* __LINUX_XHCI_SIDEBAND_H */
+

2023-10-17 20:05:16

by Wesley Cheng

[permalink] [raw]
Subject: [PATCH v9 15/34] dt-bindings: usb: dwc3: Limit num-hc-interrupters definition

Ensure that the number of XHCI secondary interrupters defined for a DWC3
based implementation is limited to 8. XHCI in general can potentially
support up to 1024 interrupters.

Reviewed-by: Rob Herring <[email protected]>
Signed-off-by: Wesley Cheng <[email protected]>
---
Documentation/devicetree/bindings/usb/snps,dwc3.yaml | 4 ++++
1 file changed, 4 insertions(+)

diff --git a/Documentation/devicetree/bindings/usb/snps,dwc3.yaml b/Documentation/devicetree/bindings/usb/snps,dwc3.yaml
index d81c2e849ca9..3e9141e8a005 100644
--- a/Documentation/devicetree/bindings/usb/snps,dwc3.yaml
+++ b/Documentation/devicetree/bindings/usb/snps,dwc3.yaml
@@ -433,6 +433,10 @@ properties:
items:
enum: [1, 4, 8, 16, 32, 64, 128, 256]

+ num-hc-interrupters:
+ maximum: 8
+ default: 1
+
port:
$ref: /schemas/graph.yaml#/properties/port
description:

2023-10-17 20:05:24

by Wesley Cheng

[permalink] [raw]
Subject: [PATCH v9 30/34] ASoC: qcom: qdsp6: Add SND kcontrol for fetching offload status

Add a kcontrol to the platform sound card to fetch the current offload
status. This can allow for userspace to ensure/check which USB SND
resources are actually busy versus having to attempt opening the USB SND
devices, which will result in an error if offloading is active.

Signed-off-by: Wesley Cheng <[email protected]>
---
sound/soc/qcom/qdsp6/q6usb.c | 104 ++++++++++++++++++++++++++++++++++-
1 file changed, 101 insertions(+), 3 deletions(-)

diff --git a/sound/soc/qcom/qdsp6/q6usb.c b/sound/soc/qcom/qdsp6/q6usb.c
index a95276b7d91d..d2f60ce66cf3 100644
--- a/sound/soc/qcom/qdsp6/q6usb.c
+++ b/sound/soc/qcom/qdsp6/q6usb.c
@@ -30,6 +30,8 @@ struct q6usb_status {
unsigned int num_pcm;
unsigned int chip_index;
unsigned int pcm_index;
+ bool prepared;
+ bool running;
};

struct q6usb_port_data {
@@ -52,6 +54,17 @@ static const struct snd_soc_dapm_route q6usb_dapm_routes[] = {
{"USB Playback", NULL, "USB_RX_BE"},
};

+static int q6usb_find_running(struct q6usb_port_data *data)
+{
+ int i;
+
+ for (i = 0; i < SNDRV_CARDS; i++) {
+ if (data->status[i].running)
+ return i;
+ }
+ return -ENODEV;
+}
+
static int q6usb_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
@@ -81,14 +94,40 @@ static int q6usb_hw_params(struct snd_pcm_substream *substream,
goto out;

data->status[data->sel_card_idx].pcm_index = data->sel_pcm_idx;
+ data->status[data->sel_card_idx].prepared = true;
out:
mutex_unlock(&data->mutex);

return ret;
}

+static int q6usb_prepare(struct snd_pcm_substream *substream,
+ struct snd_soc_dai *dai)
+{
+ struct q6usb_port_data *data = dev_get_drvdata(dai->dev);
+
+ mutex_lock(&data->mutex);
+ data->status[data->sel_card_idx].running = true;
+ mutex_unlock(&data->mutex);
+
+ return 0;
+}
+
+static void q6usb_shutdown(struct snd_pcm_substream *substream,
+ struct snd_soc_dai *dai)
+{
+ struct q6usb_port_data *data = dev_get_drvdata(dai->dev);
+
+ mutex_lock(&data->mutex);
+ data->status[data->sel_card_idx].running = false;
+ data->status[data->sel_card_idx].prepared = false;
+ mutex_unlock(&data->mutex);
+}
+
static const struct snd_soc_dai_ops q6usb_ops = {
.hw_params = q6usb_hw_params,
+ .prepare = q6usb_prepare,
+ .shutdown = q6usb_shutdown,
};

static struct snd_soc_dai_driver q6usb_be_dais[] = {
@@ -148,10 +187,15 @@ static int q6usb_put_offload_dev(struct snd_kcontrol *kcontrol,
int pcmidx;
int cardidx;

+ mutex_lock(&data->mutex);
+
+ /* Don't allow changes to the offloading devices if session is busy */
+ if (data->sel_card_idx >= 0 && data->status[data->sel_card_idx].prepared)
+ goto out;
+
cardidx = ucontrol->value.integer.value[0];
pcmidx = ucontrol->value.integer.value[1];

- mutex_lock(&data->mutex);
if ((cardidx >= 0 && test_bit(cardidx, &data->available_card_slot))) {
data->sel_card_idx = cardidx;
changed = 1;
@@ -162,6 +206,8 @@ static int q6usb_put_offload_dev(struct snd_kcontrol *kcontrol,
data->idx_valid = true;
changed = 1;
}
+
+out:
mutex_unlock(&data->mutex);

return changed;
@@ -187,11 +233,59 @@ static const struct snd_kcontrol_new q6usb_offload_dev_ctrl = {
.put = q6usb_put_offload_dev,
};

+static int q6usb_mixer_get_offload_status(struct snd_kcontrol *kcontrol,
+ struct snd_ctl_elem_value *ucontrol)
+{
+ struct snd_soc_component *component = snd_kcontrol_chip(kcontrol);
+ struct q6usb_port_data *data = dev_get_drvdata(component->dev);
+ int running;
+ int card_idx;
+ int pcm_idx;
+
+ running = q6usb_find_running(data);
+ if (running < 0) {
+ card_idx = -1;
+ pcm_idx = -1;
+ } else {
+ card_idx = running;
+ pcm_idx = data->status[running].pcm_index;
+ }
+
+ ucontrol->value.integer.value[0] = card_idx;
+ ucontrol->value.integer.value[1] = pcm_idx;
+ return 0;
+}
+
+static int q6usb_offload_ctl_info(struct snd_kcontrol *kcontrol,
+ struct snd_ctl_elem_info *uinfo)
+{
+ uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
+ uinfo->count = 2;
+ uinfo->value.integer.min = 0;
+ uinfo->value.integer.max = SNDRV_CARDS;
+
+ return 0;
+}
+
+static const struct snd_kcontrol_new q6usb_offload_control = {
+ .iface = SNDRV_CTL_ELEM_IFACE_CARD,
+ .access = SNDRV_CTL_ELEM_ACCESS_READ,
+ .name = "Q6USB offload status",
+ .info = q6usb_offload_ctl_info,
+ .get = q6usb_mixer_get_offload_status,
+ .put = NULL,
+};
+
/* Build a mixer control for a UAC connector control (jack-detect) */
static void q6usb_connector_control_init(struct snd_soc_component *component)
{
int ret;

+ ret = snd_ctl_add(component->card->snd_card,
+ snd_ctl_new1(&q6usb_offload_control, component));
+ if (ret < 0)
+ return;
+
ret = snd_ctl_add(component->card->snd_card,
snd_ctl_new1(&q6usb_offload_dev_ctrl, component));
if (ret < 0)
@@ -229,8 +323,12 @@ static int q6usb_alsa_connection_cb(struct snd_soc_usb *usb,

mutex_lock(&data->mutex);
if (connected) {
- /* We only track the latest USB headset plugged in */
- if (!data->idx_valid || data->sel_card_idx < 0)
+ /*
+ * Update the latest USB headset plugged in, if session is
+ * idle.
+ */
+ if ((!data->idx_valid || data->sel_card_idx < 0) &&
+ !data->status[data->sel_card_idx].prepared)
data->sel_card_idx = sdev->card_idx;

set_bit(sdev->card_idx, &data->available_card_slot);

2023-10-17 20:05:56

by Wesley Cheng

[permalink] [raw]
Subject: [PATCH v9 16/34] usb: dwc3: Specify maximum number of XHCI interrupters

Allow for the DWC3 host driver to pass along XHCI property that defines
how many interrupters to allocate. This is in relation for the number of
event rings that can be potentially used by other processors within the
system.

Acked-by: Thinh Nguyen <[email protected]>
Signed-off-by: Wesley Cheng <[email protected]>
---
drivers/usb/dwc3/core.c | 12 ++++++++++++
drivers/usb/dwc3/core.h | 2 ++
drivers/usb/dwc3/host.c | 5 ++++-
3 files changed, 18 insertions(+), 1 deletion(-)

diff --git a/drivers/usb/dwc3/core.c b/drivers/usb/dwc3/core.c
index d25490965b27..0fa986fd34ca 100644
--- a/drivers/usb/dwc3/core.c
+++ b/drivers/usb/dwc3/core.c
@@ -1496,6 +1496,7 @@ static void dwc3_get_properties(struct dwc3 *dwc)
u8 tx_thr_num_pkt_prd = 0;
u8 tx_max_burst_prd = 0;
u8 tx_fifo_resize_max_num;
+ u16 num_hc_interrupters;
const char *usb_psy_name;
int ret;

@@ -1518,6 +1519,9 @@ static void dwc3_get_properties(struct dwc3 *dwc)
*/
tx_fifo_resize_max_num = 6;

+ /* default to a single XHCI interrupter */
+ num_hc_interrupters = 1;
+
dwc->maximum_speed = usb_get_maximum_speed(dev);
dwc->max_ssp_rate = usb_get_maximum_ssp_rate(dev);
dwc->dr_mode = usb_get_dr_mode(dev);
@@ -1569,6 +1573,12 @@ static void dwc3_get_properties(struct dwc3 *dwc)
&tx_thr_num_pkt_prd);
device_property_read_u8(dev, "snps,tx-max-burst-prd",
&tx_max_burst_prd);
+ device_property_read_u16(dev, "num-hc-interrupters",
+ &num_hc_interrupters);
+ /* DWC3 core allowed to have a max of 8 interrupters */
+ if (num_hc_interrupters > 8)
+ num_hc_interrupters = 8;
+
dwc->do_fifo_resize = device_property_read_bool(dev,
"tx-fifo-resize");
if (dwc->do_fifo_resize)
@@ -1657,6 +1667,8 @@ static void dwc3_get_properties(struct dwc3 *dwc)
dwc->imod_interval = 0;

dwc->tx_fifo_resize_max_num = tx_fifo_resize_max_num;
+
+ dwc->num_hc_interrupters = num_hc_interrupters;
}

/* check whether the core supports IMOD */
diff --git a/drivers/usb/dwc3/core.h b/drivers/usb/dwc3/core.h
index c6c87acbd376..2ce5e1e59380 100644
--- a/drivers/usb/dwc3/core.h
+++ b/drivers/usb/dwc3/core.h
@@ -1060,6 +1060,7 @@ struct dwc3_scratchpad_array {
* @tx_max_burst_prd: max periodic ESS transmit burst size
* @tx_fifo_resize_max_num: max number of fifos allocated during txfifo resize
* @clear_stall_protocol: endpoint number that requires a delayed status phase
+ * @num_hc_interrupters: number of host controller interrupters
* @hsphy_interface: "utmi" or "ulpi"
* @connected: true when we're connected to a host, false otherwise
* @softconnect: true when gadget connect is called, false when disconnect runs
@@ -1294,6 +1295,7 @@ struct dwc3 {
u8 tx_max_burst_prd;
u8 tx_fifo_resize_max_num;
u8 clear_stall_protocol;
+ u16 num_hc_interrupters;

const char *hsphy_interface;

diff --git a/drivers/usb/dwc3/host.c b/drivers/usb/dwc3/host.c
index 61f57fe5bb78..79ce359c342a 100644
--- a/drivers/usb/dwc3/host.c
+++ b/drivers/usb/dwc3/host.c
@@ -61,7 +61,7 @@ static int dwc3_host_get_irq(struct dwc3 *dwc)

int dwc3_host_init(struct dwc3 *dwc)
{
- struct property_entry props[4];
+ struct property_entry props[5];
struct platform_device *xhci;
int ret, irq;
int prop_idx = 0;
@@ -107,6 +107,9 @@ int dwc3_host_init(struct dwc3 *dwc)
if (DWC3_VER_IS_WITHIN(DWC3, ANY, 300A))
props[prop_idx++] = PROPERTY_ENTRY_BOOL("quirk-broken-port-ped");

+ props[prop_idx++] = PROPERTY_ENTRY_U16("num-hc-interrupters",
+ dwc->num_hc_interrupters);
+
if (prop_idx) {
ret = device_create_managed_software_node(&xhci->dev, props, NULL);
if (ret) {

2023-10-17 20:06:25

by Wesley Cheng

[permalink] [raw]
Subject: [PATCH v9 09/34] ASoC: qcom: qdsp6: Introduce USB AFE port to q6dsp

The QC ADSP is able to support USB playback endpoints, so that the main
application processor can be placed into lower CPU power modes. This adds
the required AFE port configurations and port start command to start an
audio session.

Specifically, the QC ADSP can support all potential endpoints that are
exposed by the audio data interface. This includes, feedback endpoints
(both implicit and explicit) as well as the isochronous (data) endpoints.
The size of audio samples sent per USB frame (microframe) will be adjusted
based on information received on the feedback endpoint.

Signed-off-by: Wesley Cheng <[email protected]>
---
sound/soc/qcom/qdsp6/q6afe-dai.c | 56 +++++++
sound/soc/qcom/qdsp6/q6afe.c | 183 ++++++++++++++++++++++-
sound/soc/qcom/qdsp6/q6afe.h | 35 ++++-
sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c | 23 +++
sound/soc/qcom/qdsp6/q6dsp-lpass-ports.h | 1 +
sound/soc/qcom/qdsp6/q6routing.c | 9 ++
6 files changed, 305 insertions(+), 2 deletions(-)

diff --git a/sound/soc/qcom/qdsp6/q6afe-dai.c b/sound/soc/qcom/qdsp6/q6afe-dai.c
index 3faa7e0eb0dd..e46c064253d7 100644
--- a/sound/soc/qcom/qdsp6/q6afe-dai.c
+++ b/sound/soc/qcom/qdsp6/q6afe-dai.c
@@ -91,6 +91,40 @@ static int q6hdmi_hw_params(struct snd_pcm_substream *substream,
return 0;
}

+static int q6usb_hw_params(struct snd_pcm_substream *substream,
+ struct snd_pcm_hw_params *params,
+ struct snd_soc_dai *dai)
+{
+ struct q6afe_dai_data *dai_data = dev_get_drvdata(dai->dev);
+ int channels = params_channels(params);
+ int rate = params_rate(params);
+ struct q6afe_usb_cfg *usb = &dai_data->port_config[dai->id].usb_audio;
+
+ usb->sample_rate = rate;
+ usb->num_channels = channels;
+
+ switch (params_format(params)) {
+ case SNDRV_PCM_FORMAT_U16_LE:
+ case SNDRV_PCM_FORMAT_S16_LE:
+ case SNDRV_PCM_FORMAT_SPECIAL:
+ usb->bit_width = 16;
+ break;
+ case SNDRV_PCM_FORMAT_S24_LE:
+ case SNDRV_PCM_FORMAT_S24_3LE:
+ usb->bit_width = 24;
+ break;
+ case SNDRV_PCM_FORMAT_S32_LE:
+ usb->bit_width = 32;
+ break;
+ default:
+ dev_err(dai->dev, "%s: invalid format %d\n",
+ __func__, params_format(params));
+ return -EINVAL;
+ }
+
+ return 0;
+}
+
static int q6i2s_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
@@ -391,6 +425,10 @@ static int q6afe_dai_prepare(struct snd_pcm_substream *substream,
q6afe_cdc_dma_port_prepare(dai_data->port[dai->id],
&dai_data->port_config[dai->id].dma_cfg);
break;
+ case USB_RX:
+ q6afe_usb_port_prepare(dai_data->port[dai->id],
+ &dai_data->port_config[dai->id].usb_audio);
+ break;
default:
return -EINVAL;
}
@@ -617,6 +655,9 @@ static const struct snd_soc_dapm_route q6afe_dapm_routes[] = {
{"TX_CODEC_DMA_TX_5", NULL, "TX_CODEC_DMA_TX_5 Capture"},
{"RX_CODEC_DMA_RX_6 Playback", NULL, "RX_CODEC_DMA_RX_6"},
{"RX_CODEC_DMA_RX_7 Playback", NULL, "RX_CODEC_DMA_RX_7"},
+
+ /* USB playback AFE port receives data for playback, hence use the RX port */
+ {"USB Playback", NULL, "USB_RX"},
};

static int msm_dai_q6_dai_probe(struct snd_soc_dai *dai)
@@ -644,6 +685,18 @@ static int msm_dai_q6_dai_remove(struct snd_soc_dai *dai)
return 0;
}

+static const struct snd_soc_dai_ops q6usb_ops = {
+ .probe = msm_dai_q6_dai_probe,
+ .prepare = q6afe_dai_prepare,
+ .hw_params = q6usb_hw_params,
+ .shutdown = q6afe_dai_shutdown,
+ /*
+ * Startup callback not needed, as AFE port start command passes the PCM
+ * parameters within the AFE command, which is provided by the PCM core
+ * during the prepare() stage.
+ */
+};
+
static const struct snd_soc_dai_ops q6hdmi_ops = {
.probe = msm_dai_q6_dai_probe,
.remove = msm_dai_q6_dai_remove,
@@ -942,6 +995,8 @@ static const struct snd_soc_dapm_widget q6afe_dai_widgets[] = {
0, SND_SOC_NOPM, 0, 0),
SND_SOC_DAPM_AIF_IN("RX_CODEC_DMA_RX_7", "NULL",
0, SND_SOC_NOPM, 0, 0),
+
+ SND_SOC_DAPM_AIF_IN("USB_RX", NULL, 0, SND_SOC_NOPM, 0, 0),
};

static const struct snd_soc_component_driver q6afe_dai_component = {
@@ -1056,6 +1111,7 @@ static int q6afe_dai_dev_probe(struct platform_device *pdev)
cfg.q6i2s_ops = &q6i2s_ops;
cfg.q6tdm_ops = &q6tdm_ops;
cfg.q6dma_ops = &q6dma_ops;
+ cfg.q6usb_ops = &q6usb_ops;
dais = q6dsp_audio_ports_set_config(dev, &cfg, &num_dais);

return devm_snd_soc_register_component(dev, &q6afe_dai_component, dais, num_dais);
diff --git a/sound/soc/qcom/qdsp6/q6afe.c b/sound/soc/qcom/qdsp6/q6afe.c
index 919e326b9462..f49c69472b5c 100644
--- a/sound/soc/qcom/qdsp6/q6afe.c
+++ b/sound/soc/qcom/qdsp6/q6afe.c
@@ -34,6 +34,8 @@
#define AFE_MODULE_TDM 0x0001028A

#define AFE_PARAM_ID_CDC_SLIMBUS_SLAVE_CFG 0x00010235
+#define AFE_PARAM_ID_USB_AUDIO_DEV_PARAMS 0x000102A5
+#define AFE_PARAM_ID_USB_AUDIO_DEV_LPCM_FMT 0x000102AA

#define AFE_PARAM_ID_LPAIF_CLK_CONFIG 0x00010238
#define AFE_PARAM_ID_INT_DIGITAL_CDC_CLK_CONFIG 0x00010239
@@ -43,6 +45,7 @@
#define AFE_PARAM_ID_TDM_CONFIG 0x0001029D
#define AFE_PARAM_ID_PORT_SLOT_MAPPING_CONFIG 0x00010297
#define AFE_PARAM_ID_CODEC_DMA_CONFIG 0x000102B8
+#define AFE_PARAM_ID_USB_AUDIO_CONFIG 0x000102A4
#define AFE_CMD_REMOTE_LPASS_CORE_HW_VOTE_REQUEST 0x000100f4
#define AFE_CMD_RSP_REMOTE_LPASS_CORE_HW_VOTE_REQUEST 0x000100f5
#define AFE_CMD_REMOTE_LPASS_CORE_HW_DEVOTE_REQUEST 0x000100f6
@@ -71,12 +74,16 @@
#define AFE_PORT_CONFIG_I2S_WS_SRC_INTERNAL 0x1
#define AFE_LINEAR_PCM_DATA 0x0

+#define AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG 0x1

/* Port IDs */
#define AFE_API_VERSION_HDMI_CONFIG 0x1
#define AFE_PORT_ID_MULTICHAN_HDMI_RX 0x100E
#define AFE_PORT_ID_HDMI_OVER_DP_RX 0x6020

+/* USB AFE port */
+#define AFE_PORT_ID_USB_RX 0x7000
+
#define AFE_API_VERSION_SLIMBUS_CONFIG 0x1
/* Clock set API version */
#define AFE_API_VERSION_CLOCK_SET 1
@@ -512,12 +519,109 @@ struct afe_param_id_cdc_dma_cfg {
u16 active_channels_mask;
} __packed;

+struct afe_param_id_usb_cfg {
+/* Minor version used for tracking USB audio device configuration.
+ * Supported values: AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG
+ */
+ u32 cfg_minor_version;
+/* Sampling rate of the port.
+ * Supported values:
+ * - AFE_PORT_SAMPLE_RATE_8K
+ * - AFE_PORT_SAMPLE_RATE_11025
+ * - AFE_PORT_SAMPLE_RATE_12K
+ * - AFE_PORT_SAMPLE_RATE_16K
+ * - AFE_PORT_SAMPLE_RATE_22050
+ * - AFE_PORT_SAMPLE_RATE_24K
+ * - AFE_PORT_SAMPLE_RATE_32K
+ * - AFE_PORT_SAMPLE_RATE_44P1K
+ * - AFE_PORT_SAMPLE_RATE_48K
+ * - AFE_PORT_SAMPLE_RATE_96K
+ * - AFE_PORT_SAMPLE_RATE_192K
+ */
+ u32 sample_rate;
+/* Bit width of the sample.
+ * Supported values: 16, 24
+ */
+ u16 bit_width;
+/* Number of channels.
+ * Supported values: 1 and 2
+ */
+ u16 num_channels;
+/* Data format supported by the USB. The supported value is
+ * 0 (#AFE_USB_AUDIO_DATA_FORMAT_LINEAR_PCM).
+ */
+ u16 data_format;
+/* this field must be 0 */
+ u16 reserved;
+/* device token of actual end USB audio device */
+ u32 dev_token;
+/* endianness of this interface */
+ u32 endian;
+/* service interval */
+ u32 service_interval;
+} __packed;
+
+/**
+ * struct afe_param_id_usb_audio_dev_params
+ * @cfg_minor_version: Minor version used for tracking USB audio device
+ * configuration.
+ * Supported values:
+ * AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG
+ * @dev_token: device token of actual end USB audio device
+ **/
+struct afe_param_id_usb_audio_dev_params {
+ u32 cfg_minor_version;
+ u32 dev_token;
+} __packed;
+
+/**
+ * struct afe_param_id_usb_audio_dev_lpcm_fmt
+ * @cfg_minor_version: Minor version used for tracking USB audio device
+ * configuration.
+ * Supported values:
+ * AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG
+ * @endian: endianness of this interface
+ **/
+struct afe_param_id_usb_audio_dev_lpcm_fmt {
+ u32 cfg_minor_version;
+ u32 endian;
+} __packed;
+
+/**
+ * struct afe_param_id_usb_audio_dev_latency_mode
+ * @cfg_minor_version: Minor version used for tracking USB audio device
+ * configuration.
+ * Supported values:
+ * AFE_API_MINOR_VERSION_USB_AUDIO_LATENCY_MODE
+ * @mode: latency mode for the USB audio device
+ **/
+struct afe_param_id_usb_audio_dev_latency_mode {
+ u32 minor_version;
+ u32 mode;
+} __packed;
+
+#define AFE_PARAM_ID_USB_AUDIO_SVC_INTERVAL 0x000102B7
+
+/**
+ * struct afe_param_id_usb_audio_svc_interval
+ * @cfg_minor_version: Minor version used for tracking USB audio device
+ * configuration.
+ * Supported values:
+ * AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG
+ * @svc_interval: service interval
+ **/
+struct afe_param_id_usb_audio_svc_interval {
+ u32 cfg_minor_version;
+ u32 svc_interval;
+} __packed;
+
union afe_port_config {
struct afe_param_id_hdmi_multi_chan_audio_cfg hdmi_multi_ch;
struct afe_param_id_slimbus_cfg slim_cfg;
struct afe_param_id_i2s_cfg i2s_cfg;
struct afe_param_id_tdm_cfg tdm_cfg;
struct afe_param_id_cdc_dma_cfg dma_cfg;
+ struct afe_param_id_usb_cfg usb_cfg;
} __packed;


@@ -832,6 +936,7 @@ static struct afe_port_map port_maps[AFE_PORT_MAX] = {
RX_CODEC_DMA_RX_6, 1, 1},
[RX_CODEC_DMA_RX_7] = { AFE_PORT_ID_RX_CODEC_DMA_RX_7,
RX_CODEC_DMA_RX_7, 1, 1},
+ [USB_RX] = { AFE_PORT_ID_USB_RX, USB_RX, 1, 1},
};

static void q6afe_port_free(struct kref *ref)
@@ -1289,6 +1394,79 @@ void q6afe_tdm_port_prepare(struct q6afe_port *port,
}
EXPORT_SYMBOL_GPL(q6afe_tdm_port_prepare);

+static int afe_port_send_usb_dev_param(struct q6afe_port *port, struct q6afe_usb_cfg *cfg)
+{
+ union afe_port_config *pcfg = &port->port_cfg;
+ struct afe_param_id_usb_audio_dev_params usb_dev;
+ struct afe_param_id_usb_audio_dev_lpcm_fmt lpcm_fmt;
+ struct afe_param_id_usb_audio_svc_interval svc_int;
+ int ret = 0;
+
+ if (!pcfg) {
+ dev_err(port->afe->dev, "%s: Error, no configuration data\n", __func__);
+ ret = -EINVAL;
+ goto exit;
+ }
+
+ memset(&usb_dev, 0, sizeof(usb_dev));
+ memset(&lpcm_fmt, 0, sizeof(lpcm_fmt));
+ memset(&svc_int, 0, sizeof(svc_int));
+
+ usb_dev.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
+ ret = q6afe_port_set_param_v2(port, &usb_dev,
+ AFE_PARAM_ID_USB_AUDIO_DEV_PARAMS,
+ AFE_MODULE_AUDIO_DEV_INTERFACE, sizeof(usb_dev));
+ if (ret) {
+ dev_err(port->afe->dev, "%s: AFE device param cmd failed %d\n",
+ __func__, ret);
+ goto exit;
+ }
+
+ lpcm_fmt.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
+ lpcm_fmt.endian = pcfg->usb_cfg.endian;
+ ret = q6afe_port_set_param_v2(port, &lpcm_fmt,
+ AFE_PARAM_ID_USB_AUDIO_DEV_LPCM_FMT,
+ AFE_MODULE_AUDIO_DEV_INTERFACE, sizeof(lpcm_fmt));
+ if (ret) {
+ dev_err(port->afe->dev, "%s: AFE device param cmd LPCM_FMT failed %d\n",
+ __func__, ret);
+ goto exit;
+ }
+
+ svc_int.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
+ svc_int.svc_interval = pcfg->usb_cfg.service_interval;
+ ret = q6afe_port_set_param_v2(port, &svc_int,
+ AFE_PARAM_ID_USB_AUDIO_SVC_INTERVAL,
+ AFE_MODULE_AUDIO_DEV_INTERFACE, sizeof(svc_int));
+ if (ret)
+ dev_err(port->afe->dev, "%s: AFE device param cmd svc_interval failed %d\n",
+ __func__, ret);
+
+exit:
+ return ret;
+}
+
+/**
+ * q6afe_usb_port_prepare() - Prepare usb afe port.
+ *
+ * @port: Instance of afe port
+ * @cfg: USB configuration for the afe port
+ *
+ */
+void q6afe_usb_port_prepare(struct q6afe_port *port,
+ struct q6afe_usb_cfg *cfg)
+{
+ union afe_port_config *pcfg = &port->port_cfg;
+
+ pcfg->usb_cfg.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
+ pcfg->usb_cfg.sample_rate = cfg->sample_rate;
+ pcfg->usb_cfg.num_channels = cfg->num_channels;
+ pcfg->usb_cfg.bit_width = cfg->bit_width;
+
+ afe_port_send_usb_dev_param(port, cfg);
+}
+EXPORT_SYMBOL_GPL(q6afe_usb_port_prepare);
+
/**
* q6afe_hdmi_port_prepare() - Prepare hdmi afe port.
*
@@ -1611,7 +1789,10 @@ struct q6afe_port *q6afe_port_get_from_id(struct device *dev, int id)
break;
case AFE_PORT_ID_WSA_CODEC_DMA_RX_0 ... AFE_PORT_ID_RX_CODEC_DMA_RX_7:
cfg_type = AFE_PARAM_ID_CODEC_DMA_CONFIG;
- break;
+ break;
+ case AFE_PORT_ID_USB_RX:
+ cfg_type = AFE_PARAM_ID_USB_AUDIO_CONFIG;
+ break;
default:
dev_err(dev, "Invalid port id 0x%x\n", port_id);
return ERR_PTR(-EINVAL);
diff --git a/sound/soc/qcom/qdsp6/q6afe.h b/sound/soc/qcom/qdsp6/q6afe.h
index 30fd77e2f458..ef47b4ae9e27 100644
--- a/sound/soc/qcom/qdsp6/q6afe.h
+++ b/sound/soc/qcom/qdsp6/q6afe.h
@@ -5,7 +5,7 @@

#include <dt-bindings/sound/qcom,q6afe.h>

-#define AFE_PORT_MAX 129
+#define AFE_PORT_MAX 137

#define MSM_AFE_PORT_TYPE_RX 0
#define MSM_AFE_PORT_TYPE_TX 1
@@ -205,6 +205,36 @@ struct q6afe_cdc_dma_cfg {
u16 active_channels_mask;
};

+/**
+ * struct q6afe_usb_cfg
+ * @cfg_minor_version: Minor version used for tracking USB audio device
+ * configuration.
+ * Supported values:
+ * AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG
+ * @sample_rate: Sampling rate of the port
+ * Supported values:
+ * AFE_PORT_SAMPLE_RATE_8K
+ * AFE_PORT_SAMPLE_RATE_11025
+ * AFE_PORT_SAMPLE_RATE_12K
+ * AFE_PORT_SAMPLE_RATE_16K
+ * AFE_PORT_SAMPLE_RATE_22050
+ * AFE_PORT_SAMPLE_RATE_24K
+ * AFE_PORT_SAMPLE_RATE_32K
+ * AFE_PORT_SAMPLE_RATE_44P1K
+ * AFE_PORT_SAMPLE_RATE_48K
+ * AFE_PORT_SAMPLE_RATE_96K
+ * AFE_PORT_SAMPLE_RATE_192K
+ * @bit_width: Bit width of the sample.
+ * Supported values: 16, 24
+ * @num_channels: Number of channels
+ * Supported values: 1, 2
+ **/
+struct q6afe_usb_cfg {
+ u32 cfg_minor_version;
+ u32 sample_rate;
+ u16 bit_width;
+ u16 num_channels;
+};

struct q6afe_port_config {
struct q6afe_hdmi_cfg hdmi;
@@ -212,6 +242,7 @@ struct q6afe_port_config {
struct q6afe_i2s_cfg i2s_cfg;
struct q6afe_tdm_cfg tdm;
struct q6afe_cdc_dma_cfg dma_cfg;
+ struct q6afe_usb_cfg usb_audio;
};

struct q6afe_port;
@@ -221,6 +252,8 @@ int q6afe_port_start(struct q6afe_port *port);
int q6afe_port_stop(struct q6afe_port *port);
void q6afe_port_put(struct q6afe_port *port);
int q6afe_get_port_id(int index);
+void q6afe_usb_port_prepare(struct q6afe_port *port,
+ struct q6afe_usb_cfg *cfg);
void q6afe_hdmi_port_prepare(struct q6afe_port *port,
struct q6afe_hdmi_cfg *cfg);
void q6afe_slim_port_prepare(struct q6afe_port *port,
diff --git a/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c b/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c
index 4919001de08b..4a96b11f7fd1 100644
--- a/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c
+++ b/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c
@@ -97,6 +97,26 @@
}

static struct snd_soc_dai_driver q6dsp_audio_fe_dais[] = {
+ {
+ .playback = {
+ .stream_name = "USB Playback",
+ .rates = SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_11025 |
+ SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_22050 |
+ SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_44100 |
+ SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_96000 |
+ SNDRV_PCM_RATE_192000,
+ .formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S16_BE |
+ SNDRV_PCM_FMTBIT_U16_LE | SNDRV_PCM_FMTBIT_U16_BE |
+ SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S24_BE |
+ SNDRV_PCM_FMTBIT_U24_LE | SNDRV_PCM_FMTBIT_U24_BE,
+ .channels_min = 1,
+ .channels_max = 2,
+ .rate_min = 8000,
+ .rate_max = 192000,
+ },
+ .id = USB_RX,
+ .name = "USB_RX",
+ },
{
.playback = {
.stream_name = "HDMI Playback",
@@ -624,6 +644,9 @@ struct snd_soc_dai_driver *q6dsp_audio_ports_set_config(struct device *dev,
case WSA_CODEC_DMA_RX_0 ... RX_CODEC_DMA_RX_7:
q6dsp_audio_fe_dais[i].ops = cfg->q6dma_ops;
break;
+ case USB_RX:
+ q6dsp_audio_fe_dais[i].ops = cfg->q6usb_ops;
+ break;
default:
break;
}
diff --git a/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.h b/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.h
index 7f052c8a1257..d8dde6dd0aca 100644
--- a/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.h
+++ b/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.h
@@ -11,6 +11,7 @@ struct q6dsp_audio_port_dai_driver_config {
const struct snd_soc_dai_ops *q6i2s_ops;
const struct snd_soc_dai_ops *q6tdm_ops;
const struct snd_soc_dai_ops *q6dma_ops;
+ const struct snd_soc_dai_ops *q6usb_ops;
};

struct snd_soc_dai_driver *q6dsp_audio_ports_set_config(struct device *dev,
diff --git a/sound/soc/qcom/qdsp6/q6routing.c b/sound/soc/qcom/qdsp6/q6routing.c
index bba07899f8fc..a57f45950ae3 100644
--- a/sound/soc/qcom/qdsp6/q6routing.c
+++ b/sound/soc/qcom/qdsp6/q6routing.c
@@ -514,6 +514,9 @@ static int msm_routing_put_audio_mixer(struct snd_kcontrol *kcontrol,
return 1;
}

+static const struct snd_kcontrol_new usb_mixer_controls[] = {
+ Q6ROUTING_RX_MIXERS(USB_RX) };
+
static const struct snd_kcontrol_new hdmi_mixer_controls[] = {
Q6ROUTING_RX_MIXERS(HDMI_RX) };

@@ -949,6 +952,10 @@ static const struct snd_soc_dapm_widget msm_qdsp6_widgets[] = {
SND_SOC_DAPM_MIXER("MultiMedia8 Mixer", SND_SOC_NOPM, 0, 0,
mmul8_mixer_controls, ARRAY_SIZE(mmul8_mixer_controls)),

+ SND_SOC_DAPM_MIXER("USB Mixer", SND_SOC_NOPM, 0, 0,
+ usb_mixer_controls,
+ ARRAY_SIZE(usb_mixer_controls)),
+
};

static const struct snd_soc_dapm_route intercon[] = {
@@ -1042,6 +1049,8 @@ static const struct snd_soc_dapm_route intercon[] = {
{"MM_UL6", NULL, "MultiMedia6 Mixer"},
{"MM_UL7", NULL, "MultiMedia7 Mixer"},
{"MM_UL8", NULL, "MultiMedia8 Mixer"},
+
+ Q6ROUTING_RX_DAPM_ROUTE("USB Mixer", "USB_RX"),
};

static int routing_hw_params(struct snd_soc_component *component,

2023-10-17 23:23:18

by Pierre-Louis Bossart

[permalink] [raw]
Subject: Re: [PATCH v9 00/34] Introduce QC USB SND audio offloading support

It's been a very long time since I reviewed earlier versions, and I am
still lost on terminology and concepts. The explanations below should
really be added as a .rst file in Documentation for reference, not just
as a cover letter.

> Several Qualcomm based chipsets can support USB audio offloading to a
> dedicated audio DSP, which can take over issuing transfers to the USB
> host controller. The intention is to reduce the load on the main
> processors in the SoC, and allow them to be placed into lower power modes.
> There are several parts to this design:
> 1. Adding ASoC binding layer
> 2. Create a USB backend for Q6DSP

"backend" is a loaded terms for ASoC. Can you clarify which part of the
ascii art below is a 'backend'?

> 3. Introduce XHCI interrupter support
> 4. Create vendor ops for the USB SND driver
>
> USB | ASoC
> --------------------------------------------------------------------
> | _________________________
> | |sm8250 platform card |
> | |_________________________|
> | | |
> | ___V____ ____V____
> | |Q6USB | |Q6AFE |
> | |"codec" | |"cpu" |
> | |________| |_________|
> | ^ ^ ^
> | | |________|
> | ___V____ |
> | |SOC-USB | |
> ________ ________ | | |
> |USB SND |<--->|QC offld|<------------>|________| |
> |(card.c)| | |<---------- |
> |________| |________|___ | | |
> ^ ^ | | | ____________V_________
> | | | | | |APR/GLINK |
> __ V_______________V_____ | | | |______________________|
> |USB SND (endpoint.c) | | | | ^
> |_________________________| | | | |
> ^ | | | ___________V___________
> | | | |->|audio DSP |
> ___________V_____________ | | |_______________________|
> |XHCI HCD |<- |
> |_________________________| |
>
>
> Adding ASoC binding layer:
> soc-usb: Intention is to treat a USB port similar to a headphone jack.

What is a 'port'? USB refers to "interfaces" and "endpoints". Is a
"port" a 1:1 mapping to "endpoint"?

Below I read "AFE port" so not sure what concepts refer to what.

> The port is always present on the device, but cable/pin status can be
> enabled/disabled. Expose mechanisms for USB backend ASoC drivers to
> communicate with USB SND.
>
> Create a USB backend for Q6DSP:
> q6usb: Basic backend driver that will be responsible for maintaining the

The asciiart above suggests that q6usb exposes a codec DAI - but the
backend dailink is created by the platform card?

> resources needed to initiate a playback stream using the Q6DSP. Will

is capture supported? there's explicit references to "num_capture" in
following patches.

> be the entity that checks to make sure the connected USB audio device
> supports the requested PCM format. If it does not, the PCM open call will
> fail, and userpsace ALSA can take action accordingly.
>
> Introduce XHCI interrupter support:
> XHCI HCD supports multiple interrupters, which allows for events to be routed
> to different event rings. This is determined by "Interrupter Target" field
> specified in Section "6.4.1.1 Normal TRB" of the XHCI specification.
>
> Events in the offloading case will be routed to an event ring that is assigned
> to the audio DSP.
>
> Create vendor ops for the USB SND driver:
> qc_audio_offload: This particular driver has several components associated
> with it:
> - QMI stream request handler
> - XHCI interrupter and resource management
> - audio DSP memory management
>
> When the audio DSP wants to enable a playback stream, the request is first
> received by the ASoC platform sound card. Depending on the selected route,
> ASoC will bring up the individual DAIs in the path. The Q6USB backend DAI
> will send an AFE port start command (with enabling the USB playback path), and
> the audio DSP will handle the request accordingly.

what about capture, e.g. for a headset?

> Part of the AFE USB port start handling will have an exchange of control
> messages using the QMI protocol. The qc_audio_offload driver will populate the
> buffer information:
> - Event ring base address
> - EP transfer ring base address
>
> and pass it along to the audio DSP. All endpoint management will now be handed
> over to the DSP, and the main processor is not involved in transfers.
>
> Overall, implementing this feature will still expose separate sound card and PCM
> devices for both the platorm card and USB audio device:

typo: platform

> 0 [SM8250MTPWCD938]: sm8250 - SM8250-MTP-WCD9380-WSA8810-VA-D
> SM8250-MTP-WCD9380-WSA8810-VA-DMIC

How do you plan on exposing the USB PCM device?

The lines above are really cryptic, and with no USB reference in any of
the short/long card names it's not obvious that this card is different
from the no-offload case, is it?

> 1 [Audio ]: USB-Audio - USB Audio
> Generic USB Audio at usb-xhci-hcd.1.auto-1.4, high speed

likewise some sort of qualifier would be useful to show that card 0 and
card 1 can target the same USB endpoints.

> This is to ensure that userspace ALSA entities can decide which route to take
> when executing the audio playback. In the above, if card#1 is selected, then
> USB audio data will take the legacy path over the USB PCM drivers, etc...
>
> This feature was validated using:
> - tinymix: set/enable the multimedia path to route to USB backend
> - tinyplay: issue playback on platform card

2023-10-17 23:23:37

by Pierre-Louis Bossart

[permalink] [raw]
Subject: Re: [PATCH v9 09/34] ASoC: qcom: qdsp6: Introduce USB AFE port to q6dsp



On 10/17/23 15:00, Wesley Cheng wrote:
> The QC ADSP is able to support USB playback endpoints, so that the main

playback only?

> application processor can be placed into lower CPU power modes. This adds
> the required AFE port configurations and port start command to start an
> audio session.
>
> Specifically, the QC ADSP can support all potential endpoints that are
> exposed by the audio data interface. This includes, feedback endpoints
> (both implicit and explicit) as well as the isochronous (data) endpoints.

implicit feedback means support for capture. This is confusing...

> +static int q6usb_hw_params(struct snd_pcm_substream *substream,
> + struct snd_pcm_hw_params *params,
> + struct snd_soc_dai *dai)
> +{
> + struct q6afe_dai_data *dai_data = dev_get_drvdata(dai->dev);
> + int channels = params_channels(params);
> + int rate = params_rate(params);
> + struct q6afe_usb_cfg *usb = &dai_data->port_config[dai->id].usb_audio;
> +
> + usb->sample_rate = rate;
> + usb->num_channels = channels;
> +
> + switch (params_format(params)) {
> + case SNDRV_PCM_FORMAT_U16_LE:
> + case SNDRV_PCM_FORMAT_S16_LE:
> + case SNDRV_PCM_FORMAT_SPECIAL:

what does FORMAT_SPECIAL mean? the only other reference I see to this is
related to SLIMbus, not sure how this is related?

> + usb->bit_width = 16;
> + break;
> + case SNDRV_PCM_FORMAT_S24_LE:
> + case SNDRV_PCM_FORMAT_S24_3LE:
> + usb->bit_width = 24;
> + break;
> + case SNDRV_PCM_FORMAT_S32_LE:
> + usb->bit_width = 32;
> + break;
> + default:
> + dev_err(dai->dev, "%s: invalid format %d\n",
> + __func__, params_format(params));
> + return -EINVAL;
> + }
> +
> + return 0;
> +}

> @@ -617,6 +655,9 @@ static const struct snd_soc_dapm_route q6afe_dapm_routes[] = {
> {"TX_CODEC_DMA_TX_5", NULL, "TX_CODEC_DMA_TX_5 Capture"},
> {"RX_CODEC_DMA_RX_6 Playback", NULL, "RX_CODEC_DMA_RX_6"},
> {"RX_CODEC_DMA_RX_7 Playback", NULL, "RX_CODEC_DMA_RX_7"},
> +
> + /* USB playback AFE port receives data for playback, hence use the RX port */
> + {"USB Playback", NULL, "USB_RX"},

Capture for implicit feedback?

> };
>
> static int msm_dai_q6_dai_probe(struct snd_soc_dai *dai)
> @@ -644,6 +685,18 @@ static int msm_dai_q6_dai_remove(struct snd_soc_dai *dai)
> return 0;
> }
>
> +static const struct snd_soc_dai_ops q6usb_ops = {
> + .probe = msm_dai_q6_dai_probe,
> + .prepare = q6afe_dai_prepare,
> + .hw_params = q6usb_hw_params,

this is rather confusing with two different layers used for hw_params
and prepare? Additional comments or explanations wouldn't hurt.

> + .shutdown = q6afe_dai_shutdown,
> + /*
> + * Startup callback not needed, as AFE port start command passes the PCM
> + * parameters within the AFE command, which is provided by the PCM core
> + * during the prepare() stage.

This doesn't really explain why you need a shutdown?


> + * struct afe_param_id_usb_audio_dev_latency_mode
> + * @cfg_minor_version: Minor version used for tracking USB audio device
> + * configuration.
> + * Supported values:
> + * AFE_API_MINOR_VERSION_USB_AUDIO_LATENCY_MODE
> + * @mode: latency mode for the USB audio device

what are the different latency modes? and is this related to the latency
reporting that was added in the USB2 audio class IIRC?

> +static int afe_port_send_usb_dev_param(struct q6afe_port *port, struct q6afe_usb_cfg *cfg)
> +{
> + union afe_port_config *pcfg = &port->port_cfg;
> + struct afe_param_id_usb_audio_dev_params usb_dev;
> + struct afe_param_id_usb_audio_dev_lpcm_fmt lpcm_fmt;
> + struct afe_param_id_usb_audio_svc_interval svc_int;
> + int ret = 0;

useless init overridden...
> +
> + if (!pcfg) {
> + dev_err(port->afe->dev, "%s: Error, no configuration data\n", __func__);
> + ret = -EINVAL;
> + goto exit;
> + }
> +
> + memset(&usb_dev, 0, sizeof(usb_dev));
> + memset(&lpcm_fmt, 0, sizeof(lpcm_fmt));
> + memset(&svc_int, 0, sizeof(svc_int));
> +
> + usb_dev.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
> + ret = q6afe_port_set_param_v2(port, &usb_dev,

.... here

> + AFE_PARAM_ID_USB_AUDIO_DEV_PARAMS,
> + AFE_MODULE_AUDIO_DEV_INTERFACE, sizeof(usb_dev));
> + if (ret) {
> + dev_err(port->afe->dev, "%s: AFE device param cmd failed %d\n",
> + __func__, ret);
> + goto exit;
> + }
> +
> + lpcm_fmt.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
> + lpcm_fmt.endian = pcfg->usb_cfg.endian;
> + ret = q6afe_port_set_param_v2(port, &lpcm_fmt,
> + AFE_PARAM_ID_USB_AUDIO_DEV_LPCM_FMT,
> + AFE_MODULE_AUDIO_DEV_INTERFACE, sizeof(lpcm_fmt));
> + if (ret) {
> + dev_err(port->afe->dev, "%s: AFE device param cmd LPCM_FMT failed %d\n",
> + __func__, ret);
> + goto exit;
> + }
> +
> + svc_int.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
> + svc_int.svc_interval = pcfg->usb_cfg.service_interval;
> + ret = q6afe_port_set_param_v2(port, &svc_int,
> + AFE_PARAM_ID_USB_AUDIO_SVC_INTERVAL,
> + AFE_MODULE_AUDIO_DEV_INTERFACE, sizeof(svc_int));
> + if (ret)
> + dev_err(port->afe->dev, "%s: AFE device param cmd svc_interval failed %d\n",
> + __func__, ret);
> +
> +exit:
> + return ret;
> +}

> -#define AFE_PORT_MAX 129
> +#define AFE_PORT_MAX 137

does this mean 8 ports are reserved for USB?

Or is this 137 just a random index coming from the AFE design?


2023-10-17 23:23:50

by Pierre-Louis Bossart

[permalink] [raw]
Subject: Re: [PATCH v9 20/34] ALSA: usb-audio: Check for support for requested audio format



On 10/17/23 15:00, Wesley Cheng wrote:
> Allow for checks on a specific USB audio device to see if a requested PCM
> format is supported. This is needed for support for when playback is

This is needed for support when playback is

> initiated by the ASoC USB backend path.
>
> Signed-off-by: Wesley Cheng <[email protected]>
> ---
> sound/usb/card.c | 40 ++++++++++++++++++++++++++++++++++++++++
> sound/usb/card.h | 11 +++++++++++
> 2 files changed, 51 insertions(+)
>
> diff --git a/sound/usb/card.c b/sound/usb/card.c
> index c0b312e264bf..88f431917c15 100644
> --- a/sound/usb/card.c
> +++ b/sound/usb/card.c
> @@ -162,6 +162,46 @@ int snd_usb_unregister_platform_ops(void)
> }
> EXPORT_SYMBOL_GPL(snd_usb_unregister_platform_ops);
>
> +/*
> + * Checks to see if requested audio profile, i.e sample rate, # of
> + * channels, etc... is supported by the substream associated to the
> + * USB audio device.
> + */
> +struct snd_usb_stream *snd_usb_find_suppported_substream(int card_idx,
> + struct snd_pcm_hw_params *params, int direction)
> +{
> + struct snd_usb_audio *chip;
> + struct snd_usb_substream *subs = NULL;

useless init?

> + struct snd_usb_stream *as;
> + const struct audioformat *fmt;
> +
> + /*
> + * Register mutex is held when populating and clearing usb_chip
> + * array.
> + */
> + mutex_lock(&register_mutex);
> + chip = usb_chip[card_idx];
> + if (!chip) {
> + mutex_unlock(&register_mutex);
> + return NULL;
> + }
> +
> + if (enable[card_idx]) {
> + list_for_each_entry(as, &chip->pcm_list, list) {
> + subs = &as->substream[direction];
> + fmt = snd_usb_find_substream_format(subs, params);
> + if (fmt) {
> + mutex_unlock(&register_mutex);
> + return as;
> + }
> + }
> + }
> + mutex_unlock(&register_mutex);
> +
> + return NULL;
> +}
> +EXPORT_SYMBOL_GPL(snd_usb_find_suppported_substream);
> +
> /*
> * disconnect streams
> * called from usb_audio_disconnect()
> diff --git a/sound/usb/card.h b/sound/usb/card.h
> index 2884912adc96..e26292363cf0 100644
> --- a/sound/usb/card.h
> +++ b/sound/usb/card.h
> @@ -216,4 +216,15 @@ struct snd_usb_platform_ops {
>
> int snd_usb_register_platform_ops(struct snd_usb_platform_ops *ops);
> int snd_usb_unregister_platform_ops(void);
> +
> +#if IS_ENABLED(CONFIG_SND_USB_AUDIO)
> +struct snd_usb_stream *snd_usb_find_suppported_substream(int card_idx,
> + struct snd_pcm_hw_params *params, int direction);
> +#else
> +static struct snd_usb_stream *snd_usb_find_suppported_substream(int card_idx,
> + struct snd_pcm_hw_params *params, int direction)
> +{
> + return NULL;
> +}
> +#endif /* IS_ENABLED(CONFIG_SND_USB_AUDIO) */
> #endif /* __USBAUDIO_CARD_H */

2023-10-17 23:24:09

by Pierre-Louis Bossart

[permalink] [raw]
Subject: Re: [PATCH v9 30/34] ASoC: qcom: qdsp6: Add SND kcontrol for fetching offload status



On 10/17/23 15:01, Wesley Cheng wrote:
> Add a kcontrol to the platform sound card to fetch the current offload
> status. This can allow for userspace to ensure/check which USB SND
> resources are actually busy versus having to attempt opening the USB SND
> devices, which will result in an error if offloading is active.

I think I mentioned this a while back, but why not add the status in the
USB card itself? That's a generic component that all userspace agent
could query. Having a QCOM-specific control doesn't make the life of
userspace easier IMHO.


2023-10-17 23:24:25

by Pierre-Louis Bossart

[permalink] [raw]
Subject: Re: [PATCH v9 34/34] ASoC: usb: Rediscover USB SND devices on USB port add



On 10/17/23 15:01, Wesley Cheng wrote:
> In case the USB backend device has not been initialized/probed, USB SND
> device connections can still occur. When the USB backend is eventually
> made available, previous USB SND device connections are not communicated to
> the USB backend. Call snd_usb_rediscover_devices() to generate the connect
> callbacks for all USB SND devices connected. This will allow for the USB
> backend to be updated with the current set of devices available.
>
> The chip array entries are all populated and removed while under the
> register_mutex, so going over potential race conditions:
>
> Thread#1:
> q6usb_component_probe()
> --> snd_soc_usb_add_port()
> --> snd_usb_rediscover_devices()
> --> mutex_lock(register_mutex)
>
> Thread#2
> --> usb_audio_disconnect()
> --> mutex_lock(register_mutex)
>
> So either thread#1 or thread#2 will complete first. If
>
> Thread#1 completes before thread#2:
> SOC USB will notify DPCM backend of the device connection. Shortly
> after, once thread#2 runs, we will get a disconnect event for the
> connected device.
>
> Thread#2 completes before thread#1:
> Then during snd_usb_rediscover_devices() it won't notify of any
> connection for that particular chip index.
Looks like you are assuming the regular USB audio stuff is probed first?

What if it's not the case? Have you tested with a manual 'blacklist' and
"modprobe" sequence long after all the DSP stuff is initialized?

It really reminds me of audio+display issues, and the same opens apply IMHO.

2023-10-17 23:24:58

by Pierre-Louis Bossart

[permalink] [raw]
Subject: Re: [PATCH v9 19/34] ALSA: usb-audio: qcom: Introduce QC USB SND offloading support


> +config SND_USB_AUDIO_QMI
> + tristate "Qualcomm Audio Offload driver"
> + depends on QCOM_QMI_HELPERS && SND_USB_AUDIO && USB_XHCI_SIDEBAND
> + select SND_PCM

This select is not needed:

config SND_USB_AUDIO
tristate "USB Audio/MIDI driver"
select SND_HWDEP
select SND_RAWMIDI
select SND_PCM


> +#include <linux/ctype.h>
> +#include <linux/moduleparam.h>
> +#include <linux/module.h>
> +#include <linux/usb.h>
> +#include <linux/init.h>

alphabetical order?

> +#include <linux/usb/hcd.h>
> +#include <linux/usb/xhci-sideband.h>
> +#include <linux/usb/quirks.h>
> +#include <linux/usb/audio.h>
> +#include <linux/usb/audio-v2.h>
> +#include <linux/usb/audio-v3.h>
> +#include <linux/soc/qcom/qmi.h>
> +#include <linux/iommu.h>
> +#include <linux/dma-mapping.h>
> +#include <linux/dma-map-ops.h>
> +#include <sound/q6usboffload.h>
> +
> +#include <sound/control.h>
> +#include <sound/core.h>
> +#include <sound/info.h>
> +#include <sound/pcm.h>
> +#include <sound/pcm_params.h>
> +#include <sound/initval.h>
> +
> +#include <sound/soc.h>
> +#include <sound/soc-usb.h>
> +#include "../usbaudio.h"
> +#include "../card.h"
> +#include "../endpoint.h"
> +#include "../helper.h"
> +#include "../pcm.h"
> +#include "../format.h"
> +#include "../power.h"
> +#include "usb_audio_qmi_v01.h"
> +
> +/* Stream disable request timeout during USB device disconnect */
> +#define DEV_RELEASE_WAIT_TIMEOUT 10000 /* in ms */

DEV_RELEASE_WAIT_TIMEOUT_MS?

why 10s btw?

> +
> +/* Data interval calculation parameters */
> +#define BUS_INTERVAL_FULL_SPEED 1000 /* in us */
> +#define BUS_INTERVAL_HIGHSPEED_AND_ABOVE 125 /* in us */
> +#define MAX_BINTERVAL_ISOC_EP 16
> +
> +#define QMI_STREAM_REQ_CARD_NUM_MASK 0xffff0000
> +#define QMI_STREAM_REQ_DEV_NUM_MASK 0xff00
> +#define QMI_STREAM_REQ_DIRECTION 0xff
> +
> +/* iommu resource parameters and management */
> +#define PREPEND_SID_TO_IOVA(iova, sid) ((u64)(((u64)(iova)) | \
> + (((u64)sid) << 32)))
> +#define IOVA_BASE 0x1000
> +#define IOVA_XFER_RING_BASE (IOVA_BASE + PAGE_SIZE * (SNDRV_CARDS + 1))
> +#define IOVA_XFER_BUF_BASE (IOVA_XFER_RING_BASE + PAGE_SIZE * SNDRV_CARDS * 32)
> +#define IOVA_XFER_RING_MAX (IOVA_XFER_BUF_BASE - PAGE_SIZE)
> +#define IOVA_XFER_BUF_MAX (0xfffff000 - PAGE_SIZE)
> +
> +#define MAX_XFER_BUFF_LEN (24 * PAGE_SIZE)
> +
> +struct iova_info {
> + struct list_head list;
> + unsigned long start_iova;
> + size_t size;
> + bool in_use;
> +};
> +
> +struct intf_info {
> + unsigned long data_xfer_ring_va;
> + size_t data_xfer_ring_size;
> + unsigned long sync_xfer_ring_va;
> + size_t sync_xfer_ring_size;
> + unsigned long xfer_buf_va;
> + size_t xfer_buf_size;
> + phys_addr_t xfer_buf_pa;
> + unsigned int data_ep_pipe;
> + unsigned int sync_ep_pipe;
> + u8 *xfer_buf;
> + u8 intf_num;
> + u8 pcm_card_num;
> + u8 pcm_dev_num;
> + u8 direction;
> + bool in_use;
> +};
> +
> +struct uaudio_qmi_dev {
> + struct device *dev;
> + u32 sid;
> + u32 intr_num;
> + struct xhci_ring *sec_ring;
> + struct iommu_domain *domain;
> +
> + /* list to keep track of available iova */
> + struct list_head xfer_ring_list;
> + size_t xfer_ring_iova_size;
> + unsigned long curr_xfer_ring_iova;
> + struct list_head xfer_buf_list;
> + size_t xfer_buf_iova_size;
> + unsigned long curr_xfer_buf_iova;
> +
> + /* bit fields representing pcm card enabled */
> + unsigned long card_slot;
> + /* indicate event ring mapped or not */
> + bool er_mapped;
> + /* reference count to number of possible consumers */
> + atomic_t qdev_in_use;
> + /* idx to last udev card number plugged in */
> + unsigned int last_card_num;
> +};
> +
> +struct uaudio_dev {
> + struct usb_device *udev;
> + /* audio control interface */
> + struct usb_host_interface *ctrl_intf;
> + unsigned int usb_core_id;
> + atomic_t in_use;
> + struct kref kref;
> + wait_queue_head_t disconnect_wq;
> +
> + /* interface specific */
> + int num_intf;
> + struct intf_info *info;
> + struct snd_usb_audio *chip;
> +
> + /* xhci sideband */
> + struct xhci_sideband *sb;
> +
> + /* SoC USB device */
> + struct snd_soc_usb_device *sdev;
> +};

these structures feel like a set of kitchen sinks... Or a possible
copy-paste, I don't know how one would add all these pointers on their own?

Do you really need all this? Is there not a way to use existing
substructures?


> +static int get_data_interval_from_si(struct snd_usb_substream *subs,
> + u32 service_interval)
> +{
> + unsigned int bus_intval, bus_intval_mult, binterval;
> +
> + if (subs->dev->speed >= USB_SPEED_HIGH)
> + bus_intval = BUS_INTERVAL_HIGHSPEED_AND_ABOVE;
> + else
> + bus_intval = BUS_INTERVAL_FULL_SPEED;
> +
> + if (service_interval % bus_intval)
> + return -EINVAL;
> +
> + bus_intval_mult = service_interval / bus_intval;
> + binterval = ffs(bus_intval_mult);
> + if (!binterval || binterval > MAX_BINTERVAL_ISOC_EP)
> + return -EINVAL;
> +
> + /* check if another bit is set then bail out */
> + bus_intval_mult = bus_intval_mult >> binterval;
> + if (bus_intval_mult)
> + return -EINVAL;
> +
> + return (binterval - 1);
> +}

This also feels like a generic helper. I don't see what's Qualcomm
specific here?


> +static unsigned long uaudio_iommu_map(enum mem_type mtype, bool dma_coherent,
> + phys_addr_t pa, size_t size, struct sg_table *sgt)
> +{
> + unsigned long va_sg, va = 0;
> + bool map = true;
> + int i, ret;
> + size_t sg_len, total_len = 0;
> + struct scatterlist *sg;
> + phys_addr_t pa_sg;
> + int prot = IOMMU_READ | IOMMU_WRITE;

reverse x-mas tree style?

> +
> + if (dma_coherent)
> + prot |= IOMMU_CACHE;
> +
> + switch (mtype) {
> + case MEM_EVENT_RING:
> + va = IOVA_BASE;
> + /* er already mapped */
> + if (uaudio_qdev->er_mapped)
> + map = false;
> + break;
> + case MEM_XFER_RING:
> + va = uaudio_get_iova(&uaudio_qdev->curr_xfer_ring_iova,
> + &uaudio_qdev->xfer_ring_iova_size, &uaudio_qdev->xfer_ring_list,
> + size);
> + break;
> + case MEM_XFER_BUF:
> + va = uaudio_get_iova(&uaudio_qdev->curr_xfer_buf_iova,
> + &uaudio_qdev->xfer_buf_iova_size, &uaudio_qdev->xfer_buf_list,
> + size);
> + break;
> + default:
> + dev_err(uaudio_qdev->dev, "unknown mem type %d\n", mtype);
> + }
> +
> + if (!va || !map)
> + goto done;
> +
> + if (!sgt)
> + goto skip_sgt_map;
> +
> + va_sg = va;
> + for_each_sg(sgt->sgl, sg, sgt->nents, i) {
> + sg_len = PAGE_ALIGN(sg->offset + sg->length);
> + pa_sg = page_to_phys(sg_page(sg));
> + ret = iommu_map(uaudio_qdev->domain, va_sg, pa_sg, sg_len,
> + prot, GFP_KERNEL);
> + if (ret) {
> + dev_err(uaudio_qdev->dev, "mapping failed ret%d\n", ret);
> + dev_err(uaudio_qdev->dev,
> + "type:%d, pa:%pa iova:0x%08lx sg_len:%zu\n",
> + mtype, &pa_sg, va_sg, sg_len);
> + uaudio_iommu_unmap(MEM_XFER_BUF, va, size, total_len);
> + va = 0;

so it's an error but the function returns 0?

> + goto done;
> + }
> + dev_dbg(uaudio_qdev->dev,
> + "type:%d map pa:%pa to iova:0x%08lx len:%zu offset:%u\n",
> + mtype, &pa_sg, va_sg, sg_len, sg->offset);
> + va_sg += sg_len;
> + total_len += sg_len;
> + }
> +
> + if (size != total_len) {
> + dev_err(uaudio_qdev->dev, "iova size %zu != mapped iova size %zu\n",
> + size, total_len);
> + uaudio_iommu_unmap(MEM_XFER_BUF, va, size, total_len);
> + va = 0;
> + }
> + return va;
> +
> +skip_sgt_map:
> + dev_dbg(uaudio_qdev->dev, "type:%d map pa:%pa to iova:0x%08lx size:%zu\n",
> + mtype, &pa, va, size);
> +
> + ret = iommu_map(uaudio_qdev->domain, va, pa, size, prot, GFP_KERNEL);
> + if (ret)
> + dev_err(uaudio_qdev->dev,
> + "failed to map pa:%pa iova:0x%lx type:%d ret:%d\n",
> + &pa, va, mtype, ret);
> +done:
> + return va;
> +}
> +
> +/* looks up alias, if any, for controller DT node and returns the index */
> +static int usb_get_controller_id(struct usb_device *udev)
> +{
> + if (udev->bus->sysdev && udev->bus->sysdev->of_node)
> + return of_alias_get_id(udev->bus->sysdev->of_node, "usb");
> +
> + return -ENODEV;
> +}
> +
> +/**
> + * uaudio_dev_intf_cleanup() - cleanup transfer resources
> + * @udev: usb device
> + * @info: usb offloading interface
> + *
> + * Cleans up the transfer ring related resources which are assigned per
> + * endpoint from XHCI. This is invoked when the USB endpoints are no
> + * longer in use by the adsp.
> + *
> + */
> +static void uaudio_dev_intf_cleanup(struct usb_device *udev,
> + struct intf_info *info)
> +{
> + uaudio_iommu_unmap(MEM_XFER_RING, info->data_xfer_ring_va,
> + info->data_xfer_ring_size, info->data_xfer_ring_size);
> + info->data_xfer_ring_va = 0;
> + info->data_xfer_ring_size = 0;
> +
> + uaudio_iommu_unmap(MEM_XFER_RING, info->sync_xfer_ring_va,
> + info->sync_xfer_ring_size, info->sync_xfer_ring_size);
> + info->sync_xfer_ring_va = 0;
> + info->sync_xfer_ring_size = 0;
> +
> + uaudio_iommu_unmap(MEM_XFER_BUF, info->xfer_buf_va,
> + info->xfer_buf_size, info->xfer_buf_size);
> + info->xfer_buf_va = 0;
> +
> + usb_free_coherent(udev, info->xfer_buf_size,
> + info->xfer_buf, info->xfer_buf_pa);
> + info->xfer_buf_size = 0;
> + info->xfer_buf = NULL;
> + info->xfer_buf_pa = 0;
> +
> + info->in_use = false;
> +}
> +
> +/**
> + * uaudio_event_ring_cleanup_free() - cleanup secondary event ring
> + * @dev: usb offload device
> + *
> + * Cleans up the secondary event ring that was requested. This will
> + * occur when the adsp is no longer transferring data on the USB bus
> + * across all endpoints.
> + *
> + */
> +static void uaudio_event_ring_cleanup_free(struct uaudio_dev *dev)
> +{
> + clear_bit(dev->chip->card->number, &uaudio_qdev->card_slot);
> + /* all audio devices are disconnected */
> + if (!uaudio_qdev->card_slot) {
> + uaudio_iommu_unmap(MEM_EVENT_RING, IOVA_BASE, PAGE_SIZE,
> + PAGE_SIZE);
> + xhci_sideband_remove_interrupter(uadev[dev->chip->card->number].sb);
> + }
> +}
> +
> +static void uaudio_dev_cleanup(struct uaudio_dev *dev)

there should be a comment that this assumes a mutex is locked in the caller.

> +{
> + int if_idx;
> +
> + if (!dev->udev)
> + return;
> +
> + /* free xfer buffer and unmap xfer ring and buf per interface */
> + for (if_idx = 0; if_idx < dev->num_intf; if_idx++) {
> + if (!dev->info[if_idx].in_use)
> + continue;
> + uaudio_dev_intf_cleanup(dev->udev, &dev->info[if_idx]);
> + dev_dbg(uaudio_qdev->dev, "release resources: intf# %d card# %d\n",
> + dev->info[if_idx].intf_num, dev->chip->card->number);
> + }
> +
> + dev->num_intf = 0;
> +
> + /* free interface info */
> + kfree(dev->info);
> + dev->info = NULL;
> + uaudio_event_ring_cleanup_free(dev);
> + dev->udev = NULL;
> +}
> +
> +/**
> + * disable_audio_stream() - disable usb snd endpoints
> + * @subs: usb substream
> + *
> + * Closes the USB SND endpoints associated with the current audio stream
> + * used. This will decrement the USB SND endpoint opened reference count.
> + *
> + */
> +static void disable_audio_stream(struct snd_usb_substream *subs)
> +{
> + struct snd_usb_audio *chip = subs->stream->chip;
> +
> + snd_usb_hw_free(subs);
> + snd_usb_autosuspend(chip);
> +}
> +
> +/* QMI service disconnect handlers */
> +static void qmi_disconnect_work(struct work_struct *w)
> +{
> + struct intf_info *info;
> + int idx, if_idx;
> + struct snd_usb_substream *subs;
> + struct snd_usb_audio *chip;
> +
> + mutex_lock(&qdev_mutex);
> + /* find all active intf for set alt 0 and cleanup usb audio dev */
> + for (idx = 0; idx < SNDRV_CARDS; idx++) {
> + if (!atomic_read(&uadev[idx].in_use))
> + continue;
> +
> + chip = uadev[idx].chip;
> + for (if_idx = 0; if_idx < uadev[idx].num_intf; if_idx++) {
> + if (!uadev[idx].info || !uadev[idx].info[if_idx].in_use)
> + continue;
> + info = &uadev[idx].info[if_idx];
> + subs = find_substream(info->pcm_card_num,
> + info->pcm_dev_num,
> + info->direction);
> + if (!subs || !chip || atomic_read(&chip->shutdown)) {
> + dev_err(&subs->dev->dev,
> + "no sub for c#%u dev#%u dir%u\n",
> + info->pcm_card_num,
> + info->pcm_dev_num,
> + info->direction);
> + continue;
> + }
> + disable_audio_stream(subs);
> + }
> + atomic_set(&uadev[idx].in_use, 0);
> + mutex_lock(&chip->mutex);
> + uaudio_dev_cleanup(&uadev[idx]);
> + mutex_unlock(&chip->mutex);
> + }
> + mutex_unlock(&qdev_mutex);
> +}
> +
> +/**
> + * qmi_bye_cb() - qmi bye message callback
> + * @handle: QMI handle
> + * @node: id of the dying node
> + *
> + * This callback is invoked when the QMI bye control message is received
> + * from the QMI client. Handle the message accordingly by ensuring that
> + * the USB offload path is disabled and cleaned up. At this point, ADSP
> + * is not utilizing the USB bus.
> + *
> + */
> +static void qmi_bye_cb(struct qmi_handle *handle, unsigned int node)
> +{
> + struct uaudio_qmi_svc *svc = uaudio_svc;
> +
> + if (svc->uaudio_svc_hdl != handle)
> + return;
> +
> + if (svc->client_connected && svc->client_sq.sq_node == node) {
> + queue_work(svc->uaudio_wq, &svc->qmi_disconnect_work);
> + svc->client_sq.sq_node = 0;
> + svc->client_sq.sq_port = 0;
> + svc->client_sq.sq_family = 0;
> + svc->client_connected = false;
> + }
> +}
> +
> +/**
> + * qmi_svc_disconnect_cb() - qmi client disconnected
> + * @handle: QMI handle
> + * @node: id of the dying node
> + * @port: port of the dying client
> + *
> + * Invoked when the remote QMI client is disconnected. Handle this event
> + * the same way as when the QMI bye message is received. This will ensure
> + * the USB offloading path is disabled and cleaned up.
> + *
> + */
> +static void qmi_svc_disconnect_cb(struct qmi_handle *handle,
> + unsigned int node, unsigned int port)
> +{
> + struct uaudio_qmi_svc *svc;
> +
> + if (uaudio_svc == NULL)
> + return;
> +
> + svc = uaudio_svc;
> + if (svc->uaudio_svc_hdl != handle)
> + return;
> +
> + if (svc->client_connected && svc->client_sq.sq_node == node &&
> + svc->client_sq.sq_port == port) {
> + queue_work(svc->uaudio_wq, &svc->qmi_disconnect_work);
> + svc->client_sq.sq_node = 0;
> + svc->client_sq.sq_port = 0;
> + svc->client_sq.sq_family = 0;
> + svc->client_connected = false;

this feels racy, shouldn't all these reset values be set in the work
function?

> + }
> +}
> +
> +/* QMI client callback handlers from QMI interface */
> +static struct qmi_ops uaudio_svc_ops_options = {
> + .bye = qmi_bye_cb,
> + .del_client = qmi_svc_disconnect_cb,
> +};
> +
> +/* kref release callback when all streams are disabled */
> +static void uaudio_dev_release(struct kref *kref)
> +{
> + struct uaudio_dev *dev = container_of(kref, struct uaudio_dev, kref);
> +
> + uaudio_event_ring_cleanup_free(dev);
> + atomic_set(&dev->in_use, 0);
> + wake_up(&dev->disconnect_wq);
> +}
> +
> +/**
> + * enable_audio_stream() - enable usb snd endpoints
> + * @subs: usb substream
> + * @pcm_format: pcm format requested
> + * @channels: number of channels
> + * @cur_rate: sample rate
> + * @datainterval: interval
> + *
> + * Opens all USB SND endpoints used for the data interface. This will increment
> + * the USB SND endpoint's opened count. Requests to keep the interface resumed
> + * until the audio stream is stopped. Will issue the USB set interface control
> + * message to enable the data interface.
> + *
> + */
> +static int enable_audio_stream(struct snd_usb_substream *subs,
> + snd_pcm_format_t pcm_format,
> + unsigned int channels, unsigned int cur_rate,
> + int datainterval)
> +{
> + struct snd_usb_audio *chip = subs->stream->chip;
> + struct snd_pcm_hw_params params;
> + struct snd_mask *m;
> + struct snd_interval *i;
> + int ret;
> +
> + _snd_pcm_hw_params_any(&params);
> +
> + m = hw_param_mask(&params, SNDRV_PCM_HW_PARAM_FORMAT);
> + snd_mask_leave(m, pcm_format);
> +
> + i = hw_param_interval(&params, SNDRV_PCM_HW_PARAM_CHANNELS);
> + snd_interval_setinteger(i);
> + i->min = i->max = channels;
> +
> + i = hw_param_interval(&params, SNDRV_PCM_HW_PARAM_RATE);
> + snd_interval_setinteger(i);
> + i->min = i->max = cur_rate;
> +
> + pm_runtime_barrier(&chip->intf[0]->dev);
> + snd_usb_autoresume(chip);
> +
> + ret = snd_usb_hw_params(subs, &params);
> + if (ret < 0)
> + goto put_suspend;
> +
> + if (!atomic_read(&chip->shutdown)) {
> + ret = snd_usb_lock_shutdown(chip);
> + if (ret < 0)
> + goto detach_ep;
> +
> + if (subs->sync_endpoint) {
> + ret = snd_usb_endpoint_prepare(chip, subs->sync_endpoint);
> + if (ret < 0)
> + goto unlock;
> + }
> +
> + ret = snd_usb_endpoint_prepare(chip, subs->data_endpoint);
> + if (ret < 0)
> + goto unlock;
> +
> + snd_usb_unlock_shutdown(chip);
> +
> + dev_dbg(uaudio_qdev->dev,
> + "selected %s iface:%d altsetting:%d datainterval:%dus\n",
> + subs->direction ? "capture" : "playback",
> + subs->cur_audiofmt->iface, subs->cur_audiofmt->altsetting,
> + (1 << subs->cur_audiofmt->datainterval) *
> + (subs->dev->speed >= USB_SPEED_HIGH ?
> + BUS_INTERVAL_HIGHSPEED_AND_ABOVE :
> + BUS_INTERVAL_FULL_SPEED));
> + }
> +
> + return 0;
> +
> +unlock:
> + snd_usb_unlock_shutdown(chip);
> +
> +detach_ep:
> + snd_usb_hw_free(subs);
> +
> +put_suspend:
> + snd_usb_autosuspend(chip);
> +
> + return ret;
> +}
> +
> +/* returns usb hcd sysdev */
> +static struct device *usb_get_usb_backend(struct usb_device *udev)
> +{
> + if (udev->bus->sysdev && udev->bus->sysdev->of_node)
> + return udev->bus->sysdev;
> +
> + return NULL;
> +}
> +
> +/**
> + * prepare_qmi_response() - prepare stream enable response
> + * @subs: usb substream
> + * @req_msg: QMI request message
> + * @resp: QMI response buffer
> + * @info_idx: usb interface array index
> + *
> + * Prepares the QMI response for a USB QMI stream enable request. Will parse
> + * out the parameters within the stream enable request, in order to match
> + * requested audio profile to the ones exposed by the USB device connected.
> + *
> + * In addition, will fetch the XHCI transfer resources needed for the handoff to
> + * happen. This includes, transfer ring and buffer addresses and secondary event
> + * ring address. These parameters will be communicated as part of the USB QMI
> + * stream enable response.
> + *
> + */
> +static int prepare_qmi_response(struct snd_usb_substream *subs,
> + struct qmi_uaudio_stream_req_msg_v01 *req_msg,
> + struct qmi_uaudio_stream_resp_msg_v01 *resp, int info_idx)
> +{
> + struct usb_interface *iface;
> + struct usb_host_interface *alts;
> + struct usb_interface_descriptor *altsd;
> + struct usb_interface_assoc_descriptor *assoc;
> + struct usb_host_endpoint *ep;
> + struct uac_format_type_i_continuous_descriptor *fmt;
> + struct uac_format_type_i_discrete_descriptor *fmt_v1;
> + struct uac_format_type_i_ext_descriptor *fmt_v2;
> + struct uac1_as_header_descriptor *as;
> + struct q6usb_offload *data;
> + int ret;
> + int protocol, card_num, pcm_dev_num;
> + void *hdr_ptr;
> + u8 *xfer_buf;
> + unsigned int data_ep_pipe = 0, sync_ep_pipe = 0;
> + u32 len, mult, remainder, xfer_buf_len;
> + unsigned long va, tr_data_va = 0, tr_sync_va = 0;
> + phys_addr_t xhci_pa, xfer_buf_pa, tr_data_pa = 0, tr_sync_pa = 0;
> + struct sg_table *sgt;
> + struct sg_table xfer_buf_sgt;
> + struct page *pg;
> + bool dma_coherent;

consider simplifying or splitting in different functions? you have 20
lines and probably 30-odd variables. This is a bit beyond what reviewers
can handle...
> +
> + iface = usb_ifnum_to_if(subs->dev, subs->cur_audiofmt->iface);
> + if (!iface) {
> + dev_err(uaudio_qdev->dev, "interface # %d does not exist\n",
> + subs->cur_audiofmt->iface);
> + ret = -ENODEV;
> + goto err;
> + }
> +
> + assoc = iface->intf_assoc;
> + pcm_dev_num = (req_msg->usb_token & QMI_STREAM_REQ_DEV_NUM_MASK) >> 8;
> + xfer_buf_len = req_msg->xfer_buff_size;
> + card_num = uaudio_qdev->last_card_num;
> +
> + alts = &iface->altsetting[subs->cur_audiofmt->altset_idx];
> + altsd = get_iface_desc(alts);
> + protocol = altsd->bInterfaceProtocol;
> +
> + /* get format type */
> + if (protocol != UAC_VERSION_3) {
> + fmt = snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL,
> + UAC_FORMAT_TYPE);
> + if (!fmt) {
> + dev_err(uaudio_qdev->dev,
> + "%u:%d : no UAC_FORMAT_TYPE desc\n",
> + subs->cur_audiofmt->iface,
> + subs->cur_audiofmt->altset_idx);
> + ret = -ENODEV;
> + goto err;
> + }
> + }
> +
> + if (!uadev[card_num].ctrl_intf) {
> + dev_err(uaudio_qdev->dev, "audio ctrl intf info not cached\n");
> + ret = -ENODEV;
> + goto err;
> + }
> +
> + if (protocol != UAC_VERSION_3) {
> + hdr_ptr = snd_usb_find_csint_desc(uadev[card_num].ctrl_intf->extra,
> + uadev[card_num].ctrl_intf->extralen, NULL,
> + UAC_HEADER);
> + if (!hdr_ptr) {
> + dev_err(uaudio_qdev->dev, "no UAC_HEADER desc\n");
> + ret = -ENODEV;
> + goto err;
> + }
> + }
> +
> + if (protocol == UAC_VERSION_1) {
> + struct uac1_ac_header_descriptor *uac1_hdr = hdr_ptr;
> +
> + as = snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL,
> + UAC_AS_GENERAL);
> + if (!as) {
> + dev_err(uaudio_qdev->dev,
> + "%u:%d : no UAC_AS_GENERAL desc\n",
> + subs->cur_audiofmt->iface,
> + subs->cur_audiofmt->altset_idx);
> + ret = -ENODEV;
> + goto err;
> + }
> + resp->data_path_delay = as->bDelay;
> + resp->data_path_delay_valid = 1;
> + fmt_v1 = (struct uac_format_type_i_discrete_descriptor *)fmt;
> + resp->usb_audio_subslot_size = fmt_v1->bSubframeSize;
> + resp->usb_audio_subslot_size_valid = 1;
> +
> + resp->usb_audio_spec_revision = le16_to_cpu(uac1_hdr->bcdADC);
> + resp->usb_audio_spec_revision_valid = 1;
> + } else if (protocol == UAC_VERSION_2) {
> + struct uac2_ac_header_descriptor *uac2_hdr = hdr_ptr;
> +
> + fmt_v2 = (struct uac_format_type_i_ext_descriptor *)fmt;
> + resp->usb_audio_subslot_size = fmt_v2->bSubslotSize;
> + resp->usb_audio_subslot_size_valid = 1;
> +
> + resp->usb_audio_spec_revision = le16_to_cpu(uac2_hdr->bcdADC);
> + resp->usb_audio_spec_revision_valid = 1;
> + } else if (protocol == UAC_VERSION_3) {
> + if (assoc->bFunctionSubClass ==
> + UAC3_FUNCTION_SUBCLASS_FULL_ADC_3_0) {
> + dev_err(uaudio_qdev->dev, "full adc is not supported\n");
> + ret = -EINVAL;
> + }
> +
> + switch (le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize)) {
> + case UAC3_BADD_EP_MAXPSIZE_SYNC_MONO_16:
> + case UAC3_BADD_EP_MAXPSIZE_SYNC_STEREO_16:
> + case UAC3_BADD_EP_MAXPSIZE_ASYNC_MONO_16:
> + case UAC3_BADD_EP_MAXPSIZE_ASYNC_STEREO_16: {
> + resp->usb_audio_subslot_size = 0x2;
> + break;
> + }
> +
> + case UAC3_BADD_EP_MAXPSIZE_SYNC_MONO_24:
> + case UAC3_BADD_EP_MAXPSIZE_SYNC_STEREO_24:
> + case UAC3_BADD_EP_MAXPSIZE_ASYNC_MONO_24:
> + case UAC3_BADD_EP_MAXPSIZE_ASYNC_STEREO_24: {
> + resp->usb_audio_subslot_size = 0x3;
> + break;
> + }
> +
> + default:
> + dev_err(uaudio_qdev->dev,
> + "%d: %u: Invalid wMaxPacketSize\n",
> + subs->cur_audiofmt->iface,
> + subs->cur_audiofmt->altset_idx);
> + ret = -EINVAL;
> + goto err;
> + }
> + resp->usb_audio_subslot_size_valid = 1;
> + } else {
> + dev_err(uaudio_qdev->dev, "unknown protocol version %x\n",
> + protocol);
> + ret = -ENODEV;
> + goto err;
> + }

these 100-odd lines look like duplicated code. Why would we redo the
parsing of UAC3 stuff in a QCOM-specific driver?

> +
> + resp->slot_id = subs->dev->slot_id;
> + resp->slot_id_valid = 1;
> +
> + memcpy(&resp->std_as_opr_intf_desc, &alts->desc, sizeof(alts->desc));
> + resp->std_as_opr_intf_desc_valid = 1;
> +
> + ep = usb_pipe_endpoint(subs->dev, subs->data_endpoint->pipe);
> + if (!ep) {
> + dev_err(uaudio_qdev->dev, "data ep # %d context is null\n",
> + subs->data_endpoint->ep_num);
> + ret = -ENODEV;
> + goto err;
> + }
> + data_ep_pipe = subs->data_endpoint->pipe;
> + memcpy(&resp->std_as_data_ep_desc, &ep->desc, sizeof(ep->desc));
> + resp->std_as_data_ep_desc_valid = 1;
> +
> + ret = xhci_sideband_add_endpoint(uadev[card_num].sb, ep);
> + if (ret < 0) {
> + dev_err(uaudio_qdev->dev, "failed to add data ep to sideband\n");
> + ret = -ENODEV;
> + goto err;
> + }
> +
> + sgt = xhci_sideband_get_endpoint_buffer(uadev[card_num].sb, ep);
> + if (!sgt) {
> + dev_err(uaudio_qdev->dev, "failed to get data ep ring address\n");
> + ret = -ENODEV;
> + goto drop_data_ep;
> + }
> +
> + pg = sg_page(sgt->sgl);
> + tr_data_pa = page_to_phys(pg);
> + resp->xhci_mem_info.tr_data.pa = sg_dma_address(sgt->sgl);
> + sg_free_table(sgt);
> +
> + if (subs->sync_endpoint) {
> + ep = usb_pipe_endpoint(subs->dev, subs->sync_endpoint->pipe);
> + if (!ep) {
> + dev_err(uaudio_qdev->dev, "implicit fb on data ep\n");
> + goto skip_sync_ep;
> + }
> + sync_ep_pipe = subs->sync_endpoint->pipe;
> + memcpy(&resp->std_as_sync_ep_desc, &ep->desc, sizeof(ep->desc));
> + resp->std_as_sync_ep_desc_valid = 1;
> +
> + ret = xhci_sideband_add_endpoint(uadev[card_num].sb, ep);
> + if (ret < 0) {
> + dev_err(uaudio_qdev->dev,
> + "failed to add sync ep to sideband\n");
> + ret = -ENODEV;
> + goto drop_data_ep;
> + }
> +
> + sgt = xhci_sideband_get_endpoint_buffer(uadev[card_num].sb, ep);
> + if (!sgt) {
> + dev_err(uaudio_qdev->dev, "failed to get sync ep ring address\n");
> + ret = -ENODEV;
> + goto drop_sync_ep;
> + }
> +
> + pg = sg_page(sgt->sgl);
> + tr_sync_pa = page_to_phys(pg);
> + resp->xhci_mem_info.tr_sync.pa = sg_dma_address(sgt->sgl);
> + sg_free_table(sgt);
> + }
> +
> +skip_sync_ep:
> + data = snd_soc_usb_find_priv_data(usb_get_usb_backend(subs->dev));
> + if (!data)
> + goto drop_sync_ep;
> +
> + uaudio_qdev->domain = data->domain;
> + uaudio_qdev->sid = data->sid;
> + uaudio_qdev->intr_num = data->intr_num;
> + uaudio_qdev->dev = data->dev;
> +
> + resp->interrupter_num_valid = 1;
> + resp->controller_num_valid = 0;
> + ret = usb_get_controller_id(subs->dev);
> + if (ret >= 0) {
> + resp->controller_num = ret;
> + resp->controller_num_valid = 1;
> + }
> + /* map xhci data structures PA memory to iova */
> + dma_coherent = dev_is_dma_coherent(subs->dev->bus->sysdev);
> +
> + /* event ring */
> + ret = xhci_sideband_create_interrupter(uadev[card_num].sb, uaudio_qdev->intr_num);
> + if (ret < 0) {
> + dev_err(uaudio_qdev->dev, "failed to fetch interrupter\n");
> + ret = -ENODEV;
> + goto drop_sync_ep;
> + }
> +
> + sgt = xhci_sideband_get_event_buffer(uadev[card_num].sb);
> + if (!sgt) {
> + dev_err(uaudio_qdev->dev, "failed to get event ring address\n");
> + ret = -ENODEV;
> + goto free_sec_ring;
> + }
> +
> + xhci_pa = page_to_phys(sg_page(sgt->sgl));
> + resp->xhci_mem_info.evt_ring.pa = sg_dma_address(sgt->sgl);
> + sg_free_table(sgt);
> + if (!xhci_pa) {
> + dev_err(uaudio_qdev->dev,
> + "failed to get sec event ring address\n");
> + ret = -ENODEV;
> + goto free_sec_ring;
> + }
> +
> + resp->interrupter_num = xhci_sideband_interrupter_id(uadev[card_num].sb);
> +
> + va = uaudio_iommu_map(MEM_EVENT_RING, dma_coherent, xhci_pa, PAGE_SIZE,
> + NULL);
> + if (!va) {
> + ret = -ENOMEM;
> + goto free_sec_ring;
> + }
> +
> + resp->xhci_mem_info.evt_ring.va = PREPEND_SID_TO_IOVA(va,
> + uaudio_qdev->sid);
> + resp->xhci_mem_info.evt_ring.size = PAGE_SIZE;
> + uaudio_qdev->er_mapped = true;
> +
> + resp->speed_info = get_speed_info(subs->dev->speed);
> + if (resp->speed_info == USB_QMI_DEVICE_SPEED_INVALID_V01) {
> + ret = -ENODEV;
> + goto unmap_er;
> + }
> +
> + resp->speed_info_valid = 1;
> +
> + /* data transfer ring */
> + va = uaudio_iommu_map(MEM_XFER_RING, dma_coherent, tr_data_pa,
> + PAGE_SIZE, NULL);
> + if (!va) {
> + ret = -ENOMEM;
> + goto unmap_er;
> + }
> +
> + tr_data_va = va;
> + resp->xhci_mem_info.tr_data.va = PREPEND_SID_TO_IOVA(va,
> + uaudio_qdev->sid);
> + resp->xhci_mem_info.tr_data.size = PAGE_SIZE;
> +
> + /* sync transfer ring */
> + if (!resp->xhci_mem_info.tr_sync.pa)
> + goto skip_sync;
> +
> + xhci_pa = resp->xhci_mem_info.tr_sync.pa;
> + va = uaudio_iommu_map(MEM_XFER_RING, dma_coherent, tr_sync_pa,
> + PAGE_SIZE, NULL);
> + if (!va) {
> + ret = -ENOMEM;
> + goto unmap_data;
> + }
> +
> + tr_sync_va = va;
> + resp->xhci_mem_info.tr_sync.va = PREPEND_SID_TO_IOVA(va,
> + uaudio_qdev->sid);
> + resp->xhci_mem_info.tr_sync.size = PAGE_SIZE;
> +
> +skip_sync:
> + /* xfer buffer, multiple of 4K only */
> + if (!xfer_buf_len)
> + xfer_buf_len = PAGE_SIZE;
> +
> + mult = xfer_buf_len / PAGE_SIZE;
> + remainder = xfer_buf_len % PAGE_SIZE;
> + len = mult * PAGE_SIZE;
> + len += remainder ? PAGE_SIZE : 0;
> +
> + if (len > MAX_XFER_BUFF_LEN) {
> + dev_err(uaudio_qdev->dev,
> + "req buf len %d > max buf len %lu, setting %lu\n",
> + len, MAX_XFER_BUFF_LEN, MAX_XFER_BUFF_LEN);
> + len = MAX_XFER_BUFF_LEN;
> + }
> +
> + xfer_buf = usb_alloc_coherent(subs->dev, len, GFP_KERNEL, &xfer_buf_pa);
> + if (!xfer_buf) {
> + ret = -ENOMEM;
> + goto unmap_sync;
> + }
> +
> + dma_get_sgtable(subs->dev->bus->sysdev, &xfer_buf_sgt, xfer_buf, xfer_buf_pa,
> + len);
> + va = uaudio_iommu_map(MEM_XFER_BUF, dma_coherent, xfer_buf_pa, len,
> + &xfer_buf_sgt);
> + if (!va) {
> + ret = -ENOMEM;
> + goto unmap_sync;
> + }
> +
> + resp->xhci_mem_info.xfer_buff.pa = xfer_buf_pa;
> + resp->xhci_mem_info.xfer_buff.size = len;
> +
> + resp->xhci_mem_info.xfer_buff.va = PREPEND_SID_TO_IOVA(va,
> + uaudio_qdev->sid);
> +
> + resp->xhci_mem_info_valid = 1;
> +
> + sg_free_table(&xfer_buf_sgt);
> +
> + if (!atomic_read(&uadev[card_num].in_use)) {
> + kref_init(&uadev[card_num].kref);
> + init_waitqueue_head(&uadev[card_num].disconnect_wq);
> + uadev[card_num].num_intf =
> + subs->dev->config->desc.bNumInterfaces;
> + uadev[card_num].info = kcalloc(uadev[card_num].num_intf,
> + sizeof(struct intf_info), GFP_KERNEL);
> + if (!uadev[card_num].info) {
> + ret = -ENOMEM;
> + goto unmap_sync;
> + }
> + uadev[card_num].udev = subs->dev;
> + atomic_set(&uadev[card_num].in_use, 1);
> + } else {
> + kref_get(&uadev[card_num].kref);
> + }
> +
> + uadev[card_num].usb_core_id = resp->controller_num;
> +
> + /* cache intf specific info to use it for unmap and free xfer buf */
> + uadev[card_num].info[info_idx].data_xfer_ring_va = tr_data_va;
> + uadev[card_num].info[info_idx].data_xfer_ring_size = PAGE_SIZE;
> + uadev[card_num].info[info_idx].sync_xfer_ring_va = tr_sync_va;
> + uadev[card_num].info[info_idx].sync_xfer_ring_size = PAGE_SIZE;
> + uadev[card_num].info[info_idx].xfer_buf_va = va;
> + uadev[card_num].info[info_idx].xfer_buf_pa = xfer_buf_pa;
> + uadev[card_num].info[info_idx].xfer_buf_size = len;
> + uadev[card_num].info[info_idx].data_ep_pipe = data_ep_pipe;
> + uadev[card_num].info[info_idx].sync_ep_pipe = sync_ep_pipe;
> + uadev[card_num].info[info_idx].xfer_buf = xfer_buf;
> + uadev[card_num].info[info_idx].pcm_card_num = card_num;
> + uadev[card_num].info[info_idx].pcm_dev_num = pcm_dev_num;
> + uadev[card_num].info[info_idx].direction = subs->direction;
> + uadev[card_num].info[info_idx].intf_num = subs->cur_audiofmt->iface;
> + uadev[card_num].info[info_idx].in_use = true;
> +
> + set_bit(card_num, &uaudio_qdev->card_slot);
> +
> + return 0;
> +
> +unmap_sync:
> + usb_free_coherent(subs->dev, len, xfer_buf, xfer_buf_pa);
> + uaudio_iommu_unmap(MEM_XFER_RING, tr_sync_va, PAGE_SIZE, PAGE_SIZE);
> +unmap_data:
> + uaudio_iommu_unmap(MEM_XFER_RING, tr_data_va, PAGE_SIZE, PAGE_SIZE);
> +unmap_er:
> + uaudio_iommu_unmap(MEM_EVENT_RING, IOVA_BASE, PAGE_SIZE, PAGE_SIZE);
> +free_sec_ring:
> + xhci_sideband_remove_interrupter(uadev[card_num].sb);
> +drop_sync_ep:
> + if (subs->sync_endpoint)
> + xhci_sideband_remove_endpoint(uadev[card_num].sb,
> + usb_pipe_endpoint(subs->dev, subs->sync_endpoint->pipe));
> +drop_data_ep:
> + xhci_sideband_remove_endpoint(uadev[card_num].sb,
> + usb_pipe_endpoint(subs->dev, subs->data_endpoint->pipe));
> +
> +err:
> + return ret;
> +}

this is really the largest function I've seen in a while... Can this use
helpers or be more modular?

> +
> +/**
> + * handle_uaudio_stream_req() - handle stream enable/disable request
> + * @handle: QMI client handle
> + * @sq: qrtr socket
> + * @txn: QMI transaction context
> + * @decoded_msg: decoded QMI message
> + *
> + * Main handler for the QMI stream enable/disable requests. This executes the
> + * corresponding enable/disable stream apis, respectively.
> + *
> + */
> +static void handle_uaudio_stream_req(struct qmi_handle *handle,
> + struct sockaddr_qrtr *sq,
> + struct qmi_txn *txn,
> + const void *decoded_msg)
> +{
> + struct qmi_uaudio_stream_req_msg_v01 *req_msg;
> + struct qmi_uaudio_stream_resp_msg_v01 resp = {{0}, 0};
> + struct snd_usb_substream *subs;
> + struct snd_usb_audio *chip = NULL;
> + struct uaudio_qmi_svc *svc = uaudio_svc;
> + struct intf_info *info;
> + struct usb_host_endpoint *ep;
> + u8 pcm_card_num, pcm_dev_num, direction;
> + int info_idx = -EINVAL, datainterval = -EINVAL, ret = 0;
> +
> + if (!svc->client_connected) {
> + svc->client_sq = *sq;
> + svc->client_connected = true;
> + }
> +
> + mutex_lock(&qdev_mutex);
> + req_msg = (struct qmi_uaudio_stream_req_msg_v01 *)decoded_msg;
> + if (!req_msg->audio_format_valid || !req_msg->bit_rate_valid ||
> + !req_msg->number_of_ch_valid || !req_msg->xfer_buff_size_valid) {
> + ret = -EINVAL;

this looks like copy pasted code, this function return void so all uses
of 'ret' are not so useful, are they?

> + goto response;
> + }
> +
> + if (!uaudio_qdev) {
> + ret = -EINVAL;
> + goto response;
> + }
> +
> + direction = (req_msg->usb_token & QMI_STREAM_REQ_DIRECTION);
> + pcm_dev_num = (req_msg->usb_token & QMI_STREAM_REQ_DEV_NUM_MASK) >> 8;
> + pcm_card_num = req_msg->enable ? uaudio_qdev->last_card_num :
> + ffs(uaudio_qdev->card_slot) - 1;
> + if (pcm_card_num >= SNDRV_CARDS) {
> + ret = -EINVAL;
> + goto response;
> + }
> +
> + if (req_msg->audio_format > USB_QMI_PCM_FORMAT_U32_BE) {
> + ret = -EINVAL;
> + goto response;
> + }
> +
> + subs = find_substream(pcm_card_num, pcm_dev_num, direction);
> + chip = uadev[pcm_card_num].chip;
> + if (!subs || !chip || atomic_read(&chip->shutdown)) {
> + ret = -ENODEV;
> + goto response;
> + }
> +
> + info_idx = info_idx_from_ifnum(pcm_card_num, subs->cur_audiofmt ?
> + subs->cur_audiofmt->iface : -1, req_msg->enable);
> + if (atomic_read(&chip->shutdown) || !subs->stream || !subs->stream->pcm
> + || !subs->stream->chip) {
> + ret = -ENODEV;
> + goto response;
> + }
> +
> + if (req_msg->enable) {
> + if (info_idx < 0 || chip->system_suspend) {
> + ret = -EBUSY;
> + goto response;
> + }
> + }
> +
> + if (req_msg->service_interval_valid) {
> + ret = get_data_interval_from_si(subs,
> + req_msg->service_interval);
> + if (ret == -EINVAL)
> + goto response;
> +
> + datainterval = ret;
> + }
> +
> + uadev[pcm_card_num].ctrl_intf = chip->ctrl_intf;
> +
> + if (req_msg->enable) {
> + ret = enable_audio_stream(subs,
> + map_pcm_format(req_msg->audio_format),
> + req_msg->number_of_ch, req_msg->bit_rate,
> + datainterval);
> +
> + if (!ret)
> + ret = prepare_qmi_response(subs, req_msg, &resp,
> + info_idx);
> + } else {
> + info = &uadev[pcm_card_num].info[info_idx];
> + if (info->data_ep_pipe) {
> + ep = usb_pipe_endpoint(uadev[pcm_card_num].udev,
> + info->data_ep_pipe);
> + if (ep)
> + xhci_sideband_stop_endpoint(uadev[pcm_card_num].sb,
> + ep);
> + xhci_sideband_remove_endpoint(uadev[pcm_card_num].sb, ep);
> + info->data_ep_pipe = 0;
> + }
> +
> + if (info->sync_ep_pipe) {
> + ep = usb_pipe_endpoint(uadev[pcm_card_num].udev,
> + info->sync_ep_pipe);
> + if (ep)
> + xhci_sideband_stop_endpoint(uadev[pcm_card_num].sb,
> + ep);
> + xhci_sideband_remove_endpoint(uadev[pcm_card_num].sb, ep);
> + info->sync_ep_pipe = 0;
> + }
> +
> + disable_audio_stream(subs);
> + }
> +
> +response:
> + if (!req_msg->enable && ret != -EINVAL && ret != -ENODEV) {
> + mutex_lock(&chip->mutex);
> + if (info_idx >= 0) {
> + info = &uadev[pcm_card_num].info[info_idx];
> + uaudio_dev_intf_cleanup(
> + uadev[pcm_card_num].udev,
> + info);
> + }
> + if (atomic_read(&uadev[pcm_card_num].in_use))
> + kref_put(&uadev[pcm_card_num].kref,
> + uaudio_dev_release);
> + mutex_unlock(&chip->mutex);
> + }
> + mutex_unlock(&qdev_mutex);
> +
> + resp.usb_token = req_msg->usb_token;
> + resp.usb_token_valid = 1;
> + resp.internal_status = ret;
> + resp.internal_status_valid = 1;
> + resp.status = ret ? USB_QMI_STREAM_REQ_FAILURE_V01 : ret;
> + resp.status_valid = 1;
> + ret = qmi_send_response(svc->uaudio_svc_hdl, sq, txn,
> + QMI_UAUDIO_STREAM_RESP_V01,
> + QMI_UAUDIO_STREAM_RESP_MSG_V01_MAX_MSG_LEN,
> + qmi_uaudio_stream_resp_msg_v01_ei, &resp);

ret is not used?

> +}


I stopped here...

2023-10-18 00:26:36

by Wesley Cheng

[permalink] [raw]
Subject: Re: [PATCH v9 00/34] Introduce QC USB SND audio offloading support

Hi Pierre,

On 10/17/2023 1:58 PM, Pierre-Louis Bossart wrote:
> It's been a very long time since I reviewed earlier versions, and I am
> still lost on terminology and concepts. The explanations below should
> really be added as a .rst file in Documentation for reference, not just
> as a cover letter.
>

Thanks for the review!

Sure, maybe I can write a more comprehensive documentation that saves
these details somewhere. Will add a RST documentation for material
where necessary.

>> Several Qualcomm based chipsets can support USB audio offloading to a
>> dedicated audio DSP, which can take over issuing transfers to the USB
>> host controller. The intention is to reduce the load on the main
>> processors in the SoC, and allow them to be placed into lower power modes.
>> There are several parts to this design:
>> 1. Adding ASoC binding layer
>> 2. Create a USB backend for Q6DSP
>
> "backend" is a loaded terms for ASoC. Can you clarify which part of the
> ascii art below is a 'backend'?
>

This would be the Q6USB entity which is the DPCM backend for this
particular audio path.

>> 3. Introduce XHCI interrupter support
>> 4. Create vendor ops for the USB SND driver
>>
>> USB | ASoC
>> --------------------------------------------------------------------
>> | _________________________
>> | |sm8250 platform card |
>> | |_________________________|
>> | | |
>> | ___V____ ____V____
>> | |Q6USB | |Q6AFE |
>> | |"codec" | |"cpu" |
>> | |________| |_________|
>> | ^ ^ ^
>> | | |________|
>> | ___V____ |
>> | |SOC-USB | |
>> ________ ________ | | |
>> |USB SND |<--->|QC offld|<------------>|________| |
>> |(card.c)| | |<---------- |
>> |________| |________|___ | | |
>> ^ ^ | | | ____________V_________
>> | | | | | |APR/GLINK |
>> __ V_______________V_____ | | | |______________________|
>> |USB SND (endpoint.c) | | | | ^
>> |_________________________| | | | |
>> ^ | | | ___________V___________
>> | | | |->|audio DSP |
>> ___________V_____________ | | |_______________________|
>> |XHCI HCD |<- |
>> |_________________________| |
>>
>>
>> Adding ASoC binding layer:
>> soc-usb: Intention is to treat a USB port similar to a headphone jack.
>
> What is a 'port'? USB refers to "interfaces" and "endpoints". Is a
> "port" a 1:1 mapping to "endpoint"?
>
> Below I read "AFE port" so not sure what concepts refer to what.
>

"Port" in this explanation refers to the USB port. So the audio device
connected. You are right that a USB device can enumerate w/ multiple
interfaces (ie UAC + HID + ...) so the closest relation to "port" is
"interface." It is not a 1:1 mapping w/ the number of endpoints exposed
by a device.

"AFE port" is just something that has been termed from the audio DSP
end, so that concept of port is not related to the port where USB
devices are connected to. This is something that is defined within the
audio DSP.

>> The port is always present on the device, but cable/pin status can be
>> enabled/disabled. Expose mechanisms for USB backend ASoC drivers to
>> communicate with USB SND.
>>
>> Create a USB backend for Q6DSP:
>> q6usb: Basic backend driver that will be responsible for maintaining the
>
> The asciiart above suggests that q6usb exposes a codec DAI - but the
> backend dailink is created by the platform card?
>

That is my understanding, at least. The machine driver (sm8250.c) has
an API that parses our DT node for the DAI relationships
(qcom_snd_parse_of()), and seems to also create the dailinks.

>> resources needed to initiate a playback stream using the Q6DSP. Will
>
> is capture supported? there's explicit references to "num_capture" in
> following patches.
>

We (QCOM) do not support capture at the moment, but the num_capture was
added to the soc-usb driver, which is platform independent. This is in
case other vendors want to add this support, but have capture included
as well.

>> be the entity that checks to make sure the connected USB audio device
>> supports the requested PCM format. If it does not, the PCM open call will
>> fail, and userpsace ALSA can take action accordingly.
>>
>> Introduce XHCI interrupter support:
>> XHCI HCD supports multiple interrupters, which allows for events to be routed
>> to different event rings. This is determined by "Interrupter Target" field
>> specified in Section "6.4.1.1 Normal TRB" of the XHCI specification.
>>
>> Events in the offloading case will be routed to an event ring that is assigned
>> to the audio DSP.
>>
>> Create vendor ops for the USB SND driver:
>> qc_audio_offload: This particular driver has several components associated
>> with it:
>> - QMI stream request handler
>> - XHCI interrupter and resource management
>> - audio DSP memory management
>>
>> When the audio DSP wants to enable a playback stream, the request is first
>> received by the ASoC platform sound card. Depending on the selected route,
>> ASoC will bring up the individual DAIs in the path. The Q6USB backend DAI
>> will send an AFE port start command (with enabling the USB playback path), and
>> the audio DSP will handle the request accordingly.
>
> what about capture, e.g. for a headset?
>

Not supported yet at the moment.

>> Part of the AFE USB port start handling will have an exchange of control
>> messages using the QMI protocol. The qc_audio_offload driver will populate the
>> buffer information:
>> - Event ring base address
>> - EP transfer ring base address
>>
>> and pass it along to the audio DSP. All endpoint management will now be handed
>> over to the DSP, and the main processor is not involved in transfers.
>>
>> Overall, implementing this feature will still expose separate sound card and PCM
>> devices for both the platorm card and USB audio device:
>
> typo: platform
>

Thanks, will fix this.

>> 0 [SM8250MTPWCD938]: sm8250 - SM8250-MTP-WCD9380-WSA8810-VA-D
>> SM8250-MTP-WCD9380-WSA8810-VA-DMIC
>
> How do you plan on exposing the USB PCM device?
>
> The lines above are really cryptic, and with no USB reference in any of
> the short/long card names it's not obvious that this card is different
> from the no-offload case, is it?
>

In the end, since the offload case is handled by the audio DSP, it would
have to go through the platform/machine sound card. That is the sm8250
device above.

>> 1 [Audio ]: USB-Audio - USB Audio
>> Generic USB Audio at usb-xhci-hcd.1.auto-1.4, high speed
>
> likewise some sort of qualifier would be useful to show that card 0 and
> card 1 can target the same USB endpoints.
>

Do userspace entities look at this card string? Assuming there is only
one platform card, there are situations where maybe multiple USB audio
devices are connected to the same USB root hub, so offloading can happen
on any one of them (not at the same time).

Thanks
Wesley Cheng

2023-10-18 01:46:20

by Wesley Cheng

[permalink] [raw]
Subject: Re: [PATCH v9 09/34] ASoC: qcom: qdsp6: Introduce USB AFE port to q6dsp

Hi Pierre,

On 10/17/2023 2:32 PM, Pierre-Louis Bossart wrote:
>
>
> On 10/17/23 15:00, Wesley Cheng wrote:
>> The QC ADSP is able to support USB playback endpoints, so that the main
>
> playback only?
>

Correct, playback only at this time.

>> application processor can be placed into lower CPU power modes. This adds
>> the required AFE port configurations and port start command to start an
>> audio session.
>>
>> Specifically, the QC ADSP can support all potential endpoints that are
>> exposed by the audio data interface. This includes, feedback endpoints
>> (both implicit and explicit) as well as the isochronous (data) endpoints.
>
> implicit feedback means support for capture. This is confusing...
>

I mean, a USB device can expose a capture path, but as of now, we won't
enable the offloading to the audio DSP for it. However, if we're
executing playback, and device does support implicit feedback, we will
pass that along to the audio DSP to utilize.

>> +static int q6usb_hw_params(struct snd_pcm_substream *substream,
>> + struct snd_pcm_hw_params *params,
>> + struct snd_soc_dai *dai)
>> +{
>> + struct q6afe_dai_data *dai_data = dev_get_drvdata(dai->dev);
>> + int channels = params_channels(params);
>> + int rate = params_rate(params);
>> + struct q6afe_usb_cfg *usb = &dai_data->port_config[dai->id].usb_audio;
>> +
>> + usb->sample_rate = rate;
>> + usb->num_channels = channels;
>> +
>> + switch (params_format(params)) {
>> + case SNDRV_PCM_FORMAT_U16_LE:
>> + case SNDRV_PCM_FORMAT_S16_LE:
>> + case SNDRV_PCM_FORMAT_SPECIAL:
>
> what does FORMAT_SPECIAL mean? the only other reference I see to this is
> related to SLIMbus, not sure how this is related?
>

Thanks for catching this. It shouldn't be included in this path.

>> + usb->bit_width = 16;
>> + break;
>> + case SNDRV_PCM_FORMAT_S24_LE:
>> + case SNDRV_PCM_FORMAT_S24_3LE:
>> + usb->bit_width = 24;
>> + break;
>> + case SNDRV_PCM_FORMAT_S32_LE:
>> + usb->bit_width = 32;
>> + break;
>> + default:
>> + dev_err(dai->dev, "%s: invalid format %d\n",
>> + __func__, params_format(params));
>> + return -EINVAL;
>> + }
>> +
>> + return 0;
>> +}
>
>> @@ -617,6 +655,9 @@ static const struct snd_soc_dapm_route q6afe_dapm_routes[] = {
>> {"TX_CODEC_DMA_TX_5", NULL, "TX_CODEC_DMA_TX_5 Capture"},
>> {"RX_CODEC_DMA_RX_6 Playback", NULL, "RX_CODEC_DMA_RX_6"},
>> {"RX_CODEC_DMA_RX_7 Playback", NULL, "RX_CODEC_DMA_RX_7"},
>> +
>> + /* USB playback AFE port receives data for playback, hence use the RX port */
>> + {"USB Playback", NULL, "USB_RX"},
>
> Capture for implicit feedback?
>

Please refer to the above comment.

>> };
>>
>> static int msm_dai_q6_dai_probe(struct snd_soc_dai *dai)
>> @@ -644,6 +685,18 @@ static int msm_dai_q6_dai_remove(struct snd_soc_dai *dai)
>> return 0;
>> }
>>
>> +static const struct snd_soc_dai_ops q6usb_ops = {
>> + .probe = msm_dai_q6_dai_probe,
>> + .prepare = q6afe_dai_prepare,
>> + .hw_params = q6usb_hw_params,
>
> this is rather confusing with two different layers used for hw_params
> and prepare? Additional comments or explanations wouldn't hurt.
>

I thought this was how the ASoC design was. Each DAI defined for a
particular path has it own set of callbacks implemented to bring up any
required resources for that entity. So in this case, it initializes the
"cpu" DAI, which is the main component that handles communication with
the audio DSP.

>> + .shutdown = q6afe_dai_shutdown,
>> + /*
>> + * Startup callback not needed, as AFE port start command passes the PCM
>> + * parameters within the AFE command, which is provided by the PCM core
>> + * during the prepare() stage.
>
> This doesn't really explain why you need a shutdown?
>
>

Sure, I'll add a comment. shutdown() is needed to actually issue a AFE
port stop command to stop pumping audio data on a particular AFE port.
This occurs when userspace closes the PCM device for the platform sound
card, and is triggered for all linked DAIs.

>> + * struct afe_param_id_usb_audio_dev_latency_mode
>> + * @cfg_minor_version: Minor version used for tracking USB audio device
>> + * configuration.
>> + * Supported values:
>> + * AFE_API_MINOR_VERSION_USB_AUDIO_LATENCY_MODE
>> + * @mode: latency mode for the USB audio device
>
> what are the different latency modes? and is this related to the latency
> reporting that was added in the USB2 audio class IIRC?
>

Must've missed removing this part during one of the earlier revision
cleanups I had done. We aren't setting this parameter currently on the
AFE side, and it isn't utilized either in the audio DSP, so I will
remove this definition.

>> +static int afe_port_send_usb_dev_param(struct q6afe_port *port, struct q6afe_usb_cfg *cfg)
>> +{
>> + union afe_port_config *pcfg = &port->port_cfg;
>> + struct afe_param_id_usb_audio_dev_params usb_dev;
>> + struct afe_param_id_usb_audio_dev_lpcm_fmt lpcm_fmt;
>> + struct afe_param_id_usb_audio_svc_interval svc_int;
>> + int ret = 0;
>
> useless init overridden...

Will fix this.

>> +
>> + if (!pcfg) {
>> + dev_err(port->afe->dev, "%s: Error, no configuration data\n", __func__);
>> + ret = -EINVAL;
>> + goto exit;
>> + }
>> +
>> + memset(&usb_dev, 0, sizeof(usb_dev));
>> + memset(&lpcm_fmt, 0, sizeof(lpcm_fmt));
>> + memset(&svc_int, 0, sizeof(svc_int));
>> +
>> + usb_dev.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
>> + ret = q6afe_port_set_param_v2(port, &usb_dev,
>
> .... here
>
>> + AFE_PARAM_ID_USB_AUDIO_DEV_PARAMS,
>> + AFE_MODULE_AUDIO_DEV_INTERFACE, sizeof(usb_dev));
>> + if (ret) {
>> + dev_err(port->afe->dev, "%s: AFE device param cmd failed %d\n",
>> + __func__, ret);
>> + goto exit;
>> + }
>> +
>> + lpcm_fmt.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
>> + lpcm_fmt.endian = pcfg->usb_cfg.endian;
>> + ret = q6afe_port_set_param_v2(port, &lpcm_fmt,
>> + AFE_PARAM_ID_USB_AUDIO_DEV_LPCM_FMT,
>> + AFE_MODULE_AUDIO_DEV_INTERFACE, sizeof(lpcm_fmt));
>> + if (ret) {
>> + dev_err(port->afe->dev, "%s: AFE device param cmd LPCM_FMT failed %d\n",
>> + __func__, ret);
>> + goto exit;
>> + }
>> +
>> + svc_int.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
>> + svc_int.svc_interval = pcfg->usb_cfg.service_interval;
>> + ret = q6afe_port_set_param_v2(port, &svc_int,
>> + AFE_PARAM_ID_USB_AUDIO_SVC_INTERVAL,
>> + AFE_MODULE_AUDIO_DEV_INTERFACE, sizeof(svc_int));
>> + if (ret)
>> + dev_err(port->afe->dev, "%s: AFE device param cmd svc_interval failed %d\n",
>> + __func__, ret);
>> +
>> +exit:
>> + return ret;
>> +}
>
>> -#define AFE_PORT_MAX 129
>> +#define AFE_PORT_MAX 137
>
> does this mean 8 ports are reserved for USB?
>
> Or is this 137 just a random index coming from the AFE design?
>
>

Its the latter. Each port has a defined number/ID on the audio DSP AFE end.

Thanks
Wesley Cheng

2023-10-18 13:57:31

by Pierre-Louis Bossart

[permalink] [raw]
Subject: Re: [PATCH v9 09/34] ASoC: qcom: qdsp6: Introduce USB AFE port to q6dsp


>>> Specifically, the QC ADSP can support all potential endpoints that are
>>> exposed by the audio data interface.  This includes, feedback endpoints
>>> (both implicit and explicit) as well as the isochronous (data)
>>> endpoints.
>>
>> implicit feedback means support for capture. This is confusing...
>>
>
> I mean, a USB device can expose a capture path, but as of now, we won't
> enable the offloading to the audio DSP for it.  However, if we're
> executing playback, and device does support implicit feedback, we will
> pass that along to the audio DSP to utilize.

Not following. Implicit feedback means a capture stream *SHALL* be
started. Are you saying this capture stream is hidden and handled at the
DSP level only? If yes, what prevents you from exposing the capture
stream to userspace as well?

I must be missing something.

>>>   +static const struct snd_soc_dai_ops q6usb_ops = {
>>> +    .probe        = msm_dai_q6_dai_probe,
>>> +    .prepare    = q6afe_dai_prepare,
>>> +    .hw_params    = q6usb_hw_params,
>>
>> this is rather confusing with two different layers used for hw_params
>> and prepare? Additional comments or explanations wouldn't hurt.
>>
>
> I thought this was how the ASoC design was.  Each DAI defined for a
> particular path has it own set of callbacks implemented to bring up any
> required resources for that entity.  So in this case, it initializes the
> "cpu" DAI, which is the main component that handles communication with
> the audio DSP.

Usually prepare and hw_params rely on the type of DAI callbacks, but
here you are mixing "q6afe" and "q6usb" which are shown in your Patch0
diagram as "cpu" and "codec" dais respectively. I don't think it's
correct to tie the two, it's a clear layering violation IMHO. The codec
dai .prepare should not invoke something that modifies the state of the
CPU dai, which should have its own .prepare callback.

2023-10-18 13:58:06

by Pierre-Louis Bossart

[permalink] [raw]
Subject: Re: [PATCH v9 00/34] Introduce QC USB SND audio offloading support



On 10/17/23 19:25, Wesley Cheng wrote:
> Hi Pierre,
>
> On 10/17/2023 1:58 PM, Pierre-Louis Bossart wrote:
>> It's been a very long time since I reviewed earlier versions, and I am
>> still lost on terminology and concepts. The explanations below should
>> really be added as a .rst file in Documentation for reference, not just
>> as a cover letter.
>>
>
> Thanks for the review!
>
> Sure, maybe I can write a more comprehensive documentation that saves
> these details somewhere.  Will add a RST documentation for material
> where necessary.
>
>>> Several Qualcomm based chipsets can support USB audio offloading to a
>>> dedicated audio DSP, which can take over issuing transfers to the USB
>>> host controller.  The intention is to reduce the load on the main
>>> processors in the SoC, and allow them to be placed into lower power
>>> modes.
>>> There are several parts to this design:
>>>    1. Adding ASoC binding layer
>>>    2. Create a USB backend for Q6DSP
>>
>> "backend" is a loaded terms for ASoC. Can you clarify which part of the
>> ascii art below is a 'backend'?
>>
>
> This would be the Q6USB entity which is the DPCM backend for this
> particular audio path.

DPCM is about dailinks. Technically the q6usb entity is a codec dai
which is part of a DPCM backend dailink.
>
>>>    3. Introduce XHCI interrupter support
>>>    4. Create vendor ops for the USB SND driver
>>>
>>>        USB                          |            ASoC
>>> --------------------------------------------------------------------
>>>                                     |  _________________________
>>>                                     | |sm8250 platform card     |
>>>                                     | |_________________________|
>>>                                     |         |           |
>>>                                     |      ___V____   ____V____
>>>                                     |     |Q6USB   | |Q6AFE    |
>>>                                     |     |"codec" | |"cpu"    |
>>>                                     |     |________| |_________|
>>>                                     |         ^  ^        ^
>>>                                     |         |  |________|
>>>                                     |      ___V____    |
>>>                                     |     |SOC-USB |   |
>>>     ________       ________               |        |   |
>>>    |USB SND |<--->|QC offld|<------------>|________|   |
>>>    |(card.c)|     |        |<----------                |
>>>    |________|     |________|___     | |                |
>>>        ^               ^       |    | |    ____________V_________
>>>        |               |       |    | |   |APR/GLINK             |
>>>     __ V_______________V_____  |    | |   |______________________|
>>>    |USB SND (endpoint.c)     | |    | |              ^
>>>    |_________________________| |    | |              |
>>>                ^               |    | |   ___________V___________
>>>                |               |    | |->|audio DSP              |
>>>     ___________V_____________  |    |    |_______________________|
>>>    |XHCI HCD                 |<-    |
>>>    |_________________________|      |
>>>
>>>
>>> Adding ASoC binding layer:
>>> soc-usb: Intention is to treat a USB port similar to a headphone jack.
>>
>> What is a 'port'? USB refers to "interfaces" and "endpoints". Is a
>> "port" a 1:1 mapping to "endpoint"?
>>
>> Below I read "AFE port" so not sure what concepts refer to what.
>>
>
> "Port" in this explanation refers to the USB port.  So the audio device
> connected.  You are right that a USB device can enumerate w/ multiple
> interfaces (ie UAC + HID + ...) so the closest relation to "port" is
> "interface."  It is not a 1:1 mapping w/ the number of endpoints exposed
> by a device.
>
> "AFE port" is just something that has been termed from the audio DSP
> end, so that concept of port is not related to the port where USB
> devices are connected to.  This is something that is defined within the
> audio DSP.

Wow. So there's a "USB port" and "AFE port". I would recommend avoiding
the same term for completely different concepts. Why not use "USB device"?

>>>   0 [SM8250MTPWCD938]: sm8250 - SM8250-MTP-WCD9380-WSA8810-VA-D
>>>                        SM8250-MTP-WCD9380-WSA8810-VA-DMIC
>>
>> How do you plan on exposing the USB PCM device?
>>
>> The lines above are really cryptic, and with no USB reference in any of
>> the short/long card names it's not obvious that this card is different
>> from the no-offload case, is it?
>>
>
> In the end, since the offload case is handled by the audio DSP, it would
> have to go through the platform/machine sound card.  That is the sm8250
> device above.
>
>>>   1 [Audio          ]: USB-Audio - USB Audio
>>>                        Generic USB Audio at usb-xhci-hcd.1.auto-1.4,
>>> high speed
>>
>> likewise some sort of qualifier would be useful to show that card 0 and
>> card 1 can target the same USB endpoints.
>>
>
> Do userspace entities look at this card string?  Assuming there is only
> one platform card, there are situations where maybe multiple USB audio
> devices are connected to the same USB root hub, so offloading can happen
> on any one of them (not at the same time).

Jaroslav cares, as measured by the changes over the years to make the
card names more self-explanatory.

I really don't see anything in the SM8250MTPWCD938 card name that would
hint at the support of USB. If it's not in the card string, maybe this
can be added in the component string as well (amixer -Dhw:0 info). The
point is that userspace should not have to maintain an 'accept-list' of
card names but have the means to check the USB offload capability with a
vendor-neutral convention.

2023-10-18 19:37:34

by Wesley Cheng

[permalink] [raw]
Subject: Re: [PATCH v9 09/34] ASoC: qcom: qdsp6: Introduce USB AFE port to q6dsp

Hi Pierre,

On 10/18/2023 6:47 AM, Pierre-Louis Bossart wrote:
>
>>>> Specifically, the QC ADSP can support all potential endpoints that are
>>>> exposed by the audio data interface.  This includes, feedback endpoints
>>>> (both implicit and explicit) as well as the isochronous (data)
>>>> endpoints.
>>>
>>> implicit feedback means support for capture. This is confusing...
>>>
>>
>> I mean, a USB device can expose a capture path, but as of now, we won't
>> enable the offloading to the audio DSP for it.  However, if we're
>> executing playback, and device does support implicit feedback, we will
>> pass that along to the audio DSP to utilize.
>
> Not following. Implicit feedback means a capture stream *SHALL* be
> started. Are you saying this capture stream is hidden and handled at the
> DSP level only? If yes, what prevents you from exposing the capture
> stream to userspace as well?
>
> I must be missing something.
>

My understanding is that with implicit feedback endpoints, it allows for
another data endpoint in the opposite direction to be utilized as a
feedback endpoint (versus having to expose another EP, such as in the
case of explicit feedback). For example, if we are enabling the
playback path (and the device does have a capture data ep) then the data
ep used for the capture path can be used.

USB2.0 spec, section 5.12.4.3 (Implicit Feedback)
"
Two cases can arise:
• One or more asynchronous sink endpoints are accompanied by an
asynchronous source endpoint. The
data rate on the source endpoint can be used as implicit feedback
information to adjust the data rate on
the sink endpoint(s).
• One or more adaptive source endpoints are accompanied by an adaptive
sink endpoint. The source
endpoint can adjust its data rate based on the data rate received by the
sink endpoint.
"

The DSP will get this as part of the USB sync endpoint information which
it will use to enable this EP.

>>>>   +static const struct snd_soc_dai_ops q6usb_ops = {
>>>> +    .probe        = msm_dai_q6_dai_probe,
>>>> +    .prepare    = q6afe_dai_prepare,
>>>> +    .hw_params    = q6usb_hw_params,
>>>
>>> this is rather confusing with two different layers used for hw_params
>>> and prepare? Additional comments or explanations wouldn't hurt.
>>>
>>
>> I thought this was how the ASoC design was.  Each DAI defined for a
>> particular path has it own set of callbacks implemented to bring up any
>> required resources for that entity.  So in this case, it initializes the
>> "cpu" DAI, which is the main component that handles communication with
>> the audio DSP.
>
> Usually prepare and hw_params rely on the type of DAI callbacks, but
> here you are mixing "q6afe" and "q6usb" which are shown in your Patch0
> diagram as "cpu" and "codec" dais respectively. I don't think it's
> correct to tie the two, it's a clear layering violation IMHO. The codec
> dai .prepare should not invoke something that modifies the state of the
> CPU dai, which should have its own .prepare callback.

OK, I think I know where the misunderstanding is. The API callback for
hw_params() that is being registered here exists in q6afe, but with the
q6usb prefix. I will fix that in the next rev.

Thanks
Wesley Cheng

2023-10-18 20:21:41

by Wesley Cheng

[permalink] [raw]
Subject: Re: [PATCH v9 00/34] Introduce QC USB SND audio offloading support

Hi Pierre,

On 10/18/2023 6:54 AM, Pierre-Louis Bossart wrote:
>
>
> On 10/17/23 19:25, Wesley Cheng wrote:
>> Hi Pierre,
>>
>> On 10/17/2023 1:58 PM, Pierre-Louis Bossart wrote:
>>> It's been a very long time since I reviewed earlier versions, and I am
>>> still lost on terminology and concepts. The explanations below should
>>> really be added as a .rst file in Documentation for reference, not just
>>> as a cover letter.
>>>
>>
>> Thanks for the review!
>>
>> Sure, maybe I can write a more comprehensive documentation that saves
>> these details somewhere.  Will add a RST documentation for material
>> where necessary.
>>
>>>> Several Qualcomm based chipsets can support USB audio offloading to a
>>>> dedicated audio DSP, which can take over issuing transfers to the USB
>>>> host controller.  The intention is to reduce the load on the main
>>>> processors in the SoC, and allow them to be placed into lower power
>>>> modes.
>>>> There are several parts to this design:
>>>>    1. Adding ASoC binding layer
>>>>    2. Create a USB backend for Q6DSP
>>>
>>> "backend" is a loaded terms for ASoC. Can you clarify which part of the
>>> ascii art below is a 'backend'?
>>>
>>
>> This would be the Q6USB entity which is the DPCM backend for this
>> particular audio path.
>
> DPCM is about dailinks. Technically the q6usb entity is a codec dai
> which is part of a DPCM backend dailink.
>>
>>>>    3. Introduce XHCI interrupter support
>>>>    4. Create vendor ops for the USB SND driver
>>>>
>>>>        USB                          |            ASoC
>>>> --------------------------------------------------------------------
>>>>                                     |  _________________________
>>>>                                     | |sm8250 platform card     |
>>>>                                     | |_________________________|
>>>>                                     |         |           |
>>>>                                     |      ___V____   ____V____
>>>>                                     |     |Q6USB   | |Q6AFE    |
>>>>                                     |     |"codec" | |"cpu"    |
>>>>                                     |     |________| |_________|
>>>>                                     |         ^  ^        ^
>>>>                                     |         |  |________|
>>>>                                     |      ___V____    |
>>>>                                     |     |SOC-USB |   |
>>>>     ________       ________               |        |   |
>>>>    |USB SND |<--->|QC offld|<------------>|________|   |
>>>>    |(card.c)|     |        |<----------                |
>>>>    |________|     |________|___     | |                |
>>>>        ^               ^       |    | |    ____________V_________
>>>>        |               |       |    | |   |APR/GLINK             |
>>>>     __ V_______________V_____  |    | |   |______________________|
>>>>    |USB SND (endpoint.c)     | |    | |              ^
>>>>    |_________________________| |    | |              |
>>>>                ^               |    | |   ___________V___________
>>>>                |               |    | |->|audio DSP              |
>>>>     ___________V_____________  |    |    |_______________________|
>>>>    |XHCI HCD                 |<-    |
>>>>    |_________________________|      |
>>>>
>>>>
>>>> Adding ASoC binding layer:
>>>> soc-usb: Intention is to treat a USB port similar to a headphone jack.
>>>
>>> What is a 'port'? USB refers to "interfaces" and "endpoints". Is a
>>> "port" a 1:1 mapping to "endpoint"?
>>>
>>> Below I read "AFE port" so not sure what concepts refer to what.
>>>
>>
>> "Port" in this explanation refers to the USB port.  So the audio device
>> connected.  You are right that a USB device can enumerate w/ multiple
>> interfaces (ie UAC + HID + ...) so the closest relation to "port" is
>> "interface."  It is not a 1:1 mapping w/ the number of endpoints exposed
>> by a device.
>>
>> "AFE port" is just something that has been termed from the audio DSP
>> end, so that concept of port is not related to the port where USB
>> devices are connected to.  This is something that is defined within the
>> audio DSP.
>
> Wow. So there's a "USB port" and "AFE port". I would recommend avoiding
> the same term for completely different concepts. Why not use "USB device"?
>

I think maybe USB interface is probably the most acceptable, since even
at the USB snd level, they work based on usb_interface, not on the udev
(USB device) itself.

>>>>   0 [SM8250MTPWCD938]: sm8250 - SM8250-MTP-WCD9380-WSA8810-VA-D
>>>>                        SM8250-MTP-WCD9380-WSA8810-VA-DMIC
>>>
>>> How do you plan on exposing the USB PCM device?
>>>
>>> The lines above are really cryptic, and with no USB reference in any of
>>> the short/long card names it's not obvious that this card is different
>>> from the no-offload case, is it?
>>>
>>
>> In the end, since the offload case is handled by the audio DSP, it would
>> have to go through the platform/machine sound card.  That is the sm8250
>> device above.
>>
>>>>   1 [Audio          ]: USB-Audio - USB Audio
>>>>                        Generic USB Audio at usb-xhci-hcd.1.auto-1.4,
>>>> high speed
>>>
>>> likewise some sort of qualifier would be useful to show that card 0 and
>>> card 1 can target the same USB endpoints.
>>>
>>
>> Do userspace entities look at this card string?  Assuming there is only
>> one platform card, there are situations where maybe multiple USB audio
>> devices are connected to the same USB root hub, so offloading can happen
>> on any one of them (not at the same time).
>
> Jaroslav cares, as measured by the changes over the years to make the
> card names more self-explanatory.
>
> I really don't see anything in the SM8250MTPWCD938 card name that would
> hint at the support of USB. If it's not in the card string, maybe this
> can be added in the component string as well (amixer -Dhw:0 info). The
> point is that userspace should not have to maintain an 'accept-list' of
> card names but have the means to check the USB offload capability with a
> vendor-neutral convention.

I'll take a look at adding it into the components string. At least in
that case, we'd be able to dynamically modify to say if USB offload is
supported or not based on the child entries/paths that are defined in
the DT node.

Thanks
Wesley Cheng

2023-10-18 20:22:09

by Wesley Cheng

[permalink] [raw]
Subject: Re: [PATCH v9 20/34] ALSA: usb-audio: Check for support for requested audio format

Hi Pierre,

On 10/17/2023 3:29 PM, Pierre-Louis Bossart wrote:
>
>
> On 10/17/23 15:00, Wesley Cheng wrote:
>> Allow for checks on a specific USB audio device to see if a requested PCM
>> format is supported. This is needed for support for when playback is
>
> This is needed for support when playback is
>

Will fix this typo

>> initiated by the ASoC USB backend path.
>>
>> Signed-off-by: Wesley Cheng <[email protected]>
>> ---
>> sound/usb/card.c | 40 ++++++++++++++++++++++++++++++++++++++++
>> sound/usb/card.h | 11 +++++++++++
>> 2 files changed, 51 insertions(+)
>>
>> diff --git a/sound/usb/card.c b/sound/usb/card.c
>> index c0b312e264bf..88f431917c15 100644
>> --- a/sound/usb/card.c
>> +++ b/sound/usb/card.c
>> @@ -162,6 +162,46 @@ int snd_usb_unregister_platform_ops(void)
>> }
>> EXPORT_SYMBOL_GPL(snd_usb_unregister_platform_ops);
>>
>> +/*
>> + * Checks to see if requested audio profile, i.e sample rate, # of
>> + * channels, etc... is supported by the substream associated to the
>> + * USB audio device.
>> + */
>> +struct snd_usb_stream *snd_usb_find_suppported_substream(int card_idx,
>> + struct snd_pcm_hw_params *params, int direction)
>> +{
>> + struct snd_usb_audio *chip;
>> + struct snd_usb_substream *subs = NULL;
>
> useless init?
>

Agreed.

Thanks
Wesley Cheng

2023-10-19 01:42:57

by Wesley Cheng

[permalink] [raw]
Subject: Re: [PATCH v9 30/34] ASoC: qcom: qdsp6: Add SND kcontrol for fetching offload status

Hi Pierre,

On 10/17/2023 3:53 PM, Pierre-Louis Bossart wrote:
>
>
> On 10/17/23 15:01, Wesley Cheng wrote:
>> Add a kcontrol to the platform sound card to fetch the current offload
>> status. This can allow for userspace to ensure/check which USB SND
>> resources are actually busy versus having to attempt opening the USB SND
>> devices, which will result in an error if offloading is active.
>
> I think I mentioned this a while back, but why not add the status in the
> USB card itself? That's a generic component that all userspace agent
> could query. Having a QCOM-specific control doesn't make the life of
> userspace easier IMHO.
>
>

Will take a look at this based on the comments you had in the other
kcontrol patch. Seeing if we can move it to a more generic layer.

Thanks
Wesley Cheng

2023-10-19 13:04:39

by Pierre-Louis Bossart

[permalink] [raw]
Subject: Re: [PATCH v9 09/34] ASoC: qcom: qdsp6: Introduce USB AFE port to q6dsp



>>>>> Specifically, the QC ADSP can support all potential endpoints that are
>>>>> exposed by the audio data interface.  This includes, feedback
>>>>> endpoints
>>>>> (both implicit and explicit) as well as the isochronous (data)
>>>>> endpoints.
>>>>
>>>> implicit feedback means support for capture. This is confusing...
>>>>
>>>
>>> I mean, a USB device can expose a capture path, but as of now, we won't
>>> enable the offloading to the audio DSP for it.  However, if we're
>>> executing playback, and device does support implicit feedback, we will
>>> pass that along to the audio DSP to utilize.
>>
>> Not following. Implicit feedback means a capture stream *SHALL* be
>> started. Are you saying this capture stream is hidden and handled at the
>> DSP level only? If yes, what prevents you from exposing the capture
>> stream to userspace as well?
>>
>> I must be missing something.
>>
>
> My understanding is that with implicit feedback endpoints, it allows for
> another data endpoint in the opposite direction to be utilized as a
> feedback endpoint (versus having to expose another EP, such as in the
> case of explicit feedback).  For example, if we are enabling the
> playback path (and the device does have a capture data ep) then the data
> ep used for the capture path can be used.

That's right, so all the plumbing is enabled for the capture path...
Making a decision to discard the data is very odd, all the work has
already been done at lower levels, so why not expose the captured data?

2023-10-19 18:43:07

by Wesley Cheng

[permalink] [raw]
Subject: Re: [PATCH v9 09/34] ASoC: qcom: qdsp6: Introduce USB AFE port to q6dsp

Hi Pierre,

On 10/18/2023 6:00 PM, Pierre-Louis Bossart wrote:
>
>
>>>>>> Specifically, the QC ADSP can support all potential endpoints that are
>>>>>> exposed by the audio data interface.  This includes, feedback
>>>>>> endpoints
>>>>>> (both implicit and explicit) as well as the isochronous (data)
>>>>>> endpoints.
>>>>>
>>>>> implicit feedback means support for capture. This is confusing...
>>>>>
>>>>
>>>> I mean, a USB device can expose a capture path, but as of now, we won't
>>>> enable the offloading to the audio DSP for it.  However, if we're
>>>> executing playback, and device does support implicit feedback, we will
>>>> pass that along to the audio DSP to utilize.
>>>
>>> Not following. Implicit feedback means a capture stream *SHALL* be
>>> started. Are you saying this capture stream is hidden and handled at the
>>> DSP level only? If yes, what prevents you from exposing the capture
>>> stream to userspace as well?
>>>
>>> I must be missing something.
>>>
>>
>> My understanding is that with implicit feedback endpoints, it allows for
>> another data endpoint in the opposite direction to be utilized as a
>> feedback endpoint (versus having to expose another EP, such as in the
>> case of explicit feedback).  For example, if we are enabling the
>> playback path (and the device does have a capture data ep) then the data
>> ep used for the capture path can be used.
>
> That's right, so all the plumbing is enabled for the capture path...
> Making a decision to discard the data is very odd, all the work has
> already been done at lower levels, so why not expose the captured data?
>

So that would be at the USB level, but from the audio DSP end, there are
still things that need to be enabled to route the data properly. For
feedback endpoints, the data we're actually sending won't involve the
audio streaming side of things on the DSP.

Thanks
Wesley Cheng

2023-10-19 19:26:29

by Wesley Cheng

[permalink] [raw]
Subject: Re: [PATCH v9 30/34] ASoC: qcom: qdsp6: Add SND kcontrol for fetching offload status

Hi Pierre,

On 10/18/2023 6:41 PM, Wesley Cheng wrote:
> Hi Pierre,
>
> On 10/17/2023 3:53 PM, Pierre-Louis Bossart wrote:
>>
>>
>> On 10/17/23 15:01, Wesley Cheng wrote:
>>> Add a kcontrol to the platform sound card to fetch the current offload
>>> status.  This can allow for userspace to ensure/check which USB SND
>>> resources are actually busy versus having to attempt opening the USB SND
>>> devices, which will result in an error if offloading is active.
>>
>> I think I mentioned this a while back, but why not add the status in the
>> USB card itself? That's a generic component that all userspace agent
>> could query. Having a QCOM-specific control doesn't make the life of
>> userspace easier IMHO.
>>
>>
>
> Will take a look at this based on the comments you had in the other
> kcontrol patch.  Seeing if we can move it to a more generic layer.
>

I think it would make more sense to see if we can keep all the offload
kcontrols under the sound card exposed by the platform. Especially, if
we are going to modify the components string of the card to signify that
it supports USB offload.

Thanks
Wesley Cheng

2023-10-20 13:25:07

by Pierre-Louis Bossart

[permalink] [raw]
Subject: Re: [PATCH v9 30/34] ASoC: qcom: qdsp6: Add SND kcontrol for fetching offload status


>>>> Add a kcontrol to the platform sound card to fetch the current offload
>>>> status.  This can allow for userspace to ensure/check which USB SND
>>>> resources are actually busy versus having to attempt opening the USB
>>>> SND
>>>> devices, which will result in an error if offloading is active.
>>>
>>> I think I mentioned this a while back, but why not add the status in the
>>> USB card itself? That's a generic component that all userspace agent
>>> could query. Having a QCOM-specific control doesn't make the life of
>>> userspace easier IMHO.
>>>
>>>
>>
>> Will take a look at this based on the comments you had in the other
>> kcontrol patch.  Seeing if we can move it to a more generic layer.
>>
>
> I think it would make more sense to see if we can keep all the offload
> kcontrols under the sound card exposed by the platform.  Especially, if
> we are going to modify the components string of the card to signify that
> it supports USB offload.

A two-way relationship would be ideal, i.e.
- the USB card has an indicator that it's currently bound with another
"platform" card that offers optimized offloaded capabilities.
- the platform card has a indicator that it exposes one or more PCM
devices routed to the USB card endpoint.

Android/HAL would typically start with the latter while other more
generic solutions would start from the former.

2023-10-23 21:56:25

by Wesley Cheng

[permalink] [raw]
Subject: Re: [PATCH v9 34/34] ASoC: usb: Rediscover USB SND devices on USB port add

Hi Pierre,

On 10/17/2023 4:11 PM, Pierre-Louis Bossart wrote:
>
>
> On 10/17/23 15:01, Wesley Cheng wrote:
>> In case the USB backend device has not been initialized/probed, USB SND
>> device connections can still occur. When the USB backend is eventually
>> made available, previous USB SND device connections are not communicated to
>> the USB backend. Call snd_usb_rediscover_devices() to generate the connect
>> callbacks for all USB SND devices connected. This will allow for the USB
>> backend to be updated with the current set of devices available.
>>
>> The chip array entries are all populated and removed while under the
>> register_mutex, so going over potential race conditions:
>>
>> Thread#1:
>> q6usb_component_probe()
>> --> snd_soc_usb_add_port()
>> --> snd_usb_rediscover_devices()
>> --> mutex_lock(register_mutex)
>>
>> Thread#2
>> --> usb_audio_disconnect()
>> --> mutex_lock(register_mutex)
>>
>> So either thread#1 or thread#2 will complete first. If
>>
>> Thread#1 completes before thread#2:
>> SOC USB will notify DPCM backend of the device connection. Shortly
>> after, once thread#2 runs, we will get a disconnect event for the
>> connected device.
>>
>> Thread#2 completes before thread#1:
>> Then during snd_usb_rediscover_devices() it won't notify of any
>> connection for that particular chip index.
> Looks like you are assuming the regular USB audio stuff is probed first?
>
> What if it's not the case? Have you tested with a manual 'blacklist' and
> "modprobe" sequence long after all the DSP stuff is initialized?
>
> It really reminds me of audio+display issues, and the same opens apply IMHO.

Not necessarily...if the USB audio driver is not probed, then that is
the same scenario as when there is no USB audio capable device plugged
in, while the offload path is waiting for the connect event. I think
this is the standard scenario.

In the situation where the platform sound card hasn't probed yet and USB
audio devices are being identified, then that is basically the scenario
that would be more of an issue, since its USB SND that notifies of the
connection state (at the time of connect/disconnect).

I've tried with building these drivers as modules and probing them at
different times/sequences, and I haven't seen an issue so far.

Thanks
Wesley Cheng

2023-10-24 14:26:08

by Pierre-Louis Bossart

[permalink] [raw]
Subject: Re: [PATCH v9 34/34] ASoC: usb: Rediscover USB SND devices on USB port add



On 10/23/23 16:54, Wesley Cheng wrote:
> Hi Pierre,
>
> On 10/17/2023 4:11 PM, Pierre-Louis Bossart wrote:
>>
>>
>> On 10/17/23 15:01, Wesley Cheng wrote:
>>> In case the USB backend device has not been initialized/probed, USB SND
>>> device connections can still occur.  When the USB backend is eventually
>>> made available, previous USB SND device connections are not
>>> communicated to
>>> the USB backend.  Call snd_usb_rediscover_devices() to generate the
>>> connect
>>> callbacks for all USB SND devices connected.  This will allow for the
>>> USB
>>> backend to be updated with the current set of devices available.
>>>
>>> The chip array entries are all populated and removed while under the
>>> register_mutex, so going over potential race conditions:
>>>
>>> Thread#1:
>>>    q6usb_component_probe()
>>>      --> snd_soc_usb_add_port()
>>>        --> snd_usb_rediscover_devices()
>>>          --> mutex_lock(register_mutex)
>>>
>>> Thread#2
>>>    --> usb_audio_disconnect()
>>>      --> mutex_lock(register_mutex)
>>>
>>> So either thread#1 or thread#2 will complete first.  If
>>>
>>> Thread#1 completes before thread#2:
>>>    SOC USB will notify DPCM backend of the device connection.  Shortly
>>>    after, once thread#2 runs, we will get a disconnect event for the
>>>    connected device.
>>>
>>> Thread#2 completes before thread#1:
>>>    Then during snd_usb_rediscover_devices() it won't notify of any
>>>    connection for that particular chip index.
>> Looks like you are assuming the regular USB audio stuff is probed first?
>>
>> What if it's not the case? Have you tested with a manual 'blacklist' and
>> "modprobe" sequence long after all the DSP stuff is initialized?
>>
>> It really reminds me of audio+display issues, and the same opens apply
>> IMHO.
>
> Not necessarily...if the USB audio driver is not probed, then that is
> the same scenario as when there is no USB audio capable device plugged
> in, while the offload path is waiting for the connect event. I think
> this is the standard scenario.
>
> In the situation where the platform sound card hasn't probed yet and USB
> audio devices are being identified, then that is basically the scenario
> that would be more of an issue, since its USB SND that notifies of the
> connection state (at the time of connect/disconnect).

Not following if this scenario is covered?

> I've tried with building these drivers as modules and probing them at
> different times/sequences, and I haven't seen an issue so far.

The scenario I have in mind is this:

the platform driver is on the deny list, the USB driver detects a
device. When the platform driver probes at a later time (with a manual
modprobe to make delays really long), how would the notification be handled?

Between audio and display, we use the 'drm_audio_component' layer to
model these sort of run-time binding between independent driver stacks.
It's not used here but we need a moral equivalent, don't we?

It would really help if you documented a bit more the dependencies or
timing assumptions, to make sure we have a stable solution to build on.

2023-10-25 03:24:59

by Albert Wang

[permalink] [raw]
Subject: Re: [PATCH v9 04/34] xhci: sideband: add initial api to register a sideband entity

>+ * Returns the address of the endpoint buffer where xHC controller reads queued
>+ * transfer TRBs from. This is the starting address of the ringbuffer where the
>+ * sidband cliend should write TRBs to.

A typo here 'sideband cliend', it apparently should be 'sideband client'.


On Wed, Oct 18, 2023 at 4:03 AM Wesley Cheng <[email protected]> wrote:
>
> From: Mathias Nyman <[email protected]>
>
> Introduce XHCI sideband, which manages the USB endpoints being requested by
> a client driver. This is used for when client drivers are attempting to
> offload USB endpoints to another entity for handling USB transfers. XHCI
> sideband will allow for drivers to fetch the required information about the
> transfer ring, so the user can submit transfers independently. Expose the
> required APIs for drivers to register and request for a USB endpoint and to
> manage XHCI secondary interrupters.
>
> Multiple ring segment page linking and proper endpoint clean up added by
> Wesley Cheng to complete original concept code by Mathias Nyman.
>
> Signed-off-by: Mathias Nyman <[email protected]>
> Co-developed-by: Wesley Cheng <[email protected]>
> Signed-off-by: Wesley Cheng <[email protected]>
> ---
> drivers/usb/host/Kconfig | 9 +
> drivers/usb/host/Makefile | 4 +
> drivers/usb/host/xhci-sideband.c | 371 ++++++++++++++++++++++++++++++
> drivers/usb/host/xhci.h | 4 +
> include/linux/usb/xhci-sideband.h | 66 ++++++
> 5 files changed, 454 insertions(+)
> create mode 100644 drivers/usb/host/xhci-sideband.c
> create mode 100644 include/linux/usb/xhci-sideband.h
>
> diff --git a/drivers/usb/host/Kconfig b/drivers/usb/host/Kconfig
> index 4448d0ab06f0..923af11c1982 100644
> --- a/drivers/usb/host/Kconfig
> +++ b/drivers/usb/host/Kconfig
> @@ -104,6 +104,15 @@ config USB_XHCI_RZV2M
> Say 'Y' to enable the support for the xHCI host controller
> found in Renesas RZ/V2M SoC.
>
> +config USB_XHCI_SIDEBAND
> + bool "xHCI support for sideband"
> + help
> + Say 'Y' to enable the support for the xHCI sideband capability.
> + provide a mechanism for a sideband datapath for payload associated
> + with audio class endpoints. This allows for an audio DSP to use
> + xHCI USB endpoints directly, allowing CPU to sleep while playing
> + audio
> +
> config USB_XHCI_TEGRA
> tristate "xHCI support for NVIDIA Tegra SoCs"
> depends on PHY_TEGRA_XUSB
> diff --git a/drivers/usb/host/Makefile b/drivers/usb/host/Makefile
> index be4e5245c52f..4df946c05ba0 100644
> --- a/drivers/usb/host/Makefile
> +++ b/drivers/usb/host/Makefile
> @@ -32,6 +32,10 @@ endif
> xhci-rcar-hcd-y += xhci-rcar.o
> xhci-rcar-hcd-$(CONFIG_USB_XHCI_RZV2M) += xhci-rzv2m.o
>
> +ifneq ($(CONFIG_USB_XHCI_SIDEBAND),)
> + xhci-hcd-y += xhci-sideband.o
> +endif
> +
> obj-$(CONFIG_USB_PCI) += pci-quirks.o
>
> obj-$(CONFIG_USB_EHCI_HCD) += ehci-hcd.o
> diff --git a/drivers/usb/host/xhci-sideband.c b/drivers/usb/host/xhci-sideband.c
> new file mode 100644
> index 000000000000..cc4f90375e00
> --- /dev/null
> +++ b/drivers/usb/host/xhci-sideband.c
> @@ -0,0 +1,371 @@
> +// SPDX-License-Identifier: GPL-2.0
> +
> +/*
> + * xHCI host controller sideband support
> + *
> + * Copyright (c) 2023, Intel Corporation.
> + *
> + * Author: Mathias Nyman
> + */
> +
> +#include <linux/usb/xhci-sideband.h>
> +#include <linux/dma-direct.h>
> +
> +#include "xhci.h"
> +
> +/* sideband internal helpers */
> +static struct sg_table *
> +xhci_ring_to_sgtable(struct xhci_sideband *sb, struct xhci_ring *ring)
> +{
> + struct xhci_segment *seg;
> + struct sg_table *sgt;
> + unsigned int n_pages;
> + struct page **pages;
> + struct device *dev;
> + size_t sz;
> + int i;
> +
> + dev = xhci_to_hcd(sb->xhci)->self.sysdev;
> + sz = ring->num_segs * TRB_SEGMENT_SIZE;
> + n_pages = PAGE_ALIGN(sz) >> PAGE_SHIFT;
> + pages = kvmalloc_array(n_pages, sizeof(struct page *), GFP_KERNEL);
> + if (!pages)
> + return NULL;
> +
> + sgt = kzalloc(sizeof(struct sg_table), GFP_KERNEL);
> + if (!sgt) {
> + kvfree(pages);
> + return NULL;
> + }
> +
> + seg = ring->first_seg;
> + /*
> + * Rings can potentially have multiple segments, create an array that
> + * carries page references to allocated segments. Utilize the
> + * sg_alloc_table_from_pages() to create the sg table, and to ensure
> + * that page links are created.
> + */
> + for (i = 0; i < ring->num_segs; i++) {
> + dma_get_sgtable(dev, sgt, seg->trbs, seg->dma,
> + TRB_SEGMENT_SIZE);
> + pages[i] = sg_page(sgt->sgl);
> + sg_free_table(sgt);
> + seg = seg->next;
> + }
> +
> + if (sg_alloc_table_from_pages(sgt, pages, n_pages, 0, sz, GFP_KERNEL)) {
> + kvfree(pages);
> + kfree(sgt);
> +
> + return NULL;
> + }
> + /*
> + * Save first segment dma address to sg dma_address field for the sideband
> + * client to have access to the IOVA of the ring.
> + */
> + sg_dma_address(sgt->sgl) = ring->first_seg->dma;
> +
> + return sgt;
> +}
> +
> +static void
> +__xhci_sideband_remove_endpoint(struct xhci_sideband *sb, struct xhci_virt_ep *ep)
> +{
> + /*
> + * Issue a stop endpoint command when an endpoint is removed.
> + * The stop ep cmd handler will handle the ring cleanup.
> + */
> + xhci_stop_endpoint_sync(sb->xhci, ep, 0, GFP_KERNEL);
> +
> + ep->sideband = NULL;
> + sb->eps[ep->ep_index] = NULL;
> +}
> +
> +/* sideband api functions */
> +
> +/**
> + * xhci_sideband_add_endpoint - add endpoint to sideband access list
> + * @sb: sideband instance for this usb device
> + * @host_ep: usb host endpoint
> + *
> + * Adds an endpoint to the list of sideband accessed endpoints for this usb
> + * device.
> + * After an endpoint is added the sideband client can get the endpoint transfer
> + * ring buffer by calling xhci_sideband_endpoint_buffer()
> + *
> + * Return: 0 on success, negative error otherwise.
> + */
> +int
> +xhci_sideband_add_endpoint(struct xhci_sideband *sb,
> + struct usb_host_endpoint *host_ep)
> +{
> + struct xhci_virt_ep *ep;
> + unsigned int ep_index;
> +
> + ep_index = xhci_get_endpoint_index(&host_ep->desc);
> + ep = &sb->vdev->eps[ep_index];
> +
> + if (ep->ep_state & EP_HAS_STREAMS)
> + return -EINVAL;
> +
> + /*
> + * Note, we don't know the DMA mask of the audio DSP device, if its
> + * smaller than for xhci it won't be able to access the endpoint ring
> + * buffer. This could be solved by not allowing the audio class driver
> + * to add the endpoint the normal way, but instead offload it immediately,
> + * and let this function add the endpoint and allocate the ring buffer
> + * with the smallest common DMA mask
> + */
> +
> + if (sb->eps[ep_index] || ep->sideband)
> + return -EBUSY;
> +
> + ep->sideband = sb;
> + sb->eps[ep_index] = ep;
> +
> + return 0;
> +}
> +EXPORT_SYMBOL_GPL(xhci_sideband_add_endpoint);
> +
> +/**
> + * xhci_sideband_remove_endpoint - remove endpoint from sideband access list
> + * @sb: sideband instance for this usb device
> + * @host_ep: usb host endpoint
> + *
> + * Removes an endpoint from the list of sideband accessed endpoints for this usb
> + * device.
> + * sideband client should no longer touch the endpoint transfer buffer after
> + * calling this.
> + *
> + * Return: 0 on success, negative error otherwise.
> + */
> +int
> +xhci_sideband_remove_endpoint(struct xhci_sideband *sb,
> + struct usb_host_endpoint *host_ep)
> +{
> + struct xhci_virt_ep *ep;
> + unsigned int ep_index;
> +
> + ep_index = xhci_get_endpoint_index(&host_ep->desc);
> + ep = sb->eps[ep_index];
> +
> + if (!ep || !ep->sideband)
> + return -ENODEV;
> +
> + __xhci_sideband_remove_endpoint(sb, ep);
> + xhci_initialize_ring_info(ep->ring, 1);
> +
> + return 0;
> +}
> +EXPORT_SYMBOL_GPL(xhci_sideband_remove_endpoint);
> +
> +int
> +xhci_sideband_stop_endpoint(struct xhci_sideband *sb,
> + struct usb_host_endpoint *host_ep)
> +{
> + struct xhci_virt_ep *ep;
> + unsigned int ep_index;
> +
> + ep_index = xhci_get_endpoint_index(&host_ep->desc);
> + ep = sb->eps[ep_index];
> +
> + if (!ep || ep->sideband != sb)
> + return -EINVAL;
> +
> + return xhci_stop_endpoint_sync(sb->xhci, ep, 0);
> +}
> +EXPORT_SYMBOL_GPL(xhci_sideband_stop_endpoint);
> +
> +/**
> + * xhci_sideband_get_endpoint_buffer - gets the endpoint transfer buffer address
> + * @sb: sideband instance for this usb device
> + * @host_ep: usb host endpoint
> + *
> + * Returns the address of the endpoint buffer where xHC controller reads queued
> + * transfer TRBs from. This is the starting address of the ringbuffer where the
> + * sidband cliend should write TRBs to.
> + *
> + * Caller needs to free the returned sg_table
> + *
> + * Return: struct sg_table * if successful. NULL otherwise.
> + */
> +struct sg_table *
> +xhci_sideband_get_endpoint_buffer(struct xhci_sideband *sb,
> + struct usb_host_endpoint *host_ep)
> +{
> + struct xhci_virt_ep *ep;
> + unsigned int ep_index;
> +
> + ep_index = xhci_get_endpoint_index(&host_ep->desc);
> + ep = sb->eps[ep_index];
> +
> + if (!ep)
> + return NULL;
> +
> + return xhci_ring_to_sgtable(sb, ep->ring);
> +}
> +EXPORT_SYMBOL_GPL(xhci_sideband_get_endpoint_buffer);
> +
> +/**
> + * xhci_sideband_get_event_buffer - return the event buffer for this device
> + * @sb: sideband instance for this usb device
> + *
> + * If a secondary xhci interupter is set up for this usb device then this
> + * function returns the address of the event buffer where xHC writes
> + * the transfer completion events.
> + *
> + * Caller needs to free the returned sg_table
> + *
> + * Return: struct sg_table * if successful. NULL otherwise.
> + */
> +struct sg_table *
> +xhci_sideband_get_event_buffer(struct xhci_sideband *sb)
> +{
> + if (!sb->ir)
> + return NULL;
> +
> + return xhci_ring_to_sgtable(sb, sb->ir->event_ring);
> +}
> +EXPORT_SYMBOL_GPL(xhci_sideband_get_event_buffer);
> +
> +/**
> + * xhci_sideband_create_interrupter - creates a new interrupter for this sideband
> + * @sb: sideband instance for this usb device
> + *
> + * Sets up a xhci interrupter that can be used for this sideband accessed usb
> + * device. Transfer events for this device can be routed to this interrupters
> + * event ring by setting the 'Interrupter Target' field correctly when queueing
> + * the transfer TRBs.
> + * Once this interrupter is created the interrupter target ID can be obtained
> + * by calling xhci_sideband_interrupter_id()
> + *
> + * Returns 0 on success, negative error otherwise
> + */
> +int
> +xhci_sideband_create_interrupter(struct xhci_sideband *sb)
> +{
> + if (sb->ir)
> + return -EBUSY;
> +
> + sb->ir = xhci_create_secondary_interrupter(xhci_to_hcd(sb->xhci));
> + if (!sb->ir)
> + return -ENOMEM;
> +
> + return 0;
> +}
> +EXPORT_SYMBOL_GPL(xhci_sideband_create_interrupter);
> +
> +/**
> + * xhci_sideband_remove_interrupter - remove the interrupter from a sideband
> + * @sb: sideband instance for this usb device
> + *
> + * Removes a registered interrupt for a sideband. This would allow for other
> + * sideband users to utilize this interrupter.
> + */
> +void
> +xhci_sideband_remove_interrupter(struct xhci_sideband *sb)
> +{
> + if (!sb || !sb->ir)
> + return;
> +
> + xhci_remove_secondary_interrupter(xhci_to_hcd(sb->xhci), sb->ir);
> +
> + sb->ir = NULL;
> +}
> +EXPORT_SYMBOL_GPL(xhci_sideband_remove_interrupter);
> +
> +/**
> + * xhci_sideband_interrupter_id - return the interrupter target id
> + * @sb: sideband instance for this usb device
> + *
> + * If a secondary xhci interrupter is set up for this usb device then this
> + * function returns the ID used by the interrupter. The sideband client
> + * needs to write this ID to the 'Interrupter Target' field of the transfer TRBs
> + * it queues on the endpoints transfer ring to ensure transfer completion event
> + * are written by xHC to the correct interrupter event ring.
> + *
> + * Returns interrupter id on success, negative error othgerwise
> + */
> +int
> +xhci_sideband_interrupter_id(struct xhci_sideband *sb)
> +{
> + if (!sb || !sb->ir)
> + return -ENODEV;
> +
> + return sb->ir->intr_num;
> +}
> +EXPORT_SYMBOL_GPL(xhci_sideband_interrupter_id);
> +
> +/**
> + * xhci_sideband_register - register a sideband for a usb device
> + * @udev: usb device to be accessed via sideband
> + *
> + * Allows for clients to utilize XHCI interrupters and fetch transfer and event
> + * ring parameters for executing data transfers.
> + *
> + * Return: pointer to a new xhci_sideband instance if successful. NULL otherwise.
> + */
> +struct xhci_sideband *
> +xhci_sideband_register(struct usb_device *udev)
> +{
> + struct usb_hcd *hcd = bus_to_hcd(udev->bus);
> + struct xhci_hcd *xhci = hcd_to_xhci(hcd);
> + struct xhci_virt_device *vdev;
> + struct xhci_sideband *sb;
> +
> + /* make sure the usb device is connected to a xhci controller */
> + if (!udev->slot_id)
> + return NULL;
> +
> + sb = kzalloc_node(sizeof(*sb), GFP_KERNEL, dev_to_node(hcd->self.sysdev));
> + if (!sb)
> + return NULL;
> +
> + /* check this device isn't already controlled via sideband */
> + spin_lock_irq(&xhci->lock);
> +
> + vdev = xhci->devs[udev->slot_id];
> +
> + if (!vdev || vdev->sideband) {
> + xhci_warn(xhci, "XHCI sideband for slot %d already in use\n",
> + udev->slot_id);
> + spin_unlock_irq(&xhci->lock);
> + kfree(sb);
> + return NULL;
> + }
> +
> + sb->xhci = xhci;
> + sb->vdev = vdev;
> + vdev->sideband = sb;
> +
> + spin_unlock_irq(&xhci->lock);
> +
> + return sb;
> +}
> +EXPORT_SYMBOL_GPL(xhci_sideband_register);
> +
> +/**
> + * xhci_sideband_unregister - unregister sideband access to a usb device
> + * @sb: sideband instance to be unregistered
> + *
> + * Unregisters sideband access to a usb device and frees the sideband
> + * instance.
> + * After this the endpoint and interrupter event buffers should no longer
> + * be accessed via sideband. The xhci driver can now take over handling
> + * the buffers.
> + */
> +void
> +xhci_sideband_unregister(struct xhci_sideband *sb)
> +{
> + int i;
> +
> + for (i = 0; i < EP_CTX_PER_DEV; i++)
> + if (sb->eps[i])
> + __xhci_sideband_remove_endpoint(sb, sb->eps[i]);
> +
> + xhci_sideband_remove_interrupter(sb);
> +
> + sb->vdev->sideband = NULL;
> + kfree(sb);
> +}
> +EXPORT_SYMBOL_GPL(xhci_sideband_unregister);
> diff --git a/drivers/usb/host/xhci.h b/drivers/usb/host/xhci.h
> index 4b8caaed6f95..339d37c3a3d9 100644
> --- a/drivers/usb/host/xhci.h
> +++ b/drivers/usb/host/xhci.h
> @@ -947,6 +947,8 @@ struct xhci_virt_ep {
> int next_frame_id;
> /* Use new Isoch TRB layout needed for extended TBC support */
> bool use_extended_tbc;
> + /* set if this endpoint is controlled via sideband access*/
> + struct xhci_sideband *sideband;
> };
>
> enum xhci_overhead_type {
> @@ -1010,6 +1012,8 @@ struct xhci_virt_device {
> u16 current_mel;
> /* Used for the debugfs interfaces. */
> void *debugfs_private;
> + /* set if this device is registered for sideband access */
> + struct xhci_sideband *sideband;
> };
>
> /*
> diff --git a/include/linux/usb/xhci-sideband.h b/include/linux/usb/xhci-sideband.h
> new file mode 100644
> index 000000000000..c1457d1800f4
> --- /dev/null
> +++ b/include/linux/usb/xhci-sideband.h
> @@ -0,0 +1,66 @@
> +/* SPDX-License-Identifier: GPL-2.0 */
> +/*
> + * xHCI host controller sideband support
> + *
> + * Copyright (c) 2023, Intel Corporation.
> + *
> + * Author: Mathias Nyman <[email protected]>
> + */
> +
> +#ifndef __LINUX_XHCI_SIDEBAND_H
> +#define __LINUX_XHCI_SIDEBAND_H
> +
> +#include <linux/scatterlist.h>
> +#include <linux/usb.h>
> +
> +#define EP_CTX_PER_DEV 31 /* FIMXME defined twice, from xhci.h */
> +
> +struct xhci_sideband;
> +
> +/**
> + * struct xhci_sideband - representation of a sideband accessed usb device.
> + * @xhci: The xhci host controller the usb device is connected to
> + * @vdev: the usb device accessed via sideband
> + * @eps: array of endpoints controlled via sideband
> + * @ir: event handling and buffer for sideband accessed device
> + *
> + * FIXME usb device accessed via sideband Keeping track of sideband accessed usb devices.
> + */
> +
> +struct xhci_sideband {
> + struct xhci_hcd *xhci;
> + struct xhci_virt_device *vdev;
> + struct xhci_virt_ep *eps[EP_CTX_PER_DEV];
> + struct xhci_interrupter *ir;
> +};
> +
> +struct xhci_sideband *
> +xhci_sideband_register(struct usb_device *udev);
> +void
> +xhci_sideband_unregister(struct xhci_sideband *sb);
> +int
> +xhci_sideband_add_endpoint(struct xhci_sideband *sb,
> + struct usb_host_endpoint *host_ep);
> +int
> +xhci_sideband_remove_endpoint(struct xhci_sideband *sb,
> + struct usb_host_endpoint *host_ep);
> +int
> +xhci_sideband_stop_endpoint(struct xhci_sideband *sb,
> + struct usb_host_endpoint *host_ep);
> +struct sg_table *
> +xhci_sideband_get_endpoint_buffer(struct xhci_sideband *sb,
> + struct usb_host_endpoint *host_ep);
> +struct sg_table *
> +xhci_sideband_get_event_buffer(struct xhci_sideband *sb);
> +
> +int
> +xhci_sideband_create_interrupter(struct xhci_sideband *sb);
> +
> +void
> +xhci_sideband_remove_interrupter(struct xhci_sideband *sb);
> +
> +int
> +xhci_sideband_interrupter_id(struct xhci_sideband *sb);
> +
> +#endif /* __LINUX_XHCI_SIDEBAND_H */
> +
>

2023-10-25 22:32:36

by Wesley Cheng

[permalink] [raw]
Subject: Re: [PATCH v9 34/34] ASoC: usb: Rediscover USB SND devices on USB port add

Hi Pierre,

On 10/24/2023 6:35 AM, Pierre-Louis Bossart wrote:
>
>
> On 10/23/23 16:54, Wesley Cheng wrote:
>> Hi Pierre,
>>
>> On 10/17/2023 4:11 PM, Pierre-Louis Bossart wrote:
>>>
>>>
>>> On 10/17/23 15:01, Wesley Cheng wrote:
>>>> In case the USB backend device has not been initialized/probed, USB SND
>>>> device connections can still occur.  When the USB backend is eventually
>>>> made available, previous USB SND device connections are not
>>>> communicated to
>>>> the USB backend.  Call snd_usb_rediscover_devices() to generate the
>>>> connect
>>>> callbacks for all USB SND devices connected.  This will allow for the
>>>> USB
>>>> backend to be updated with the current set of devices available.
>>>>
>>>> The chip array entries are all populated and removed while under the
>>>> register_mutex, so going over potential race conditions:
>>>>
>>>> Thread#1:
>>>>    q6usb_component_probe()
>>>>      --> snd_soc_usb_add_port()
>>>>        --> snd_usb_rediscover_devices()
>>>>          --> mutex_lock(register_mutex)
>>>>
>>>> Thread#2
>>>>    --> usb_audio_disconnect()
>>>>      --> mutex_lock(register_mutex)
>>>>
>>>> So either thread#1 or thread#2 will complete first.  If
>>>>
>>>> Thread#1 completes before thread#2:
>>>>    SOC USB will notify DPCM backend of the device connection.  Shortly
>>>>    after, once thread#2 runs, we will get a disconnect event for the
>>>>    connected device.
>>>>
>>>> Thread#2 completes before thread#1:
>>>>    Then during snd_usb_rediscover_devices() it won't notify of any
>>>>    connection for that particular chip index.
>>> Looks like you are assuming the regular USB audio stuff is probed first?
>>>
>>> What if it's not the case? Have you tested with a manual 'blacklist' and
>>> "modprobe" sequence long after all the DSP stuff is initialized?
>>>
>>> It really reminds me of audio+display issues, and the same opens apply
>>> IMHO.
>>
>> Not necessarily...if the USB audio driver is not probed, then that is
>> the same scenario as when there is no USB audio capable device plugged
>> in, while the offload path is waiting for the connect event. I think
>> this is the standard scenario.
>>
>> In the situation where the platform sound card hasn't probed yet and USB
>> audio devices are being identified, then that is basically the scenario
>> that would be more of an issue, since its USB SND that notifies of the
>> connection state (at the time of connect/disconnect).
>
> Not following if this scenario is covered?
>

Yes, this is covered. For example, if there are already devices
connected, but the platform sound card is still unbound. Then this
rediscover API will be called to traverse through the list of connected
USB sound devices, so that the USB DPCM dai can know about their
existence when it is probed.

>> I've tried with building these drivers as modules and probing them at
>> different times/sequences, and I haven't seen an issue so far.
>
> The scenario I have in mind is this:
>
> the platform driver is on the deny list, the USB driver detects a
> device. When the platform driver probes at a later time (with a manual
> modprobe to make delays really long), how would the notification be handled?
>

So that is essentially the same scenario as when there is no USB device
connected, ie no USB class driver is bounded to anything. Since the
notifications are all handled within USB SND (USB class driver) then if
the module isn't loaded yet, no notification is sent to the DPCM USB
backend. Once you say...modprobe the USB SND driver, then the USB
interface probe occurs, and that would issue the connect callback from
the USB SND probe routine. (keep in mind these are not platform devices,
we're working with devices under the usb bus)

> Between audio and display, we use the 'drm_audio_component' layer to
> model these sort of run-time binding between independent driver stacks.
> It's not used here but we need a moral equivalent, don't we?
>
> It would really help if you documented a bit more the dependencies or
> timing assumptions, to make sure we have a stable solution to build on.
>

I can add this to the RST that I'll make in detail, and add a summary
here in the commit message.

Thanks
Wesley Cheng