mbox series

[v9,00/34] Introduce QC USB SND audio offloading support

Message ID 20231017200109.11407-1-quic_wcheng@quicinc.com
Headers show
Series Introduce QC USB SND audio offloading support | expand

Message

Wesley Cheng Oct. 17, 2023, 8 p.m. UTC
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

Comments

Pierre-Louis Bossart Oct. 17, 2023, 8:58 p.m. UTC | #1
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
Pierre-Louis Bossart Oct. 17, 2023, 10:29 p.m. UTC | #2
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 <quic_wcheng@quicinc.com>
> ---
>  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 */
Pierre-Louis Bossart Oct. 17, 2023, 10:33 p.m. UTC | #3
On 10/17/23 15:00, Wesley Cheng wrote:
> Introduce a check for if a particular PCM format is supported by the USB

Introduce a helper to check if a ...

> audio device connected.  If the USB audio device does not have an audio
> profile which can support the requested format, then notify the USB
> backend.
> 
> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
> ---
>  include/sound/soc-usb.h |  3 +++
>  sound/soc/soc-usb.c     | 13 +++++++++++++
>  2 files changed, 16 insertions(+)
> 
> diff --git a/include/sound/soc-usb.h b/include/sound/soc-usb.h
> index 58c686f4f7ba..c6ddc055c4cd 100644
> --- a/include/sound/soc-usb.h
> +++ b/include/sound/soc-usb.h
> @@ -37,6 +37,9 @@ struct snd_soc_usb {
>  	void *priv_data;
>  };
>  
> +int snd_soc_usb_find_format(int card_idx, struct snd_pcm_hw_params *params,
> +			int direction);
> +
>  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_find_priv_data(struct device *usbdev);
> diff --git a/sound/soc/soc-usb.c b/sound/soc/soc-usb.c
> index 73b1bcc3b506..7407678a993e 100644
> --- a/sound/soc/soc-usb.c
> +++ b/sound/soc/soc-usb.c
> @@ -63,6 +63,19 @@ void *snd_soc_usb_find_priv_data(struct device *dev)
>  }
>  EXPORT_SYMBOL_GPL(snd_soc_usb_find_priv_data);
>  
> +int snd_soc_usb_find_format(int card_idx, struct snd_pcm_hw_params *params,
> +			int direction)
> +{
> +	struct snd_usb_stream *as;
> +
> +	as = snd_usb_find_suppported_substream(card_idx, params, direction);
> +	if (!as)
> +		return -EOPNOTSUPP;
> +
> +	return 0;
> +}
> +EXPORT_SYMBOL_GPL(snd_soc_usb_find_format);

Is this the right way to check for formats?

formats are defined within the scope of an endpoint, and those endpoints
are themselves defined within the scope of an interface?

I don't see a notion of endpoint here. Does this assume all endpoints
are valid, or maybe the existence of a single endpoint in a device?

Confused.
Pierre-Louis Bossart Oct. 17, 2023, 10:37 p.m. UTC | #4
On 10/17/23 15:00, Wesley Cheng wrote:
> With USB audio offloading, an audio session is started from the ASoC
> platform sound card and PCM devices.  Likewise, the USB SND path is still
> readily available for use, in case the non-offload path is desired.  In
> order to prevent the two entities from attempting to use the USB bus,
> introduce a flag that determines when either paths are in use.
> 
> If a PCM device is already in use, the check will return an error to
> userspace notifying that the stream is currently busy.  This ensures that
> only one path is using the USB substream.
> 
> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
> ---
>  sound/usb/card.h                  |  1 +
>  sound/usb/pcm.c                   | 19 +++++++++++++++++--
>  sound/usb/qcom/qc_audio_offload.c | 15 ++++++++++++++-

should this be split in a generic part and a more specific qcom patch?

