ALSA: snd-usb: add support for DSD DOP stream transport

In order to provide a compatibility way for pushing DSD
samples through ordinary PCM channels, the "DoP open Standard" was
invented. See http://www.dsd-guide.com for the official document.

The host is required to stuff DSD marker bytes (0x05, 0xfa,
alternating) in the MSB of 24 bit wide samples on the bus, in addition
to the 16 bits of actual DSD sample payload.

To support this, the hardware and software stride logic in the driver
has to be tweaked a bit, as we make the userspace believe we're
operating on 16 bit samples, while we in fact push one more byte per
channel down to the hardware.

The DOP runtime information is stored in struct snd_usb_substream, so
we can keep track of our state across multiple calls to
prepare_playback_urb_dsd_dop().

Signed-off-by: Daniel Mack <zonque@gmail.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: add DSD formats

This patch adds two formats for Direct Stream Digital (DSD), a
pulse-density encoding format which is described here:
https://en.wikipedia.org/wiki/Direct_Stream_Digital

DSD operates on 2.8, 5.6 or 11.2MHz sample rates and as a 1-bit
stream.

The two new types added by this patch describe streams that are capable
of handling DSD samples in DOP format as 8-bit or in 16-bit (or at a x8
or x16 data rate, respectively).

DSD itself specifies samples in *bit*, while DOP and ALSA handle them
as *bytes*. Hence, a factor of 8 or 16 has to be applied for the sample
rare configuration, according to the following table:

                                                  configured hardware
        176.4KHz   352.8kHz   705.6KHz     <----       sample rate

