This project is mirrored from Pull mirroring updated .
  1. 23 Nov, 2020 7 commits
    • Takashi Iwai's avatar
      ALSA: usb-audio: Refactor endpoint management · bf6313a0
      Takashi Iwai authored
      This is an intensive surgery for the endpoint and stream management
      for achieving more robust and clean code.
      The goals of this patch are:
      - More clear endpoint resource changes
      - The interface altsetting control in a single place
      Below are brief description of the whole changes.
      First off, most of the endpoint operations are moved into endpoint.c,
      so that the snd_usb_endpoint object is only referred in other places.
      The endpoint object is acquired and released via the new functions
      snd_usb_endpoint_open() and snd_usb_endpoint_close() that are called
      at PCM hw_params and hw_free callbacks, respectively.  Those are
      ref-counted and EPs can manage the multiple opens.
      The open callback receives the audioformat and hw_params arguments,
      and those are used for initializing the EP parameters; especially the
      endpoint, interface and altset numbers are read from there, as well as
      the PCM parameters like the format, rate and channels.  Those are
      stored in snd_usb_endpoint object.  If it's the secondary open, the
      function checks whether the given parameters are compatible with the
      already opened EP setup, too.
      The coupling with a sync EP (including an implicit feedback sync) is
      done by the sole snd_usb_endpoint_set_sync() call.
      The configuration of each endpoint is done in a single shot via
      snd_usb_endpoint_configure() call.  This is the place where most of
      PCM configurations are done.  A few flags and special handling in the
      snd_usb_substream are dropped along with this change.
      A significant difference wrt the configuration from the previous code
      is the order of USB host interface setups.  Now the interface is
      always disabled at beginning and (re-)enabled at the last step of
      snd_usb_endpoint_configure(), in order to be compliant with the
      standard UAC2/3.  For UAC1, the interface is set before the parameter
      setups since there seem devices that require it (e.g. Yamaha THR10),
      just like how it was done in the previous driver code.
      The start/stop are almost same as before, also single-shots.  The URB
      callbacks need to be set via snd_usb_endpoint_set_callback() like the
      previous code at the trigger phase, too.
      Finally, the flag for the re-setup is set at the device suspend
      through the full EP list, instead of PCM trigger.  This catches the
      overlooked cases where the PCM hasn't been running yet but the device
      needs the full setup after resume.
      Tested-by: default avatarKeith Milner <>
      Tested-by: default avatarDylan Robinson <>
      Signed-off-by: default avatarTakashi Iwai <>
    • Takashi Iwai's avatar
      ALSA: usb-audio: Set callbacks via snd_usb_endpoint_set_callback() · 96e221f3
      Takashi Iwai authored
      The prepare_data_urb and retire_data_urb fields of the endpoint object
      are set dynamically at PCM trigger start/stop.  Those are evaluated in
      the endpoint handler, but there can be a race, especially if two
      different PCM substreams are handling the same endpoint for the
      implicit feedback case.  Also, the data_subs field of the endpoint is
      set and accessed dynamically, too, which has the same risk.
      As a slight improvement for the concurrency, this patch introduces the
      function to set the callbacks and the data in a shot with the memory
      barrier.  In the reader side, it's also fetched with the memory
      There is still a room of race if prepare and retire callbacks are set
      during executing the URB completion.  But such an inconsistency may
      happen only for the implicit fb source, i.e. it's only about the
      capture stream.  And luckily, the capture stream never sets the
      prepare callback, hence the problem doesn't happen practically.
      Tested-by: default avatarKeith Milner <>
      Tested-by: default avatarDylan Robinson <>
      Signed-off-by: default avatarTakashi Iwai <>
    • Takashi Iwai's avatar
      ALSA: usb-audio: Stop both endpoints properly at error · 57234bc1
      Takashi Iwai authored
      start_endpoints() may leave the data endpoint running if an error
      happens at starting the sync endpoint.  We should stop both streams
      properly, instead.
      While we're at it, move the debug prints into the endpoint.c that is a
      more suitable place.
      Tested-by: default avatarKeith Milner <>
      Tested-by: default avatarDylan Robinson <>
      Signed-off-by: default avatarTakashi Iwai <>
    • Takashi Iwai's avatar
      ALSA: usb-audio: Create endpoint objects at parsing phase · 54cb3190
      Takashi Iwai authored
      Currently snd_usb_endpoint objects are created at first when the
      substream is opened and tries to assign the endpoints corresponding to
      the matching audioformat.  But since basically the all endpoints have
      been already parsed and the information have been obtained, we may
      create the endpoint objects statically at the init phase.  It's easier
      to manage for the implicit fb case, for example.
      This patch changes the endpoint object management and lets the parser
      to create the all endpoint objects.
      This change shouldn't bring any functional changes.
      Tested-by: default avatarKeith Milner <>
      Tested-by: default avatarDylan Robinson <>
      Signed-off-by: default avatarTakashi Iwai <>
    • Takashi Iwai's avatar
      ALSA: usb-audio: Add hw constraint for implicit fb sync · 5a6c3e11
      Takashi Iwai authored
      In the current code, there is no check at the stream open time whether
      the endpoint is being already used by others.  In the normal
      operations, this shouldn't happen, but in the case of the implicit
      feedback mode, it's a common problem with the full duplex operation,
      because the capture stream is always opened by the playback stream as
      an implicit sync source.
      Although we recently introduced the check of such a conflict of
      parameters at the PCM hw_params time, it doesn't give any hint at the
      hw_params itself and just gives the error.  This isn't quite
      comfortable, and it caused problems on many applications.
      This patch attempts to make the parameter handling easier by
      introducing the strict hw constraint matching with the counterpart
      stream that is being used.  That said, when an implicit feedback
      playback stream is running before a capture stream is opened, the
      capture stream carries the PCM hw-constraint to allow only the same
      sample rate, format, periods and period frames as the running playback
      stream.  If not opened or there is no conflict of endpoints, the
      behavior remains as same as before.
      Note that this kind of "weak link" should work for most cases, but
      this is no concrete solution; e.g. if an application changes the hw
      params multiple times while another stream is opened, this would lead
      to inconsistencies.
      Tested-by: default avatarKeith Milner <>
      Tested-by: default avatarDylan Robinson <>
      Signed-off-by: default avatarTakashi Iwai <>
    • Takashi Iwai's avatar
      ALSA: usb-audio: Improve some debug prints · e93e890e
      Takashi Iwai authored
      There are a few rooms for improvements wrt the debug prints:
      - The EP debug print is shown only at starting, not at stopping
      - The EP debug print contains useless object addresses
      - Some helpers show the urb and the EP object addresses, too
      This patch addresses those shortcomings.
      Tested-by: default avatarKeith Milner <>
      Tested-by: default avatarDylan Robinson <>
      Signed-off-by: default avatarTakashi Iwai <>
    • Takashi Iwai's avatar
      ALSA: usb-audio: Add snd_usb_get_endpoint() helper · c7474d09
      Takashi Iwai authored
      Factor out the code to obtain snd_usb_endpoint object matching with
      the given endpoint.  It'll be used in the later patch to add the
      implicit feedback hw-constraint.
      No functional change by this patch itself.
      Tested-by: default avatarKeith Milner <>
      Tested-by: default avatarDylan Robinson <>
      Signed-off-by: default avatarTakashi Iwai <>
  2. 06 Oct, 2020 1 commit
  3. 27 Jul, 2020 1 commit
  4. 16 Jul, 2020 1 commit
  5. 30 Jun, 2020 2 commits
  6. 15 May, 2020 1 commit
  7. 24 Apr, 2020 2 commits
    • Takashi Iwai's avatar
      ALSA: usb-audio: Fix racy list management in output queue · 5b6cc38f
      Takashi Iwai authored
      The linked list entry from FIFO is peeked at
      queue_pending_output_urbs() but the actual element pop-out is
      performed outside the spinlock, and it's potentially racy.
      Do delete the link at the right place inside the spinlock.
      Fixes: 8fdff6a3 ("ALSA: snd-usb: implement new endpoint streaming model")
      Signed-off-by: default avatarTakashi Iwai <>
    • Alexander Tsoy's avatar
      ALSA: usb-audio: Improve frames size computation · f0bd62b6
      Alexander Tsoy authored
      For computation of the the next frame size current value of fs/fps and
      accumulated fractional parts of fs/fps are used, where values are stored
      in Q16.16 format. This is quite natural for computing frame size for
      asynchronous endpoints driven by explicit feedback, since in this case
      fs/fps is a value provided by the feedback endpoint and it's already in
      the Q format. If an error is accumulated over time, the device can
      adjust fs/fps value to prevent buffer overruns/underruns.
      But for synchronous endpoints the accuracy provided by these computations
      is not enough. Due to accumulated error the driver periodically produces
      frames with incorrect size (+/- 1 audio sample).
      This patch fixes this issue by implementing a different algorithm for
      frame size computation. It is based on accumulating of the remainders
      from division fs/fps and it doesn't accumulate errors over time. This
      new method is enabled for synchronous and adaptive playback endpoints.
      Signed-off-by: default avatarAlexander Tsoy <>
      Signed-off-by: default avatarTakashi Iwai <>
  8. 13 Nov, 2019 1 commit
    • Henry Lin's avatar
      ALSA: usb-audio: not submit urb for stopped endpoint · 52869931
      Henry Lin authored
      While output urb's snd_complete_urb() is executing, calling
      prepare_outbound_urb() may cause endpoint stopped before
      prepare_outbound_urb() returns and result in next urb submitted
      to stopped endpoint. usb-audio driver cannot re-use it afterwards as
      the urb is still hold by usb stack.
      This change checks EP_FLAG_RUNNING flag after prepare_outbound_urb() again
      to let snd_complete_urb() know the endpoint already stopped and does not
      submit next urb. Below kind of error will be fixed:
      [  213.153103] usb 1-2: timeout: still 1 active urbs on EP #1
      [  213.164121] usb 1-2: cannot submit urb 0, error -16: unknown error
      Signed-off-by: default avatarHenry Lin <>
      Cc: <>
      Signed-off-by: default avatarTakashi Iwai <>
  9. 30 May, 2019 1 commit
  10. 01 Aug, 2018 1 commit
  11. 05 Jan, 2017 2 commits
    • Ioan-Adrian Ratiu's avatar
      ALSA: usb-audio: test EP_FLAG_RUNNING at urb completion · 13a6c832
      Ioan-Adrian Ratiu authored
      Testing EP_FLAG_RUNNING in snd_complete_urb() before running the completion
      logic allows us to save a few cpu cycles by returning early, skipping the
      pending urb in case the stream was stopped; the stop logic handles the urb
      and sets the completion callbacks to NULL.
      Signed-off-by: default avatarIoan-Adrian Ratiu <>
      Signed-off-by: default avatarTakashi Iwai <>
    • Ioan-Adrian Ratiu's avatar
      ALSA: usb-audio: Fix irq/process data synchronization · 1d0f9530
      Ioan-Adrian Ratiu authored
      Commit 16200948 ("ALSA: usb-audio: Fix race at stopping the stream") was
      incomplete causing another more severe kernel panic, so it got reverted.
      This fixes both the original problem and its fallout kernel race/crash.
      The original fix is to move the endpoint member NULL clearing logic inside
      wait_clear_urbs() so the irq triggering the urb completion doesn't call
      retire_capture/playback_urb() after the NULL clearing and generate a panic.
      However this creates a new race between snd_usb_endpoint_start()'s call
      to wait_clear_urbs() and the irq urb completion handler which again calls
      retire_capture/playback_urb() leading to a new NULL dereference.
      We keep the EP deactivation code in snd_usb_endpoint_start() because
      removing it will break the EP reference counting (see [1] [2] for info),
      however we don't need the "can_sleep" mechanism anymore because a new
      function was introduced (snd_usb_endpoint_sync_pending_stop()) which
      synchronizes pending stops and gets called inside the pcm prepare callback.
      It also makes sense to remove can_sleep because it was also removed from
      deactivate_urbs() signature in [3] so we benefit from more simplification.
      [1] commit 015618b9 ("ALSA: snd-usb: Fix URB cancellation at stream start")
      [2] commit e9ba389c ("ALSA: usb-audio: Fix scheduling-while-atomic bug in PCM capture stream")
      [3] commit ccc1696d ("ALSA: usb-audio: simplify endpoint deactivation code")
      Fixes: f8114f85
       ("Revert "ALSA: usb-audio: Fix race at stopping the stream"")
      Signed-off-by: default avatarIoan-Adrian Ratiu <>
      Signed-off-by: default avatarTakashi Iwai <>
  12. 21 Dec, 2016 1 commit
  13. 12 Dec, 2016 1 commit
    • Nobutaka Okabe's avatar
      ALSA: usb-audio: Eliminate noise at the start of DSD playback. · 01200730
      Nobutaka Okabe authored
      In some USB DACs, a terrible pop noise comes to be heard
      at the start of DSD playback (in the following situations).
      - play first DSD track
      - change from PCM track to DSD track
      - change from DSD64 track to DSD128 track (and etc...)
      - seek DSD track
      - Fast-Forward/Rewind DSD track
      At the start of playback, there is a little silence.
      The silence bit pattern "0x69" is required on DSD mode,
      but it is not like that.
      This patch adds DSD silence pattern to the endpoint settings.
      Signed-off-by: default avatarNobutaka Okabe <>
      Signed-off-by: default avatarTakashi Iwai <>
  14. 06 Dec, 2016 1 commit
  15. 05 Dec, 2016 1 commit
    • Takashi Iwai's avatar
      ALSA: usb-audio: Fix race at stopping the stream · 16200948
      Takashi Iwai authored
      We've got a kernel crash report showing like:
        Unable to handle kernel NULL pointer dereference at virtual address 00000008 pgd = a1d7c000
        [00000008] *pgd=31c93831, *pte=00000000, *ppte=00000000
        Internal error: Oops: 17 [#1] PREEMPT SMP ARM
        CPU: 0 PID: 250 Comm: dbus-daemon Not tainted 3.14.51-03479-gf50bdf4 #1
        task: a3ae61c0 ti: a08c8000 task.ti: a08c8000
        PC is at retire_capture_urb+0x10/0x1f4 [snd_usb_audio]
        LR is at snd_complete_urb+0x140/0x1f0 [snd_usb_audio]
        pc : [<7f0eb22c>]    lr : [<7f0e57fc>]    psr: 200e0193
        sp : a08c9c98  ip : a08c9ce8  fp : a08c9ce4
        r10: 0000000a  r9 : 00000102  r8 : 94cb3000
        r7 : 94cb3000  r6 : 94d0f000  r5 : 94d0e8e8  r4 : 94d0e000
        r3 : 7f0eb21c  r2 : 00000000  r1 : 94cb3000  r0 : 00000000
        Flags: nzCv  IRQs off  FIQs on  Mode SVC_32  ISA ARM  Segment user
        Control: 10c5387d  Table: 31d7c04a  DAC: 00000015
        Process dbus-daemon (pid: 250, stack limit = 0xa08c8238)
        Stack: (0xa08c9c98 to 0xa08ca000)
        [<7f0eb21c>] (retire_capture_urb [snd_usb_audio]) from [<7f0e57fc>] (snd_complete_urb+0x140/0x1f0 [snd_usb_audio])
        [<7f0e56bc>] (snd_complete_urb [snd_usb_audio]) from [<80371118>] (__usb_hcd_giveback_urb+0x78/0xf4)
        [<803710a0>] (__usb_hcd_giveback_urb) from [<80371514>] (usb_giveback_urb_bh+0x8c/0xc0)
        [<80371488>] (usb_giveback_urb_bh) from [<80028e3c>] (tasklet_hi_action+0xc4/0x148)
        [<80028d78>] (tasklet_hi_action) from [<80028358>] (__do_softirq+0x190/0x380)
        [<800281c8>] (__do_softirq) from [<80028858>] (irq_exit+0x8c/0xfc)
        [<800287cc>] (irq_exit) from [<8000ea88>] (handle_IRQ+0x8c/0xc8)
        [<8000e9fc>] (handle_IRQ) from [<800085e8>] (gic_handle_irq+0xbc/0xf8)
        [<8000852c>] (gic_handle_irq) from [<80509044>] (__irq_svc+0x44/0x78)
        [<80508820>] (_raw_spin_unlock_irq) from [<8004b880>] (finish_task_switch+0x5c/0x100)
        [<8004b824>] (finish_task_switch) from [<805052f0>] (__schedule+0x48c/0x6d8)
        [<80504e64>] (__schedule) from [<805055d4>] (schedule+0x98/0x9c)
        [<8050553c>] (schedule) from [<800116c8>] (do_work_pending+0x30/0xd0)
        [<80011698>] (do_work_pending) from [<8000e160>] (work_pending+0xc/0x20)
        Code: e1a0c00d e92ddff0 e24cb004 e24dd024 (e5902008)
        Kernel panic - not syncing: Fatal exception in interrupt
      There is a race between retire_capture_urb() and stop_endpoints().
      The latter is called at stopping the stream and it sets some endpoint
      fields to NULL.  But its call is asynchronous, thus the pending
      complete callback might get called after these NULL clears, and it
      leads the NULL dereference like the above.
      The fix is to move the NULL clearance after the synchronization,
      i.e. wait_clear_urbs().  This is called at prepare and hw_free
      callbacks, so it's assured to be called before the restart of the
      stream or the release of the stream.
      Also, while we're at it, put the EP_FLAG_RUNNING flag check at the
      beginning of snd_complete_urb() to skip the pending complete after the
      stream is stopped.
      Fixes: b2eb950d
       ("ALSA: usb-audio: stop both data and sync...")
      Reported-by: default avatarJiada Wang <>
      Reported-by: default avatarMark Craske <>
      Cc: <>
      Signed-off-by: default avatarTakashi Iwai <>
  16. 22 Aug, 2016 3 commits
  17. 16 Mar, 2016 1 commit
  18. 19 Oct, 2015 3 commits
    • Ricard Wanderlof's avatar
      ALSA: USB-audio: Adjust max packet size calculation for tx_length_quirk · 759c90fe
      Ricard Wanderlof authored
      For the Zoom R16/24 (tx_length_quirk set), when calculating the maximum
      sample frequency, consideration must be made for the fact that four bytes
      of the packet contain a length descriptor and consequently must not be
      counted as part of the audio data.
      This is corroborated by the wMaxPacketSize for this device, which is 108
      bytes according for the USB playback endpoint descriptor. The frame size
      is 8 bytes (2 channels of 4 bytes each), and the 108 bytes thus work out
      as 13 * 8 + 4, i.e. corresponding to 13 frames plus the additional 4 byte
      length descriptor.
      Signed-off-by: default avatarRicard Wanderlof <>
      Signed-off-by: default avatarTakashi Iwai <>
    • Ricard Wanderlof's avatar
      ALSA: USB-audio: Add quirk for Zoom R16/24 playback · e0570446
      Ricard Wanderlof authored
      The Zoom R16/24 have a nonstandard playback format where each isochronous
      packet contains a length descriptor in the first four bytes. (Curiously,
      capture data does not contain this and requires no quirk.)
      The quirk involves adding the extra length descriptor whenever outgoing
      isochronous packets are generated, both in pcm.c (outgoing audio) and
      endpoint.c (silent data).
      In order to make the quirk as unintrusive as possible, for
      pcm.c:prepare_playback_urb(), the isochronous packet descriptors are
      initially set up in the same way no matter if the quirk is enabled or not.
      Once it is time to actually copy the data into the outgoing packet buffer
      (together with the added length descriptors) the isochronous descriptors
      are adjusted in order take the increased payload length into account.
      For endpoint.c:prepare_silent_urb() it makes more sense to modify the
      actual function, partly because the function is less complex to start with
      and partly because it is not as time-critical as prepare_playback_urb()
      (whose bulk is run with interrupts disabled), so the (minute) additional
      time spent in the non-quirk case is motivated by the simplicity of having
      a single function for all cases.
      The quirk is controlled by the new tx_length_quirk member in struct
      snd_usb_substream and struct snd_usb_audio, which is conveyed to pcm.c
      and endpoint.c from quirks.c in a similar manner to the txfr_quirk member
      in the same structs.
      In contrast to txfr_quirk however, the quirk is enabled directly in
      quirks.c:create_standard_audio_quirk() by checking the USB ID in that
      function. Another option would be to introduce a new
      QUIRK_AUDIO_ZOOM_INTERFACE or somesuch, which would have made the quirk
      very plain to see in the quirk table, but it was felt that the additional
      code needed to implement it this way would just make the implementation
      more complex with no real gain.
      Tested with a Zoom R16, both by doing capture and playback separately
      using arecord and aplay (8 channel capture and 2 channel playback,
      respectively), as well as capture and playback together using Ardour, as
      well as Audacity and Qtractor together with jackd.
      The R24 is reportedly compatible with the R16 when used as an audio
      interface. Both devices share the same USB ID and have the same number of
      inputs (8) and outputs (2). Therefore "R16/24" is mentioned throughout the
      Regression tested using an Edirol UA-5 in both class compliant (16-bit)
      and "advanced" (24 bit, forces the use of quirks) modes.
      Signed-off-by: default avatarRicard Wanderlof <>
      Tested-by: default avatarPanu Matilainen <>
      Signed-off-by: default avatarTakashi Iwai <>
    • Ricard Wanderlof's avatar
      ALSA: USB-audio: Break out creation of silent urbs from prepare_outbound_urb() · 5cf310e9
      Ricard Wanderlof authored
      Refactoring in preparation for adding Zoom R16/24 quirk.
      No functional change.
      Signed-off-by: default avatarRicard Wanderlof <>
      Signed-off-by: default avatarTakashi Iwai <>
  19. 13 Oct, 2015 1 commit
    • Ricard Wanderlof's avatar
      ALSA: usb-audio: Fix max packet size calculation for USB audio · ab30965d
      Ricard Wanderlof authored
      Rounding must take place before multiplication with the frame size, since
      each packet contains a whole number of frames.
      We must also properly consider the data interval, as a larger data
      interval will result in larger packets, which, depending on the sampling
      frequency, can result in packet sizes that are less than integral
      multiples of the packet size for a lower data interval.
      Detailed explanation and rationale:
      The code before this commit had the following expression on line 613 to
      calculate the maximum isochronous packet size:
      	maxsize = ((ep->freqmax + 0xffff) * (frame_bits >> 3))
      			>> (16 - ep->datainterval);
      Here, ep->freqmax is the maximum assumed sample frequency, calculated from the
      nominal sample frequency plus 25%. It is ultimately derived from ep->freqn,
      which is in the units of frames per packet, from get_usb_full_speed_rate()
      or usb_high_speed_rate(), as applicable, in Q16.16 format.
      The expression essentially adds the Q16.16 equivalent of 0.999... (i.e.
      the largest number less than one) to the sample rate, in order to get a
      rate whose integer part is rounded up from the fractional value. The
      multiplication with (frame_bits >> 3) yields the number of bytes in a
      packet, and the (16 >> ep->datainterval) then converts it from Q16.16 back
      to an integer, taking into consideration the bDataInterval field of the
      endpoint descriptor (which describes how often isochronous packets are
      transmitted relative to the (micro)frame rate (125us or 1ms, for USB high
      speed and full speed, respectively)). For this discussion we will initially
      assume a bDataInterval of 0, so the second line of the expression just
      converts the Q16.16 value to an integer.
      In order to illustrate the problem, we will set frame_bits 64, which
      corresponds to a frame size of 8 bytes.
      The problem here is twofold. First, the rounding operation consists
      of the addition of 0x0.ffff and subsequent conversion to integer, but as the
      expression stands, the conversion to integer is done after multiplication
      with the frame size, rather than before. This results in the resulting
      maxsize becoming too large.
      Let's take an example. We have a sample rate of 96 kHz, so our ep->freqn is
      0xc0000 (see usb_high_speed_rate()). Add 25% (line 612) and we get 0xf0000.
      The calculated maxsize is then ((0xf0000 + 0x0ffff) * 8) >> 16 = 127 .
      However, if we do the number of bytes calculation in a less obscure way it's
      more apparent what the true corresponding packet size is: we get
      ceil(96000 * 1.25 / 8000) * 8 = 120, where 1.25 is the 25% from line 612,
      and the 8000 is the number of isochronous packets per second on a high
      speed USB connection (125 us microframe interval).
      This is fixed by performing the complete rounding operation prior to
      multiplication with the frame rate.
      The second problem is that when considering the ep->datainterval, this
      must be done before rounding, in order to take the advantage of the fact
      that if the number of bytes per packet is not an integer, the resulting
      rounded-up integer is not necessarily a factor of two when the data
      interval is increased by the same factor.
      For instance, assuming a freqency of 41 kHz, the resulting
      bytes-per-packet value for USB high speed is 41 kHz / 8000 = 5.125, or
      0x52000 in Q16.16 format. With a data interval of 1 (ep->datainterval = 0),
      this means that 6 frames per packet are needed, whereas with a data
      interval of 2 we need 10.25, i.e. 11 frames needed.
      Rephrasing the maxsize expression to:
      	maxsize = (((ep->freqmax << ep->datainterval) + 0xffff) >> 16) *
      			 (frame_bits >> 3);
      for the above 96 kHz example we instead get
      ((0xf0000 + 0xffff) >> 16) * 8 = 120 which is the correct value.
      We can also do the calculation with a non-integer sample rate which is when
      rounding comes into effect: say we have 44.1 kHz (resulting ep->freqn =
      0x58333, and resulting ep->freqmax 0x58333 * 1.25 = 0x6e3ff (rounded down)):
      Original maxsize = ((0x6e3ff + 0xffff) * 8) << 16 = 63 (63.124.. rounded down)
      True maxsize = ceil(44100 * 1.25 / 8000) * 8 = 7 * 8 = 56
      New maxsize = ((0x6e3ff + 0xffff) >> 16) * 8 = 7 * 8 = 56
      This is also corroborated by the wMaxPacketSize check on line 616. Assume
      that wMaxPacketSize = 104, with ep->maxpacksize then having the same value.
      As 104 < 127, we get maxsize = 104. ep->freqmax is then recalculated to
      (104 / 8) << 16 = 0xd0000 . Putting that rate into the original maxsize
      calculation yields a maxsize of ((0xd0000 + 0xffff) * 8) >> 16 = 111
      (with decimals 111.99988). Clearly, we should get back the 104 here,
      which we would with the new expression: ((0xd0000 + 0xffff) >> 16) * 8 = 104 .
      (The error has not been a problem because it only results in maxsize being
      a bit too big which just wastes a couple of bytes, either as a result of
      the first maxsize calculation, or because the resulting calculation will
      hit the wMaxPacketSize value before the packet is too big, resulting in
      fixing the size to wMaxPacketSize even though the packet is actually not
      too long.)
      Tested with an Edirol UA-5 both at 44.1 kHz and 96 kHz.
      Signed-off-by: default avatarRicard Wanderlof <>
      Signed-off-by: default avatarTakashi Iwai <>
  20. 26 Aug, 2015 1 commit
    • Takashi Iwai's avatar
      ALSA: usb-audio: Avoid nested autoresume calls · 47ab1545
      Takashi Iwai authored
      After the recent fix of runtime PM for USB-audio driver, we got a
      lockdep warning like:
        [ INFO: possible recursive locking detected ]
        4.2.0-rc8+ #61 Not tainted
        pulseaudio/980 is trying to acquire lock:
         (&chip->shutdown_rwsem){.+.+.+}, at: [<ffffffffa0355dac>] snd_usb_autoresume+0x1d/0x52 [snd_usb_audio]
        but task is already holding lock:
         (&chip->shutdown_rwsem){.+.+.+}, at: [<ffffffffa0355dac>] snd_usb_autoresume+0x1d/0x52 [snd_usb_audio]
      This comes from snd_usb_autoresume() invoking down_read() and it's
      used in a nested way.  Although it's basically safe, per se (as these
      are read locks), it's better to reduce such spurious warnings.
      The read lock is needed to guarantee the execution of "shutdown"
      (cleanup at disconnection) task after all concurrent tasks are
      finished.  This can be implemented in another better way.
      Also, the current check of chip->in_pm isn't good enough for
      protecting the racy execution of multiple auto-resumes.
      This patch rewrites the logic of snd_usb_autoresume() & co; namely,
      - The recursive call of autopm is avoided by the new refcount,
        chip->active.  The chip->in_pm flag is removed accordingly.
      - Instead of rwsem, another refcount, chip->usage_count, is introduced
        for tracking the period to delay the shutdown procedure.  At
        the last clear of this refcount, wake_up() to the shutdown waiter is
      - The shutdown flag is replaced with shutdown atomic count; this is
        for reducing the lock.
      - Two new helpers are introduced to simplify the management of these
        refcounts; snd_usb_lock_shutdown() increases the usage_count, checks
        the shutdown state, and does autoresume.  snd_usb_unlock_shutdown()
        does the opposite.  Most of mixer and other codes just need this,
        and simply returns an error if it receives an error from lock.
      Fixes: 9003ebb1
       ('ALSA: usb-audio: Fix runtime PM unbalance')
      Reported-and-tested-by: default avatarAlexnader Kuleshov <>
      Signed-off-by: default avatarTakashi Iwai <>
  21. 09 Nov, 2014 1 commit
    • Takashi Iwai's avatar
      ALSA: pcm: Add snd_pcm_stop_xrun() helper · 1fb8510c
      Takashi Iwai authored
      Add a new helper function snd_pcm_stop_xrun() to the standard sequnce
      lock/snd_pcm_stop(XRUN)/unlock by a single call, and replace the
      existing open codes with this helper.
      The function checks the PCM running state to prevent setting the wrong
      state, too, for more safety.
      Signed-off-by: default avatarTakashi Iwai <>
  22. 06 Nov, 2014 1 commit
    • Takashi Iwai's avatar
      ALSA: usb-audio: Trigger PCM XRUN at XRUN · 67e22500
      Takashi Iwai authored
      The usb-audio driver detects XRUN at its complete callback, but the
      actual code to trigger PCM XRUN is commented out because it caused
      deadlock in the past.  This patch revives the PCM trigger properly.
      It resulted in more than just enabling snd_pcm_stop(), but it had to
      deduce the PCM substream with proper NULL checks and holds the stream
      lock around the call.
      Signed-off-by: default avatarTakashi Iwai <>
  23. 04 Nov, 2014 1 commit
  24. 26 Jun, 2014 1 commit
    • Takashi Iwai's avatar
      ALSA: usb-audio: Fix races at disconnection and PCM closing · 92a586bd
      Takashi Iwai authored
      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: default avatarAlan Stern <>
      Cc: <>
      Signed-off-by: default avatarTakashi Iwai <>
  25. 02 May, 2014 1 commit
  26. 26 Feb, 2014 1 commit
    • Takashi Iwai's avatar
      ALSA: usb-audio: Use standard printk helpers · 0ba41d91
      Takashi Iwai authored
      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: default avatarTakashi Iwai <>
  27. 27 Nov, 2013 1 commit