mbox series

[v3,00/28] Introduce QC USB SND audio offloading support

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

Message

Wesley Cheng March 8, 2023, 11:57 p.m. UTC
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.

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

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

Mathias Nyman (1):
  xhci: Add support to allocate several interrupters

Wesley Cheng (27):
  usb: xhci: Add XHCI APIs to support USB offloading
  usb: host: xhci-mem: Cleanup pending secondary event ring events
  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: Add USB backend ASoC driver for Q6
  sound: usb: card: Introduce USB SND platform op callbacks
  sound: usb: Export USB SND APIs for modules
  dt-bindings: usb: dwc3: Add snps,num-hc-interrupters definition
  usb: dwc3: Add DT parameter to specify maximum number of interrupters
  usb: host: xhci-plat: Set XHCI max interrupters if property is present
  sound: usb: pcm: Export fixed rate check USB SND API
  sound: usb: Introduce QC USB SND offloading support
  sound: usb: card: Check for support for requested audio format
  sound: soc: soc-usb: Add PCM format check API for USB backend
  sound: soc: qcom: qusb6: Ensure PCM format is supported by USB audio
    device
  sound: usb: Prevent starting of audio stream if in use
  ASoC: dt-bindings: Add Q6USB backend bindings
  ASoC: dt-bindings: Update example for enabling USB offload on SM8250
  ASoC: qcom: qdsp6: q6afe: Split USB AFE dev_token param into separate
    API
  sound: Pass USB SND card and PCM information to SOC USB
  sound: soc: qdsp6: Add SND kcontrol to select offload device
  sound: soc: qdsp6: Add SND kcontrol for fetching offload status
  sound: usb: qc_audio_offload: Use card and PCM index from QMI request
  sound: usb: card: Allow for rediscovery of connected USB SND devices
  sound: soc: soc-usb: Rediscover USB SND devices on USB port add

 .../bindings/sound/qcom,q6usb-dais.yaml       |   49 +
 .../bindings/sound/qcom,sm8250.yaml           |   15 +
 .../devicetree/bindings/usb/snps,dwc3.yaml    |   13 +
 drivers/usb/dwc3/core.c                       |   12 +
 drivers/usb/dwc3/core.h                       |    2 +
 drivers/usb/dwc3/host.c                       |    5 +-
 drivers/usb/host/xhci-debugfs.c               |    2 +-
 drivers/usb/host/xhci-mem.c                   |  171 +-
 drivers/usb/host/xhci-plat.c                  |    2 +
 drivers/usb/host/xhci-ring.c                  |    2 +-
 drivers/usb/host/xhci.c                       |  181 +-
 drivers/usb/host/xhci.h                       |    2 +-
 .../sound/qcom,q6dsp-lpass-ports.h            |    1 +
 include/linux/usb/xhci-intr.h                 |   94 +
 include/sound/pcm_params.h                    |    4 +
 include/sound/q6usboffload.h                  |   20 +
 include/sound/soc-usb.h                       |   39 +
 sound/core/oss/pcm_oss.c                      |   58 -
 sound/core/pcm_lib.c                          |   65 +
 sound/soc/Makefile                            |    2 +-
 sound/soc/qcom/Kconfig                        |    4 +
 sound/soc/qcom/qdsp6/Makefile                 |    1 +
 sound/soc/qcom/qdsp6/q6afe-dai.c              |   50 +
 sound/soc/qcom/qdsp6/q6afe.c                  |  208 +-
 sound/soc/qcom/qdsp6/q6afe.h                  |   47 +-
 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                  |  445 ++++
 sound/soc/soc-usb.c                           |  197 ++
 sound/usb/Kconfig                             |   14 +
 sound/usb/Makefile                            |    2 +-
 sound/usb/card.c                              |   85 +
 sound/usb/card.h                              |   31 +
 sound/usb/endpoint.c                          |    2 +
 sound/usb/helper.c                            |    1 +
 sound/usb/pcm.c                               |   29 +-
 sound/usb/pcm.h                               |   12 +
 sound/usb/qcom/Makefile                       |    2 +
 sound/usb/qcom/qc_audio_offload.c             | 1790 +++++++++++++++++
 sound/usb/qcom/usb_audio_qmi_v01.c            |  892 ++++++++
 sound/usb/qcom/usb_audio_qmi_v01.h            |  162 ++
 42 files changed, 4646 insertions(+), 100 deletions(-)
 create mode 100644 Documentation/devicetree/bindings/sound/qcom,q6usb-dais.yaml
 create mode 100644 include/linux/usb/xhci-intr.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

Greg Kroah-Hartman March 9, 2023, 6:29 a.m. UTC | #1
On Wed, Mar 08, 2023 at 03:57:33PM -0800, Wesley Cheng wrote:
> -static const struct audioformat *
> +const struct audioformat *
>  find_format(struct list_head *fmt_list_head, snd_pcm_format_t format,
>  	    unsigned int rate, unsigned int channels, bool strict_match,
>  	    struct snd_usb_substream *subs)
> @@ -147,8 +147,9 @@ find_format(struct list_head *fmt_list_head, snd_pcm_format_t format,
>  	}
>  	return found;
>  }
> +EXPORT_SYMBOL_GPL(find_format);

This is a horrible name for the global symbol namespace, right?
It needs a "snd_" prefix at the very least, maybe even more.

>  
> -static const struct audioformat *
> +const struct audioformat *
>  find_substream_format(struct snd_usb_substream *subs,
>  		      const struct snd_pcm_hw_params *params)
>  {
> @@ -156,6 +157,7 @@ find_substream_format(struct snd_usb_substream *subs,
>  			   params_rate(params), params_channels(params),
>  			   true, subs);
>  }
> +EXPORT_SYMBOL_GPL(find_substream_format);

Same here.