8-bit                2.8MHz     5.6MHz
16-bit    2.8Mhz     5.6MHz    11.2MHz

         `-----------------------------'
             actual DSD sample rates

Signed-off-by: Daniel Mack <zonque@gmail.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: snd-usb: add support for bit-reversed byte formats

There is quite some confusion around the bit-ordering in DSD samples,
and no general agreement that defines whether hardware is supposed to
expect the oldest sample in the MSB or the LSB of a byte.

ALSA will hence set the rule that on the software API layer, bytes
always carry the oldest bit in the most significant bit of a byte, and
the driver has to translate that at runtime in order to match the
hardware layout.

This patch adds support for this by adding a boolean flag to the
audio format struct.

Signed-off-by: Daniel Mack <zonque@gmail.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: snd-usb: add quirks handler for DSD streams

Unfortunately, none of the UAC standards provides a way to identify DSD
(Direct Stream Digital) formats. Hence, this patch adds a quirks
handler to identify USB interfaces that are capable of handling DSD.

That quirks handler can augment the already parsed formats bit-field,
by any of the new SNDRV_PCM_FMTBIT_DSD_{U8_U16} and setting the dsd_dop
flag in the audio format, if the driver should take care for the DOP
byte stuffing.

The only devices that are known to work with this are the ones with
a 'Playback Designs' vendor id.

Signed-off-by: Daniel Mack <zonque@gmail.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb: Work around CM6631 sample rate change bug

The C-Media CM6631 USB receiver doesn't respond to changes in sample rate
while the interface is active. The same behavior is observed in other UAC2
hardware like the VIA VT1731.

Reset the interface after setting the sampling frequency on sample rate
changes, to ensure that the sample rate set by snd_usb_init_sample_rate() is
used. Otherwise, the device will try to use the sample rate of the previous
stream, causing distorted sound on sample rate changes.

The reset is performed for all UAC2 devices, as it should not affect a
standards compliant device, but it is only necessary for C-Media CM6631,
VIA VT1731 and possibly others.

Failure to read sample rate from the device is not handled as an error in
set_sample_rate_v2(), as (permanent or intermittent) failure to read sample
rate isn't essential for a successful sample rate set.

Signed-off-by: Torstein Hegge <hegge@resisty.net>
Acked-by: Clemens Ladisch <clemens@ladisch.de>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: Clean up the code in set_sample_rate_v2()

Just for cleaning up, introduce a new function get_sample_rate_v2()
for replacing two identical calls in set_sample_rate_v2().

No functional change.

Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: use endianness macros

Replace the endianness conversions with the kernel-wide swabbing macros
in get/set_sample_rate_v2.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: UAC2: do clock validity check earlier

Move the check that parse_audio_format_rates_v2() do after
receiving the clock source entity ID directly into the find
function and add a validation flag to the function.

This patch does not introduce any logic flow change.

It is provided to allow introducing automatic clock switching
easier later. By moving this uac_clock_source_is_valid callsite,
2 additional callsites can be avoided.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: UAC2: try to find and switch to valid clock

If a selector is available on a device, it may be pointing to a
clock source which is currently invalid.
If there is a valid clock source which can be selected, switch
to it.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: UAC2: auto clock selection module param

Add a module param to disable auto clock selection.
This is provided for users that expect the audio stream to
fail when the clock source is invalid (e.g., the word clock
was unintentionally disconnected).

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

Conflicts:
	sound/usb/card.c

ALSA: usb-audio: show err in set_sample_rate_v2 debug

Show the error code returned from the USB subsystem in
the debug messages.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: UAC2: support read-only freq control

Some clocks might be read-only, e.g., external clocks (see also
UAC2 4.7.2.1).

In this case, setting the sample frequency will always fail
(even if the rate is equal to the current clock rate),
therefore do not write, but read the value and compare to the
requested rate.
If the clock is read only, avoid reading it twice.

If it doesn't match, return -ENXIO since the clock is invalid for
this configuration.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb - Avoid unnecessary sample rate changes on USB 2.0 clock sources

The Scarlett 2i2 seems to take almost 500 ms to set the sample rate,
even if the clock is currently set to that value. This patch speeds
up prepare of the device, by avoiding setting the clock to something
it already is.

Signed-off-by: David Henningsson <david.henningsson@canonical.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

sound: usb: endpoint: Add dev state check in completion handler

When a USB Headset is unplug from usb host port during audio is playing,
the system is very possible to clear the urb buffer before urb completion
handler is done. Then, clear_bit call in the completion handler will access
the freed pointer and caused the system crash. Check the dev state and skip
the clear_bit call when dev stat is USB_STATE_NOTATTACHED.

CRs-fixed: 647140
Signed-off-by: Guang Jian Zeng <gzeng@codeaurora.org>

ALSA: usb-audio: spelling correction

Correct spelling of snd_usb_endpoint_implict_feedback_sink in all
occurances.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: do not trust too-big wMaxPacketSize values

commit 57e6dae1087bbaa6b33d3dd8a8e90b63888939a3 upstream.

The driver used to assume that the streaming endpoint's wMaxPacketSize
value would be an indication of how much data the endpoint expects or
sends, and compute the number of packets per URB using this value.

However, the Focusrite Scarlett 2i4 declares a value of 1024 bytes,
while only about 88 or 44 bytes are be actually used.  This discrepancy
would result in URBs with far too few packets, which would not work
correctly on the EHCI driver.

To get correct URBs, use wMaxPacketSize only as an upper limit on the
packet size.

Reported-by: James Stone <jamesmstone@gmail.com>
Tested-by: James Stone <jamesmstone@gmail.com>
Signed-off-by: Clemens Ladisch <clemens@ladisch.de>
Signed-off-by: Takashi Iwai <tiwai@suse.de>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

ALSA: usb-audio: use bitmap_weight

Use bitmap_weight to count the total number of bits set in bitmap.

Signed-off-by: Joe Perches <joe@perches.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: snd-usb: handle raw data format of UAC2 devices

UAC2 compliant audio devices may announce the capability to transport
raw audio data on their endpoints. Catch this and handle it as
'special' stream on the ALSA side.

Signed-off-by: Daniel Mack <zonque@gmail.com>
Reported-by: Andreas Koch <andreas@akdesigninc.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: pcm_format_to_bits strong-typed conversion

Add a function to handle conversion from snd_pcm_format_t
to bitwise with proper typing.

Change such conversions to use this function and silence sparse
warnings.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

Conflicts:
	include/sound/pcm.h

ALSA: usb-audio: Add missing kconfig dependecy

commit 4fa71c1550a857ff1dbfe9e99acc1f4cfec5f0d0 upstream.

The commit 44dcbbb1cd61 introduced the usage of bitreverse helpers but
forgot to add the dependency.  This patch adds the selection for
CONFIG_BITREVERSE.

Fixes: 44dcbbb1cd61 ('ALSA: snd-usb: add support for bit-reversed byte formats')
Reported-by: Fengguang Wu <fengguang.wu@intel.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>

ALSA: usb: Parse UAC2 extension unit like for UAC1

UAC2_EXTENSION_UNIT_V2 differs from UAC1_EXTENSION_UNIT, but can be handled in
the same way when parsing the unit. Otherwise parse_audio_unit() fails when it
sees an extension unit on a UAC2 device.

UAC2_EXTENSION_UNIT_V2 is outside the range allocated by UAC1.

Signed-off-by: Torstein Hegge <hegge@resisty.net>
Acked-by: Daniel Mack <zonque@gmail.com>
Cc: <stable@vger.kernel.org>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: snd-usb: mixer: propagate errors up the call chain

In check_input_term() and parse_audio_feature_unit(), propagate the
error value that has been returned by a failing function instead of
-EINVAL. That helps cleaning up the error pathes in the mixer.

Signed-off-by: Daniel Mack <zonque@gmail.com>
Cc: <stable@vger.kernel.org>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: fix endianness bug in snd_nativeinstruments_*

The usb_control_msg() function expects __u16 types and performs
the endianness conversions by itself.
However, in three places, a conversion is performed before it is
handed over to usb_control_msg(), which leads to a double conversion
(= no conversion):
* snd_usb_nativeinstruments_boot_quirk()
* snd_nativeinstruments_control_get()
* snd_nativeinstruments_control_put()

Caught by sparse:

sound/usb/mixer_quirks.c:512:38: warning: incorrect type in argument 6 (different base types)
sound/usb/mixer_quirks.c:512:38:    expected unsigned short [unsigned] [usertype] index
sound/usb/mixer_quirks.c:512:38:    got restricted __le16 [usertype] <noident>
sound/usb/mixer_quirks.c:543:35: warning: incorrect type in argument 5 (different base types)
sound/usb/mixer_quirks.c:543:35:    expected unsigned short [unsigned] [usertype] value
sound/usb/mixer_quirks.c:543:35:    got restricted __le16 [usertype] <noident>
sound/usb/mixer_quirks.c:543:56: warning: incorrect type in argument 6 (different base types)
sound/usb/mixer_quirks.c:543:56:    expected unsigned short [unsigned] [usertype] index
sound/usb/mixer_quirks.c:543:56:    got restricted __le16 [usertype] <noident>
sound/usb/quirks.c:502:35: warning: incorrect type in argument 5 (different base types)
sound/usb/quirks.c:502:35:    expected unsigned short [unsigned] [usertype] value
sound/usb/quirks.c:502:35:    got restricted __le16 [usertype] <noident>

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Acked-by: Daniel Mack <zonque@gmail.com>
Cc: <stable@vger.kernel.org>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb: Add quirk for 192KHz recording on E-Mu devices

When recording at 176.2KHz or 192Khz, the device adds a 32-bit length
header to the capture packets, which obviously needs to be ignored for
recording to work properly.

Userspace expected:  L0 L1 L2 R0 R1 R2
...but actually got: R2 L0 L1 L2 R0 R1

Also, the last byte of the length header being interpreted as L0 of
the first sample caused spikes every 0.5ms, resulting in a loud 16KHz
tone (about the highest 'B' on a piano) being present throughout
captures.

Tested at all sample rates on an E-Mu 0404USB, and tested for
regressions on a generic USB headset.

Signed-off-by: Calvin Owens <jcalvinowens@gmail.com>
Cc: <stable@vger.kernel.org>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: Trust fields given in the quirk

The maxpacksize field is given in some quirks, but it gets ignored (in
favour of wMaxPacketSize from the first endpoint.) This patch favours
the one in the quirk.

Digidesign Mbox and Mbox 2 are the only affected quirks and the devices
are assumed to be working without this patch. So for safety against the
values in the quirk being incorrect, remove them.

The datainterval is also ignored but there are not currently any quirks
which choose to override this.

Cc: Damien Zammit <damien@zamaudio.com>
Cc: Chris J Arges <christopherarges@gmail.com>
Signed-off-by: Mark Hills <mark@xwax.org>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: snd-usb: try harder to find USB_DT_CS_ENDPOINT

The USB_DT_CS_ENDPOINT class-specific endpoint descriptor is usually
stuffed directly after the standard USB endpoint descriptor, and this is
where the driver currently expects it to be.

There are, however, devices in the wild that have it the other way
around in their descriptor sets, so the USB_DT_CS_ENDPOINT comes
*before* the standard enpoint. Devices known to implement it that way
are "Sennheiser BTD-500" and Plantronics USB headsets.

When the driver can't find the USB_DT_CS_ENDPOINT, it won't be able to
change sample rates, as the bitmask for the validity of this command is
storen in bmAttributes of that descriptor.

Fix this by searching the entire interface instead of just the extra
bytes of the first endpoint, in case the latter fails.

Signed-off-by: Daniel Mack <zonque@gmail.com>
Reported-and-tested-by: Torstein Hegge <hegge@resisty.net>
Reported-and-tested-by: Yves G <alsa-user@vivigatt.com>
Cc: stable@kernel.org
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: store protocol version in struct audioformat

Instead of reading bInterfaceProtocol from the descriptor whenever it's
needed, store this value in the audioformat structure.  Besides
simplifying some code, this will allow us to correctly handle vendor-
specific devices where the descriptors are marked with other values.

Signed-off-by: Clemens Ladisch <clemens@ladisch.de>

ALSA: usb-audio: fix regression for fixed stream quirk

Commit 8f898e92aea2c24c7f379ee265d178f69ebb9c07 removed the redundant
reads of bInterfaceProtocol from the descriptors, but introduced a
regression to devices with quirks of type QUIRK_AUDIO_FIXED_ENDPOINT,
since fp->protocol is not set in setup process.

As a consequence, audio streams would not get initialized, as the
following logs show:

[   48.923043] setting usb interface 3:1
[   48.923056] Creating new capture data endpoint #81
[   48.923484] 4:3:1: cannot set freq 48000 to ep 0x81

This patch sets fp->protocol in create_fixed_stream_quirk() and
resolves the regression.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: rename alt_idx to altsetting

As Clemens Ladisch kindly explained:
 "Please note that there are two methods to identify alternate settings:
  the number, which is the value in bAlternateSetting, and the index,
  which is the index in the descriptor array.  There might be some wording
  in the USB spec that these two values must be the same, but in reality,
  [insert standard rant about firmware writers], bAlternateSetting
  must be treated as a random ID value."

This patch changes the name to express the correct usage semantics.
No functional change.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: Fix races at disconnection and PCM closing

commit 92a586bdc06de6629dae1b357dac221253f55ff8 upstream.

When a USB-audio device is disconnected while PCM is still running, we
still see some race: the disconnect callback calls
snd_usb_endpoint_free() that calls release_urbs() and then kfree()
while a PCM stream would be closed at the same time and calls
stop_endpoints() that leads to wait_clear_urbs().  That is, the EP
object might be deallocated while a PCM stream is syncing with
wait_clear_urbs() with the same EP.

Basically calling multiple wait_clear_urbs() would work fine, also
calling wait_clear_urbs() and release_urbs() would work, too, as
wait_clear_urbs() just reads some fields in ep.  The problem is the
succeeding kfree() in snd_pcm_endpoint_free().

This patch moves out the EP deallocation into the later point, the
destructor callback.  At this stage, all PCMs must have been already
closed, so it's safe to free the objects.

Reported-by: Alan Stern <stern@rowland.harvard.edu>
Signed-off-by: Takashi Iwai <tiwai@suse.de>
Signed-off-by: Jiri Slaby <jslaby@suse.cz>

ALSA: usb-audio: Suppress repetitive debug messages from retire_playback_urb()

commit a5065eb6da55b226661456e6a7435f605df98111 upstream.

BugLink: http://bugs.launchpad.net/bugs/1305133

Malfunctioning or slow devices can cause a flood of dmesg SPAM.

I've ignored checkpatch.pl complaints about the use of printk_ratelimit() in favour
of prior art in sound/usb/pcm.c.

WARNING: Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit
+	if (printk_ratelimit() &&

Cc: Jaroslav Kysela <perex@perex.cz>
Cc: Takashi Iwai <tiwai@suse.de>
Cc: Eldad Zack <eldad@fogrefinery.com>
Cc: Daniel Mack <zonque@gmail.com>
Cc: Clemens Ladisch <clemens@ladisch.de>
Signed-off-by: Tim Gardner <tim.gardner@canonical.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>
Signed-off-by: Jiri Slaby <jslaby@suse.cz>

ALSA: usb-audio: Prevent printk ratelimiting from spamming kernel log while DEBUG not defined

This (widely used) construction:

if(printk_ratelimit())
	dev_dbg()

Causes the ratelimiting to spam the kernel log with the "callbacks suppressed"
message below, even while the dev_dbg it is supposed to rate limit wouldn't
print anything because DEBUG is not defined for this device.

[  533.803964] retire_playback_urb: 852 callbacks suppressed
[  538.807930] retire_playback_urb: 852 callbacks suppressed
[  543.811897] retire_playback_urb: 852 callbacks suppressed
[  548.815745] retire_playback_urb: 852 callbacks suppressed
[  553.819826] retire_playback_urb: 852 callbacks suppressed

So use dev_dbg_ratelimited() instead of this construction.

Signed-off-by: Sander Eikelenboom <linux@eikelenboom.it>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: Resume mixer values properly

Implement reset_resume callback so that the mixer values are properly
restored.  Still no boot quirks are called, so it might not work well
on some devices.

Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: Save mixer status only once at suspend

The suspend callback of usb-audio driver may be called multiple times
per suspend when multiple USB interfaces are bound to a single sound
card instance.  In such a case, it's superfluous to save the mixer
values multiple times.  This patch fixes it by checking the counter.

Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: Fix deadlocks at resuming

The recent addition of the USB audio mixer suspend/resume may lead to
deadlocks when the driver tries to call usb_autopm_get_interface()
recursively, since the function tries to sync with the finish of the
other calls.  For avoiding it, introduce a flag indicating the resume
operation and avoids the recursive usb_autopm_get_interface() calls
during the resume.

Reported-and-tested-by: Bryan Quigley <gquigs@gmail.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: improve buffer size computations for USB PCM audio

This patch changes the way URBs are allocated and their sizes are
determined for PCM playback in the snd-usb-audio driver.  Currently
the driver allocates too few URBs for endpoints that don't use
implicit sync, making underruns more likely to occur.  This may be a
holdover from before I/O delays could be measured accurately; in any
case, it is no longer necessary.

The patch allocates as many URBs as possible, subject to four
limitations:

	The total number of URBs for the endpoint is not allowed to
	exceed MAX_URBS (which the patch increases from 8 to 12).

	The total number of packets per URB is not allowed to exceed
	MAX_PACKS (or MAX_PACKS_HS for high-speed devices), which is
	decreased from 20 to 6.

	The total duration of queued data is not allowed to exceed
	MAX_QUEUE, which is decreased from 24 ms to 18 ms.

	The total number of ALSA frames in the output queue is not
	allowed to exceed the ALSA buffer size.

The last requirement is the hardest to implement.  Currently the
number of URBs needed to fill a buffer cannot be determined in
advance, because a buffer contains a fixed number of frames whereas
the number of frames in an URB varies to match shifts in the device's
clock rate.  To solve this problem, the patch changes the logic for
deciding how many packets an URB should contain.  Rather than using as
many as possible without exceeding an ALSA period boundary, now the
driver uses only as many packets as needed to transfer a predetermined
number of frames.  As a result, unless the device's clock has an
exceedingly variable rate, the number of URBs making up each period
(and hence each buffer) will remain constant.

The overall effect of the patch is that playback works better in
low-latency settings.  The user can still specify values for
frames/period and periods/buffer that exceed the capabilities of the
hardware, of course.  But for values that are within those
capabilities, the performance will be improved.  For example, testing
shows that a high-speed device can handle 32 frames/period and 3
periods/buffer at 48 KHz, whereas the current driver starts to get
glitchy at 64 frames/period and 2 periods/buffer.

A side effect of these changes is that the "nrpacks" module parameter
is no longer used.  The patch removes it.

Signed-off-by: Alan Stern <stern@rowland.harvard.edu>
CC: Clemens Ladisch <clemens@ladisch.de>
Tested-by: Daniel Mack <zonque@gmail.com>
Tested-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

Conflicts:
	sound/usb/card.c

ALSA: usb-audio: remove unused parameter from sync_ep_set_params

Since the format is not actually used in sync_ep_set_params(),
there is no need to pass it down.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: don't deactivate URBs on in-use EP

If an endpoint in use, its associated URBs should not be
deactivated.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: work around corrupted TEAC UD-H01 feedback data

The TEAC UD-H01 firmware sends wrong feedback frequency values, thus
causing the PC to send the samples at a wrong rate, which results in
clicks and crackles in the output.

Add a workaround to detect and fix the corruption.

Signed-off-by: Clemens Ladisch <clemens@ladisch.de>
[mick37@gmx.de: use sender->udh01_fb_quirk rather than
 ep->udh01_fb_quirk in snd_usb_handle_sync_urb()]
Reported-and-tested-by: Mick <mick37@gmx.de>
Reported-and-tested-by: Andrea Messa <andr.messa@tiscali.it>
Cc: <stable@vger.kernel.org>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: add a workaround for the NuForce UDH-100

The NuForce UDH-100 numbers its interfaces incorrectly, which makes the
interface associations come out wrong, which results in the driver
erroring out with the message "Audio class v2 interfaces need an
interface association".

Work around this by searching for the interface association descriptor
also in some other place where it might have ended up.

Reported-and-tested-by: Dave Helstroom <helstroom@google.com>
Signed-off-by: Clemens Ladisch <clemens@ladisch.de>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: add channel map support

Add the support for channel maps of the PCM streams on USB audio
devices.  The channel map information is already found in
ChannelConfig descriptor entries, which haven't been referred until
now.

Each chmap entry is added to audioformat list entry and copied to TLV
dynamically instead of creating a whole chmap array.

Signed-off-by: Takashi Iwai <tiwai@suse.de>

Conflicts:
	sound/usb/card.h

ALSA: usb: supply channel maps even when wChannelConfig is unspecified

If wChannelconfig is given for some formats but not others, userspace
might not be able to set the channel map.

This is RFC because I'm not sure what the best behaviour is - to guess
the channel map from the given number of channels (it's quite likely
that one channel is MONO and two channels is FL FR), or just to supply
UNKNOWN for all channels.

But the complete lack of channel map for a format leads userspace to
believe that the format is not available at all. Or am I
misunderstanding how this should be used?

Signed-off-by: David Henningsson <david.henningsson@canonical.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb - For class 2 devices, use channel map from altsettings

The channel config from the streaming descriptor is probably a
better indicator of the channel map than the input terminal.
Use the input terminal's channel map as fallback only.

Signed-off-by: David Henningsson <david.henningsson@canonical.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb - Don't trust the channel config if the channel count changed

In case the channel count of the input terminal is not the same as
the channel count of the streaming descriptor, the channel config of
the input terminal can not be trusted. Instead fall back to a default
(guessed) channel map.

This was found on a Logitech USB Headset.

Signed-off-by: David Henningsson <david.henningsson@canonical.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb: Fix wrong mapping of RLC and RRC channels

According to USB Audio spec v2 bits 25 and 26 of bmChannelConfig are
"Back Left of Center - BLC" and "Back Right of Center - BRC",
respectively.

They are currently assigned to ALSA channels BLC/BRC. However, the ALSA
BLC/BRC are actually the rather nonsensical "bottom left center" and
"bottom right center", so the channels will be assigned wrongly. The
comments in the USB code are also similarly wrong, so this is not
readily apparent without looking at the actual specification.

Fix the channel mapping by mapping bits 25 and 26 to RLC (Rear Left
Center) and RRC (Rear Right Center), respectively, instead.

Signed-off-by: Anssi Hannula <anssi.hannula@iki.fi>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: add front jack channel selector for EMU0204

Add support for front jack channel selector which is present on EMU0204.
It allows to get 4 channels out of this soundcard.

Tested-by: Yury Bushmelev <jay@jay-tech.ru>
Signed-off-by: Vasily Khoruzhick <anarsoul@gmail.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: Add a quirk for Plantronics Gamecom 780

Plantronics Gamecom 780 headset has a firmware problem, and when the
FU 0x09 volume is changed, it results in either too loud or silence
except for a very narrow range.  This patch provides a workaround,
ignoring the node, initialize the volume in a sane value and keep
untouched.

Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=65251
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usx2y: Don't peep the card internal object

Avoid traversing the device object list of the card instance just for
checking the PCM streams.  The driver's private object already
contains the array of substream pointers, so it can be simply looked
through.  The card internal may be restructured in future, thus better
not to rely on it.

Also, this fixes the possible deadlocks in PCM mutex.  Instead of
taking multiple PCM mutexes, just take the common mutex in all
places.  Along with it, rename prepare_mutex as pcm_mutex.

Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: Define more channel map positions

For following the standard, define more channel map positions and
shuffle the items a bit:

- As both PulseAudio and gstreamer define MONO channel position
  explicitly, we should follow that, too.  The mono streams point to
  this channel position unless they are explicitly assigned to certain
  channel positions.

- Top-front-* and Top-rear-* positions are added, carried from
  PulseAudio's definitions.

- Move NA and MONO definitions at the top of table right after
  UNKNOWN, since these are more abstract in comparison with other
  practical positions.

Signed-off-by: Takashi Iwai <tiwai@suse.de>

Conflicts:
	Documentation/sound/alsa/Channel-Mapping-API.txt
	sound/pci/ctxfi/ctpcm.c

ALSA: Extend chmap definitions for UAC2

USB audio class 2 has more channel map positions than we currently
have.  Let's add missing definitions.

Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: snd-usb: add delay quirk for "Playback Design" products

"Playback Design" products need a 50ms delay after setting the USB
interface.

Signed-off-by: Daniel Mack <zonque@gmail.com>
Reported-by: Andreas Koch <andreas@akdesigninc.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: snd-usb: Playback Design: use usb_set_inferface quirk from more locations

It turns out the devices from Playback Design need the delay quirk
after usb_set_interface from clocks.c as well. Make it a proper
quirks function and factor out the code to quirks.c.

Signed-off-by: Daniel Mack <zonque@gmail.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: clear SUBSTREAM_FLAG_SYNC_EP_STARTED on error

If setting the interface fails, the SUBSTREAM_FLAG_SYNC_EP_STARTED
should be cleared.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: remove assignment from if condition

Following general kernel style.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: detect implicit feedback on Roland devices

All the Roland/Edirol/BOSS USB audio devices that need implicit feedback
show this unambiguously in their descriptors, so it might be a good idea
to let the driver detect this.

This should make playback work correctly (at least with Jack) with the
following devices:
- BOSS GT-100
- BOSS JS-8 Jam Station
- Edirol M-16DX
- Roland GAIA SH-01

Signed-off-by: Clemens Ladisch <clemens@ladisch.de>

ALSA: usb-audio: separate sync endpoint setting from set_format

Setting the sync endpoint currently takes up about half of set_format().
Move it to a dedicated function.
No functional change.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: move implicit fb quirks to separate function

Separate setting implicit feedback quirks from setting
a sync endpoint (which may also be explicit feedback or async).

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: reverse condition logic in set_sync_endpoint

Reverse logic on the conditions required to qualify for a sync endpoint
and remove one level of indendation.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: do not initialize and check implicit_fb

Since implicit_fb is not changed, !implicit_fb will always
be true - it is set only after these checks.
Similarly, there's also no need to set it at the top of the function.

Change the type of implicit_fb to bool (more appropriate).

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: remove is_playback from implicit feedback quirks

An implicit feedback endpoint can only be a capture source. The
consumer (sink) of the implicit feedback endpoint is therefore limited
to playback EPs.
Check if the target endpoint is a playback first and remove redundant
checks.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: remove implicit_fb from quirk

Since the quirks all apply to implicit feedback (the source endpoint
is always a data endpoint), there's no need to set and check
a flag for it.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: WARN_ON when alts is passed as NULL

Prevent NULL dereference in snd_usb_add_endpoints(), when
alts is passed as NULL. In this case, WARN (since this is
a non-fatal bug) and return NULL ep. Call sites treat a NULL
return value as an error.

Signed-off-by: Eldad Zack <eldad@fogrefinery.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: 6fire: fix DMA issues with URB transfer_buffer usage

Patch fixes 6fire not to use stack as URB transfer_buffer. URB buffers need to
be DMA-able, which stack is not. Furthermore, transfer_buffer should not be
allocated as part of larger device structure because DMA coherency issues and
patch fixes this issue too.

Cc: stable@vger.kernel.org
Signed-off-by: Jussi Kivilinna <jussi.kivilinna@iki.fi>
Tested-by: Torsten Schenk <torsten.schenk@zoho.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: don't push static constants on stack for %*ph

There is no need to pass constants via stack. The width may be explicitly
specified in the format.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: Fix assignment of 0/1 to bool variables

Convert 0 to false and 1 to true when assigning values to bool
variables. Inspired by commit 3db1cd5c05f35fb43eb134df6f321de4e63141f2.

The simplified semantic patch that find this problem is as
follows (http://coccinelle.lip6.fr/):

@@
bool b;
@@
(
-b = 0
+b = false
|
-b = 1
+b = true
)

Signed-off-by: Peter Senna Tschudin <peter.senna@gmail.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: Use standard printk helpers

Convert with dev_err() and co from snd_printk(), etc.
As there are too deep indirections (e.g. ep->chip->dev->dev),
a few new local macros, usb_audio_err() & co, are introduced.

Also, the device numbers in some messages are dropped, as they are
shown in the prefix automatically.

Signed-off-by: Takashi Iwai <tiwai@suse.de>

Conflicts:
	sound/usb/pcm.c

ALSA: usb-audio: work around KEF X300A firmware bug

When the driver tries to access Function Unit 10, the KEF X300A
speakers' firmware apparently locks up, making even PCM streaming
impossible.  Work around this by ignoring this FU.

Cc: <stable@vger.kernel.org>
Signed-off-by: Clemens Ladisch <clemens@ladisch.de>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: Add Audio Advantage Micro II

This patch is adding extensive support (beside standard usb audio class)
for Audio Advantage Micro II usb sound card.
Features included:
- Access to AES bits (so now sending the IEC61937 compliant stream is
possible).
- Mixer SPDIF control added to turn on/off the optical transmitter.

Signed-off-by: Przemek Rudy <prudy1@o2.pl>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: proc: use found syncmaxsize to determine feedback format

freqshift is only set for the data endpoint and syncmaxsize is only set
for the sync endpoint. This results in a syncmaxsize of zero used in the
proc output feedback format calculation, which gives a feedback format
incorrectly shown as 8.16 for UAC2 devices.

As neither the data nor the sync endpoint gives all the relevant
content, output the two combined.

Also remove the sync_endpoint "packet size" which is always zero
and the sync_endpoint "momentary freq" which is constant.

Tested with UAC2 async and UAC1 adaptive, not tested with UAC1 async.

Reported-by: B. Zhang <bb.zhang@free.fr>
Signed-off-by: Torstein Hegge <hegge@resisty.net>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: add support for many Roland/Yamaha devices

Add quirks to detect the various vendor-specific descriptors used by
Roland and Yamaha in most of their recent USB audio and MIDI devices.

Together with the previous patch, this should add audio/MIDI support for
the following USB devices:
- Edirol motion dive .tokyo performance package
- Roland MC-808 Synthesizer
- Roland BK-7m Synthesizer
- Roland VIMA JM-5/8 Synthesizer
- Roland SP-555 Sequencer
- Roland V-Synth GT Synthesizer
- Roland Music Atelier AT-75/100/300/350C/500/800/900/900C Organ
- Edirol V-Mixer M-200i/300/380/400/480/R-1000
- BOSS GT-10B Effects Processor
- Roland Fantom G6/G7/G8 Keyboard
- Cakewalk Sonar V-Studio 20/100/700 Audio Interface
- Roland GW-8 Keyboard
- Roland AX-Synth Keyboard
- Roland JUNO-Di/STAGE/Gi Keyboard
- Roland VB-99 Effects Processor
- Cakewalk UM-2G MIDI Interface
- Roland A-500S Keyboard
- Roland SD-50 Synthesizer
- Roland OCTAPAD SPD-30 Controller
- Roland Lucina AX-09 Synthesizer
- BOSS BR-800 Digital Recorder
- Roland DUO/TRI-CAPTURE (EX) Audio Interface
- BOSS RC-300 Loop Station
- Roland JUPITER-50/80 Keyboard
- Roland R-26 Recorder
- Roland SPD-SX Controller
- BOSS JS-10 Audio Player
- Roland TD-11/15/30 Drum Module
- Roland A-49/88 Keyboard
- Roland INTEGRA-7 Synthesizer
- Roland R-88 Recorder

Signed-off-by: Clemens Ladisch <clemens@ladisch.de>

ALSA: usb-audio: claim autodetected PCM interfaces all at once

snd_card_register() registers all devices newly added since the last
call.  However, the playback/capture streams are handled as one ALSA
device, so the second /dev device will not be registered if the PCM
streams are added in two steps.

QUIRK_AUTODETECT caused the probe callback to be called once for each
interface, which triggered this problem.  Work around this by handling
this like the composite quirk, i.e., autodetecting all other interfaces
that might be used for PCM or MIDI.

Signed-off-by: Clemens Ladisch <clemens@ladisch.de>

ALSA: usb-audio: fix automatic Roland/Yamaha MIDI detection

Commit aafe77cc45a5 (ALSA: usb-audio: add support for many Roland/Yamaha
devices) had several logic errors that prevented create_auto_midi_quirk
from enumerating any MIDI ports.

Reported-by: Keith A. Milner <maillist@superlative.org>
Signed-off-by: Clemens Ladisch <clemens@ladisch.de>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: snd-usb: handle the bmFormats field as unsigned int

This field may use up to 32 bits, so it should be handled as unsigned
int.

Signed-off-by: Daniel Mack <zonque@gmail.com>
Reported-by: Andreas Koch <andreas@akdesigninc.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: snd-usb: mixer: coding style fixups

Shorten some over-long lines, multi-line comments, spurious whitespaces,
curly brakets etc.  No functional change.

Signed-off-by: Daniel Mack <zonque@gmail.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: snd-usb: mixer: remove error messages on failed kmalloc()

If kmalloc() fails, warnings will be loud enough. We can safely just
return -ENOMEM in such cases.

Signed-off-by: Daniel Mack <zonque@gmail.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: improve dmesg source grepability

This improves messages from commit 80acefff3bc7bd53d46c16c683ab66c0ece20810.

Cc: Alexey Fisher <bug-track@fisher-privat.net>
Signed-off-by: Michał Mirosław <mirq-linux@rere.qmqm.pl>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: Respond to suspend and resume callbacks for MIDI input

sound/usb/card.c registers USB suspend and resume but did not previously
kill the input URBs. This means that USB MIDI devices left open across
suspend/resume had non-functional input (output still usually worked,
but it looks like that is another issue). Before this change, we would
get ESHUTDOWN for each of the input URBs at suspend time, killing input.

Signed-off-by: Adam Goode <agoode@google.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb: use multiple packets per urb for Wireless USB inbound audio

For Wireless USB audio devices, use multiple isoc packets per URB for
inbound endpoints with a datainterval < 5.  This allows the WUSB host
controller to take advantage of bursting to service endpoints whose
logical polling interval is less than the 4ms minimum polling interval
limit in WUSB.

Signed-off-by: Thomas Pugliese <thomas.pugliese@gmail.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: Whitespace cleanups for sound/usb/midi.*

Signed-off-by: Adam Goode <agoode@google.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: Adjust Gamecom 780 volume level

Original patch fixed the original problem, but the sound was far too low
for most users. This patch references a compare matrix to allow the
volume levels to act normally. I personally tested this patch myself,
and volume levels returned to normal. Please see this discussion for
more details: https://bugzilla.kernel.org/show_bug.cgi?id=65251

Signed-off-by: Paul S McSpadden <fisch602@gmail.com>
Cc: <stable@vger.kernel.org> [v3.14+]
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: Use SNDRV_DEV_CODEC for mixer objects

Instead of SNDRV_DEV_LOWLEVEL, use SNDRV_DEV_CODEC type for mixer
objects so that they are managed in a proper release order.
No functional change at this point.

Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: usb-audio: Fix format string mismatch in mixer.c

Fix format string mismatch in parse_audio_selector_unit().

Signed-off-by: Masanari Iida <standby24x7@gmail.com>
Signed-off-by: Takashi Iwai <tiwai@suse.de>

ALSA: ua101: Fix unlocked snd_pcm_stop() call

snd_pcm_stop() must be called in the PCM substream lock context.

Change-Id: I0a1305936cb22245fc9f391b2d933ee2cbd8001c
Cc: <stable@vger.kernel.org>
Acked-by: Clemens Ladisch <clemens@ladisch.de>
Signed-off-by: Takashi Iwai <tiwai@suse.de>