>  3 files changed, 32 insertions(+), 3 deletions(-)
> 
> diff --git a/sound/usb/card.h b/sound/usb/card.h
> index e26292363cf0..01f7e10f30f4 100644
> --- a/sound/usb/card.h
> +++ b/sound/usb/card.h
> @@ -164,6 +164,7 @@ struct snd_usb_substream {
>  	unsigned int pkt_offset_adj;	/* Bytes to drop from beginning of packets (for non-compliant devices) */
>  	unsigned int stream_offset_adj;	/* Bytes to drop from beginning of stream (for non-compliant devices) */
>  
> +	unsigned int opened:1;		/* pcm device opened */
>  	unsigned int running: 1;	/* running status */
>  	unsigned int period_elapsed_pending;	/* delay period handling */
>  
> diff --git a/sound/usb/pcm.c b/sound/usb/pcm.c
> index 3adb09ce1702..c2cb52cd5d23 100644
> --- a/sound/usb/pcm.c
> +++ b/sound/usb/pcm.c
> @@ -1241,8 +1241,15 @@ static int snd_usb_pcm_open(struct snd_pcm_substream *substream)
>  	struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
>  	struct snd_pcm_runtime *runtime = substream->runtime;
>  	struct snd_usb_substream *subs = &as->substream[direction];
> +	struct snd_usb_audio *chip = subs->stream->chip;
>  	int ret;
>  
> +	mutex_lock(&chip->mutex);
> +	if (subs->opened) {
> +		mutex_unlock(&chip->mutex);
> +		return -EBUSY;
> +	}
> +
>  	runtime->hw = snd_usb_hardware;
>  	/* need an explicit sync to catch applptr update in low-latency mode */
>  	if (direction == SNDRV_PCM_STREAM_PLAYBACK &&
> @@ -1259,13 +1266,17 @@ static int snd_usb_pcm_open(struct snd_pcm_substream *substream)
>  
>  	ret = setup_hw_info(runtime, subs);
>  	if (ret < 0)
> -		return ret;
> +		goto out;
>  	ret = snd_usb_autoresume(subs->stream->chip);
>  	if (ret < 0)
> -		return ret;
> +		goto out;
>  	ret = snd_media_stream_init(subs, as->pcm, direction);
>  	if (ret < 0)
>  		snd_usb_autosuspend(subs->stream->chip);
> +	subs->opened = 1;
> +out:
> +	mutex_unlock(&chip->mutex);
> +
>  	return ret;
>  }
>  
> @@ -1274,6 +1285,7 @@ static int snd_usb_pcm_close(struct snd_pcm_substream *substream)
>  	int direction = substream->stream;
>  	struct snd_usb_stream *as = snd_pcm_substream_chip(substream);
>  	struct snd_usb_substream *subs = &as->substream[direction];
> +	struct snd_usb_audio *chip = subs->stream->chip;
>  	int ret;
>  
>  	snd_media_stop_pipeline(subs);
> @@ -1287,6 +1299,9 @@ static int snd_usb_pcm_close(struct snd_pcm_substream *substream)
>  
>  	subs->pcm_substream = NULL;
>  	snd_usb_autosuspend(subs->stream->chip);
> +	mutex_lock(&chip->mutex);
> +	subs->opened = 0;
> +	mutex_unlock(&chip->mutex);
>  
>  	return 0;
>  }
> diff --git a/sound/usb/qcom/qc_audio_offload.c b/sound/usb/qcom/qc_audio_offload.c
> index 320ce3a6688f..bd6b84f72c74 100644
> --- a/sound/usb/qcom/qc_audio_offload.c
> +++ b/sound/usb/qcom/qc_audio_offload.c
> @@ -1413,12 +1413,17 @@ static void handle_uaudio_stream_req(struct qmi_handle *handle,
>  		goto response;
>  	}
>  
> +	mutex_lock(&chip->mutex);
>  	if (req_msg->enable) {
> -		if (info_idx < 0 || chip->system_suspend) {
> +		if (info_idx < 0 || chip->system_suspend || subs->opened) {
>  			ret = -EBUSY;
> +			mutex_unlock(&chip->mutex);
> +
>  			goto response;
>  		}
> +		subs->opened = 1;
>  	}
> +	mutex_unlock(&chip->mutex);
>  
>  	if (req_msg->service_interval_valid) {
>  		ret = get_data_interval_from_si(subs,
> @@ -1440,6 +1445,11 @@ static void handle_uaudio_stream_req(struct qmi_handle *handle,
>  		if (!ret)
>  			ret = prepare_qmi_response(subs, req_msg, &resp,
>  					info_idx);
> +		if (ret < 0) {
> +			mutex_lock(&chip->mutex);
> +			subs->opened = 0;
> +			mutex_unlock(&chip->mutex);
> +		}
>  	} else {
>  		info = &uadev[pcm_card_num].info[info_idx];
>  		if (info->data_ep_pipe) {
> @@ -1463,6 +1473,9 @@ static void handle_uaudio_stream_req(struct qmi_handle *handle,
>  		}
>  
>  		disable_audio_stream(subs);
> +		mutex_lock(&chip->mutex);
> +		subs->opened = 0;
> +		mutex_unlock(&chip->mutex);
>  	}
>  
>  response:
Pierre-Louis Bossart Oct. 17, 2023, 10:39 p.m. UTC | #5
On 10/17/23 15:01, Wesley Cheng wrote:
> The Q6USB backend can carry information about the available USB SND cards
> and PCM devices discovered on the USB bus.  The dev_token field is used by
> the audio DSP to notify the USB offload driver of which card and PCM index
> to enable playback on.  Separate this into a dedicated API, so the USB
> backend can set the dev_token accordingly.  The audio DSP does not utilize
> this information until the AFE port start command is sent, which is done
> during the PCM prepare phase.
> 
> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
> ---
>  sound/soc/qcom/qdsp6/q6afe.c | 49 +++++++++++++++++++++++++-----------
>  sound/soc/qcom/qdsp6/q6afe.h |  1 +
>  2 files changed, 36 insertions(+), 14 deletions(-)
> 
> diff --git a/sound/soc/qcom/qdsp6/q6afe.c b/sound/soc/qcom/qdsp6/q6afe.c
> index 72c4e6fe20c4..f09a756246f8 100644
> --- a/sound/soc/qcom/qdsp6/q6afe.c
> +++ b/sound/soc/qcom/qdsp6/q6afe.c
> @@ -1394,10 +1394,42 @@ 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)
> +/**
> + * afe_port_send_usb_dev_param() - Send USB dev token
> + *
> + * @port: Instance of afe port
> + * @cardidx: USB SND card index to reference
> + * @pcmidx: USB SND PCM device index to reference
> + *
> + * The USB dev token carries information about which USB SND card instance and
> + * PCM device to execute the offload on.  This information is carried through
> + * to the stream enable QMI request, which is handled by the offload class
> + * driver.  The information is parsed to determine which USB device to query
> + * the required resources for.
> + */
> +int afe_port_send_usb_dev_param(struct q6afe_port *port, int cardidx, int pcmidx)
>  {
> -	union afe_port_config *pcfg = &port->port_cfg;
>  	struct afe_param_id_usb_audio_dev_params usb_dev;
> +	int ret;
> +
> +	memset(&usb_dev, 0, sizeof(usb_dev));
> +
> +	usb_dev.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
> +	usb_dev.dev_token = (cardidx << 16) | (pcmidx << 8);
> +	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);
> +
> +	return ret;
> +}
> +EXPORT_SYMBOL_GPL(afe_port_send_usb_dev_param);
> +
> +static int afe_port_send_usb_params(struct q6afe_port *port, struct q6afe_usb_cfg *cfg)
> +{
> +	union afe_port_config *pcfg = &port->port_cfg;
>  	struct afe_param_id_usb_audio_dev_lpcm_fmt lpcm_fmt;
>  	struct afe_param_id_usb_audio_svc_interval svc_int;
>  	int ret = 0;
> @@ -1408,20 +1440,9 @@ static int afe_port_send_usb_dev_param(struct q6afe_port *port, struct q6afe_usb
>  		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;
> -	}
> -

this feels like a questionable patch split. Why not introduce the new
helper earlier and avoid adding code then modifying the same code?

>  	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,
> @@ -1463,7 +1484,7 @@ void q6afe_usb_port_prepare(struct q6afe_port *port,
>  	pcfg->usb_cfg.num_channels = cfg->num_channels;
>  	pcfg->usb_cfg.bit_width = cfg->bit_width;
>  
> -	afe_port_send_usb_dev_param(port, cfg);
> +	afe_port_send_usb_params(port, cfg);
>  }
>  EXPORT_SYMBOL_GPL(q6afe_usb_port_prepare);
>  
> diff --git a/sound/soc/qcom/qdsp6/q6afe.h b/sound/soc/qcom/qdsp6/q6afe.h
> index ef47b4ae9e27..2ce5ba9dba69 100644
> --- a/sound/soc/qcom/qdsp6/q6afe.h
> +++ b/sound/soc/qcom/qdsp6/q6afe.h
> @@ -263,6 +263,7 @@ void q6afe_tdm_port_prepare(struct q6afe_port *port, struct q6afe_tdm_cfg *cfg);
>  void q6afe_cdc_dma_port_prepare(struct q6afe_port *port,
>  				struct q6afe_cdc_dma_cfg *cfg);
>  
> +int afe_port_send_usb_dev_param(struct q6afe_port *port, int cardidx, int pcmidx);
>  int q6afe_port_set_sysclk(struct q6afe_port *port, int clk_id,
>  			  int clk_src, int clk_root,
>  			  unsigned int freq, int dir);
Pierre-Louis Bossart Oct. 17, 2023, 10:43 p.m. UTC | #6
On 10/17/23 15:01, Wesley Cheng wrote:
> The USB backend should know about which sound resources are being shared
> between the ASoC and USB SND paths.  This can be utilized to properly
> select and maintain the offloading devices.
> 
> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
> ---
>  sound/soc/qcom/qdsp6/q6usb.c | 16 ++++++++++++++++
>  1 file changed, 16 insertions(+)
> 
> diff --git a/sound/soc/qcom/qdsp6/q6usb.c b/sound/soc/qcom/qdsp6/q6usb.c
> index 329a7d4a3c01..d697cbe7f184 100644
> --- a/sound/soc/qcom/qdsp6/q6usb.c
> +++ b/sound/soc/qcom/qdsp6/q6usb.c
> @@ -25,10 +25,18 @@
>  
>  #define SID_MASK	0xF
>  
> +struct q6usb_status {
> +	unsigned int num_pcm;

how would one know which ones are capture and which ones are playback?

This really looks like a playback-only assumption, despite earlier
mentions of capture supported.

> +	unsigned int chip_index;
> +	unsigned int pcm_index;
> +};
> +
>  struct q6usb_port_data {
>  	struct q6afe_usb_cfg usb_cfg;
>  	struct snd_soc_usb *usb;
>  	struct q6usb_offload priv;
> +	unsigned long available_card_slot;
> +	struct q6usb_status status[SNDRV_CARDS];
>  	int active_idx;
>  };
>  
> @@ -110,6 +118,14 @@ static int q6usb_alsa_connection_cb(struct snd_soc_usb *usb,
>  	if (connected) {
>  		/* We only track the latest USB headset plugged in */
>  		data->active_idx = sdev->card_idx;
> +
> +		set_bit(sdev->card_idx, &data->available_card_slot);
> +		data->status[sdev->card_idx].num_pcm = sdev->num_playback;

there you go...

> +		data->status[sdev->card_idx].chip_index = sdev->chip_idx;
> +	} else {
> +		clear_bit(sdev->card_idx, &data->available_card_slot);
> +		data->status[sdev->card_idx].num_pcm = 0;
> +		data->status[sdev->card_idx].chip_index = 0;
>  	}
>  
>  	return 0;
Pierre-Louis Bossart Oct. 17, 2023, 10:50 p.m. UTC | #7
On 10/17/23 15:01, Wesley Cheng wrote:
> Expose a kcontrol on the platform sound card, which will allow for
> userspace to determine which USB card number and PCM device to offload.
> This allows for userspace to potentially tag an alternate path for a
> specific USB SND card and PCM device.  Previously, control was absent, and
> the offload path would be enabled on the last USB SND device which was
> connected.  This logic will continue to be applicable if no mixer input is
> received for specific device selection.
> 
> An example to configure the offload device using tinymix:
> tinymix -D 0 set 'Q6USB offload SND device select' 1 0
> 
> The above will set the Q6AFE device token to choose offload on card#1 and
> pcm#0.  Device selection is made possible by setting the Q6AFE device
> token.  The audio DSP utilizes this parameter, and will pass this field
> back to the USB offload driver within the QMI stream requests.

This still begs the question on how userspace would figure what the
card1 is and which endpoint is used when PCM0 is opened?

Ideally userpace would not have to know anything about "Q6USB".
Presumably when other vendors expose their USB offload solution, we
would want a generic control name, no?

Jaroslav should chime in on this one :-)


> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
> ---
>  sound/soc/qcom/qdsp6/q6usb.c | 125 ++++++++++++++++++++++++++++++++++-
>  1 file changed, 122 insertions(+), 3 deletions(-)
> 
> diff --git a/sound/soc/qcom/qdsp6/q6usb.c b/sound/soc/qcom/qdsp6/q6usb.c
> index d697cbe7f184..a95276b7d91d 100644
> --- a/sound/soc/qcom/qdsp6/q6usb.c
> +++ b/sound/soc/qcom/qdsp6/q6usb.c
> @@ -14,6 +14,7 @@
>  #include <linux/dma-map-ops.h>
>  
>  #include <sound/pcm.h>
> +#include <sound/control.h>
>  #include <sound/soc.h>
>  #include <sound/soc-usb.h>
>  #include <sound/pcm_params.h>
> @@ -35,9 +36,12 @@ struct q6usb_port_data {
>  	struct q6afe_usb_cfg usb_cfg;
>  	struct snd_soc_usb *usb;
>  	struct q6usb_offload priv;
> +	struct mutex mutex;

missing comment on what this protects. "mutex" is really a poor
choice/name if I am honest.

>  	unsigned long available_card_slot;
>  	struct q6usb_status status[SNDRV_CARDS];
> -	int active_idx;
> +	bool idx_valid;
> +	int sel_card_idx;
> +	int sel_pcm_idx;
>  };

> +/* 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_dev_ctrl, component));
> +	if (ret < 0)
> +		return;

that error handling does not seem terribly useful...

> +}
> +
>  static int q6usb_audio_ports_of_xlate_dai_name(struct snd_soc_component *component,
>  					const struct of_phandle_args *args,
>  					const char **dai_name)
> @@ -115,9 +227,11 @@ static int q6usb_alsa_connection_cb(struct snd_soc_usb *usb,
>  
>  	data = dev_get_drvdata(usb->component->dev);
>  
> +	mutex_lock(&data->mutex);
>  	if (connected) {
>  		/* We only track the latest USB headset plugged in */
> -		data->active_idx = sdev->card_idx;
> +		if (!data->idx_valid || data->sel_card_idx < 0)
> +			data->sel_card_idx = sdev->card_idx;
>  
>  		set_bit(sdev->card_idx, &data->available_card_slot);
>  		data->status[sdev->card_idx].num_pcm = sdev->num_playback;
> @@ -127,6 +241,7 @@ static int q6usb_alsa_connection_cb(struct snd_soc_usb *usb,
>  		data->status[sdev->card_idx].num_pcm = 0;
>  		data->status[sdev->card_idx].chip_index = 0;
>  	}
> +	mutex_unlock(&data->mutex);
>  
>  	return 0;
>  }
> @@ -135,6 +250,8 @@ static int q6usb_component_probe(struct snd_soc_component *component)
>  {
>  	struct q6usb_port_data *data = dev_get_drvdata(component->dev);
>  
> +	q6usb_connector_control_init(component);
> +
>  	data->usb = snd_soc_usb_add_port(component->dev, &data->priv, q6usb_alsa_connection_cb);
>  	if (IS_ERR(data->usb)) {
>  		dev_err(component->dev, "failed to add usb port\n");
> @@ -189,6 +306,8 @@ static int q6usb_dai_dev_probe(struct platform_device *pdev)
>  
>  	data->priv.domain = iommu_get_domain_for_dev(&pdev->dev);
>  
> +	mutex_init(&data->mutex);
> +
>  	data->priv.dev = dev;
>  	dev_set_drvdata(dev, data);
>
Pierre-Louis Bossart Oct. 17, 2023, 11:03 p.m. UTC | #8
On 10/17/23 15:01, Wesley Cheng wrote:
> The headphone jack framework has a well defined infrastructure for
> notifying userspace entities through input devices.  Expose a jack device
> that carries information about if an offload capable device is connected.
> Applications can further identify specific offloading information through
> other SND kcontrols.

maybe I am mistaken but if you expose a jack, is there not a need to
implement a .set_jack callback in the component driver?

>  static void q6usb_connector_control_init(struct snd_soc_component *component)
>  {
> +	struct q6usb_port_data *data = dev_get_drvdata(component->dev);
>  	int ret;
>  
>  	ret = snd_ctl_add(component->card->snd_card,
> @@ -290,6 +293,11 @@ static void q6usb_connector_control_init(struct snd_soc_component *component)
>  				snd_ctl_new1(&q6usb_offload_dev_ctrl, component));
>  	if (ret < 0)
>  		return;
> +
> +	ret = snd_soc_card_jack_new(component->card, "USB offload",
> +					SND_JACK_HEADSET, &data->hs_jack);
> +	if (ret)
> +		return;

Also if you report a jack then usually there's a difference between
SND_JACK_HEADPHONE and SND_JACK_HEADSET - where the latter case hints at
capture support.

Clearly you don't have capture support for now, so should this be
SND_JACK_HEADPHONE ?

I must say I still don't get how this entire patchset would be used, for
playback userspace *may* use offload but for any sort of voice call then
userspace *shall* rely on the legacy USB card. Is this not a
show-stopper for CRAS or PipeWire?
Pierre-Louis Bossart Oct. 17, 2023, 11:07 p.m. UTC | #9
On 10/17/23 15:01, Wesley Cheng wrote:
> In case of notifying SND platform drivers of connection events, some of
> these use cases, such as offloading, require an ASoC USB backend device to
> be initialized before the events can be handled.  If the USB backend device
> has not yet been probed, this leads to missing initial USB audio device
> connection events.
> 
> Expose an API that traverses the usb_chip array for connected devices, and
> to call the respective connection callback registered to the SND platform
> driver.
> 
> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
> ---
>  sound/usb/card.c | 19 +++++++++++++++++++
>  sound/usb/card.h |  2 ++
>  2 files changed, 21 insertions(+)
> 
> diff --git a/sound/usb/card.c b/sound/usb/card.c
> index 88f431917c15..7d3f470754ca 100644
> --- a/sound/usb/card.c
> +++ b/sound/usb/card.c
> @@ -202,6 +202,25 @@ struct snd_usb_stream *snd_usb_find_suppported_substream(int card_idx,
>  }
>  EXPORT_SYMBOL_GPL(snd_usb_find_suppported_substream);
>  
> +/*
> + * in case the platform driver was not ready at the time of USB SND
> + * device connect, expose an API to discover all connected USB devices
> + * so it can populate any dependent resources/structures.

it's really unclear how the "platform driver was not ready at the time
of USB SND device connect" condition can be detected. It's my
understanding that we should never assume any specific order or timing
on platform driver probes. And things should also work if a driver is
unbound.

> + */
> +void snd_usb_rediscover_devices(void)
> +{
> +	int i;
> +
> +	mutex_lock(&register_mutex);
> +	for (i = 0; i < SNDRV_CARDS; i++) {
> +		if (usb_chip[i])
> +			if (platform_ops && platform_ops->connect_cb)
> +				platform_ops->connect_cb(usb_chip[i]);
> +	}
> +	mutex_unlock(&register_mutex);
> +}
> +EXPORT_SYMBOL_GPL(snd_usb_rediscover_devices);
> +
>  /*
>   * disconnect streams
>   * called from usb_audio_disconnect()
> diff --git a/sound/usb/card.h b/sound/usb/card.h
> index 01f7e10f30f4..c0aeda17ed69 100644
> --- a/sound/usb/card.h
> +++ b/sound/usb/card.h
> @@ -221,11 +221,13 @@ 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);
> +void snd_usb_rediscover_devices(void);
>  #else
>  static struct snd_usb_stream *snd_usb_find_suppported_substream(int card_idx,
>  			struct snd_pcm_hw_params *params, int direction)
>  {
>  	return NULL;
>  }
> +static void snd_usb_rediscover_devices(void) { }
>  #endif /* IS_ENABLED(CONFIG_SND_USB_AUDIO) */
>  #endif /* __USBAUDIO_CARD_H */
Pierre-Louis Bossart Oct. 17, 2023, 11:11 p.m. UTC | #10
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.
Pierre-Louis Bossart Oct. 17, 2023, 11:21 p.m. UTC | #11
> +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...
Wesley Cheng Oct. 18, 2023, 12:25 a.m. UTC | #12
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
Pierre-Louis Bossart Oct. 18, 2023, 1:54 p.m. UTC | #13
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.
Wesley Cheng Oct. 18, 2023, 8:20 p.m. UTC | #14
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
Wesley Cheng Oct. 18, 2023, 8:21 p.m. UTC | #15
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 <quic_wcheng@quicinc.com>
>> ---
>>   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
Wesley Cheng Oct. 18, 2023, 8:33 p.m. UTC | #16
Hi Pierre,

On 10/17/2023 3:33 PM, Pierre-Louis Bossart wrote:
> 
> 
> On 10/17/23 15:00, Wesley Cheng wrote:
>> Introduce a check for if a particular PCM format is supported by the USB
> 
> Introduce a helper to check if a ...
> 

Ack.

>> audio device connected.  If the USB audio device does not have an audio
>> profile which can support the requested format, then notify the USB
>> backend.
>>
>> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
>> ---
>>   include/sound/soc-usb.h |  3 +++
>>   sound/soc/soc-usb.c     | 13 +++++++++++++
>>   2 files changed, 16 insertions(+)
>>
>> diff --git a/include/sound/soc-usb.h b/include/sound/soc-usb.h
>> index 58c686f4f7ba..c6ddc055c4cd 100644
>> --- a/include/sound/soc-usb.h
>> +++ b/include/sound/soc-usb.h
>> @@ -37,6 +37,9 @@ struct snd_soc_usb {
>>   	void *priv_data;
>>   };
>>   
>> +int snd_soc_usb_find_format(int card_idx, struct snd_pcm_hw_params *params,
>> +			int direction);
>> +
>>   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_find_priv_data(struct device *usbdev);
>> diff --git a/sound/soc/soc-usb.c b/sound/soc/soc-usb.c
>> index 73b1bcc3b506..7407678a993e 100644
>> --- a/sound/soc/soc-usb.c
>> +++ b/sound/soc/soc-usb.c
>> @@ -63,6 +63,19 @@ void *snd_soc_usb_find_priv_data(struct device *dev)
>>   }
>>   EXPORT_SYMBOL_GPL(snd_soc_usb_find_priv_data);
>>   
>> +int snd_soc_usb_find_format(int card_idx, struct snd_pcm_hw_params *params,
>> +			int direction)
>> +{
>> +	struct snd_usb_stream *as;
>> +
>> +	as = snd_usb_find_suppported_substream(card_idx, params, direction);
>> +	if (!as)
>> +		return -EOPNOTSUPP;
>> +
>> +	return 0;
>> +}
>> +EXPORT_SYMBOL_GPL(snd_soc_usb_find_format);
> 
> Is this the right way to check for formats?
> 
> formats are defined within the scope of an endpoint, and those endpoints
> are themselves defined within the scope of an interface?
> 
> I don't see a notion of endpoint here. Does this assume all endpoints
> are valid, or maybe the existence of a single endpoint in a device?
> 
> Confused.

At least in terms of USB and USB UAC, formats are defined within an 
audio streaming interface descriptor, which will include multiple (up to 
2) USB endpoints.  Those endpoints will be described w/ both an audio 
streaming endpoint descriptor as well as a standard USB endpoint 
descriptor.  The audio interface/format descriptors are the ones that 
carry the information about what formats are supported by the USB 
device.  So this API finds a possible USB AS streaming descriptor on the 
device that matches the requested one.  Endpoints will be opened 
subsequently when the audio stream is started, and an interface is 
enabled by sending a SET_INTERFACE control packet on the USB bus.

Thanks
Wesley Cheng
Wesley Cheng Oct. 18, 2023, 8:33 p.m. UTC | #17
Hi Pierre,

On 10/17/2023 3:37 PM, Pierre-Louis Bossart wrote:
> 
> 
> On 10/17/23 15:00, Wesley Cheng wrote:
>> With USB audio offloading, an audio session is started from the ASoC
>> platform sound card and PCM devices.  Likewise, the USB SND path is still
>> readily available for use, in case the non-offload path is desired.  In
>> order to prevent the two entities from attempting to use the USB bus,
>> introduce a flag that determines when either paths are in use.
>>
>> If a PCM device is already in use, the check will return an error to
>> userspace notifying that the stream is currently busy.  This ensures that
>> only one path is using the USB substream.
>>
>> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
>> ---
>>   sound/usb/card.h                  |  1 +
>>   sound/usb/pcm.c                   | 19 +++++++++++++++++--
>>   sound/usb/qcom/qc_audio_offload.c | 15 ++++++++++++++-
> 
> should this be split in a generic part and a more specific qcom patch?
> 

Got it.

Thanks
Wesley Cheng
Wesley Cheng Oct. 19, 2023, 12:10 a.m. UTC | #18
Hi Pierre,

On 10/17/2023 3:39 PM, Pierre-Louis Bossart wrote:
> 
> 
> On 10/17/23 15:01, Wesley Cheng wrote:
>> The Q6USB backend can carry information about the available USB SND cards
>> and PCM devices discovered on the USB bus.  The dev_token field is used by
>> the audio DSP to notify the USB offload driver of which card and PCM index
>> to enable playback on.  Separate this into a dedicated API, so the USB
>> backend can set the dev_token accordingly.  The audio DSP does not utilize
>> this information until the AFE port start command is sent, which is done
>> during the PCM prepare phase.
>>
>> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
>> ---
>>   sound/soc/qcom/qdsp6/q6afe.c | 49 +++++++++++++++++++++++++-----------
>>   sound/soc/qcom/qdsp6/q6afe.h |  1 +
>>   2 files changed, 36 insertions(+), 14 deletions(-)
>>
>> diff --git a/sound/soc/qcom/qdsp6/q6afe.c b/sound/soc/qcom/qdsp6/q6afe.c
>> index 72c4e6fe20c4..f09a756246f8 100644
>> --- a/sound/soc/qcom/qdsp6/q6afe.c
>> +++ b/sound/soc/qcom/qdsp6/q6afe.c
>> @@ -1394,10 +1394,42 @@ 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)
>> +/**
>> + * afe_port_send_usb_dev_param() - Send USB dev token
>> + *
>> + * @port: Instance of afe port
>> + * @cardidx: USB SND card index to reference
>> + * @pcmidx: USB SND PCM device index to reference
>> + *
>> + * The USB dev token carries information about which USB SND card instance and
>> + * PCM device to execute the offload on.  This information is carried through
>> + * to the stream enable QMI request, which is handled by the offload class
>> + * driver.  The information is parsed to determine which USB device to query
>> + * the required resources for.
>> + */
>> +int afe_port_send_usb_dev_param(struct q6afe_port *port, int cardidx, int pcmidx)
>>   {
>> -	union afe_port_config *pcfg = &port->port_cfg;
>>   	struct afe_param_id_usb_audio_dev_params usb_dev;
>> +	int ret;
>> +
>> +	memset(&usb_dev, 0, sizeof(usb_dev));
>> +
>> +	usb_dev.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
>> +	usb_dev.dev_token = (cardidx << 16) | (pcmidx << 8);
>> +	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);
>> +
>> +	return ret;
>> +}
>> +EXPORT_SYMBOL_GPL(afe_port_send_usb_dev_param);
>> +
>> +static int afe_port_send_usb_params(struct q6afe_port *port, struct q6afe_usb_cfg *cfg)
>> +{
>> +	union afe_port_config *pcfg = &port->port_cfg;
>>   	struct afe_param_id_usb_audio_dev_lpcm_fmt lpcm_fmt;
>>   	struct afe_param_id_usb_audio_svc_interval svc_int;
>>   	int ret = 0;
>> @@ -1408,20 +1440,9 @@ static int afe_port_send_usb_dev_param(struct q6afe_port *port, struct q6afe_usb
>>   		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;
>> -	}
>> -
> 
> this feels like a questionable patch split. Why not introduce the new
> helper earlier and avoid adding code then modifying the same code?
> 

Let me see if I can squash this with the change that adds the USB AFE port.

Thanks
Wesley Cheng
Wesley Cheng Oct. 19, 2023, 1 a.m. UTC | #19
Hi Pierre,

On 10/17/2023 3:43 PM, Pierre-Louis Bossart wrote:
> 
> 
> On 10/17/23 15:01, Wesley Cheng wrote:
>> The USB backend should know about which sound resources are being shared
>> between the ASoC and USB SND paths.  This can be utilized to properly
>> select and maintain the offloading devices.
>>
>> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
>> ---
>>   sound/soc/qcom/qdsp6/q6usb.c | 16 ++++++++++++++++
>>   1 file changed, 16 insertions(+)
>>
>> diff --git a/sound/soc/qcom/qdsp6/q6usb.c b/sound/soc/qcom/qdsp6/q6usb.c
>> index 329a7d4a3c01..d697cbe7f184 100644
>> --- a/sound/soc/qcom/qdsp6/q6usb.c
>> +++ b/sound/soc/qcom/qdsp6/q6usb.c
>> @@ -25,10 +25,18 @@
>>   
>>   #define SID_MASK	0xF
>>   
>> +struct q6usb_status {
>> +	unsigned int num_pcm;
> 
> how would one know which ones are capture and which ones are playback?
> 
> This really looks like a playback-only assumption, despite earlier
> mentions of capture supported.
> 

Yes, playback only, which is the reasoning for only having one parameter 
here.  I will rename it though to be clearer.

Thanks
Wesley Cheng

>> +	unsigned int chip_index;
>> +	unsigned int pcm_index;
>> +};
>> +
>>   struct q6usb_port_data {
>>   	struct q6afe_usb_cfg usb_cfg;
>>   	struct snd_soc_usb *usb;
>>   	struct q6usb_offload priv;
>> +	unsigned long available_card_slot;
>> +	struct q6usb_status status[SNDRV_CARDS];
>>   	int active_idx;
>>   };
>>   
>> @@ -110,6 +118,14 @@ static int q6usb_alsa_connection_cb(struct snd_soc_usb *usb,
>>   	if (connected) {
>>   		/* We only track the latest USB headset plugged in */
>>   		data->active_idx = sdev->card_idx;
>> +
>> +		set_bit(sdev->card_idx, &data->available_card_slot);
>> +		data->status[sdev->card_idx].num_pcm = sdev->num_playback;
> 
> there you go...
> 
>> +		data->status[sdev->card_idx].chip_index = sdev->chip_idx;
>> +	} else {
>> +		clear_bit(sdev->card_idx, &data->available_card_slot);
>> +		data->status[sdev->card_idx].num_pcm = 0;
>> +		data->status[sdev->card_idx].chip_index = 0;
>>   	}
>>   
>>   	return 0;
Wesley Cheng Oct. 19, 2023, 1:39 a.m. UTC | #20
Hi Pierre,

On 10/17/2023 3:50 PM, Pierre-Louis Bossart wrote:
> 
> 
> On 10/17/23 15:01, Wesley Cheng wrote:
>> Expose a kcontrol on the platform sound card, which will allow for
>> userspace to determine which USB card number and PCM device to offload.
>> This allows for userspace to potentially tag an alternate path for a
>> specific USB SND card and PCM device.  Previously, control was absent, and
>> the offload path would be enabled on the last USB SND device which was
>> connected.  This logic will continue to be applicable if no mixer input is
>> received for specific device selection.
>>
>> An example to configure the offload device using tinymix:
>> tinymix -D 0 set 'Q6USB offload SND device select' 1 0
>>
>> The above will set the Q6AFE device token to choose offload on card#1 and
>> pcm#0.  Device selection is made possible by setting the Q6AFE device
>> token.  The audio DSP utilizes this parameter, and will pass this field
>> back to the USB offload driver within the QMI stream requests.
> 
> This still begs the question on how userspace would figure what the
> card1 is and which endpoint is used when PCM0 is opened?
> 

Assuming we have something maybe in the component string for card1, then 
maybe that will help in this case as you mentioned earlier.  Again, I 
think my understanding of "endpoint" here is referring to the USB 
endpoint.  However, that isn't normally how we should think about it. 
 From the USB sound perspective, it would be the USB interface that is 
selected, and the USB endpoints that that interface descriptor includes 
(up to 2 usb eps).

> Ideally userpace would not have to know anything about "Q6USB".
> Presumably when other vendors expose their USB offload solution, we
> would want a generic control name, no?
> 

Hmm...initially I was keeping the sound kcontrol implementation based on 
a vendor specific approach.  Although, it might be good to standardize 
it a bit.  I could see if we can add this to within soc-usb so whenever 
we just create a soc usb device, it would also create and initialize the 
kcontrols as well?

> Jaroslav should chime in on this one :-)
> 
> 
>> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
>> ---
>>   sound/soc/qcom/qdsp6/q6usb.c | 125 ++++++++++++++++++++++++++++++++++-
>>   1 file changed, 122 insertions(+), 3 deletions(-)
>>
>> diff --git a/sound/soc/qcom/qdsp6/q6usb.c b/sound/soc/qcom/qdsp6/q6usb.c
>> index d697cbe7f184..a95276b7d91d 100644
>> --- a/sound/soc/qcom/qdsp6/q6usb.c
>> +++ b/sound/soc/qcom/qdsp6/q6usb.c
>> @@ -14,6 +14,7 @@
>>   #include <linux/dma-map-ops.h>
>>   
>>   #include <sound/pcm.h>
>> +#include <sound/control.h>
>>   #include <sound/soc.h>
>>   #include <sound/soc-usb.h>
>>   #include <sound/pcm_params.h>
>> @@ -35,9 +36,12 @@ struct q6usb_port_data {
>>   	struct q6afe_usb_cfg usb_cfg;
>>   	struct snd_soc_usb *usb;
>>   	struct q6usb_offload priv;
>> +	struct mutex mutex;
> 
> missing comment on what this protects. "mutex" is really a poor
> choice/name if I am honest.
> 
>>   	unsigned long available_card_slot;
>>   	struct q6usb_status status[SNDRV_CARDS];
>> -	int active_idx;
>> +	bool idx_valid;
>> +	int sel_card_idx;
>> +	int sel_pcm_idx;
>>   };
> 
>> +/* 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_dev_ctrl, component));
>> +	if (ret < 0)
>> +		return;
> 
> that error handling does not seem terribly useful...
> 

Based on your earlier comment, this might change :)

Thanks
Wesley Cheng
Wesley Cheng Oct. 23, 2023, 9:54 p.m. UTC | #21
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
Pierre-Louis Bossart Oct. 24, 2023, 1:35 p.m. UTC | #22
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.
Wesley Cheng Oct. 25, 2023, 10:31 p.m. UTC | #23
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