>  
>  bool snd_usb_pcm_has_fixed_rate(struct snd_usb_substream *subs)
>  {
> @@ -446,7 +448,7 @@ int snd_usb_pcm_resume(struct snd_usb_stream *as)
>  	return 0;
>  }
>  
> -static void close_endpoints(struct snd_usb_audio *chip,
> +void close_endpoints(struct snd_usb_audio *chip,
>  			    struct snd_usb_substream *subs)
>  {
>  	if (subs->data_endpoint) {
> @@ -460,6 +462,7 @@ static void close_endpoints(struct snd_usb_audio *chip,
>  		subs->sync_endpoint = NULL;
>  	}
>  }
> +EXPORT_SYMBOL(close_endpoints);

Same here.

thanks,

greg k-h
Greg Kroah-Hartman March 9, 2023, 6:38 a.m. UTC | #2
On Wed, Mar 08, 2023 at 03:57:25PM -0800, Wesley Cheng wrote:
> Some use cases, such as USB audio offloading, will allow for a DSP to take
> over issuing USB transfers to the host controller.  In order for the DSP to
> submit transfers for a particular endpoint, and to handle its events, the
> client driver will need to query for some parameters allocated by XHCI.
> 
> - XHCI secondary interrupter event ring address
> - XHCI transfer ring address (for a particular EP)
> - Stop endpoint command API
> 
> Once the resources are handed off to the DSP, the offload begins, and the
> main processor can enter idle.  When stopped, since there are no URBs
> submitted from the main processor, the client will just issue a stop
> endpoint command to halt any pending transfers.
> 
> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
> ---
>  drivers/usb/host/xhci.c       | 130 ++++++++++++++++++++++++++++++++++
>  include/linux/usb/xhci-intr.h |   8 +++
>  2 files changed, 138 insertions(+)

Please use checkpatch.pl on your patches before sending them out :(

Some other minor comments:

> diff --git a/drivers/usb/host/xhci.c b/drivers/usb/host/xhci.c
> index 88435b9cd66e..5c6b3d8f834c 100644
> --- a/drivers/usb/host/xhci.c
> +++ b/drivers/usb/host/xhci.c
> @@ -1603,6 +1603,136 @@ static int xhci_check_args(struct usb_hcd *hcd, struct usb_device *udev,
>  	return 1;
>  }
>  
> +int xhci_stop_endpoint(struct usb_device *udev,
> +			struct usb_host_endpoint *ep)

That all can be on one line, right?

And no documentation for a global function?

> +{
> +	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
> +	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
> +	unsigned int ep_index;
> +	struct xhci_virt_device *virt_dev;
> +	struct xhci_command *cmd;
> +	unsigned long flags;
> +	int ret = 0;
> +
> +	ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
> +	if (ret <= 0)
> +		return ret;
> +
> +	cmd = xhci_alloc_command(xhci, true, GFP_NOIO);
> +	if (!cmd)
> +		return -ENOMEM;
> +
> +	spin_lock_irqsave(&xhci->lock, flags);
> +	virt_dev = xhci->devs[udev->slot_id];
> +	if (!virt_dev) {
> +		ret = -ENODEV;
> +		goto err;
> +	}
> +
> +	ep_index = xhci_get_endpoint_index(&ep->desc);
> +	if (virt_dev->eps[ep_index].ring &&
> +			virt_dev->eps[ep_index].ring->dequeue) {
> +		ret = xhci_queue_stop_endpoint(xhci, cmd, udev->slot_id,
> +				ep_index, 0);
> +		if (ret)
> +			goto err;
> +
> +		xhci_ring_cmd_db(xhci);
> +		spin_unlock_irqrestore(&xhci->lock, flags);
> +
> +		/* Wait for stop endpoint command to finish */
> +		wait_for_completion(cmd->completion);
> +
> +		if (cmd->status == COMP_COMMAND_ABORTED ||
> +				cmd->status == COMP_STOPPED) {
> +			xhci_warn(xhci,
> +				"stop endpoint command timeout for ep%d%s\n",
> +				usb_endpoint_num(&ep->desc),
> +				usb_endpoint_dir_in(&ep->desc) ? "in" : "out");
> +			ret = -ETIME;
> +				}
> +		goto free_cmd;
> +	}
> +
> +err:
> +	spin_unlock_irqrestore(&xhci->lock, flags);
> +free_cmd:
> +	xhci_free_command(xhci, cmd);
> +
> +	return ret;
> +}
> +EXPORT_SYMBOL_GPL(xhci_stop_endpoint);
> +
> +/* Retrieve the transfer ring base address for a specific endpoint. */

At least some comment, but not much for a global function.

> +phys_addr_t xhci_get_xfer_resource(struct usb_device *udev,
> +					struct usb_host_endpoint *ep, dma_addr_t *dma)
> +{
> +	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
> +	struct device *dev = hcd->self.sysdev;
> +	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
> +	struct sg_table sgt;
> +	phys_addr_t pa;
> +	int ret;
> +	unsigned int ep_index;
> +	struct xhci_virt_device *virt_dev;
> +	unsigned long flags;
> +
> +	if (!HCD_RH_RUNNING(hcd))
> +		return 0;

Isn't 0 a valid address?


> +
> +	ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
> +	if (ret <= 0) {
> +		xhci_err(xhci, "%s: invalid args\n", __func__);
> +		return 0;
> +	}
> +
> +	spin_lock_irqsave(&xhci->lock, flags);
> +
> +	virt_dev = xhci->devs[udev->slot_id];
> +	ep_index = xhci_get_endpoint_index(&ep->desc);
> +
> +	if (virt_dev->eps[ep_index].ring &&
> +		virt_dev->eps[ep_index].ring->first_seg) {
> +
> +		dma_get_sgtable(dev, &sgt,
> +			virt_dev->eps[ep_index].ring->first_seg->trbs,
> +			virt_dev->eps[ep_index].ring->first_seg->dma,
> +			TRB_SEGMENT_SIZE);
> +
> +		*dma = virt_dev->eps[ep_index].ring->first_seg->dma;
> +
> +		pa = page_to_phys(sg_page(sgt.sgl));
> +		sg_free_table(&sgt);
> +		spin_unlock_irqrestore(&xhci->lock, flags);
> +
> +		return pa;
> +	}
> +	spin_unlock_irqrestore(&xhci->lock, flags);
> +
> +	return 0;
> +}
> +EXPORT_SYMBOL_GPL(xhci_get_xfer_resource);
> +
> +phys_addr_t xhci_get_ir_resource(struct usb_device *udev, struct xhci_interrupter *ir)

kerneldoc for global functions?

> +{
> +	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
> +	struct device *dev = hcd->self.sysdev;
> +	struct sg_table sgt;
> +	phys_addr_t pa;
> +
> +	if (!ir)
> +		return 0;

How can ir ever be NULL?  You control the callers, just don't do that.

> +
> +	dma_get_sgtable(dev, &sgt, ir->event_ring->first_seg->trbs,
> +		ir->event_ring->first_seg->dma, TRB_SEGMENT_SIZE);
> +
> +	pa = page_to_phys(sg_page(sgt.sgl));
> +	sg_free_table(&sgt);
> +
> +	return pa;
> +}
> +EXPORT_SYMBOL_GPL(xhci_get_ir_resource);
> +
>  static int xhci_configure_endpoint(struct xhci_hcd *xhci,
>  		struct usb_device *udev, struct xhci_command *command,
>  		bool ctx_change, bool must_succeed);
> diff --git a/include/linux/usb/xhci-intr.h b/include/linux/usb/xhci-intr.h
> index 738b0f0481a6..d42cc9a1e698 100644
> --- a/include/linux/usb/xhci-intr.h
> +++ b/include/linux/usb/xhci-intr.h
> @@ -80,7 +80,15 @@ struct xhci_interrupter {
>  	u64	s3_erst_dequeue;
>  };
>  
> +/* Secondary interrupter */
>  struct xhci_interrupter *
>  xhci_create_secondary_interrupter(struct usb_hcd *hcd, int intr_num);
>  void xhci_remove_secondary_interrupter(struct usb_hcd *hcd, struct xhci_interrupter *ir);
> +
> +/* Offload */
> +int xhci_stop_endpoint(struct usb_device *udev,
> +			struct usb_host_endpoint *ep);
> +phys_addr_t xhci_get_xfer_resource(struct usb_device *udev,
> +					struct usb_host_endpoint *ep, dma_addr_t *dma);
> +phys_addr_t xhci_get_ir_resource(struct usb_device *udev, struct xhci_interrupter *ir);

Why are these functions unique to offload?

thanks,

greg k-h
Greg Kroah-Hartman March 9, 2023, 6:44 a.m. UTC | #3
On Wed, Mar 08, 2023 at 03:57:32PM -0800, Wesley Cheng wrote:
> Allow for different platforms to be notified on USB SND connect/disconnect
> seqeunces.  This allows for platform USB SND modules to properly initialize
> and populate internal structures with references to the USB SND chip
> device.
> 
> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
> ---
>  sound/usb/card.c | 36 ++++++++++++++++++++++++++++++++++++
>  sound/usb/card.h | 20 ++++++++++++++++++++
>  2 files changed, 56 insertions(+)
> 
> diff --git a/sound/usb/card.c b/sound/usb/card.c
> index 26268ffb8274..9bcbaa0c0a55 100644
> --- a/sound/usb/card.c
> +++ b/sound/usb/card.c
> @@ -117,6 +117,30 @@ MODULE_PARM_DESC(skip_validation, "Skip unit descriptor validation (default: no)
>  static DEFINE_MUTEX(register_mutex);
>  static struct snd_usb_audio *usb_chip[SNDRV_CARDS];
>  static struct usb_driver usb_audio_driver;
> +static struct snd_usb_platform_ops *platform_ops;

As I've said before, you can not just have one of these.  They need to
be per-bus structure.  Or per-device, something dynamic, not static like
this.

> +int snd_usb_register_platform_ops(struct snd_usb_platform_ops *ops)
> +{
> +	if (platform_ops)
> +		return -EEXIST;
> +
> +	mutex_lock(&register_mutex);
> +	platform_ops = ops;
> +	mutex_unlock(&register_mutex);

Your locking is odd for a single pointer, why is it needed at all?

Also you check the pointer before using the lock, which defeats the lock
in the first place.

thanks,

greg k-h
Greg Kroah-Hartman March 9, 2023, 6:46 a.m. UTC | #4
On Wed, Mar 08, 2023 at 03:57:23PM -0800, Wesley Cheng wrote:
> Changes in v3:
> - Changed prefix from RFC to PATCH
> - Rebased entire series to usb-next
> - Updated copyright years

This is much better, thanks.  I've done some very brief high-level
skimming and found minor issues, and one major one.  I'll let others
review this in more depth right now, as I am way behind in reviewing
other USB patches and need to get to them first.

thanks,

greg k-h
Takashi Sakamoto March 9, 2023, 8:29 a.m. UTC | #5
Hi,

On Wed, Mar 08, 2023 at 03:57:38PM -0800, Wesley Cheng wrote:
> diff --git a/sound/usb/qcom/qc_audio_offload.c b/sound/usb/qcom/qc_audio_offload.c
> new file mode 100644
> index 000000000000..2663906644f2
> --- /dev/null
> +++ b/sound/usb/qcom/qc_audio_offload.c
> ...
> +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;
> +	const struct audioformat *fmt;
> +	int ret;
> +	bool fixed_rate;
> +
> +	_snd_pcm_hw_params_any(&params);
> +	_snd_pcm_hw_param_set(&params, SNDRV_PCM_HW_PARAM_FORMAT,
> +			(__force int) pcm_format, 0);
> +	_snd_pcm_hw_param_set(&params, SNDRV_PCM_HW_PARAM_CHANNELS,
> +			channels, 0);
> +	_snd_pcm_hw_param_set(&params, SNDRV_PCM_HW_PARAM_RATE,
> +			cur_rate, 0);

I think the above code is equivalent to below code.

```
// 1. Initialize the hardware parameter so that it expresses
// the maximum flags of mask parameters and the maximum range of integer
// parameters.
_snd_pcm_hw_params_any(&params);

// 2. Then shrink the mask parameters and integer parameters.
struct snd_mask *mask;
struct snd_interval *interval;

mask = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
snd_mask_leave(mask, pcm_format);

interval = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
snd_interval_setinteger(&interval);
interval.min = interval.max = channels;

interval = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE);
snd_interval_setinteger(&interval);
interval.min = interval.max = cur_rate;
```

In '[PATCH v3 10/28] sound: usb: Export USB SND APIs for modules', some
codes moved from ALSA Open Sound System compatibility layer to ALSA core
to export some kernel APIs. The '_snd_pcm_hw_param_set()' is one of
them. If they were needed just for the above operations, it would be
exaggerating just for the driver.

Of course, we can assume that the similar kernel API would be required
for the other drivers (OSS PCM, USB gadget, and so on.). However, at
present, it is preferable to focus just on your driver. 

(I note that typical sound PCM driver has code to shrink hardware
parameters in PCM rule. It consists of a set of test and refine API.)


Regards

Takashi Sakamoto
Srinivas Kandagatla March 9, 2023, 9 a.m. UTC | #6
On 08/03/2023 23:57, Wesley Cheng wrote:
> Q6DSP supports handling of USB playback audio data if USB audio offloading
> is enabled.  Add a new definition for the USB_RX AFE port, which is
> referenced when the AFE port is started.
> 
> Acked-by: Krzysztof Kozlowski <krzysztof.kozlowski@linaro.org>
> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>


Reviewed-by: Srinivas Kandagatla <srinivas.kandagatla@linaro.org>
> ---
>   include/dt-bindings/sound/qcom,q6dsp-lpass-ports.h | 1 +
>   1 file changed, 1 insertion(+)
> 
> diff --git a/include/dt-bindings/sound/qcom,q6dsp-lpass-ports.h b/include/dt-bindings/sound/qcom,q6dsp-lpass-ports.h
> index 9f7c5103bc82..746bc462bb2e 100644
> --- a/include/dt-bindings/sound/qcom,q6dsp-lpass-ports.h
> +++ b/include/dt-bindings/sound/qcom,q6dsp-lpass-ports.h
> @@ -131,6 +131,7 @@
>   #define RX_CODEC_DMA_RX_7	126
>   #define QUINARY_MI2S_RX		127
>   #define QUINARY_MI2S_TX		128
> +#define USB_RX				129
>   
>   #define LPASS_CLK_ID_PRI_MI2S_IBIT	1
>   #define LPASS_CLK_ID_PRI_MI2S_EBIT	2
Srinivas Kandagatla March 9, 2023, 9:01 a.m. UTC | #7
On 08/03/2023 23:57, Wesley Cheng wrote:
> The QC ADSP is able to support USB playback endpoints, so that the main
> application processor can be placed into lower CPU power modes.  This adds
> the required AFE port configurations and port start command to start an
> audio session.
> 
> Specifically, the QC ADSP can support all potential endpoints that are
> exposed by the audio data interface.  This includes, feedback endpoints
> (both implicit and explicit) as well as the isochronous (data) endpoints.
> The size of audio samples sent per USB frame (microframe) will be adjusted
> based on information received on the feedback endpoint.
> 
> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>

thanks for the work,


Reviewed-by: Srinivas Kandagatla <srinivas.kandagatla@linaro.org>

> ---
>   sound/soc/qcom/qdsp6/q6afe-dai.c         |  50 ++++++
>   sound/soc/qcom/qdsp6/q6afe.c             | 185 ++++++++++++++++++++++-
>   sound/soc/qcom/qdsp6/q6afe.h             |  46 +++++-
>   sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c |  23 +++
>   sound/soc/qcom/qdsp6/q6dsp-lpass-ports.h |   1 +
>   sound/soc/qcom/qdsp6/q6routing.c         |   9 ++
>   6 files changed, 312 insertions(+), 2 deletions(-)
> 
> diff --git a/sound/soc/qcom/qdsp6/q6afe-dai.c b/sound/soc/qcom/qdsp6/q6afe-dai.c
> index 8bb7452b8f18..bda79d77c8d8 100644
> --- a/sound/soc/qcom/qdsp6/q6afe-dai.c
> +++ b/sound/soc/qcom/qdsp6/q6afe-dai.c
> @@ -111,6 +111,40 @@ static int q6hdmi_hw_params(struct snd_pcm_substream *substream,
>   	return 0;
>   }
>   
> +static int q6usb_hw_params(struct snd_pcm_substream *substream,
> +			   struct snd_pcm_hw_params *params,
> +			   struct snd_soc_dai *dai)
> +{
> +	struct q6afe_dai_data *dai_data = dev_get_drvdata(dai->dev);
> +	int channels = params_channels(params);
> +	int rate = params_rate(params);
> +	struct q6afe_usb_cfg *usb = &dai_data->port_config[dai->id].usb_audio;
> +
> +	usb->sample_rate = rate;
> +	usb->num_channels = channels;
> +
> +	switch (params_format(params)) {
> +	case SNDRV_PCM_FORMAT_U16_LE:
> +	case SNDRV_PCM_FORMAT_S16_LE:
> +	case SNDRV_PCM_FORMAT_SPECIAL:
> +		usb->bit_width = 16;
> +		break;
> +	case SNDRV_PCM_FORMAT_S24_LE:
> +	case SNDRV_PCM_FORMAT_S24_3LE:
> +		usb->bit_width = 24;
> +		break;
> +	case SNDRV_PCM_FORMAT_S32_LE:
> +		usb->bit_width = 32;
> +		break;
> +	default:
> +		dev_err(dai->dev, "%s: invalid format %d\n",
> +			__func__, params_format(params));
> +		return -EINVAL;
> +	}
> +
> +	return 0;
> +}
> +
>   static int q6i2s_hw_params(struct snd_pcm_substream *substream,
>   			   struct snd_pcm_hw_params *params,
>   			   struct snd_soc_dai *dai)
> @@ -411,6 +445,10 @@ static int q6afe_dai_prepare(struct snd_pcm_substream *substream,
>   		q6afe_cdc_dma_port_prepare(dai_data->port[dai->id],
>   					   &dai_data->port_config[dai->id].dma_cfg);
>   		break;
> +	case USB_RX:
> +		q6afe_usb_port_prepare(dai_data->port[dai->id],
> +				       &dai_data->port_config[dai->id].usb_audio);
> +		break;
>   	default:
>   		return -EINVAL;
>   	}
> @@ -637,6 +675,15 @@ static const struct snd_soc_dapm_route q6afe_dapm_routes[] = {
>   	{"TX_CODEC_DMA_TX_5", NULL, "TX_CODEC_DMA_TX_5 Capture"},
>   	{"RX_CODEC_DMA_RX_6 Playback", NULL, "RX_CODEC_DMA_RX_6"},
>   	{"RX_CODEC_DMA_RX_7 Playback", NULL, "RX_CODEC_DMA_RX_7"},
> +
> +	/* USB playback AFE port receives data for playback, hence use the RX port */
> +	{"USB Playback", NULL, "USB_RX"},
> +};
> +
> +static const struct snd_soc_dai_ops q6usb_ops = {
> +	.prepare	= q6afe_dai_prepare,
> +	.hw_params	= q6usb_hw_params,
> +	.shutdown	= q6afe_dai_shutdown,
>   };
>   
>   static const struct snd_soc_dai_ops q6hdmi_ops = {
> @@ -952,6 +999,8 @@ static const struct snd_soc_dapm_widget q6afe_dai_widgets[] = {
>   		0, SND_SOC_NOPM, 0, 0),
>   	SND_SOC_DAPM_AIF_IN("RX_CODEC_DMA_RX_7", "NULL",
>   		0, SND_SOC_NOPM, 0, 0),
> +
> +	SND_SOC_DAPM_AIF_IN("USB_RX", NULL, 0, SND_SOC_NOPM, 0, 0),
>   };
>   
>   static const struct snd_soc_component_driver q6afe_dai_component = {
> @@ -1068,6 +1117,7 @@ static int q6afe_dai_dev_probe(struct platform_device *pdev)
>   	cfg.q6i2s_ops = &q6i2s_ops;
>   	cfg.q6tdm_ops = &q6tdm_ops;
>   	cfg.q6dma_ops = &q6dma_ops;
> +	cfg.q6usb_ops = &q6usb_ops;
>   	dais = q6dsp_audio_ports_set_config(dev, &cfg, &num_dais);
>   
>   	return devm_snd_soc_register_component(dev, &q6afe_dai_component, dais, num_dais);
> diff --git a/sound/soc/qcom/qdsp6/q6afe.c b/sound/soc/qcom/qdsp6/q6afe.c
> index 919e326b9462..43baf93f9c89 100644
> --- a/sound/soc/qcom/qdsp6/q6afe.c
> +++ b/sound/soc/qcom/qdsp6/q6afe.c
> @@ -34,6 +34,8 @@
>   #define AFE_MODULE_TDM			0x0001028A
>   
>   #define AFE_PARAM_ID_CDC_SLIMBUS_SLAVE_CFG 0x00010235
> +#define AFE_PARAM_ID_USB_AUDIO_DEV_PARAMS    0x000102A5
> +#define AFE_PARAM_ID_USB_AUDIO_DEV_LPCM_FMT 0x000102AA
>   
>   #define AFE_PARAM_ID_LPAIF_CLK_CONFIG	0x00010238
>   #define AFE_PARAM_ID_INT_DIGITAL_CDC_CLK_CONFIG	0x00010239
> @@ -43,6 +45,7 @@
>   #define AFE_PARAM_ID_TDM_CONFIG	0x0001029D
>   #define AFE_PARAM_ID_PORT_SLOT_MAPPING_CONFIG	0x00010297
>   #define AFE_PARAM_ID_CODEC_DMA_CONFIG	0x000102B8
> +#define AFE_PARAM_ID_USB_AUDIO_CONFIG    0x000102A4
>   #define AFE_CMD_REMOTE_LPASS_CORE_HW_VOTE_REQUEST	0x000100f4
>   #define AFE_CMD_RSP_REMOTE_LPASS_CORE_HW_VOTE_REQUEST   0x000100f5
>   #define AFE_CMD_REMOTE_LPASS_CORE_HW_DEVOTE_REQUEST	0x000100f6
> @@ -71,12 +74,16 @@
>   #define AFE_PORT_CONFIG_I2S_WS_SRC_INTERNAL	0x1
>   #define AFE_LINEAR_PCM_DATA				0x0
>   
> +#define AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG 0x1
>   
>   /* Port IDs */
>   #define AFE_API_VERSION_HDMI_CONFIG	0x1
>   #define AFE_PORT_ID_MULTICHAN_HDMI_RX	0x100E
>   #define AFE_PORT_ID_HDMI_OVER_DP_RX	0x6020
>   
> +/* USB AFE port */
> +#define AFE_PORT_ID_USB_RX                       0x7000
> +
>   #define AFE_API_VERSION_SLIMBUS_CONFIG 0x1
>   /* Clock set API version */
>   #define AFE_API_VERSION_CLOCK_SET 1
> @@ -512,12 +519,109 @@ struct afe_param_id_cdc_dma_cfg {
>   	u16	active_channels_mask;
>   } __packed;
>   
> +struct afe_param_id_usb_cfg {
> +/* Minor version used for tracking USB audio device configuration.
> + * Supported values: AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG
> + */
> +	u32                  cfg_minor_version;
> +/* Sampling rate of the port.
> + * Supported values:
> + * - AFE_PORT_SAMPLE_RATE_8K
> + * - AFE_PORT_SAMPLE_RATE_11025
> + * - AFE_PORT_SAMPLE_RATE_12K
> + * - AFE_PORT_SAMPLE_RATE_16K
> + * - AFE_PORT_SAMPLE_RATE_22050
> + * - AFE_PORT_SAMPLE_RATE_24K
> + * - AFE_PORT_SAMPLE_RATE_32K
> + * - AFE_PORT_SAMPLE_RATE_44P1K
> + * - AFE_PORT_SAMPLE_RATE_48K
> + * - AFE_PORT_SAMPLE_RATE_96K
> + * - AFE_PORT_SAMPLE_RATE_192K
> + */
> +	u32                  sample_rate;
> +/* Bit width of the sample.
> + * Supported values: 16, 24
> + */
> +	u16                  bit_width;
> +/* Number of channels.
> + * Supported values: 1 and 2
> + */
> +	u16                  num_channels;
> +/* Data format supported by the USB. The supported value is
> + * 0 (#AFE_USB_AUDIO_DATA_FORMAT_LINEAR_PCM).
> + */
> +	u16                  data_format;
> +/* this field must be 0 */
> +	u16                  reserved;
> +/* device token of actual end USB aduio device */
> +	u32                  dev_token;
> +/* endianness of this interface */
> +	u32                   endian;
> +/* service interval */
> +	u32                  service_interval;
> +} __packed;
> +
> +/**
> + * struct afe_param_id_usb_audio_dev_params
> + * @cfg_minor_version: Minor version used for tracking USB audio device
> + * configuration.
> + * Supported values:
> + *     AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG
> + * @dev_token: device token of actual end USB aduio device
> + **/
> +struct afe_param_id_usb_audio_dev_params {
> +	u32	cfg_minor_version;
> +	u32	dev_token;
> +} __packed;
> +
> +/**
> + * struct afe_param_id_usb_audio_dev_lpcm_fmt
> + * @cfg_minor_version: Minor version used for tracking USB audio device
> + * configuration.
> + * Supported values:
> + *     AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG
> + * @endian: endianness of this interface
> + **/
> +struct afe_param_id_usb_audio_dev_lpcm_fmt {
> +	u32	cfg_minor_version;
> +	u32	endian;
> +} __packed;
> +
> +/**
> + * struct afe_param_id_usb_audio_dev_latency_mode
> + * @cfg_minor_version: Minor version used for tracking USB audio device
> + * configuration.
> + * Supported values:
> + *     AFE_API_MINOR_VERSION_USB_AUDIO_LATENCY_MODE
> + * @mode: latency mode for the USB audio device
> + **/
> +struct afe_param_id_usb_audio_dev_latency_mode {
> +	u32	minor_version;
> +	u32	mode;
> +} __packed;
> +
> +#define AFE_PARAM_ID_USB_AUDIO_SVC_INTERVAL     0x000102B7
> +
> +/**
> + * struct afe_param_id_usb_audio_svc_interval
> + * @cfg_minor_version: Minor version used for tracking USB audio device
> + * configuration.
> + * Supported values:
> + *     AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG
> + * @svc_interval: service interval
> + **/
> +struct afe_param_id_usb_audio_svc_interval {
> +	u32	cfg_minor_version;
> +	u32	svc_interval;
> +} __packed;
> +
>   union afe_port_config {
>   	struct afe_param_id_hdmi_multi_chan_audio_cfg hdmi_multi_ch;
>   	struct afe_param_id_slimbus_cfg           slim_cfg;
>   	struct afe_param_id_i2s_cfg	i2s_cfg;
>   	struct afe_param_id_tdm_cfg	tdm_cfg;
>   	struct afe_param_id_cdc_dma_cfg	dma_cfg;
> +	struct afe_param_id_usb_cfg usb_cfg;
>   } __packed;
>   
>   
> @@ -832,6 +936,7 @@ static struct afe_port_map port_maps[AFE_PORT_MAX] = {
>   				RX_CODEC_DMA_RX_6, 1, 1},
>   	[RX_CODEC_DMA_RX_7] = { AFE_PORT_ID_RX_CODEC_DMA_RX_7,
>   				RX_CODEC_DMA_RX_7, 1, 1},
> +	[USB_RX] = { AFE_PORT_ID_USB_RX, USB_RX, 1, 1},
>   };
>   
>   static void q6afe_port_free(struct kref *ref)
> @@ -1289,6 +1394,81 @@ void q6afe_tdm_port_prepare(struct q6afe_port *port,
>   }
>   EXPORT_SYMBOL_GPL(q6afe_tdm_port_prepare);
>   
> +static int afe_port_send_usb_dev_param(struct q6afe_port *port, struct q6afe_usb_cfg *cfg)
> +{
> +	union afe_port_config *pcfg = &port->port_cfg;
> +	struct afe_param_id_usb_audio_dev_params usb_dev;
> +	struct afe_param_id_usb_audio_dev_lpcm_fmt lpcm_fmt;
> +	struct afe_param_id_usb_audio_svc_interval svc_int;
> +	int ret = 0;
> +
> +	if (!pcfg) {
> +		dev_err(port->afe->dev, "%s: Error, no configuration data\n", __func__);
> +		ret = -EINVAL;
> +		goto exit;
> +	}
> +
> +	memset(&usb_dev, 0, sizeof(usb_dev));
> +	memset(&lpcm_fmt, 0, sizeof(lpcm_fmt));
> +	memset(&svc_int, 0, sizeof(svc_int));
> +
> +	usb_dev.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
> +	q6afe_port_set_param_v2(port, &usb_dev,
> +				AFE_PARAM_ID_USB_AUDIO_DEV_PARAMS,
> +				AFE_MODULE_AUDIO_DEV_INTERFACE, sizeof(usb_dev));
> +	if (ret) {
> +		dev_err(port->afe->dev, "%s: AFE device param cmd failed %d\n",
> +			__func__, ret);
> +		goto exit;
> +	}
> +
> +	lpcm_fmt.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
> +	lpcm_fmt.endian = pcfg->usb_cfg.endian;
> +	ret = q6afe_port_set_param_v2(port, &lpcm_fmt,
> +				      AFE_PARAM_ID_USB_AUDIO_DEV_LPCM_FMT,
> +				      AFE_MODULE_AUDIO_DEV_INTERFACE, sizeof(lpcm_fmt));
> +	if (ret) {
> +		dev_err(port->afe->dev, "%s: AFE device param cmd LPCM_FMT failed %d\n",
> +			__func__, ret);
> +		goto exit;
> +	}
> +
> +	svc_int.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
> +	svc_int.svc_interval = pcfg->usb_cfg.service_interval;
> +	ret = q6afe_port_set_param_v2(port, &svc_int,
> +				      AFE_PARAM_ID_USB_AUDIO_SVC_INTERVAL,
> +				      AFE_MODULE_AUDIO_DEV_INTERFACE, sizeof(svc_int));
> +	if (ret) {
> +		dev_err(port->afe->dev, "%s: AFE device param cmd svc_interval failed %d\n",
> +			__func__, ret);
> +		ret = -EINVAL;
> +		goto exit;
> +	}
> +exit:
> +	return ret;
> +}
> +
> +/**
> + * q6afe_usb_port_prepare() - Prepare usb afe port.
> + *
> + * @port: Instance of afe port
> + * @cfg: USB configuration for the afe port
> + *
> + */
> +void q6afe_usb_port_prepare(struct q6afe_port *port,
> +			     struct q6afe_usb_cfg *cfg)
> +{
> +	union afe_port_config *pcfg = &port->port_cfg;
> +
> +	pcfg->usb_cfg.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
> +	pcfg->usb_cfg.sample_rate = cfg->sample_rate;
> +	pcfg->usb_cfg.num_channels = cfg->num_channels;
> +	pcfg->usb_cfg.bit_width = cfg->bit_width;
> +
> +	afe_port_send_usb_dev_param(port, cfg);
> +}
> +EXPORT_SYMBOL_GPL(q6afe_usb_port_prepare);
> +
>   /**
>    * q6afe_hdmi_port_prepare() - Prepare hdmi afe port.
>    *
> @@ -1611,7 +1791,10 @@ struct q6afe_port *q6afe_port_get_from_id(struct device *dev, int id)
>   		break;
>   	case AFE_PORT_ID_WSA_CODEC_DMA_RX_0 ... AFE_PORT_ID_RX_CODEC_DMA_RX_7:
>   		cfg_type = AFE_PARAM_ID_CODEC_DMA_CONFIG;
> -	break;
> +		break;
> +	case AFE_PORT_ID_USB_RX:
> +		cfg_type = AFE_PARAM_ID_USB_AUDIO_CONFIG;
> +		break;
>   	default:
>   		dev_err(dev, "Invalid port id 0x%x\n", port_id);
>   		return ERR_PTR(-EINVAL);
> diff --git a/sound/soc/qcom/qdsp6/q6afe.h b/sound/soc/qcom/qdsp6/q6afe.h
> index 30fd77e2f458..e098a3e15135 100644
> --- a/sound/soc/qcom/qdsp6/q6afe.h
> +++ b/sound/soc/qcom/qdsp6/q6afe.h
> @@ -5,7 +5,7 @@
>   
>   #include <dt-bindings/sound/qcom,q6afe.h>
>   
> -#define AFE_PORT_MAX		129
> +#define AFE_PORT_MAX		130
>   
>   #define MSM_AFE_PORT_TYPE_RX 0
>   #define MSM_AFE_PORT_TYPE_TX 1
> @@ -205,6 +205,47 @@ struct q6afe_cdc_dma_cfg {
>   	u16	active_channels_mask;
>   };
>   
> +/**
> + * struct q6afe_usb_cfg
> + * @cfg_minor_version: Minor version used for tracking USB audio device
> + * configuration.
> + * Supported values:
> + *     AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG
> + * @sample_rate: Sampling rate of the port
> + *    Supported values:
> + *      AFE_PORT_SAMPLE_RATE_8K
> + *      AFE_PORT_SAMPLE_RATE_11025
> + *      AFE_PORT_SAMPLE_RATE_12K
> + *      AFE_PORT_SAMPLE_RATE_16K
> + *      AFE_PORT_SAMPLE_RATE_22050
> + *      AFE_PORT_SAMPLE_RATE_24K
> + *      AFE_PORT_SAMPLE_RATE_32K
> + *      AFE_PORT_SAMPLE_RATE_44P1K
> + *      AFE_PORT_SAMPLE_RATE_48K
> + *      AFE_PORT_SAMPLE_RATE_96K
> + *      AFE_PORT_SAMPLE_RATE_192K
> + * @bit_width: Bit width of the sample.
> + *    Supported values: 16, 24
> + * @num_channels: Number of channels
> + *    Supported values: 1, 2
> + * @data_format: Data format supported by the USB
> + *    Supported values: 0
> + * @reserved: this field must be 0
> + * @dev_token: device token of actual end USB audio device
> + * @endian: endianness of this interface
> + * @service_interval: service interval
> + **/
> +struct q6afe_usb_cfg {
> +	u32	cfg_minor_version;
> +	u32     sample_rate;
> +	u16	bit_width;
> +	u16	num_channels;
> +	u16	data_format;
> +	u16	reserved;
> +	u32	dev_token;
> +	u32	endian;
> +	u32	service_interval;
> +};
>   
>   struct q6afe_port_config {
>   	struct q6afe_hdmi_cfg hdmi;
> @@ -212,6 +253,7 @@ struct q6afe_port_config {
>   	struct q6afe_i2s_cfg i2s_cfg;
>   	struct q6afe_tdm_cfg tdm;
>   	struct q6afe_cdc_dma_cfg dma_cfg;
> +	struct q6afe_usb_cfg usb_audio;
>   };
>   
>   struct q6afe_port;
> @@ -221,6 +263,8 @@ int q6afe_port_start(struct q6afe_port *port);
>   int q6afe_port_stop(struct q6afe_port *port);
>   void q6afe_port_put(struct q6afe_port *port);
>   int q6afe_get_port_id(int index);
> +void q6afe_usb_port_prepare(struct q6afe_port *port,
> +			     struct q6afe_usb_cfg *cfg);
>   void q6afe_hdmi_port_prepare(struct q6afe_port *port,
>   			    struct q6afe_hdmi_cfg *cfg);
>   void q6afe_slim_port_prepare(struct q6afe_port *port,
> diff --git a/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c b/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c
> index f67c16fd90b9..39719c3f1767 100644
> --- a/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c
> +++ b/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.c
> @@ -81,6 +81,26 @@
>   
>   
>   static struct snd_soc_dai_driver q6dsp_audio_fe_dais[] = {
> +	{
> +		.playback = {
> +			.stream_name = "USB Playback",
> +			.rates = SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_11025 |
> +					SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_22050 |
> +					SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_44100 |
> +					SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_96000 |
> +					SNDRV_PCM_RATE_192000,
> +			.formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S16_BE |
> +					SNDRV_PCM_FMTBIT_U16_LE | SNDRV_PCM_FMTBIT_U16_BE |
> +					SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S24_BE |
> +					SNDRV_PCM_FMTBIT_U24_LE | SNDRV_PCM_FMTBIT_U24_BE,
> +			.channels_min = 1,
> +			.channels_max = 2,
> +			.rate_min =	8000,
> +			.rate_max = 192000,
> +		},
> +		.id = USB_RX,
> +		.name = "USB_RX",
> +	},
>   	{
>   		.playback = {
>   			.stream_name = "HDMI Playback",
> @@ -616,6 +636,9 @@ struct snd_soc_dai_driver *q6dsp_audio_ports_set_config(struct device *dev,
>   		case WSA_CODEC_DMA_RX_0 ... RX_CODEC_DMA_RX_7:
>   			q6dsp_audio_fe_dais[i].ops = cfg->q6dma_ops;
>   			break;
> +		case USB_RX:
> +			q6dsp_audio_fe_dais[i].ops = cfg->q6usb_ops;
> +			break;
>   		default:
>   			break;
>   		}
> diff --git a/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.h b/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.h
> index 7f052c8a1257..d8dde6dd0aca 100644
> --- a/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.h
> +++ b/sound/soc/qcom/qdsp6/q6dsp-lpass-ports.h
> @@ -11,6 +11,7 @@ struct q6dsp_audio_port_dai_driver_config {
>   	const struct snd_soc_dai_ops *q6i2s_ops;
>   	const struct snd_soc_dai_ops *q6tdm_ops;
>   	const struct snd_soc_dai_ops *q6dma_ops;
> +	const struct snd_soc_dai_ops *q6usb_ops;
>   };
>   
>   struct snd_soc_dai_driver *q6dsp_audio_ports_set_config(struct device *dev,
> diff --git a/sound/soc/qcom/qdsp6/q6routing.c b/sound/soc/qcom/qdsp6/q6routing.c
> index 928fd23e2c27..dc2357b4b2c7 100644
> --- a/sound/soc/qcom/qdsp6/q6routing.c
> +++ b/sound/soc/qcom/qdsp6/q6routing.c
> @@ -514,6 +514,9 @@ static int msm_routing_put_audio_mixer(struct snd_kcontrol *kcontrol,
>   	return 1;
>   }
>   
> +static const struct snd_kcontrol_new usb_mixer_controls[] = {
> +	Q6ROUTING_RX_MIXERS(USB_RX) };
> +
>   static const struct snd_kcontrol_new hdmi_mixer_controls[] = {
>   	Q6ROUTING_RX_MIXERS(HDMI_RX) };
>   
> @@ -949,6 +952,10 @@ static const struct snd_soc_dapm_widget msm_qdsp6_widgets[] = {
>   	SND_SOC_DAPM_MIXER("MultiMedia8 Mixer", SND_SOC_NOPM, 0, 0,
>   		mmul8_mixer_controls, ARRAY_SIZE(mmul8_mixer_controls)),
>   
> +	SND_SOC_DAPM_MIXER("USB Mixer", SND_SOC_NOPM, 0, 0,
> +			   usb_mixer_controls,
> +			   ARRAY_SIZE(usb_mixer_controls)),
> +
>   };
>   
>   static const struct snd_soc_dapm_route intercon[] = {
> @@ -1042,6 +1049,8 @@ static const struct snd_soc_dapm_route intercon[] = {
>   	{"MM_UL6", NULL, "MultiMedia6 Mixer"},
>   	{"MM_UL7", NULL, "MultiMedia7 Mixer"},
>   	{"MM_UL8", NULL, "MultiMedia8 Mixer"},
> +
> +	Q6ROUTING_RX_DAPM_ROUTE("USB Mixer", "USB_RX"),
>   };
>   
>   static int routing_hw_params(struct snd_soc_component *component,
Oliver Neukum March 9, 2023, 10:34 a.m. UTC | #8
On 09.03.23 00:57, Wesley Cheng wrote:

> @@ -1865,8 +1889,15 @@ void xhci_mem_cleanup(struct xhci_hcd *xhci)
>   
>   	cancel_delayed_work_sync(&xhci->cmd_timer);
>   
> -	xhci_free_interrupter(xhci, xhci->interrupter);
> -	xhci->interrupter = NULL;
> +	for (i = 1; i < xhci->max_interrupters; i++) {
> +		if (xhci->interrupters[i])
> +			xhci_remove_secondary_interrupter(xhci_to_hcd(xhci),
> +							  xhci->interrupters[i]);
> +	}
> +
> +	/* free the primary interrupter, interrupter number 0 */
> +	xhci_free_interrupter(xhci, xhci->interrupters[0]);
> +	xhci->interrupters[0] = NULL;
>   	xhci_dbg_trace(xhci, trace_xhci_dbg_init, "Freed primary event ring");

Any reason you are not just counting down to zero?

> +	if (idx > 0) {
> +		ir = xhci_alloc_interrupter(xhci, idx, GFP_KERNEL);
> +		if (!ir) {
> +			spin_unlock_irqrestore(&xhci->lock, flags);

Why use _irqrestore?

	Regards
		Oliver
Takashi Iwai March 9, 2023, 10:51 a.m. UTC | #9
On Thu, 09 Mar 2023 00:57:24 +0100,
Wesley Cheng wrote:
> +struct xhci_interrupter *
> +xhci_create_secondary_interrupter(struct usb_hcd *hcd, int intr_num)
> +{
> +	struct xhci_hcd *xhci = hcd_to_xhci(hcd);
> +	struct xhci_interrupter *ir;
> +	unsigned int i;
> +	unsigned int idx = 0;
> +	unsigned long flags;
> +
> +	if (!xhci->interrupters || intr_num > xhci->max_interrupters)
> +		return NULL;
> +
> +	spin_lock_irqsave(&xhci->lock, flags);
....
> +	if (idx > 0) {
> +		ir = xhci_alloc_interrupter(xhci, idx, GFP_KERNEL);
> +		if (!ir) {
> +			spin_unlock_irqrestore(&xhci->lock, flags);
> +			return NULL;
> +		}
> +		ir->intr_num = idx;
> +		xhci->interrupters[idx] = ir;
> +		spin_unlock_irqrestore(&xhci->lock, flags);

You can't use GFP_KERNEL allocation inside the spinlock.


Takashi
Oliver Neukum March 9, 2023, 11:16 a.m. UTC | #10
On 09.03.23 00:57, Wesley Cheng wrote:
> Allow for different platforms to be notified on USB SND connect/disconnect
> seqeunces.  This allows for platform USB SND modules to properly initialize
> and populate internal structures with references to the USB SND chip
> device.
> 
> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
> ---
>   sound/usb/card.c | 36 ++++++++++++++++++++++++++++++++++++
>   sound/usb/card.h | 20 ++++++++++++++++++++
>   2 files changed, 56 insertions(+)
> 
> diff --git a/sound/usb/card.c b/sound/usb/card.c
> index 26268ffb8274..9bcbaa0c0a55 100644
> --- a/sound/usb/card.c
> +++ b/sound/usb/card.c
> @@ -117,6 +117,30 @@ MODULE_PARM_DESC(skip_validation, "Skip unit descriptor validation (default: no)
>   static DEFINE_MUTEX(register_mutex);
>   static struct snd_usb_audio *usb_chip[SNDRV_CARDS];
>   static struct usb_driver usb_audio_driver;
> +static struct snd_usb_platform_ops *platform_ops;
> +
> +int snd_usb_register_platform_ops(struct snd_usb_platform_ops *ops)
> +{
> +	if (platform_ops)
> +		return -EEXIST;
> +
> +	mutex_lock(&register_mutex);
> +	platform_ops = ops;
> +	mutex_unlock(&register_mutex);

This looks _highly_ suspicious.
Why does the assignment need a lock, but the check does not?

	Regards
		Oliver
Oliver Neukum March 9, 2023, 11:32 a.m. UTC | #11
On 09.03.23 00:57, Wesley Cheng wrote:
  
> +/*
> + * 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.
> + */
> +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)

Really check this every time?

	Regards
		Oliver
Takashi Iwai March 9, 2023, 2:10 p.m. UTC | #12
On Thu, 09 Mar 2023 07:44:13 +0100,
Greg KH wrote:
> 
> On Wed, Mar 08, 2023 at 03:57:32PM -0800, Wesley Cheng wrote:
> > Allow for different platforms to be notified on USB SND connect/disconnect
> > seqeunces.  This allows for platform USB SND modules to properly initialize
> > and populate internal structures with references to the USB SND chip
> > device.
> > 
> > Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
> > ---
> >  sound/usb/card.c | 36 ++++++++++++++++++++++++++++++++++++
> >  sound/usb/card.h | 20 ++++++++++++++++++++
> >  2 files changed, 56 insertions(+)
> > 
> > diff --git a/sound/usb/card.c b/sound/usb/card.c
> > index 26268ffb8274..9bcbaa0c0a55 100644
> > --- a/sound/usb/card.c
> > +++ b/sound/usb/card.c
> > @@ -117,6 +117,30 @@ MODULE_PARM_DESC(skip_validation, "Skip unit descriptor validation (default: no)
> >  static DEFINE_MUTEX(register_mutex);
> >  static struct snd_usb_audio *usb_chip[SNDRV_CARDS];
> >  static struct usb_driver usb_audio_driver;
> > +static struct snd_usb_platform_ops *platform_ops;
> 
> As I've said before, you can not just have one of these.  They need to
> be per-bus structure.  Or per-device, something dynamic, not static like
> this.

Basically the change for USB-audio driver is a kind of add-on/plugin;
that is, it allows the platform_ops to override some operations of the
standard USB-audio driver for supporting the offload operations.

So, in that sense, this add-on itself is neither per-bus nor
per-device, and it's fine as a single pointer for now, IMO, since this
is the only known use case and it'd simplify the code.  If we'll have
more similar requirements in future, we may extend the implementation
and the API to allow the registration of multiple addons, too.

Though, there are a few obvious coding issues in the current patches,
and they have to be addressed, sure :)


thanks,

Takashi
Pierre-Louis Bossart March 9, 2023, 5:13 p.m. UTC | #13
On 3/8/23 17:57, Wesley Cheng wrote:
> Changes in v3:
> - Changed prefix from RFC to PATCH
> - Rebased entire series to usb-next
> - Updated copyright years

You may want to move the per-version changes after the description of
this patchset.

> 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.


---> start of the 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

clarify what 'backend' means. I would guess you are referring to the
ASoC DPCM concept of Back-End, which typically exposes an audio
interface controlled by a DSP?

If yes, the description should be

"Create a Q6DSP ASoC DPCM BackEnd for USB audio playback/record".

>   3. Introduce XHCI interrupter support
>   4. Create vendor ops for the USB SND driver

Add an introduction as to why this would be needed? which 'vendor' are
we talking about, is this on the SOC side or the USB device side?

> 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.

port == backend?

Using different words for the same concept is a sure way to lose the
reviewers, and not describing different concepts isn't much better.

> Create a USB backend for Q6DSP:
> q6usb: Basic backend driver that will be responsible for maintaining the

What does this mean? Is this a module that registers a set of ASoC DAIs?

It's not clear to me what a 'backend driver' means either in a USB or
ASoC context.

> 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.

If it's an ASoC backend, there is no PCM open call. You're probably
referring to the hw_params, not the open/startup anyways.

> 
> 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

so how does this 'qc_audio_offload' interface with 'q6usb' described
above? how are the roles different or complementary?

> 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...

I already voiced my concerns about exposing two cards, each with their
own set of volume controls with the same device. It would be much better
to have an additional offloaded PCM device for card0...

But if the consensus is to have two cards, it's still not clear how the
routing would be selected. In the case where there are two USB audio
devices attached, the offloaded path would only support one of the two.
How would userspace know which of the two is selected?

And how would userspace know the difference anyways between two physical
devices attached to the platform with no offload, and one physical
device with one additional offload path? The names you selected can't be
used to identify that card1 is the optimized version of card0.

Before we review low-level kernel plumbing, it would be good to give a
better overview of how userspace applications are supposed to interact
with the cards and identify the offloaded path. Testing with
tinyplay/tinymix is fine, but that's a developer-level or CI unit test.
we've got to see the broader picture of how a sound server would use
this USB offload capability.
Pierre-Louis Bossart March 9, 2023, 5:54 p.m. UTC | #14
> +config QC_USB_AUDIO_OFFLOAD
> +	tristate "Qualcomm Audio Offload driver"

"Qualcomm USB Audio Offload driver"

> +	select SND_PCM

depends on SND_USB_AUDIO ?

> +	help
> +	  Say Y here to enable the Qualcomm USB audio offloading feature
> +
> +	  This module sets up the required QMI stream enable/disable
> +	  responses to requests generated by the audio DSP.  It passes the
> +	  USB transfer resource references, so that the audio DSP can issue
> +	  USB transfers to the host controller.
> +
> +	  To compile this driver as a module, choose M here: the module
> +	  will be called qc-audio-offload.

> +#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-intr.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 "../midi.h"
> +#include "../mixer.h"
> +#include "../proc.h"
> +#include "../quirks.h"
> +#include "../endpoint.h"
> +#include "../helper.h"
> +#include "../pcm.h"
> +#include "../format.h"
> +#include "../power.h"
> +#include "../stream.h"
> +#include "../media.h"

this looks weird, are all these needed?

> +
> +#define SND_PCM_CARD_NUM_MASK 0xffff0000
> +#define SND_PCM_DEV_NUM_MASK 0xff00
> +#define SND_PCM_STREAM_DIRECTION 0xff

The prefix looks wrong, or it duplicates SND_PCM stuff?

> +
> +/* 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_interrupter *ir;
> +	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 card_num;
> +	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;
> +};

This looks too detailed, isnt' that a duplication of other structures
that exist in the regular USB audio part?

There's nothing that looks QCOM-specific anyways.

> +
> +static struct uaudio_dev uadev[SNDRV_CARDS];
> +static struct uaudio_qmi_dev *uaudio_qdev;
> +static struct uaudio_qmi_svc *uaudio_svc;
> +static DEFINE_MUTEX(qdev_mutex);
> +
> +struct uaudio_qmi_svc {
> +	struct qmi_handle *uaudio_svc_hdl;
> +	struct work_struct qmi_disconnect_work;
> +	struct workqueue_struct *uaudio_wq;
> +	struct sockaddr_qrtr client_sq;
> +	bool client_connected;
> +};
> +
> +enum mem_type {
> +	MEM_EVENT_RING,
> +	MEM_XFER_RING,
> +	MEM_XFER_BUF,
> +};

prefixes better than 'MEM'?

> +
> +/* Supported audio formats */
> +enum usb_qmi_audio_format {
> +	USB_QMI_PCM_FORMAT_S8 = 0,
> +	USB_QMI_PCM_FORMAT_U8,
> +	USB_QMI_PCM_FORMAT_S16_LE,
> +	USB_QMI_PCM_FORMAT_S16_BE,
> +	USB_QMI_PCM_FORMAT_U16_LE,
> +	USB_QMI_PCM_FORMAT_U16_BE,
> +	USB_QMI_PCM_FORMAT_S24_LE,
> +	USB_QMI_PCM_FORMAT_S24_BE,
> +	USB_QMI_PCM_FORMAT_U24_LE,
> +	USB_QMI_PCM_FORMAT_U24_BE,
> +	USB_QMI_PCM_FORMAT_S24_3LE,
> +	USB_QMI_PCM_FORMAT_S24_3BE,
> +	USB_QMI_PCM_FORMAT_U24_3LE,
> +	USB_QMI_PCM_FORMAT_U24_3BE,
> +	USB_QMI_PCM_FORMAT_S32_LE,
> +	USB_QMI_PCM_FORMAT_S32_BE,
> +	USB_QMI_PCM_FORMAT_U32_LE,
> +	USB_QMI_PCM_FORMAT_U32_BE,
> +};
> +
> +static enum usb_audio_device_speed_enum_v01
> +get_speed_info(enum usb_device_speed udev_speed)
> +{
> +	switch (udev_speed) {
> +	case USB_SPEED_LOW:
> +		return USB_AUDIO_DEVICE_SPEED_LOW_V01;
> +	case USB_SPEED_FULL:
> +		return USB_AUDIO_DEVICE_SPEED_FULL_V01;
> +	case USB_SPEED_HIGH:
> +		return USB_AUDIO_DEVICE_SPEED_HIGH_V01;
> +	case USB_SPEED_SUPER:
> +		return USB_AUDIO_DEVICE_SPEED_SUPER_V01;
> +	case USB_SPEED_SUPER_PLUS:
> +		return USB_AUDIO_DEVICE_SPEED_SUPER_PLUS_V01;
> +	default:
> +		return USB_AUDIO_DEVICE_SPEED_INVALID_V01;
> +	}
> +}

this doesn't look qcom-specific, why is this here?

> +
> +static struct snd_usb_substream *find_substream(unsigned int card_num,
> +	unsigned int pcm_idx, unsigned int direction)
> +{
> +	struct snd_usb_stream *as;
> +	struct snd_usb_substream *subs = NULL;
> +	struct snd_usb_audio *chip;
> +
> +	chip = uadev[card_num].chip;
> +	if (!chip || atomic_read(&chip->shutdown))
> +		goto done;
> +
> +	if (pcm_idx >= chip->pcm_devs)
> +		goto done;
> +
> +	if (direction > SNDRV_PCM_STREAM_CAPTURE)
> +		goto done;
> +
> +	list_for_each_entry(as, &chip->pcm_list, list) {
> +		if (as->pcm_index == pcm_idx) {
> +			subs = &as->substream[direction];
> +			goto done;
> +		}
> +	}
> +
> +done:
> +	return subs;
> +}
> +
> +static int info_idx_from_ifnum(int card_num, int intf_num, bool enable)
> +{
> +	int i;
> +
> +	/*
> +	 * default index 0 is used when info is allocated upon
> +	 * first enable audio stream req for a pcm device
> +	 */
> +	if (enable && !uadev[card_num].info)
> +		return 0;
> +
> +	for (i = 0; i < uadev[card_num].num_intf; i++) {
> +		if (enable && !uadev[card_num].info[i].in_use)
> +			return i;
> +		else if (!enable &&
> +				uadev[card_num].info[i].intf_num == intf_num)
> +			return i;
> +	}
> +
> +	return -EINVAL;
> +}
> +
> +static int get_data_interval_from_si(struct snd_usb_substream *subs,
> +	u32 service_interval)
> +{
> +	unsigned int bus_intval, bus_intval_mult, binterval;
> +
> +	if (subs->dev->speed >= USB_SPEED_HIGH)
> +		bus_intval = BUS_INTERVAL_HIGHSPEED_AND_ABOVE;
> +	else
> +		bus_intval = BUS_INTERVAL_FULL_SPEED;
> +
> +	if (service_interval % bus_intval)
> +		return -EINVAL;
> +
> +	bus_intval_mult = service_interval / bus_intval;
> +	binterval = ffs(bus_intval_mult);
> +	if (!binterval || binterval > MAX_BINTERVAL_ISOC_EP)
> +		return -EINVAL;
> +
> +	/* check if another bit is set then bail out */
> +	bus_intval_mult = bus_intval_mult >> binterval;
> +	if (bus_intval_mult)
> +		return -EINVAL;
> +
> +	return (binterval - 1);
> +}

this doesn't look qcom-specific either, is this a set of helpers that
need to be moved somewhere else?


> +/**
> + * 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;
> +
> +	if (subs->data_endpoint || subs->sync_endpoint) {
> +		close_endpoints(chip, subs);
> +
> +		mutex_lock(&chip->mutex);
> +		subs->cur_audiofmt = NULL;
> +		mutex_unlock(&chip->mutex);
> +	}
> +
> +	snd_usb_autosuspend(chip);
> +}

also not qcom-specific?

> +/* kref release callback when all streams are disabled */

what does "all streams disabled" mean, and when does this happen?

> +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);
> +}


> +static int __init qc_usb_audio_offload_init(void)
> +{
> +	struct uaudio_qmi_svc *svc;
> +	int ret;
> +
> +	ret = snd_usb_register_platform_ops(&offload_ops);
> +	if (ret < 0)
> +		return ret;

so what happens if snd_usb is blacklisted or takes time to probe?

This seems to assume a timing dependency when USB is initialized/probed
first?

> +
> +	svc = kzalloc(sizeof(struct uaudio_qmi_svc), GFP_KERNEL);
> +	if (!svc) {
> +		ret = -ENOMEM;
> +		goto unreg_ops;
> +	}
> +
> +	svc->uaudio_wq = create_singlethread_workqueue("uaudio_svc");
> +	if (!svc->uaudio_wq) {
> +		ret = -ENOMEM;
> +		goto free_svc;
> +	}
> +
> +	svc->uaudio_svc_hdl = kzalloc(sizeof(struct qmi_handle), GFP_KERNEL);
> +	if (!svc->uaudio_svc_hdl) {
> +		ret = -ENOMEM;
> +		goto free_wq;
> +	}
> +
> +	ret = qmi_handle_init(svc->uaudio_svc_hdl,
> +				QMI_UAUDIO_STREAM_REQ_MSG_V01_MAX_MSG_LEN,
> +				&uaudio_svc_ops_options,
> +				&uaudio_stream_req_handlers);
> +	ret = qmi_add_server(svc->uaudio_svc_hdl, UAUDIO_STREAM_SERVICE_ID_V01,
> +					UAUDIO_STREAM_SERVICE_VERS_V01, 0);
> +
> +	INIT_WORK(&svc->qmi_disconnect_work, qmi_disconnect_work);
> +	uaudio_svc = svc;
> +
> +	return 0;
> +
> +free_wq:
> +	destroy_workqueue(svc->uaudio_wq);
> +free_svc:
> +	kfree(svc);
> +unreg_ops:
> +	snd_usb_unregister_platform_ops();
> +
> +	return ret;
> +}
> +
> +static void __exit qc_usb_audio_offload_exit(void)
> +{
> +	struct uaudio_qmi_svc *svc = uaudio_svc;
> +
> +	qmi_handle_release(svc->uaudio_svc_hdl);
> +	flush_workqueue(svc->uaudio_wq);
> +	destroy_workqueue(svc->uaudio_wq);
> +	kfree(svc);
> +	uaudio_svc = NULL;
> +	snd_usb_unregister_platform_ops();
> +}
> +
> +module_init(qc_usb_audio_offload_init);
> +module_exit(qc_usb_audio_offload_exit);

what causes this module to be loaded?

> +
> +MODULE_DESCRIPTION("QC USB Audio Offloading");
> +MODULE_LICENSE("GPL");
> diff --git a/sound/usb/qcom/usb_audio_qmi_v01.c b/sound/usb/qcom/usb_audio_qmi_v01.c
> new file mode 100644
> index 000000000000..1a0f2f579786
> --- /dev/null
> +++ b/sound/usb/qcom/usb_audio_qmi_v01.c
> @@ -0,0 +1,892 @@
> +// SPDX-License-Identifier: GPL-2.0
> +/*
> + * Copyright (c) 2022-2023 Qualcomm Innovation Center, Inc. All rights reserved.
> + */
> +
> +#include <linux/soc/qcom/qmi.h>
> +
> +#include "usb_audio_qmi_v01.h"
> +
> +static struct qmi_elem_info mem_info_v01_ei[] = {
> +	{
> +		.data_type	= QMI_UNSIGNED_8_BYTE,
> +		.elem_len	= 1,
> +		.elem_size	= sizeof(u64),
> +		.array_type	= NO_ARRAY,
> +		.tlv_type	= 0,
> +		.offset		= offsetof(struct mem_info_v01, va),
> +	},

maybe move these arrays to a different patch that we don't need to
scroll-through or review...

> +	{
> +		.data_type	= QMI_UNSIGNED_8_BYTE,
> +		.elem_len	= 1,
> +		.elem_size	= sizeof(u64),
> +		.array_type	= NO_ARRAY,
> +		.tlv_type	= 0,
> +		.offset		= offsetof(struct mem_info_v01, pa),
> +	},
> +	{
> +		.data_type	= QMI_UNSIGNED_4_BYTE,
> +		.elem_len	= 1,
> +		.elem_size	= sizeof(u32),
> +		.array_type	= NO_ARRAY,
> +		.tlv_type	= 0,
> +		.offset		= offsetof(struct mem_info_v01, size),
> +	},
> +	{
> +		.data_type	= QMI_EOTI,
> +		.array_type	= NO_ARRAY,
> +		.tlv_type	= QMI_COMMON_TLV_TYPE,
> +	},
> +};
Wesley Cheng March 9, 2023, 7:51 p.m. UTC | #15
Hi Greg,

On 3/8/2023 10:38 PM, Greg KH wrote:
> On Wed, Mar 08, 2023 at 03:57:25PM -0800, Wesley Cheng wrote:
>> Some use cases, such as USB audio offloading, will allow for a DSP to take
>> over issuing USB transfers to the host controller.  In order for the DSP to
>> submit transfers for a particular endpoint, and to handle its events, the
>> client driver will need to query for some parameters allocated by XHCI.
>>
>> - XHCI secondary interrupter event ring address
>> - XHCI transfer ring address (for a particular EP)
>> - Stop endpoint command API
>>
>> Once the resources are handed off to the DSP, the offload begins, and the
>> main processor can enter idle.  When stopped, since there are no URBs
>> submitted from the main processor, the client will just issue a stop
>> endpoint command to halt any pending transfers.
>>
>> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
>> ---
>>   drivers/usb/host/xhci.c       | 130 ++++++++++++++++++++++++++++++++++
>>   include/linux/usb/xhci-intr.h |   8 +++
>>   2 files changed, 138 insertions(+)
> 
> Please use checkpatch.pl on your patches before sending them out :(
> 
> Some other minor comments:
> 

Thanks for taking the time to review these!

Hmm, I did run checkpatch, and cleaned up the warnings it did give. 
However, I think something changed with regards to the tools on my host 
env.  Will address those and make sure it runs properly next time.

Will fix the minor changes you mentioned, and focus on the general 
questions you had.

>> diff --git a/include/linux/usb/xhci-intr.h b/include/linux/usb/xhci-intr.h
>> index 738b0f0481a6..d42cc9a1e698 100644
>> --- a/include/linux/usb/xhci-intr.h
>> +++ b/include/linux/usb/xhci-intr.h
>> @@ -80,7 +80,15 @@ struct xhci_interrupter {
>>   	u64	s3_erst_dequeue;
>>   };
>>   
>> +/* Secondary interrupter */
>>   struct xhci_interrupter *
>>   xhci_create_secondary_interrupter(struct usb_hcd *hcd, int intr_num);
>>   void xhci_remove_secondary_interrupter(struct usb_hcd *hcd, struct xhci_interrupter *ir);
>> +
>> +/* Offload */
>> +int xhci_stop_endpoint(struct usb_device *udev,
>> +			struct usb_host_endpoint *ep);
>> +phys_addr_t xhci_get_xfer_resource(struct usb_device *udev,
>> +					struct usb_host_endpoint *ep, dma_addr_t *dma);
>> +phys_addr_t xhci_get_ir_resource(struct usb_device *udev, struct xhci_interrupter *ir);
> 
> Why are these functions unique to offload?
> 

Wanted to separate the set of APIs used for creating a secondary 
interrupter versus offload related ones.  In general, the APIs under the 
secondary interrupter portion can be used for other things other than 
offloading.  As Mathias pointed out, they had a use case where they 
wanted to utilize the secondary interrupter to actually route and 
receive interrupts on the secondary ring, not to suppress them. (which 
is opposite of what the offload concept is doing)

Now for the offload section, those are specific to that feature, because 
we need to pass certain memory information about what was allocated by 
XHCI to the entity that we are offloading the IO operations to.  Hence, 
why they are APIs which fetch the transfer ring and event ring 
addresses.  In addition, we do have the stop EP as well, since in the 
offload case, since the main processor doesn't submit TDs (transfer 
descriptors) then it isn't aware there are transfers in progress.  When 
the endpoint is released, then the offload driver needs to be the one 
that halts the EP.

As you mentioned, I will add documentation to better describe these.

Thanks
Wesley Cheng
Wesley Cheng March 9, 2023, 9:10 p.m. UTC | #16
Hi Pierre,

On 3/9/2023 9:13 AM, Pierre-Louis Bossart wrote:
> 
> 
> On 3/8/23 17:57, Wesley Cheng wrote:
>> Changes in v3:
>> - Changed prefix from RFC to PATCH
>> - Rebased entire series to usb-next
>> - Updated copyright years
> 
> You may want to move the per-version changes after the description of
> this patchset.
> 

Thanks for reading through this :).

Sure, will do that going forward.

>> 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.
> 
> 
> ---> start of the 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
> 
> clarify what 'backend' means. I would guess you are referring to the
> ASoC DPCM concept of Back-End, which typically exposes an audio
> interface controlled by a DSP?
> 
> If yes, the description should be
> 
> "Create a Q6DSP ASoC DPCM BackEnd for USB audio playback/record".
> 

You're correct.  "backend" was referring to a Q6DSP ASoC DPCM backend.

>>    3. Introduce XHCI interrupter support
>>    4. Create vendor ops for the USB SND driver
> 
> Add an introduction as to why this would be needed? which 'vendor' are
> we talking about, is this on the SOC side or the USB device side?
> 

This would be referring to the SoC side.  For example, QCOM can 
potentially have a different implementation of offloading USB SND to the 
audio DSP versus another OEM.  This is to allow those other entities to 
be able to define their own offload methodology.

For the most part, the common operations across all offloading 
implementations have so far is being able to handle USB SND 
connect/disconnect events.

>> 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.
> 
> port == backend?
> 
> Using different words for the same concept is a sure way to lose the
> reviewers, and not describing different concepts isn't much better.
> 

Yes, port is corresponding to the

>> Create a USB backend for Q6DSP:
>> q6usb: Basic backend driver that will be responsible for maintaining the
> 
> What does this mean? Is this a module that registers a set of ASoC DAIs?
> 
> It's not clear to me what a 'backend driver' means either in a USB or
> ASoC context.
> 

Will fix this up next time.  It refers to a Q6DSP DPCM ASoC backend, as 
you mentioned above.

>> 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.
> 
> If it's an ASoC backend, there is no PCM open call. You're probably
> referring to the hw_params, not the open/startup anyways.
> 

Correct.  Will fix this.

>>
>> 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
> 
> so how does this 'qc_audio_offload' interface with 'q6usb' described
> above? how are the roles different or complementary?
> 
So in general you can think that the qc_audio_offload is a complement to 
the USB SND USB class driver, while q6usb is to ASoC.  Since the ASoC 
framework doesn't have any communication with USB SND, the ASoC DPCM USB 
backend (q6usb) will have to be the entity that maintains what is going 
on in USB SND.  That way, sessions initiated through the ASoC managed 
sound card can evaluate what is available based on information reported 
by q6usb.

qc_audio_offload and q6usb will have some interaction between each 
other.  The majority of communication between qc_audio_offload and q6usb 
is reporting the device connection events.

>> 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...
> 
> I already voiced my concerns about exposing two cards, each with their
> own set of volume controls with the same device. It would be much better
> to have an additional offloaded PCM device for card0...
> 
> But if the consensus is to have two cards, it's still not clear how the
> routing would be selected. In the case where there are two USB audio
> devices attached, the offloaded path would only support one of the two.
> How would userspace know which of the two is selected?
> 

With patch#24:
https://lore.kernel.org/linux-usb/20230308235751.495-25-quic_wcheng@quicinc.com/T/#u

Now, userspace can at least choose which device it wants to offload. 
Part of doing that would mean userspace knows what USB SND card devices 
are available, so it is aware of which devices are shared (between the 
offload and USB SND path)

> And how would userspace know the difference anyways between two physical
> devices attached to the platform with no offload, and one physical
> device with one additional offload path? The names you selected can't be
> used to identify that card1 is the optimized version of card0.
> 

Is userspace currently able to differentiate between cards that are 
created by USB SND versus ASoC?  How complex can the userspace card 
discovery be?  Can it query kcontrols at this point in time?  If so, 
maybe we can change the names of the newly added ones to reflect that it 
is an offload device?

SND kcontrol names are currently:
Q6USB offload status
Q6USB offload SND device select

> Before we review low-level kernel plumbing, it would be good to give a
> better overview of how userspace applications are supposed to interact
> with the cards and identify the offloaded path. Testing with
> tinyplay/tinymix is fine, but that's a developer-level or CI unit test.
> we've got to see the broader picture of how a sound server would use
> this USB offload capability.

Sure, I think that is fine.  I was hoping that at least adding some of 
the new kcontrols would help userspace make use of this path in general, 
but we can add more information if required.

Thanks
Wesley Cheng
Pierre-Louis Bossart March 10, 2023, 12:37 a.m. UTC | #17
>>> 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
>>
>> so how does this 'qc_audio_offload' interface with 'q6usb' described
>> above? how are the roles different or complementary?
>>
> So in general you can think that the qc_audio_offload is a complement to
> the USB SND USB class driver, while q6usb is to ASoC.  Since the ASoC

Humm, that is far from clear. I don't get how a something that interacts
with the USB class driver can also be in charge of the audio DSP memory
management.

> framework doesn't have any communication with USB SND, the ASoC DPCM USB
> backend (q6usb) will have to be the entity that maintains what is going
> on in USB SND.  That way, sessions initiated through the ASoC managed
> sound card can evaluate what is available based on information reported
> by q6usb.
> 
> qc_audio_offload and q6usb will have some interaction between each
> other.  The majority of communication between qc_audio_offload and q6usb
> is reporting the device connection events.

It's already complicated to figure out how the DSP and USB class driver
might interact and probe/timing dependencies, but with two additional
drivers in the mix it's really hard to understand.

Maybe ascii-art would help describe the concepts and types of
information exchanged. Maintaining a consistent state across multiple
drivers is not an easy task.

> 
>>> 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...
>>
>> I already voiced my concerns about exposing two cards, each with their
>> own set of volume controls with the same device. It would be much better
>> to have an additional offloaded PCM device for card0...
>>
>> But if the consensus is to have two cards, it's still not clear how the
>> routing would be selected. In the case where there are two USB audio
>> devices attached, the offloaded path would only support one of the two.
>> How would userspace know which of the two is selected?
>>
> 
> With patch#24:
> https://lore.kernel.org/linux-usb/20230308235751.495-25-quic_wcheng@quicinc.com/T/#u
> 
> Now, userspace can at least choose which device it wants to offload.
> Part of doing that would mean userspace knows what USB SND card devices
> are available, so it is aware of which devices are shared (between the
> offload and USB SND path)
> 
>> And how would userspace know the difference anyways between two physical
>> devices attached to the platform with no offload, and one physical
>> device with one additional offload path? The names you selected can't be
>> used to identify that card1 is the optimized version of card0.
>>
> 
> Is userspace currently able to differentiate between cards that are
> created by USB SND versus ASoC?  How complex can the userspace card
> discovery be?  Can it query kcontrols at this point in time?  If so,
> maybe we can change the names of the newly added ones to reflect that it
> is an offload device?
> 
> SND kcontrol names are currently:
> Q6USB offload status
> Q6USB offload SND device select

I must admit I've never seen kcontrols being used to identify what the
card is, and in this case it's a pretend-card that's just an improved
version of another. It might be easier to use something else, such as
the component strings.
> 
>> Before we review low-level kernel plumbing, it would be good to give a
>> better overview of how userspace applications are supposed to interact
>> with the cards and identify the offloaded path. Testing with
>> tinyplay/tinymix is fine, but that's a developer-level or CI unit test.
>> we've got to see the broader picture of how a sound server would use
>> this USB offload capability.
> 
> Sure, I think that is fine.  I was hoping that at least adding some of
> the new kcontrols would help userspace make use of this path in general,
> but we can add more information if required.

Can I ask if this solution has been used with a complete userspace stack
already? I could see how this might be used with a relatively fixed
Android HAL, where the platform and routing are relatively controlled. I
don't see how a more generic audio server would deal with the discovery
and routing.
Krzysztof Kozlowski March 10, 2023, 8:50 a.m. UTC | #18
On 09/03/2023 00:57, Wesley Cheng wrote:
> Add a new definition for specifying how many XHCI secondary interrupters
> can be allocated.  XHCI in general can potentially support up to 1024
> interrupters, which some uses may want to limit depending on how many
> users utilize the interrupters.
> 
> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
> ---


Acked-by: Krzysztof Kozlowski <krzysztof.kozlowski@linaro.org>

Best regards,
Krzysztof
Claudiu Beznea March 10, 2023, 12:17 p.m. UTC | #19
On 09.03.2023 01:57, Wesley Cheng wrote:
> EXTERNAL EMAIL: Do not click links or open attachments unless you know the content is safe
> 
> Some use cases, such as USB audio offloading, will allow for a DSP to take
> over issuing USB transfers to the host controller.  In order for the DSP to
> submit transfers for a particular endpoint, and to handle its events, the
> client driver will need to query for some parameters allocated by XHCI.
> 
> - XHCI secondary interrupter event ring address
> - XHCI transfer ring address (for a particular EP)
> - Stop endpoint command API
> 
> Once the resources are handed off to the DSP, the offload begins, and the
> main processor can enter idle.  When stopped, since there are no URBs
> submitted from the main processor, the client will just issue a stop
> endpoint command to halt any pending transfers.
> 
> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
> ---
>  drivers/usb/host/xhci.c       | 130 ++++++++++++++++++++++++++++++++++
>  include/linux/usb/xhci-intr.h |   8 +++
>  2 files changed, 138 insertions(+)
> 
> diff --git a/drivers/usb/host/xhci.c b/drivers/usb/host/xhci.c
> index 88435b9cd66e..5c6b3d8f834c 100644
> --- a/drivers/usb/host/xhci.c
> +++ b/drivers/usb/host/xhci.c
> @@ -1603,6 +1603,136 @@ static int xhci_check_args(struct usb_hcd *hcd, struct usb_device *udev,
>         return 1;
>  }
> 
> +int xhci_stop_endpoint(struct usb_device *udev,
> +                       struct usb_host_endpoint *ep)
> +{
> +       struct usb_hcd *hcd = bus_to_hcd(udev->bus);
> +       struct xhci_hcd *xhci = hcd_to_xhci(hcd);
> +       unsigned int ep_index;
> +       struct xhci_virt_device *virt_dev;
> +       struct xhci_command *cmd;
> +       unsigned long flags;
> +       int ret = 0;

No need to initialize it.

> +
> +       ret = xhci_check_args(hcd, udev, ep, 1, true, __func__);
> +       if (ret <= 0)
> +               return ret;
> +
> +       cmd = xhci_alloc_command(xhci, true, GFP_NOIO);
> +       if (!cmd)
> +               return -ENOMEM;
> +
> +       spin_lock_irqsave(&xhci->lock, flags);
> +       virt_dev = xhci->devs[udev->slot_id];
> +       if (!virt_dev) {
> +               ret = -ENODEV;
> +               goto err;
> +       }
> +
> +       ep_index = xhci_get_endpoint_index(&ep->desc);
> +       if (virt_dev->eps[ep_index].ring &&
> +                       virt_dev->eps[ep_index].ring->dequeue) {
> +               ret = xhci_queue_stop_endpoint(xhci, cmd, udev->slot_id,
> +                               ep_index, 0);
> +               if (ret)
> +                       goto err;
> +
> +               xhci_ring_cmd_db(xhci);
> +               spin_unlock_irqrestore(&xhci->lock, flags);
> +
> +               /* Wait for stop endpoint command to finish */
> +               wait_for_completion(cmd->completion);
> +
> +               if (cmd->status == COMP_COMMAND_ABORTED ||
> +                               cmd->status == COMP_STOPPED) {

                      ^ usually here go 2nd condition

> +                       xhci_warn(xhci,
> +                               "stop endpoint command timeout for ep%d%s\n",
> +                               usb_endpoint_num(&ep->desc),
> +                               usb_endpoint_dir_in(&ep->desc) ? "in" : "out");
> +                       ret = -ETIME;
> +                               }

} should be aligned with if

[ ... ]
Mathias Nyman March 10, 2023, 3:07 p.m. UTC | #20
On 9.3.2023 1.57, Wesley Cheng wrote:
> From: Mathias Nyman <mathias.nyman@linux.intel.com>
> 
> Introduce xHCI APIs to allow for clients to allocate and free
> interrupters.  This allocates an array of interrupters, which is based on
> the max_interrupters parameter.  The primary interrupter is set as the
> first entry in the array, and secondary interrupters following after.
> 

I'm thinking about changing this offloading xHCI API
xhci should be aware and keep track of which devices and endpoints that
are offloaded to avoid device getting offloaded twice, avoid xhci driver
from queuing anything itself for these, and act properly if the offloaded
device or entire host is removed.

So first thing audio side would need to do do is register/create an
offload entry for the device using the API:

struct xhci_sideband *xhci_sideband_register(struct usb_device *udev)

(xHCI specs calls offload sideband)
Then endpoints and interrupters can be added and removed from this
offload entry

I have some early thoughts written as non-compiling code in:

git://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git feature_interrupters
https://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git/log/?h=feature_interrupters

Let me know what you think about this.

> Signed-off-by: Mathias Nyman <mathias.nyman@linux.intel.com>
> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>

My Signed-off-by tag is being misused here.

I wrote a chunk of the code in this patch as PoC that I shared in a separate topic branch.
It was incomplete and not intended for upstream yet. (lacked locking, several fixme parts, etc..)
The rest of the code in this patch is completely new to me.

Thanks
-Mathias
Wesley Cheng March 13, 2023, 8:08 p.m. UTC | #21
Hi Mathias,

On 3/10/2023 7:07 AM, Mathias Nyman wrote:
> On 9.3.2023 1.57, Wesley Cheng wrote:
>> From: Mathias Nyman <mathias.nyman@linux.intel.com>
>>
>> Introduce xHCI APIs to allow for clients to allocate and free
>> interrupters.  This allocates an array of interrupters, which is based on
>> the max_interrupters parameter.  The primary interrupter is set as the
>> first entry in the array, and secondary interrupters following after.
>>
> 
> I'm thinking about changing this offloading xHCI API
> xhci should be aware and keep track of which devices and endpoints that
> are offloaded to avoid device getting offloaded twice, avoid xhci driver
> from queuing anything itself for these, and act properly if the offloaded
> device or entire host is removed.
> 
> So first thing audio side would need to do do is register/create an
> offload entry for the device using the API:
> 
> struct xhci_sideband *xhci_sideband_register(struct usb_device *udev)
> 
> (xHCI specs calls offload sideband)
> Then endpoints and interrupters can be added and removed from this
> offload entry
> 
> I have some early thoughts written as non-compiling code in:
> 
> git://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git 
> feature_interrupters
> https://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git/log/?h=feature_interrupters 
> 
> 
> Let me know what you think about this.
> 

The concept/framework you built looks good to me.  Makes sense to have 
XHCI better maintain the offloading users.  One thing I would request is 
to move xhci-sideband.h to the include directory since the class driver 
levels would need to be able to reference the structure and APIs you've 
exposed.

I have yet to try it with our implementation, but I'll work on plugging 
it in and fix any issues I see along the way.

Thanks
Wesley Cheng
Wesley Cheng March 13, 2023, 8:32 p.m. UTC | #22
Hi Mathias,

On 3/10/2023 7:07 AM, Mathias Nyman wrote:
> On 9.3.2023 1.57, Wesley Cheng wrote:
>> From: Mathias Nyman <mathias.nyman@linux.intel.com>
>>
>> Introduce xHCI APIs to allow for clients to allocate and free
>> interrupters.  This allocates an array of interrupters, which is based on
>> the max_interrupters parameter.  The primary interrupter is set as the
>> first entry in the array, and secondary interrupters following after.
>>
> 
> I'm thinking about changing this offloading xHCI API
> xhci should be aware and keep track of which devices and endpoints that
> are offloaded to avoid device getting offloaded twice, avoid xhci driver
> from queuing anything itself for these, and act properly if the offloaded
> device or entire host is removed.
> 
> So first thing audio side would need to do do is register/create an
> offload entry for the device using the API:
> 
> struct xhci_sideband *xhci_sideband_register(struct usb_device *udev)
> 
> (xHCI specs calls offload sideband)
> Then endpoints and interrupters can be added and removed from this
> offload entry
> 
> I have some early thoughts written as non-compiling code in:
> 
> git://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git 
> feature_interrupters
> https://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git/log/?h=feature_interrupters 
> 
> 
> Let me know what you think about this.
> 
>> Signed-off-by: Mathias Nyman <mathias.nyman@linux.intel.com>
>> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
> 
> My Signed-off-by tag is being misused here.
> 
> I wrote a chunk of the code in this patch as PoC that I shared in a 
> separate topic branch.
> It was incomplete and not intended for upstream yet. (lacked locking, 
> several fixme parts, etc..)
> The rest of the code in this patch is completely new to me.
> 

Sorry about this.  I cherry picked the change directly from your branch, 
so it carried your signed off tag with it.  Will make to include them 
properly next time.

Thanks
Wesley Cheng
Pierre-Louis Bossart March 14, 2023, 12:42 a.m. UTC | #23
On 3/13/23 18:43, Wesley Cheng wrote:
> Hi Pierre,
> 
> On 3/9/2023 4:37 PM, Pierre-Louis Bossart wrote:
>>
>>>>> 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
>>>>
>>>> so how does this 'qc_audio_offload' interface with 'q6usb' described
>>>> above? how are the roles different or complementary?
>>>>
>>> So in general you can think that the qc_audio_offload is a complement to
>>> the USB SND USB class driver, while q6usb is to ASoC.  Since the ASoC
>>
>> Humm, that is far from clear. I don't get how a something that interacts
>> with the USB class driver can also be in charge of the audio DSP memory
>> management.
>>
> 
> This is because the USB class driver is the entity which is going to
> work with the USB HCD (XHCI) in this case to fetch the required
> addresses, and map that into memory accessible by the audio DSP.  It
> would be odd to be doing that from the q6usb end, which is part of the
> ASoC layer.
> 
>>> framework doesn't have any communication with USB SND, the ASoC DPCM USB
>>> backend (q6usb) will have to be the entity that maintains what is going
>>> on in USB SND.  That way, sessions initiated through the ASoC managed
>>> sound card can evaluate what is available based on information reported
>>> by q6usb.
>>>
>>> qc_audio_offload and q6usb will have some interaction between each
>>> other.  The majority of communication between qc_audio_offload and q6usb
>>> is reporting the device connection events.
>>
>> It's already complicated to figure out how the DSP and USB class driver
>> might interact and probe/timing dependencies, but with two additional
>> drivers in the mix it's really hard to understand.
>>
> 
> I did test some cases based on existence of both these drivers
> (qc_audio_offload and q6usb).  If either one doesn't exist in the
> system, then the offload path would not work.  I did improve some of
> these potential sequences in the latest revision, such as patch#28. This
> would address scenarios where the q6usb ASoC DPCM backend wasn't probed,
> while the USB SND (and qc_audio_offload) were still detecting device
> connections.
> 
> Once the Q6USB driver is probed, then the offload snd kcontrols would be
> created, and devices would be properly identified with the rediscover api.
> 
>> Maybe ascii-art would help describe the concepts and types of
>> information exchanged. Maintaining a consistent state across multiple
>> drivers is not an easy task.
>>
> 
> Hopefully this might help?  I know its a lot to read through.

It's very helpful! Thanks for spending the time to illustrate the
different building blocks.

> 
>      USB                          |            ASoC
> --------------------------------------------------------------------
>                                   |  _________________________
>                                   | |sm8250 platform card     |
>                                   | |_________________________|
>                                   |         |           |
>                                   |      ___V____   ____V____
>                                   |     |Q6USB   | |Q6AFE    |  #5
>                                   |     |"codec" | |"cpu"    |
>                                   |     |________| |_________|
>                                   |         ^
>                                   |         |  #6
>                                   |      ___V____
>                                   |     |SOC-USB |
>   ________   #1  ________         #7    |        |
>  |USB SND |<--->|QC offld|<------------>|________|
>  |(card.c)|     |        |<----------       ^
>  |________|     |________|___ #4  | |       |
>      ^               ^       |    | |    ___V__________________
>      | #2            |  #2   |    | |   |APR/GLINK             |
>   __ V_______________V_____  |    | |   |______________________|
>  |USB SND (endpoint.c)     | |    | |              ^
>  |_________________________| |    | | #8           |
>              ^               |    | |   ___________V___________
>              | #3            |    | |->|audio DSP              |
>   ___________V_____________  |    |    |_______________________|
>  |XHCI HCD                 |<-    |
>  |_________________________|      |
> 
> 
> #1 - USB SND and QC offload:
> Initialization:
> - Register platform operations, to receive connect/disconnect events
>   from USB SND.
> - QC offload creates a QMI handle, in order to receive QMI requests
>   from the audio DSP.
> 
> Runtime:
> - USB SND passes along "struct snd_usb_audio" in order for QC offload
>   to reference USB UAC desc parsing/USB SND helper APIs.
> - USB device disconnection events will result in clearing of the chip
>   entry.
> 
> #2 - USB SND and QC offload endpoints:
> Runtime:
> - In the non-offloaded path, USB snd will utilize functions exposed by
>   USB SND endpoint, to help with fetching USB EP references and queuing
>   URBs.
> - In the offload path, qc offload will utilize the functions to fetch
>   USB EP references, so that it can use that information to query the
>   XHCI HCD.
> - Likewise, both will clean up endpoints when audio stream is not in use.
> 
> #3 - XHCI HCD:
> Initialization:
> - During XHCI probe timing, when the USB HCD is added to the system, it
>   will also initialize the secondary event rings.
> 
> Runtime:
> - During USB device plug ins/outs, allocates device slot, assigns eps,
>   and initializes transfer rings.
> 
> #4 - QC offload and XHCI:
> Runtime:
> - QC offload needs to reference the transfer ring and secondary event ring
>   addresses by executing XHCI offload management APIs.
> - This happens when audio DSP receives a USB QMI stream request.
> 
> #5 - ASoC components:
> Initialization:
> - The SM8250 platform sound card driver fetches DT node entries defining
>   the ASoC links. This chain/link has the components involved for a
>   particular Q6AFE path. (not only USB offload)
>     - "cpu" - this is the ASoC CPU DAI that handles interaction with the
>               Q6 DSP's audio protocol. (AFE ports)
>     - "codec" - the ASoC codec (backend) DAI defined
> - Registers ASoC platform sound card based on links defined in the DT node.
>   - Probes DAI components involved, ie Q6USB and Q6AFE
> 
> Runtime:
> - Q6AFE has the bulk of the interaction w/ the audio DSP to start an audio
>   session, such as issuing AFE port start commands (part of the protocol
>   used to communicate the audio session info)
> - Q6USB will be there to now check for if format requested is supported by
>   the device, and maintain offloading status.
> 
> #6 - Q6USB and SOC-USB:
> Initialization:
> - Q6USB will query QC offload for USB device connection states. (through
>   soc-usb)
> - Creates a SOC USB entry, that carries information about resources,
>   such as audio DSP memory information and requested XHCI event ring
>   index.
> 
> Runtime:
> - SOC-USB will receive connect/disconnect events and propagate to Q6USB.
>   - Q6USB makes devices available for offloading based on these events.
> - Sets Q6AFE port configurations to select the USB SND card# and PCM#.
> 
> #7 - SOC-USB and QC offload:
> Initialization:
> - Rediscover USB SND devices when the SOC-USB entry is created (if needed)
>     - For situations where the Q6USB DAI hasn't been probed.
> 
> Runtime:
> - Propagate connect/disconnect events.

Is the SOC-USB module or building blocks intended to be generic or
Qualcomm agnostic?

It's not clear to me how it would handle "audio DSP memory information
and requested XHCI event ring index."

In addition, it seems to be the "bridge" or means of communication
between qc_audio_offload and q6usb, is this not based on custom events
or triggers?

Along the same lines, this SOC-USB entity interfaces with APR/GLINK
which doesn't speak to me so it must be a QCOM interface?

I am trying to see if this design could be used for other architectures,
and the QCOM-specific and generic parts are not obvious.

> #8 - audio DSP and QC offload:
> Runtime:
> - Handle QMI requests coming from audio DSP.  These requests come AFTER
>   the Q6AFE port is opened by the Q6AFE DAI(#6)
> - Returns memory information about resources allocated by XHCI.
> - Enables audio playback when this QMI transaction is completed.
> 
>>>
>>>>> 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...
>>>>
>>>> I already voiced my concerns about exposing two cards, each with their
>>>> own set of volume controls with the same device. It would be much
>>>> better
>>>> to have an additional offloaded PCM device for card0...
>>>>
>>>> But if the consensus is to have two cards, it's still not clear how the
>>>> routing would be selected. In the case where there are two USB audio
>>>> devices attached, the offloaded path would only support one of the two.
>>>> How would userspace know which of the two is selected?
>>>>
>>>
>>> With patch#24:
>>> https://lore.kernel.org/linux-usb/20230308235751.495-25-quic_wcheng@quicinc.com/T/#u
>>>
>>> Now, userspace can at least choose which device it wants to offload.
>>> Part of doing that would mean userspace knows what USB SND card devices
>>> are available, so it is aware of which devices are shared (between the
>>> offload and USB SND path)
>>>
>>>> And how would userspace know the difference anyways between two
>>>> physical
>>>> devices attached to the platform with no offload, and one physical
>>>> device with one additional offload path? The names you selected
>>>> can't be
>>>> used to identify that card1 is the optimized version of card0.
>>>>
>>>
>>> Is userspace currently able to differentiate between cards that are
>>> created by USB SND versus ASoC?  How complex can the userspace card
>>> discovery be?  Can it query kcontrols at this point in time?  If so,
>>> maybe we can change the names of the newly added ones to reflect that it
>>> is an offload device?
>>>
>>> SND kcontrol names are currently:
>>> Q6USB offload status
>>> Q6USB offload SND device select
>>
>> I must admit I've never seen kcontrols being used to identify what the
>> card is, and in this case it's a pretend-card that's just an improved
>> version of another. It might be easier to use something else, such as
>> the component strings.
> 
> Its not exactly a pretend card, right?  This is part of the overall
> platform sound card we have in the system.  At the moment, I'm only
> testing by adding the USB audio routing, but there can be several ASoC
> links defined in the overall platform card.

Sorry, I misunderstood the proposal. I thought there would be one card
for "generic USB Audio", and another one for "DSP-offloaded USB Audio".
I assumed, probably mistakenly, that all local audio endpoints
(speaker,mics) would be exposed as a separate card.

It looks like it's more "generic USB Audio" and "DSP Audio", with the
USB offload being exposed as a PCM device of the latter.

Did I get this right? In this case, presumably there can be some sort of
UCM file for the "DSP Audio card" that contains the configuration or
knows which kcontrols to look for. But my point about detection hold.
You could perfectly well have a 'Jack control' that tells userspace when
a device is connected. That way there's no guess work, it's similar to
HDMI for Intel: the device is exposed but only valid when the jack
control is set.

> The Q6AFE CPU DAI has multiple audio AFE "ports" they can handle.  USB
> is only one of those.
> 
>>>
>>>> Before we review low-level kernel plumbing, it would be good to give a
>>>> better overview of how userspace applications are supposed to interact
>>>> with the cards and identify the offloaded path. Testing with
>>>> tinyplay/tinymix is fine, but that's a developer-level or CI unit test.
>>>> we've got to see the broader picture of how a sound server would use
>>>> this USB offload capability.
>>>
>>> Sure, I think that is fine.  I was hoping that at least adding some of
>>> the new kcontrols would help userspace make use of this path in general,
>>> but we can add more information if required.
>>
>> Can I ask if this solution has been used with a complete userspace stack
>> already? I could see how this might be used with a relatively fixed
> 
> Its been used only with the Android HAL.

ok, that aligns with what I was thinking.

> 
>> Android HAL, where the platform and routing are relatively controlled. I
>> don't see how a more generic audio server would deal with the discovery
>> and routing.
>>
> 
> This is why your input is helpful, since it provides another use case
> that wasn't considered.  I think in our previous discussions the tagging
> possibility was a good idea, and was hoping that it could help.  Could
> tag all USB SND cards to the platform sound card as well, and if the
> power saving path is chosen, it would issue the playback on the platform
> sound card. (if not in use)
> 
> In this case, the offload path wouldn't be the default routing, and only
> enabled for power optimized path.
> 
> Thanks
> Wesley Cheng
Wesley Cheng March 14, 2023, 1:42 a.m. UTC | #24
Hi Pierre,

On 3/13/2023 5:42 PM, Pierre-Louis Bossart wrote:
> 
> 
> On 3/13/23 18:43, Wesley Cheng wrote:
>> Hi Pierre,
>>
>> On 3/9/2023 4:37 PM, Pierre-Louis Bossart wrote:
>>>
>>>>>> 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
>>>>>
>>>>> so how does this 'qc_audio_offload' interface with 'q6usb' described
>>>>> above? how are the roles different or complementary?
>>>>>
>>>> So in general you can think that the qc_audio_offload is a complement to
>>>> the USB SND USB class driver, while q6usb is to ASoC.  Since the ASoC
>>>
>>> Humm, that is far from clear. I don't get how a something that interacts
>>> with the USB class driver can also be in charge of the audio DSP memory
>>> management.
>>>
>>
>> This is because the USB class driver is the entity which is going to
>> work with the USB HCD (XHCI) in this case to fetch the required
>> addresses, and map that into memory accessible by the audio DSP.  It
>> would be odd to be doing that from the q6usb end, which is part of the
>> ASoC layer.
>>
>>>> framework doesn't have any communication with USB SND, the ASoC DPCM USB
>>>> backend (q6usb) will have to be the entity that maintains what is going
>>>> on in USB SND.  That way, sessions initiated through the ASoC managed
>>>> sound card can evaluate what is available based on information reported
>>>> by q6usb.
>>>>
>>>> qc_audio_offload and q6usb will have some interaction between each
>>>> other.  The majority of communication between qc_audio_offload and q6usb
>>>> is reporting the device connection events.
>>>
>>> It's already complicated to figure out how the DSP and USB class driver
>>> might interact and probe/timing dependencies, but with two additional
>>> drivers in the mix it's really hard to understand.
>>>
>>
>> I did test some cases based on existence of both these drivers
>> (qc_audio_offload and q6usb).  If either one doesn't exist in the
>> system, then the offload path would not work.  I did improve some of
>> these potential sequences in the latest revision, such as patch#28. This
>> would address scenarios where the q6usb ASoC DPCM backend wasn't probed,
>> while the USB SND (and qc_audio_offload) were still detecting device
>> connections.
>>
>> Once the Q6USB driver is probed, then the offload snd kcontrols would be
>> created, and devices would be properly identified with the rediscover api.
>>
>>> Maybe ascii-art would help describe the concepts and types of
>>> information exchanged. Maintaining a consistent state across multiple
>>> drivers is not an easy task.
>>>
>>
>> Hopefully this might help?  I know its a lot to read through.
> 
> It's very helpful! Thanks for spending the time to illustrate the
> different building blocks.
> 
>>
>>       USB                          |            ASoC
>> --------------------------------------------------------------------
>>                                    |  _________________________
>>                                    | |sm8250 platform card     |
>>                                    | |_________________________|
>>                                    |         |           |
>>                                    |      ___V____   ____V____
>>                                    |     |Q6USB   | |Q6AFE    |  #5
>>                                    |     |"codec" | |"cpu"    |
>>                                    |     |________| |_________|
>>                                    |         ^
>>                                    |         |  #6
>>                                    |      ___V____
>>                                    |     |SOC-USB |
>>    ________   #1  ________         #7    |        |
>>   |USB SND |<--->|QC offld|<------------>|________|
>>   |(card.c)|     |        |<----------       ^
>>   |________|     |________|___ #4  | |       |
>>       ^               ^       |    | |    ___V__________________
>>       | #2            |  #2   |    | |   |APR/GLINK             |
>>    __ V_______________V_____  |    | |   |______________________|
>>   |USB SND (endpoint.c)     | |    | |              ^
>>   |_________________________| |    | | #8           |
>>               ^               |    | |   ___________V___________
>>               | #3            |    | |->|audio DSP              |
>>    ___________V_____________  |    |    |_______________________|
>>   |XHCI HCD                 |<-    |
>>   |_________________________|      |
>>
>>
>> #1 - USB SND and QC offload:
>> Initialization:
>> - Register platform operations, to receive connect/disconnect events
>>    from USB SND.
>> - QC offload creates a QMI handle, in order to receive QMI requests
>>    from the audio DSP.
>>
>> Runtime:
>> - USB SND passes along "struct snd_usb_audio" in order for QC offload
>>    to reference USB UAC desc parsing/USB SND helper APIs.
>> - USB device disconnection events will result in clearing of the chip
>>    entry.
>>
>> #2 - USB SND and QC offload endpoints:
>> Runtime:
>> - In the non-offloaded path, USB snd will utilize functions exposed by
>>    USB SND endpoint, to help with fetching USB EP references and queuing
>>    URBs.
>> - In the offload path, qc offload will utilize the functions to fetch
>>    USB EP references, so that it can use that information to query the
>>    XHCI HCD.
>> - Likewise, both will clean up endpoints when audio stream is not in use.
>>
>> #3 - XHCI HCD:
>> Initialization:
>> - During XHCI probe timing, when the USB HCD is added to the system, it
>>    will also initialize the secondary event rings.
>>
>> Runtime:
>> - During USB device plug ins/outs, allocates device slot, assigns eps,
>>    and initializes transfer rings.
>>
>> #4 - QC offload and XHCI:
>> Runtime:
>> - QC offload needs to reference the transfer ring and secondary event ring
>>    addresses by executing XHCI offload management APIs.
>> - This happens when audio DSP receives a USB QMI stream request.
>>
>> #5 - ASoC components:
>> Initialization:
>> - The SM8250 platform sound card driver fetches DT node entries defining
>>    the ASoC links. This chain/link has the components involved for a
>>    particular Q6AFE path. (not only USB offload)
>>      - "cpu" - this is the ASoC CPU DAI that handles interaction with the
>>                Q6 DSP's audio protocol. (AFE ports)
>>      - "codec" - the ASoC codec (backend) DAI defined
>> - Registers ASoC platform sound card based on links defined in the DT node.
>>    - Probes DAI components involved, ie Q6USB and Q6AFE
>>
>> Runtime:
>> - Q6AFE has the bulk of the interaction w/ the audio DSP to start an audio
>>    session, such as issuing AFE port start commands (part of the protocol
>>    used to communicate the audio session info)
>> - Q6USB will be there to now check for if format requested is supported by
>>    the device, and maintain offloading status.
>>
>> #6 - Q6USB and SOC-USB:
>> Initialization:
>> - Q6USB will query QC offload for USB device connection states. (through
>>    soc-usb)
>> - Creates a SOC USB entry, that carries information about resources,
>>    such as audio DSP memory information and requested XHCI event ring
>>    index.
>>
>> Runtime:
>> - SOC-USB will receive connect/disconnect events and propagate to Q6USB.
>>    - Q6USB makes devices available for offloading based on these events.
>> - Sets Q6AFE port configurations to select the USB SND card# and PCM#.
>>
>> #7 - SOC-USB and QC offload:
>> Initialization:
>> - Rediscover USB SND devices when the SOC-USB entry is created (if needed)
>>      - For situations where the Q6USB DAI hasn't been probed.
>>
>> Runtime:
>> - Propagate connect/disconnect events.
> 
> Is the SOC-USB module or building blocks intended to be generic or
> Qualcomm agnostic?
> 

This should be generic.

> It's not clear to me how it would handle "audio DSP memory information
> and requested XHCI event ring index."
> 

Each soc-usb entry that is created by the ASoC DPCM backend DAI (q6usb) 
will be able to hold "private data" that, in QC case, is defined as:
struct q6usb_offload

This is passed within the snd_soc_usb_add_port() call:
snd_soc_usb_add_port(component->dev, &data->priv, q6usb_alsa_connection_cb);

So depending on the user, the private data can contain their own struct 
with the information they require.

> In addition, it seems to be the "bridge" or means of communication
> between qc_audio_offload and q6usb, is this not based on custom events
> or triggers?
> 

Ideally, no, it shouldn't be based on custom events.  Intention for the 
connect_cb() that is defined is just to receive USB device discovery 
events from USB SND.  From the qc_audio_offload, we call 
snd_soc_usb_connect() within our platform op that we register to USB SND.

//Platform connect_cb() - called from USB SND probe (device connected)
static void qc_usb_audio_offload_probe(struct snd_usb_audio *chip)
{
...
snd_soc_usb_connect(usb_get_usb_backend(udev), chip->card->number,
				chip->index, chip->pcm_devs);

In the QC situation, we used this to build a list of active devices 
connected.

> Along the same lines, this SOC-USB entity interfaces with APR/GLINK
> which doesn't speak to me so it must be a QCOM interface?
> 

Sorry for not labeling those in the diagram, but yes, those are QC 
specific interfaces.  You can just think of it as a type of IPC transport.

> I am trying to see if this design could be used for other architectures,
> and the QCOM-specific and generic parts are not obvious.
> 
>> #8 - audio DSP and QC offload:
>> Runtime:
>> - Handle QMI requests coming from audio DSP.  These requests come AFTER
>>    the Q6AFE port is opened by the Q6AFE DAI(#6)
>> - Returns memory information about resources allocated by XHCI.
>> - Enables audio playback when this QMI transaction is completed.
>>
>>>>
>>>>>> 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...
>>>>>
>>>>> I already voiced my concerns about exposing two cards, each with their
>>>>> own set of volume controls with the same device. It would be much
>>>>> better
>>>>> to have an additional offloaded PCM device for card0...
>>>>>
>>>>> But if the consensus is to have two cards, it's still not clear how the
>>>>> routing would be selected. In the case where there are two USB audio
>>>>> devices attached, the offloaded path would only support one of the two.
>>>>> How would userspace know which of the two is selected?
>>>>>
>>>>
>>>> With patch#24:
>>>> https://lore.kernel.org/linux-usb/20230308235751.495-25-quic_wcheng@quicinc.com/T/#u
>>>>
>>>> Now, userspace can at least choose which device it wants to offload.
>>>> Part of doing that would mean userspace knows what USB SND card devices
>>>> are available, so it is aware of which devices are shared (between the
>>>> offload and USB SND path)
>>>>
>>>>> And how would userspace know the difference anyways between two
>>>>> physical
>>>>> devices attached to the platform with no offload, and one physical
>>>>> device with one additional offload path? The names you selected
>>>>> can't be
>>>>> used to identify that card1 is the optimized version of card0.
>>>>>
>>>>
>>>> Is userspace currently able to differentiate between cards that are
>>>> created by USB SND versus ASoC?  How complex can the userspace card
>>>> discovery be?  Can it query kcontrols at this point in time?  If so,
>>>> maybe we can change the names of the newly added ones to reflect that it
>>>> is an offload device?
>>>>
>>>> SND kcontrol names are currently:
>>>> Q6USB offload status
>>>> Q6USB offload SND device select
>>>
>>> I must admit I've never seen kcontrols being used to identify what the
>>> card is, and in this case it's a pretend-card that's just an improved
>>> version of another. It might be easier to use something else, such as
>>> the component strings.
>>
>> Its not exactly a pretend card, right?  This is part of the overall
>> platform sound card we have in the system.  At the moment, I'm only
>> testing by adding the USB audio routing, but there can be several ASoC
>> links defined in the overall platform card.
> 
> Sorry, I misunderstood the proposal. I thought there would be one card
> for "generic USB Audio", and another one for "DSP-offloaded USB Audio".
> I assumed, probably mistakenly, that all local audio endpoints
> (speaker,mics) would be exposed as a separate card.
> 

Ah got it.  No, that isn't the case here.

> It looks like it's more "generic USB Audio" and "DSP Audio", with the
> USB offload being exposed as a PCM device of the latter.
> 
> Did I get this right? In this case, presumably there can be some sort of

Yep that's correct!

> UCM file for the "DSP Audio card" that contains the configuration or
> knows which kcontrols to look for. But my point about detection hold.
> You could perfectly well have a 'Jack control' that tells userspace when
> a device is connected. That way there's no guess work, it's similar to
> HDMI for Intel: the device is exposed but only valid when the jack
> control is set.
> 

Hmm, ok.  Let me see if I can switch up some things.  Maybe replace the 
current snd_soc_dapm_enable_pin() calls in the q6usb connection_cb and 
replace that with a snd jack report. (the snd jack implementation 
already takes care of updating the pin if needed)

Thanks
Wesley Cheng

>> The Q6AFE CPU DAI has multiple audio AFE "ports" they can handle.  USB
>> is only one of those.
>>
>>>>
>>>>> Before we review low-level kernel plumbing, it would be good to give a
>>>>> better overview of how userspace applications are supposed to interact
>>>>> with the cards and identify the offloaded path. Testing with
>>>>> tinyplay/tinymix is fine, but that's a developer-level or CI unit test.
>>>>> we've got to see the broader picture of how a sound server would use
>>>>> this USB offload capability.
>>>>
>>>> Sure, I think that is fine.  I was hoping that at least adding some of
>>>> the new kcontrols would help userspace make use of this path in general,
>>>> but we can add more information if required.
>>>
>>> Can I ask if this solution has been used with a complete userspace stack
>>> already? I could see how this might be used with a relatively fixed
>>
>> Its been used only with the Android HAL.
> 
> ok, that aligns with what I was thinking.
> 
>>
>>> Android HAL, where the platform and routing are relatively controlled. I
>>> don't see how a more generic audio server would deal with the discovery
>>> and routing.
>>>
>>
>> This is why your input is helpful, since it provides another use case
>> that wasn't considered.  I think in our previous discussions the tagging
>> possibility was a good idea, and was hoping that it could help.  Could
>> tag all USB SND cards to the platform sound card as well, and if the
>> power saving path is chosen, it would issue the playback on the platform
>> sound card. (if not in use)
>>
>> In this case, the offload path wouldn't be the default routing, and only
>> enabled for power optimized path.
>>
>> Thanks
>> Wesley Cheng
Pierre-Louis Bossart March 14, 2023, 2:22 a.m. UTC | #25
<snip>

>>
>>>
>>>       USB                          |            ASoC
>>> --------------------------------------------------------------------
>>>                                    |  _________________________
>>>                                    | |sm8250 platform card     |
>>>                                    | |_________________________|
>>>                                    |         |           |
>>>                                    |      ___V____   ____V____
>>>                                    |     |Q6USB   | |Q6AFE    |  #5
>>>                                    |     |"codec" | |"cpu"    |
>>>                                    |     |________| |_________|
>>>                                    |         ^
>>>                                    |         |  #6
>>>                                    |      ___V____
>>>                                    |     |SOC-USB |
>>>    ________   #1  ________         #7    |        |
>>>   |USB SND |<--->|QC offld|<------------>|________|
>>>   |(card.c)|     |        |<----------       ^
>>>   |________|     |________|___ #4  | |       |
>>>       ^               ^       |    | |    ___V__________________
>>>       | #2            |  #2   |    | |   |APR/GLINK             |
>>>    __ V_______________V_____  |    | |   |______________________|
>>>   |USB SND (endpoint.c)     | |    | |              ^
>>>   |_________________________| |    | | #8           |
>>>               ^               |    | |   ___________V___________
>>>               | #3            |    | |->|audio DSP              |
>>>    ___________V_____________  |    |    |_______________________|
>>>   |XHCI HCD                 |<-    |
>>>   |_________________________|      |
>>>
>>>
>>> #1 - USB SND and QC offload:
>>> Initialization:
>>> - Register platform operations, to receive connect/disconnect events
>>>    from USB SND.
>>> - QC offload creates a QMI handle, in order to receive QMI requests
>>>    from the audio DSP.
>>>
>>> Runtime:
>>> - USB SND passes along "struct snd_usb_audio" in order for QC offload
>>>    to reference USB UAC desc parsing/USB SND helper APIs.
>>> - USB device disconnection events will result in clearing of the chip
>>>    entry.
>>>
>>> #2 - USB SND and QC offload endpoints:
>>> Runtime:
>>> - In the non-offloaded path, USB snd will utilize functions exposed by
>>>    USB SND endpoint, to help with fetching USB EP references and queuing
>>>    URBs.
>>> - In the offload path, qc offload will utilize the functions to fetch
>>>    USB EP references, so that it can use that information to query the
>>>    XHCI HCD.
>>> - Likewise, both will clean up endpoints when audio stream is not in
>>> use.
>>>
>>> #3 - XHCI HCD:
>>> Initialization:
>>> - During XHCI probe timing, when the USB HCD is added to the system, it
>>>    will also initialize the secondary event rings.
>>>
>>> Runtime:
>>> - During USB device plug ins/outs, allocates device slot, assigns eps,
>>>    and initializes transfer rings.
>>>
>>> #4 - QC offload and XHCI:
>>> Runtime:
>>> - QC offload needs to reference the transfer ring and secondary event
>>> ring
>>>    addresses by executing XHCI offload management APIs.
>>> - This happens when audio DSP receives a USB QMI stream request.
>>>
>>> #5 - ASoC components:
>>> Initialization:
>>> - The SM8250 platform sound card driver fetches DT node entries defining
>>>    the ASoC links. This chain/link has the components involved for a
>>>    particular Q6AFE path. (not only USB offload)
>>>      - "cpu" - this is the ASoC CPU DAI that handles interaction with
>>> the
>>>                Q6 DSP's audio protocol. (AFE ports)
>>>      - "codec" - the ASoC codec (backend) DAI defined
>>> - Registers ASoC platform sound card based on links defined in the DT
>>> node.
>>>    - Probes DAI components involved, ie Q6USB and Q6AFE
>>>
>>> Runtime:
>>> - Q6AFE has the bulk of the interaction w/ the audio DSP to start an
>>> audio
>>>    session, such as issuing AFE port start commands (part of the
>>> protocol
>>>    used to communicate the audio session info)
>>> - Q6USB will be there to now check for if format requested is
>>> supported by
>>>    the device, and maintain offloading status.
>>>
>>> #6 - Q6USB and SOC-USB:
>>> Initialization:
>>> - Q6USB will query QC offload for USB device connection states. (through
>>>    soc-usb)
>>> - Creates a SOC USB entry, that carries information about resources,
>>>    such as audio DSP memory information and requested XHCI event ring
>>>    index.
>>>
>>> Runtime:
>>> - SOC-USB will receive connect/disconnect events and propagate to Q6USB.
>>>    - Q6USB makes devices available for offloading based on these events.
>>> - Sets Q6AFE port configurations to select the USB SND card# and PCM#.
>>>
>>> #7 - SOC-USB and QC offload:
>>> Initialization:
>>> - Rediscover USB SND devices when the SOC-USB entry is created (if
>>> needed)
>>>      - For situations where the Q6USB DAI hasn't been probed.
>>>
>>> Runtime:
>>> - Propagate connect/disconnect events.
>>
>> Is the SOC-USB module or building blocks intended to be generic or
>> Qualcomm agnostic?
>>
> 
> This should be generic.

ok, but then how would it communicate with APR/GLINK described below [1]
> 
>> It's not clear to me how it would handle "audio DSP memory information
>> and requested XHCI event ring index."
>>
> 
> Each soc-usb entry that is created by the ASoC DPCM backend DAI (q6usb)
> will be able to hold "private data" that, in QC case, is defined as:
> struct q6usb_offload
> 
> This is passed within the snd_soc_usb_add_port() call:
> snd_soc_usb_add_port(component->dev, &data->priv,
> q6usb_alsa_connection_cb);
> 
> So depending on the user, the private data can contain their own struct
> with the information they require.

ok, so "handle private data such as audio DSP memory information
>> and requested XHCI event ring index" is what you meant. That'd fine.

>> In addition, it seems to be the "bridge" or means of communication
>> between qc_audio_offload and q6usb, is this not based on custom events
>> or triggers?
>>
> 
> Ideally, no, it shouldn't be based on custom events.  Intention for the
> connect_cb() that is defined is just to receive USB device discovery
> events from USB SND.  From the qc_audio_offload, we call
> snd_soc_usb_connect() within our platform op that we register to USB SND.
> 
> //Platform connect_cb() - called from USB SND probe (device connected)
> static void qc_usb_audio_offload_probe(struct snd_usb_audio *chip)
> {
> ...
> snd_soc_usb_connect(usb_get_usb_backend(udev), chip->card->number,
>                 chip->index, chip->pcm_devs);
> 
> In the QC situation, we used this to build a list of active devices
> connected.
> 
>> Along the same lines, this SOC-USB entity interfaces with APR/GLINK
>> which doesn't speak to me so it must be a QCOM interface?>>
> 
> Sorry for not labeling those in the diagram, but yes, those are QC
> specific interfaces.  You can just think of it as a type of IPC transport.

[1] ... something's not clear on how a generic 'soc-usb' component can
directly talk to a vendor-specific IPC.

Is there a missing layer?

>> I am trying to see if this design could be used for other architectures,
>> and the QCOM-specific and generic parts are not obvious.
>>
>>> #8 - audio DSP and QC offload:
>>> Runtime:
>>> - Handle QMI requests coming from audio DSP.  These requests come AFTER
>>>    the Q6AFE port is opened by the Q6AFE DAI(#6)
>>> - Returns memory information about resources allocated by XHCI.
>>> - Enables audio playback when this QMI transaction is completed.
>>>
>>>>>
>>>>>>> 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...
>>>>>>
>>>>>> I already voiced my concerns about exposing two cards, each with
>>>>>> their
>>>>>> own set of volume controls with the same device. It would be much
>>>>>> better
>>>>>> to have an additional offloaded PCM device for card0...
>>>>>>
>>>>>> But if the consensus is to have two cards, it's still not clear
>>>>>> how the
>>>>>> routing would be selected. In the case where there are two USB audio
>>>>>> devices attached, the offloaded path would only support one of the
>>>>>> two.
>>>>>> How would userspace know which of the two is selected?
>>>>>>
>>>>>
>>>>> With patch#24:
>>>>> https://lore.kernel.org/linux-usb/20230308235751.495-25-quic_wcheng@quicinc.com/T/#u
>>>>>
>>>>> Now, userspace can at least choose which device it wants to offload.
>>>>> Part of doing that would mean userspace knows what USB SND card
>>>>> devices
>>>>> are available, so it is aware of which devices are shared (between the
>>>>> offload and USB SND path)
>>>>>
>>>>>> And how would userspace know the difference anyways between two
>>>>>> physical
>>>>>> devices attached to the platform with no offload, and one physical
>>>>>> device with one additional offload path? The names you selected
>>>>>> can't be
>>>>>> used to identify that card1 is the optimized version of card0.
>>>>>>
>>>>>
>>>>> Is userspace currently able to differentiate between cards that are
>>>>> created by USB SND versus ASoC?  How complex can the userspace card
>>>>> discovery be?  Can it query kcontrols at this point in time?  If so,
>>>>> maybe we can change the names of the newly added ones to reflect
>>>>> that it
>>>>> is an offload device?
>>>>>
>>>>> SND kcontrol names are currently:
>>>>> Q6USB offload status
>>>>> Q6USB offload SND device select
>>>>
>>>> I must admit I've never seen kcontrols being used to identify what the
>>>> card is, and in this case it's a pretend-card that's just an improved
>>>> version of another. It might be easier to use something else, such as
>>>> the component strings.
>>>
>>> Its not exactly a pretend card, right?  This is part of the overall
>>> platform sound card we have in the system.  At the moment, I'm only
>>> testing by adding the USB audio routing, but there can be several ASoC
>>> links defined in the overall platform card.
>>
>> Sorry, I misunderstood the proposal. I thought there would be one card
>> for "generic USB Audio", and another one for "DSP-offloaded USB Audio".
>> I assumed, probably mistakenly, that all local audio endpoints
>> (speaker,mics) would be exposed as a separate card.
>>
> 
> Ah got it.  No, that isn't the case here.
> 
>> It looks like it's more "generic USB Audio" and "DSP Audio", with the
>> USB offload being exposed as a PCM device of the latter.
>>
>> Did I get this right? In this case, presumably there can be some sort of
> 
> Yep that's correct!

ok, that's good.

My initial thought was to add a 'DSP offload' PCM to the USB card, you
added a "USB offload" PCM to the DSP card. Nice logical swap!

Your proposal might be easier in practice since there's typically a
vendor-specific configuration file (UCM or custom) file for the DSP,
where USB information can be added.

It's more problematic to change a generic USB card as we know it today
and bolt vendor-specific DSP information on top.

The only open I have with your option is that there are still two
control paths to e.g. set the volume. It would be so much easier for
userspace if there was a single volume control no matter what path is
used for data, or make sure the kcontrols are 'mirrored' somehow. If we
found a way to address this issue that would be ideal.

>> UCM file for the "DSP Audio card" that contains the configuration or
>> knows which kcontrols to look for. But my point about detection hold.
>> You could perfectly well have a 'Jack control' that tells userspace when
>> a device is connected. That way there's no guess work, it's similar to
>> HDMI for Intel: the device is exposed but only valid when the jack
>> control is set.
>>
> 
> Hmm, ok.  Let me see if I can switch up some things.  Maybe replace the
> current snd_soc_dapm_enable_pin() calls in the q6usb connection_cb and
> replace that with a snd jack report. (the snd jack implementation
> already takes care of updating the pin if needed)

The jack is useful to let userspace know if a PCM device, i.e. a
Front-End, can be used. But if you expose a PCM device, nothing prevents
an application from trying to open and use it, we recently had such an
issue due to a change in PipeWire that tried to open a non-functional
HDMI device. So you do need something to bail if the PCM device is
mistakenly used.

DAPM pin management seems different, it will turn-on/off parts of the
graph connected to an endpoint. Userpace will typically not know
anything about pin management, it's an in-kernel concept.

Not sure if you have to choose, those are two different layers, no?
Wesley Cheng March 15, 2023, 7:42 p.m. UTC | #26
Hi Pierre,

On 3/15/2023 7:30 AM, Pierre-Louis Bossart wrote:
> Hi Wesley,
> 
>> Sorry made a mistake on the diagram.  There is no connection from
>> SOC-USB to the APR/GLINK.  The Q6USB driver will be the one that is
>> going to configure some of the Q6AFE ports along withe the Q6AFE DAI
>> driver.
>>
>> |            ASoC
>> ----------------------------------
>> |  _________________________
>> | |sm8250 platform card     |
>> | |_________________________|
>> |         |           |
>> |      ___V____   ____V____
>> |     |Q6USB   | |Q6AFE    |  #5
>> |     |"codec" | |"cpu"    |
>> |     |________| |_________|
>> |         ^  ^        ^
>> |      #6 |  |________|
>> |      ___V____     |
>> |     |SOC-USB |    |
>> #7    |        |    |
>> ----->|________|    |
>> ---                 |
>> | |                 |
>> | |    _____________V________
>> | |   |APR/GLINK             |
>> | |   |______________________|
>> | |              ^
>> | | #8           |
>> | |   ___________V___________
>> | |->|audio DSP              |
>> |    |_______________________|
>> |
>> |
>>
>>>>
> 
> Makes sense now, thank you for the clarification.
> 
> I'll have to dig more in this 'soc-usb' block, it's clearly a key
> component that will have to maintain a consistent state across two
> different parts of the stack and deal with probe/remove/shutdown.
> 
>>> My initial thought was to add a 'DSP offload' PCM to the USB card, you
>>> added a "USB offload" PCM to the DSP card. Nice logical swap!
>>>
>>> Your proposal might be easier in practice since there's typically a
>>> vendor-specific configuration file (UCM or custom) file for the DSP,
>>> where USB information can be added.
>>>
>>> It's more problematic to change a generic USB card as we know it today
>>> and bolt vendor-specific DSP information on top.
>>>
>>> The only open I have with your option is that there are still two
>>> control paths to e.g. set the volume. It would be so much easier for
>>> userspace if there was a single volume control no matter what path is
>>> used for data, or make sure the kcontrols are 'mirrored' somehow. If we
>>> found a way to address this issue that would be ideal.
>>>
>>
>> Got it.  Let me look to see if that is something we can address/add.  I
>> think the current implementation is that USB SND will expose some mixer
>> controls based on the UAC descriptor parsing.  Then when they want to
>> change the volume (for example) it will result in a USB SETUP transaction.
>>
>> So USB SND will eventually be the entity controlling these changes.
> 
> That's probably ok then, am I getting this right that the the DSP card
> would not expose any USB-related kcontrols then, i.e. the ONLY path to
> change volumes, etc.,  would through the regular USB card kcontrols?
> 
> That would limit the changes in the platform sound card to the addition
> of a PCM USB device.

Yes, that's correct.  There won't be any exposed USB volume controls 
from the DSP card.

Thanks
Wesley Cheng
Wesley Cheng April 25, 2023, 1:17 a.m. UTC | #27
Hi Mathias,

On 3/13/2023 1:08 PM, Wesley Cheng wrote:
> Hi Mathias,
> 
> On 3/10/2023 7:07 AM, Mathias Nyman wrote:
>> On 9.3.2023 1.57, Wesley Cheng wrote:
>>> From: Mathias Nyman <mathias.nyman@linux.intel.com>
>>>
>>> Introduce xHCI APIs to allow for clients to allocate and free
>>> interrupters.  This allocates an array of interrupters, which is 
>>> based on
>>> the max_interrupters parameter.  The primary interrupter is set as the
>>> first entry in the array, and secondary interrupters following after.
>>>
>>
>> I'm thinking about changing this offloading xHCI API
>> xhci should be aware and keep track of which devices and endpoints that
>> are offloaded to avoid device getting offloaded twice, avoid xhci driver
>> from queuing anything itself for these, and act properly if the offloaded
>> device or entire host is removed.
>>
>> So first thing audio side would need to do do is register/create an
>> offload entry for the device using the API:
>>
>> struct xhci_sideband *xhci_sideband_register(struct usb_device *udev)
>>
>> (xHCI specs calls offload sideband)
>> Then endpoints and interrupters can be added and removed from this
>> offload entry
>>
>> I have some early thoughts written as non-compiling code in:
>>
>> git://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git 
>> feature_interrupters
>> https://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git/log/?h=feature_interrupters 
>>
>>
>> Let me know what you think about this.
>>
> 
> The concept/framework you built looks good to me.  Makes sense to have 
> XHCI better maintain the offloading users.  One thing I would request is 
> to move xhci-sideband.h to the include directory since the class driver 
> levels would need to be able to reference the structure and APIs you've 
> exposed.
> 
> I have yet to try it with our implementation, but I'll work on plugging 
> it in and fix any issues I see along the way.

Sorry for the late reply on some of the efforts on adding your new 
xhci-sideband driver.

I saw your comments with respect to building the SG table for rings with 
multiple segments, ie stream xfer rings.  I had tried some things to 
achieve the page links, but after reviewing some of the Linux memory 
APIs, I'm not sure we can achieve it.  This is because we're not simply 
relying on the direct DMA ops here to build the SG table.  In the IOMMU 
mapped cases, it calls in iommu_dma_get_sgtable(), which has some 
convoluted logic to build the sgt.

Instead of allocating one sgt with multiple sgls (based on # of ring 
segments), would it make sense to just build multiple sgts for each ring 
segment?  The vendor class driver could still fetch the required memory 
information to translate each sgt to a physical address and ring segment 
linking can happen within the external DSP if it supports it.

Thanks
Wesley Cheng
Wesley Cheng June 23, 2023, 10:37 p.m. UTC | #28
Hi Mathias,

On 3/13/2023 1:32 PM, Wesley Cheng wrote:
> Hi Mathias,
> 
> On 3/10/2023 7:07 AM, Mathias Nyman wrote:
>> On 9.3.2023 1.57, Wesley Cheng wrote:
>>> From: Mathias Nyman <mathias.nyman@linux.intel.com>
>>>
>>> Introduce xHCI APIs to allow for clients to allocate and free
>>> interrupters.  This allocates an array of interrupters, which is 
>>> based on
>>> the max_interrupters parameter.  The primary interrupter is set as the
>>> first entry in the array, and secondary interrupters following after.
>>>
>>
>> I'm thinking about changing this offloading xHCI API
>> xhci should be aware and keep track of which devices and endpoints that
>> are offloaded to avoid device getting offloaded twice, avoid xhci driver
>> from queuing anything itself for these, and act properly if the offloaded
>> device or entire host is removed.
>>
>> So first thing audio side would need to do do is register/create an
>> offload entry for the device using the API:
>>
>> struct xhci_sideband *xhci_sideband_register(struct usb_device *udev)
>>
>> (xHCI specs calls offload sideband)
>> Then endpoints and interrupters can be added and removed from this
>> offload entry
>>
>> I have some early thoughts written as non-compiling code in:
>>
>> git://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git 
>> feature_interrupters
>> https://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git/log/?h=feature_interrupters 
>>
>>
>> Let me know what you think about this.
>>
>>> Signed-off-by: Mathias Nyman <mathias.nyman@linux.intel.com>
>>> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
>>
>> My Signed-off-by tag is being misused here.
>>
>> I wrote a chunk of the code in this patch as PoC that I shared in a 
>> separate topic branch.
>> It was incomplete and not intended for upstream yet. (lacked locking, 
>> several fixme parts, etc..)
>> The rest of the code in this patch is completely new to me.
>>
> 
> Sorry about this.  I cherry picked the change directly from your branch, 
> so it carried your signed off tag with it.  Will make to include them 
> properly next time.
> 

I'm about ready to submit the next revision for this set of changes, and 
I was wondering how we should handle the changes you made on:
https://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git/log/?h=feature_interrupters

I did make some modifications to some of the interrupter fixme tags you 
had, and also updated the xhci-sideband APIs with the proper logic.  I 
don't believe it is correct for me to submit a set of patches authored 
by you without your signed off tag. (checkpatch throws an error saying 
the author did not sign off on the change)

Thanks
Wesley Cheng
Wesley Cheng June 26, 2023, 3:05 p.m. UTC | #29
Hi Mathias,

On 6/26/2023 6:55 AM, Mathias Nyman wrote:
> On 24.6.2023 1.37, Wesley Cheng wrote:
>> Hi Mathias,
>>
>> On 3/13/2023 1:32 PM, Wesley Cheng wrote:
>>> Hi Mathias,
>>>
>>> On 3/10/2023 7:07 AM, Mathias Nyman wrote:
>>>> On 9.3.2023 1.57, Wesley Cheng wrote:
>>>>> From: Mathias Nyman <mathias.nyman@linux.intel.com>
>>>>>
>>>>> Introduce xHCI APIs to allow for clients to allocate and free
>>>>> interrupters.  This allocates an array of interrupters, which is 
>>>>> based on
>>>>> the max_interrupters parameter.  The primary interrupter is set as the
>>>>> first entry in the array, and secondary interrupters following after.
>>>>>
>>>>
>>>> I'm thinking about changing this offloading xHCI API
>>>> xhci should be aware and keep track of which devices and endpoints that
>>>> are offloaded to avoid device getting offloaded twice, avoid xhci 
>>>> driver
>>>> from queuing anything itself for these, and act properly if the 
>>>> offloaded
>>>> device or entire host is removed.
>>>>
>>>> So first thing audio side would need to do do is register/create an
>>>> offload entry for the device using the API:
>>>>
>>>> struct xhci_sideband *xhci_sideband_register(struct usb_device *udev)
>>>>
>>>> (xHCI specs calls offload sideband)
>>>> Then endpoints and interrupters can be added and removed from this
>>>> offload entry
>>>>
>>>> I have some early thoughts written as non-compiling code in:
>>>>
>>>> git://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git 
>>>> feature_interrupters
>>>> https://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git/log/?h=feature_interrupters 
>>>>
>>>>
>>>> Let me know what you think about this.
>>>>
>>>>> Signed-off-by: Mathias Nyman <mathias.nyman@linux.intel.com>
>>>>> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
>>>>
>>>> My Signed-off-by tag is being misused here.
>>>>
>>>> I wrote a chunk of the code in this patch as PoC that I shared in a 
>>>> separate topic branch.
>>>> It was incomplete and not intended for upstream yet. (lacked 
>>>> locking, several fixme parts, etc..)
>>>> The rest of the code in this patch is completely new to me.
>>>>
>>>
>>> Sorry about this.  I cherry picked the change directly from your 
>>> branch, so it carried your signed off tag with it.  Will make to 
>>> include them properly next time.
>>>
>>
>> I'm about ready to submit the next revision for this set of changes, 
>> and I was wondering how we should handle the changes you made on:
>> https://git.kernel.org/pub/scm/linux/kernel/git/mnyman/xhci.git/log/?h=feature_interrupters 
>>
>>
>> I did make some modifications to some of the interrupter fixme tags 
>> you had, and also updated the xhci-sideband APIs with the proper 
>> logic.  I don't believe it is correct for me to submit a set of 
>> patches authored by you without your signed off tag. (checkpatch 
>> throws an error saying the author did not sign off on the change)
>>
> 
> Note that the first patch "xhci: split allocate interrupter into 
> separate alloacte and add parts"
> is already in usb-next on its way to 6.5
> 
> Maybe Co-developed-by would work in this case, with a small explanation 
> at the end of the commit message.
> Something like:
> 
> Locking, DMA something and feataure x added by Wesley Cheng to
> complete original concept code by Mathias
> 
> Signed-off-by: Mathias Nyman <mathias.nyman@linux.intel.com>
> Co-developed-by: Wesley Cheng <quic_wcheng@quicinc.com>
> Signed-off-by: Wesley Cheng <quic_wcheng@quicinc.com>
> 

Sounds good!  Thanks for helping with a non-technical question :).  Just 
wanted to make sure I wasn't overstepping anywhere.

Thanks
Wesley Cheng