summaryrefslogtreecommitdiff
path: root/sound/core/pcm_lib.c
AgeCommit message (Collapse)Author
2023-11-27ALSA: hda: Upgrade stream-format infrastructureCezary Rojewski
Introduce a set of functions that ultimately facilite SDxFMT-related calculations in atomic manner: First, introduce snd_pcm_subformat_width() and snd_pcm_hw_params_bits() helpers that separate the base functionality from the HDAudio-specific one. snd_hdac_format_normalize() - format converter. S20_LE, S24_LE and their unsigned and BE friends are invalid from HDAudio perspective but still can be specified as function argument due to compatibility reasons. snd_hdac_stream_format_bits() - obtain just the bits-per-sample value. Does not ignore subformat and msbits parameters. snd_hdac_stream_format() and snd_hdac_spdif_stream_format() - obtain the SDxFMT value given the audio format parameters. The former is stripped away of spdif-related information. Useful for users that do not care about them. Acked-by: Mark Brown <broonie@kernel.org> Signed-off-by: Cezary Rojewski <cezary.rojewski@intel.com> Acked-by: Jaroslav Kysela <perex@perex.cz> Link: https://lore.kernel.org/r/20231117120610.1755254-5-cezary.rojewski@intel.com Signed-off-by: Takashi Iwai <tiwai@suse.de>
2023-09-02ALSA: pcm: Fix error checks of default read/write copy opsTakashi Iwai
copy_from/to_iter() returns the actually copied bytes, and the more correct check should be to compare with the given bytes, instead of zero-check. Fixes: cf393babb37a ("ALSA: pcm: Add copy ops with iov_iter") Reported-by: Al Viro <viro@zeniv.linux.org.uk> Closes: https://lore.kernel.org/r/20230902053044.GJ3390869@ZenIV Link: https://lore.kernel.org/r/20230902061044.19366-1-tiwai@suse.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2023-08-18ALSA: pcm: Drop obsoleted PCM copy_user and copy_kernel opsTakashi Iwai
Finally all users have been converted to the new PCM copy ops, let's drop the obsoleted copy_kernel and copy_user ops completely. Link: https://lore.kernel.org/r/20230815190136.8987-26-tiwai@suse.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2023-08-18ALSA: pcm: Add copy ops with iov_iterTakashi Iwai
iov_iter is a universal interface to copy the data chunk from/to user-space and kernel in a unified manner. This API can fit for ALSA PCM copy ops, too; we had to split to copy_user and copy_kernel in the past, and those can be unified to a single ops with iov_iter. This patch adds a new PCM copy ops that passes iov_iter for copying both kernel and user-space in the same way. This patch touches only the ALSA PCM core part, and the actual users will be replaced in the following patches. The expansion of iov_iter is done in the PCM core right before calling each copy callback. It's a bit suboptimal, but I took this now as it's the most straightforward replacement. The more conversion to iov_iter in the caller side is a TODO for future. As of now, the old copy_user and copy_kernel ops are still kept. Once after all users are converted, we'll drop the old copy_user and copy_kernel ops, too. Link: https://lore.kernel.org/r/20230815190136.8987-3-tiwai@suse.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2023-05-05ALSA: pcm: use exit controlled loop in snd_pcm_playback_silence()Oswald Buddenhagen
We already know that `frames` is greater than zero, because we just checked it. So we don't need to check the loop condition on the first iteration. Signed-off-by: Oswald Buddenhagen <oswald.buddenhagen@gmx.de> Link: https://lore.kernel.org/r/20230505155244.2312199-7-oswald.buddenhagen@gmx.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2023-05-05ALSA: pcm: simplify top-up mode init in snd_pcm_playback_silence()Oswald Buddenhagen
Inline the remaining call of snd_pcm_playback_hw_avail(). This makes the top-up branch more congruent with the thresholded one, and allows simplifying the handling of the corner cases. Signed-off-by: Oswald Buddenhagen <oswald.buddenhagen@gmx.de> Link: https://lore.kernel.org/r/20230505155244.2312199-6-oswald.buddenhagen@gmx.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2023-05-05ALSA: pcm: playback silence - move silence variable updates to separate functionJaroslav Kysela
The code tracking the added samples in thresholded mode and the code tracking the just played samples in top-up mode are semantically identical, so factor it out to a common function to enhance readability. Co-developed-by: Oswald Buddenhagen <oswald.buddenhagen@gmx.de> Signed-off-by: Oswald Buddenhagen <oswald.buddenhagen@gmx.de> Signed-off-by: Jaroslav Kysela <perex@perex.cz> Link: https://lore.kernel.org/r/20230505155244.2312199-5-oswald.buddenhagen@gmx.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2023-05-05ALSA: pcm: playback silence - remove extra codeJaroslav Kysela
The removed condition handles de facto only one situation where runtime->silence_filled variable is equal to runtime->buffer_size, because this variable cannot go over the buffer size. This case is implicitly caught by the required comparison of the noise distance with the threshold. Suggested-by: Oswald Buddenhagen <oswald.buddenhagen@gmx.de> Signed-off-by: Jaroslav Kysela <perex@perex.cz> Signed-off-by: Oswald Buddenhagen <oswald.buddenhagen@gmx.de> Link: https://lore.kernel.org/r/20230505155244.2312199-4-oswald.buddenhagen@gmx.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2023-05-05ALSA: pcm: fix playback silence - correct incremental silencingJaroslav Kysela
Commit 9a826ddba6e ("[ALSA] pcm core: fix silence_start calculations") came with exactly the right commit message, but the patch just made things broken in a different way: We'd fill at a too low address if the area was already partially zeroed, so we'd under-fill. This affected both thresholded mode (where it was somewhat less likely) and top-up mode (where it would be the case consistently). Co-developed-by: Oswald Buddenhagen <oswald.buddenhagen@gmx.de> Signed-off-by: Oswald Buddenhagen <oswald.buddenhagen@gmx.de> Signed-off-by: Jaroslav Kysela <perex@perex.cz> Link: https://lore.kernel.org/r/20230505155244.2312199-3-oswald.buddenhagen@gmx.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2023-05-05ALSA: pcm: fix playback silence - use the actual new_hw_ptr for the ↵Jaroslav Kysela
threshold mode The snd_pcm_playback_hw_avail() function uses runtime->status->hw_ptr. Unfortunately, in case when we call this function from snd_pcm_update_hw_ptr0(), this variable contains the previous hardware pointer. Use the new_hw_ptr argument to calculate hw_avail (filled samples by the user space) to correct the threshold comparison. The new_hw_ptr argument may also be set to ULONG_MAX which means the initialization phase. In this case, use runtime->status->hw_ptr. Suggested-by: Oswald Buddenhagen <oswald.buddenhagen@gmx.de> Signed-off-by: Jaroslav Kysela <perex@perex.cz> Reviewed-by: Oswald Buddenhagen <oswald.buddenhagen@gmx.de> Link: https://lore.kernel.org/r/20230505155244.2312199-2-oswald.buddenhagen@gmx.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2023-05-05ALSA: pcm: Revert "ALSA: pcm: rewrite snd_pcm_playback_silence()"Jaroslav Kysela
This reverts commit 9f656705c5faa18afb26d922cfc64f9fd103c38d. There was a regression (in the top-up mode). Unfortunately, the patch provided from the author of this commit is not easy to review. Keep the updated and new comments in headers. Also add a new comment that documents the missed API constraint which led to the regression. Reported-by: Jeff Chua <jeff.chua.linux@gmail.com> Link: https://lore.kernel.org/r/CAAJw_ZsbTVd3Es373x_wTNDF7RknGhCD0r+NKUSwAO7HpLAkYA@mail.gmail.com Signed-off-by: Jaroslav Kysela <perex@perex.cz> Signed-off-by: Oswald Buddenhagen <oswald.buddenhagen@gmx.de> Link: https://lore.kernel.org/r/20230505155244.2312199-1-oswald.buddenhagen@gmx.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2023-04-21ALSA: pcm: rewrite snd_pcm_playback_silence()Oswald Buddenhagen
The auto-silencer supports two modes: "thresholded" to fill up "just enough", and "top-up" to fill up "as much as possible". The two modes used rather distinct code paths, which this patch unifies. The only remaining distinction is how much we actually want to fill. This fixes a bug in thresholded mode, where we failed to use new_hw_ptr, resulting in under-fill. Top-up mode is now more well-behaved and much easier to understand in corner cases. This also updates comments in the proximity of silencing-related data structures. Signed-off-by: Oswald Buddenhagen <oswald.buddenhagen@gmx.de> Reviewed-by: Jaroslav Kysela <perex@perex.cz> Link: https://lore.kernel.org/r/20230420113324.877164-1-oswald.buddenhagen@gmx.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2023-04-08ALSA: pcm: fix wait_time calculationsOswald Buddenhagen
... in wait_for_avail() and snd_pcm_drain(). t was calculated in seconds, so it would be pretty much always zero, to be subsequently de-facto ignored due to being max(t, 10)'d. And then it (i.e., 10) would be treated as secs, which doesn't seem right. However, fixing it to properly calculate msecs would potentially cause timeouts when using twice the period size for the default timeout (which seems reasonable to me), so instead use the buffer size plus 10 percent to be on the safe side ... but that still seems insufficient, presumably because the hardware typically needs a moment to fire up. To compensate for this, we up the minimal timeout to 100ms, which is still two orders of magnitude less than the bogus minimum. substream->wait_time was also misinterpreted as jiffies, despite being documented as being in msecs. Only the soc/sof driver sets it - to 500, which looks very much like msecs were intended. Speaking of which, shouldn't snd_pcm_drain() also use substream-> wait_time? As a drive-by, make the debug messages on timeout less confusing. Signed-off-by: Oswald Buddenhagen <oswald.buddenhagen@gmx.de> Link: https://lore.kernel.org/r/20230405201219.2197774-1-oswald.buddenhagen@gmx.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2023-03-21ALSA: usb-audio: Fix recursive locking at XRUN during syncingTakashi Iwai
The recent support of low latency playback in USB-audio driver made the snd_usb_queue_pending_output_urbs() function to be called via PCM ack ops. In the new code path, the function is performed already in the PCM stream lock. The problem is that, when an XRUN is detected, the function calls snd_pcm_xrun() to notify, but snd_pcm_xrun() is supposed to be called only outside the stream lock. As a result, it leads to a deadlock of PCM stream locking. For avoiding such a recursive locking, this patch adds an additional check to the code paths in PCM core that call the ack callback; now it checks the error code from the callback, and if it's -EPIPE, the XRUN is handled in the PCM core side gracefully. Along with it, the USB-audio driver code is changed to follow that, i.e. -EPIPE is returned instead of the explicit snd_pcm_xrun() call when the function is performed already in the stream lock. Fixes: d5f871f89e21 ("ALSA: usb-audio: Improved lowlatency playback support") Reported-and-tested-by: John Keeping <john@metanate.com> Link: https://lore.kernel.org/r/20230317195128.3911155-1-john@metanate.com Reviewed-by: Jaroslav Kysela <perex@perex.cz> Reviewed-by; Takashi Sakamoto <o-takashi@sakamocchi.jp> Link: https://lore.kernel.org/r/20230320142838.494-1-tiwai@suse.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2022-09-27ALSA: pcm: Avoid reference to status->stateTakashi Iwai
In the PCM core and driver code, there are lots place referring to the current PCM state via runtime->status->state. This patch introduced a local PCM state in runtime itself and replaces those references with runtime->state. It has improvements in two aspects: - The reduction of a indirect access leads to more code optimization - It avoids a possible (unexpected) modification of the state via mmap of the status record The status->state is updated together with runtime->state, so that user-space can still read the current state via mmap like before, too. This patch touches only the ALSA core code. The changes in each driver will follow in later patches. Reviewed-by: Jaroslav Kysela <perex@perex.cz> Link: https://lore.kernel.org/r/20220926135558.26580-2-tiwai@suse.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2022-07-29ALSA: pcm: Use deferred fasync helperTakashi Iwai
For avoiding the potential deadlock via kill_fasync() call, use the new fasync helpers to defer the invocation from timer API. Note that it's merely a workaround. Reported-by: syzbot+8285e973a41b5aa68902@syzkaller.appspotmail.com Reported-by: syzbot+669c9abf11a6a011dd09@syzkaller.appspotmail.com Link: https://lore.kernel.org/r/20220728125945.29533-4-tiwai@suse.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2022-03-30ALSA: pcm: Fix potential AB/BA lock with buffer_mutex and mmap_lockTakashi Iwai
syzbot caught a potential deadlock between the PCM runtime->buffer_mutex and the mm->mmap_lock. It was brought by the recent fix to cover the racy read/write and other ioctls, and in that commit, I overlooked a (hopefully only) corner case that may take the revert lock, namely, the OSS mmap. The OSS mmap operation exceptionally allows to re-configure the parameters inside the OSS mmap syscall, where mm->mmap_mutex is already held. Meanwhile, the copy_from/to_user calls at read/write operations also take the mm->mmap_lock internally, hence it may lead to a AB/BA deadlock. A similar problem was already seen in the past and we fixed it with a refcount (in commit b248371628aa). The former fix covered only the call paths with OSS read/write and OSS ioctls, while we need to cover the concurrent access via both ALSA and OSS APIs now. This patch addresses the problem above by replacing the buffer_mutex lock in the read/write operations with a refcount similar as we've used for OSS. The new field, runtime->buffer_accessing, keeps the number of concurrent read/write operations. Unlike the former buffer_mutex protection, this protects only around the copy_from/to_user() calls; the other codes are basically protected by the PCM stream lock. The refcount can be a negative, meaning blocked by the ioctls. If a negative value is seen, the read/write aborts with -EBUSY. In the ioctl side, OTOH, they check this refcount, too, and set to a negative value for blocking unless it's already being accessed. Reported-by: syzbot+6e5c88838328e99c7e1c@syzkaller.appspotmail.com Fixes: dca947d4d26d ("ALSA: pcm: Fix races among concurrent read/write and buffer changes") Cc: <stable@vger.kernel.org> Link: https://lore.kernel.org/r/000000000000381a0d05db622a81@google.com Link: https://lore.kernel.org/r/20220330120903.4738-1-tiwai@suse.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2022-03-22ALSA: pcm: Fix races among concurrent read/write and buffer changesTakashi Iwai
In the current PCM design, the read/write syscalls (as well as the equivalent ioctls) are allowed before the PCM stream is running, that is, at PCM PREPARED state. Meanwhile, we also allow to re-issue hw_params and hw_free ioctl calls at the PREPARED state that may change or free the buffers, too. The problem is that there is no protection against those mix-ups. This patch applies the previously introduced runtime->buffer_mutex to the read/write operations so that the concurrent hw_params or hw_free call can no longer interfere during the operation. The mutex is unlocked before scheduling, so we don't take it too long. Cc: <stable@vger.kernel.org> Reviewed-by: Jaroslav Kysela <perex@perex.cz> Link: https://lore.kernel.org/r/20220322170720.3529-3-tiwai@suse.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2021-11-24ALSA: pcm: introduce INFO_NO_REWINDS flagPierre-Louis Bossart
When the hardware can only deal with a monotonically increasing appl_ptr, this flag can be set. In case the application requests a rewind, be it with a snd_pcm_rewind() or with a direct change of a mmap'ed pointer followed by a SNDRV_PCM_IOCTL_SYNC_PTR, this patch checks if a rewind occurred and returns an error. Credits to Takashi Iwai for identifying the path with SYNC_PTR and suggesting the pointer checks. Suggested-by: Takashi Iwai <tiwai@suse.de> Reviewed-by: Takashi Iwai <tiwai@suse.de> Reviewed-by: Ranjani Sridharan <ranjani.sridharan@linux.intel.com> Reviewed-by: Kai Vehmanen <kai.vehmanen@linux.intel.com> Signed-off-by: Pierre-Louis Bossart <pierre-louis.bossart@linux.intel.com> Link: https://lore.kernel.org/r/20211119230852.206310-3-pierre-louis.bossart@linux.intel.com Signed-off-by: Mark Brown <broonie@kernel.org>
2021-11-24ALSA: pcm: unconditionally check if appl_ptr is in 0..boundary rangePierre-Louis Bossart
In some cases, the appl_ptr passed by userspace is not checked before being used. This patch adds an unconditional check and returns an error code should the appl_ptr exceed the ALSA 'boundary'. Suggested-by: Takashi Iwai <tiwai@suse.de> Reviewed-by: Takashi Iwai <tiwai@suse.de> Reviewed-by: Ranjani Sridharan <ranjani.sridharan@linux.intel.com> Reviewed-by: Kai Vehmanen <kai.vehmanen@linux.intel.com> Signed-off-by: Pierre-Louis Bossart <pierre-louis.bossart@linux.intel.com> Link: https://lore.kernel.org/r/20211119230852.206310-2-pierre-louis.bossart@linux.intel.com Signed-off-by: Mark Brown <broonie@kernel.org>
2021-10-18ALSA: memalloc: Support for non-contiguous page allocationTakashi Iwai
This patch adds the support for allocation of non-contiguous DMA pages in the common memalloc helper. It's another SG-buffer type, but unlike the existing one, this is directional and requires the explicit sync / invalidation of dirty pages on non-coherent architectures. For this enhancement, the following points are changed: - snd_dma_device stores the DMA direction. - snd_dma_device stores need_sync flag indicating whether the explicit sync is required or not. - A new variant of helper functions, snd_dma_alloc_dir_pages() and *_all() are introduced; the old snd_dma_alloc_pages() and *_all() kept as just wrappers with DMA_BIDIRECTIONAL. - A new helper snd_dma_buffer_sync() is introduced; this gets called in the appropriate places. - A new allocation type, SNDRV_DMA_TYPE_NONCONTIG, is introduced. When the driver allocates pages with this new type, and it may require the SNDRV_PCM_INFO_EXPLICIT_SYNC flag set to the PCM hardware.info for taking the full control of PCM applptr and hwptr changes (that implies disabling the mmap of control/status data). When the buffer allocation is managed by snd_pcm_set_managed_buffer(), this flag is automatically set depending on the result of dma_need_sync() internally. Otherwise, if the buffer is managed manually, the driver has to set the flag explicitly, too. The explicit sync between CPU and device for non-coherent memory is performed at the points before and after read/write transfer as well as the applptr/hwptr syncptr ioctl. In the case of mmap mode, user-space is supposed to call the syncptr ioctl with the hwptr flag to update and fetch the status at first; this corresponds to CPU-sync. Then user-space advances the applptr via syncptr ioctl again with applptr flag, and this corresponds to the device sync with flushing. Other than the DMA direction and the explicit sync, the usage of this new buffer type is almost equivalent with the existing SNDRV_DMA_TYPE_DEV_SG; you can get the page and the address via snd_sgbuf_get_page() and snd_sgbuf_get_addr(), also calculate the continuous pages via snd_sgbuf_get_chunk_size(). For those SG-page handling, the non-contig type shares the same ops with the vmalloc handler. As we do always vmap the SG pages at first, the actual address can be deduced from the vmapped address easily without iterating the SG-list. Link: https://lore.kernel.org/r/20211017074859.24112-2-tiwai@suse.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2021-08-27ALSA: pcm: fix divide error in snd_pcm_lib_ioctlZubin Mithra
Syzkaller reported a divide error in snd_pcm_lib_ioctl. fifo_size is of type snd_pcm_uframes_t(unsigned long). If frame_size is 0x100000000, the error occurs. Fixes: a9960e6a293e ("ALSA: pcm: fix fifo_size frame calculation") Signed-off-by: Zubin Mithra <zsm@chromium.org> Reviewed-by: Guenter Roeck <groeck@chromium.org> Cc: <stable@vger.kernel.org> Link: https://lore.kernel.org/r/20210827153735.789452-1-zsm@chromium.org Signed-off-by: Takashi Iwai <tiwai@suse.de>
2021-06-10ALSA: pcm: add snd_pcm_period_elapsed() variant without acquiring lock of ↵Takashi Sakamoto
PCM substream Current implementation of ALSA PCM core has a kernel API, snd_pcm_period_elapsed(), for drivers to queue event to awaken processes from waiting for available frames. The function voluntarily acquires lock of PCM substream, therefore it is not called in process context for any PCM operation since the lock is already acquired. It is convenient for packet-oriented driver, at least for drivers to audio and music unit in IEEE 1394 bus. The drivers are allowed by Linux FireWire subsystem to process isochronous packets queued till recent isochronous cycle in process context in any time. This commit adds snd_pcm_period_elapsed() variant, snd_pcm_period_elapsed_without_lock(), for drivers to queue the event in the process context. Signed-off-by: Takashi Sakamoto <o-takashi@sakamocchi.jp> Link: https://lore.kernel.org/r/20210610031733.56297-2-o-takashi@sakamocchi.jp Signed-off-by: Takashi Iwai <tiwai@suse.de>
2020-12-15ALSA: pcm: use krealloc_array()Bartosz Golaszewski
Use the helper that checks for overflows internally instead of manually calculating the size of the new array. Link: https://lkml.kernel.org/r/20201109110654.12547-4-brgl@bgdev.pl Signed-off-by: Bartosz Golaszewski <bgolaszewski@baylibre.com> Reviewed-by: Takashi Iwai <tiwai@suse.de> Cc: Alexander Shishkin <alexander.shishkin@linux.intel.com> Cc: Andy Shevchenko <andriy.shevchenko@linux.intel.com> Cc: Borislav Petkov <bp@alien8.de> Cc: Borislav Petkov <bp@suse.de> Cc: Christian Knig <christian.koenig@amd.com> Cc: Christoph Lameter <cl@linux.com> Cc: Daniel Vetter <daniel@ffwll.ch> Cc: Daniel Vetter <daniel.vetter@ffwll.ch> Cc: David Airlie <airlied@linux.ie> Cc: David Rientjes <rientjes@google.com> Cc: Gustavo Padovan <gustavo@padovan.org> Cc: James Morse <james.morse@arm.com> Cc: Jaroslav Kysela <perex@perex.cz> Cc: Jason Wang <jasowang@redhat.com> Cc: Joonsoo Kim <iamjoonsoo.kim@lge.com> Cc: Linus Walleij <linus.walleij@linaro.org> Cc: Maarten Lankhorst <maarten.lankhorst@linux.intel.com> Cc: Mauro Carvalho Chehab <mchehab@kernel.org> Cc: Maxime Ripard <mripard@kernel.org> Cc: "Michael S . Tsirkin" <mst@redhat.com> Cc: Pekka Enberg <penberg@kernel.org> Cc: Robert Richter <rric@kernel.org> Cc: Sumit Semwal <sumit.semwal@linaro.org> Cc: Takashi Iwai <tiwai@suse.com> Cc: Thomas Zimmermann <tzimmermann@suse.de> Cc: Tony Luck <tony.luck@intel.com> Cc: Vlastimil Babka <vbabka@suse.cz> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
2020-10-26ALSA: fix kernel-doc markupsMauro Carvalho Chehab
Kernel-doc markups should use this format: identifier - description There is a common comment marked, instead, with kernel-doc notation. Some identifiers have different names between their prototypes and the kernel-doc markup. Signed-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org> Acked-by: Mark Brown <broonie@kernel.org> Link: https://lore.kernel.org/r/535182d6f55d7a7de293dda9676df68f5f60afc6.1603469755.git.mchehab+huawei@kernel.org Signed-off-by: Takashi Iwai <tiwai@suse.de>
2020-05-18ALSA: pcm: fix incorrect hw_base increaseBrent Lu
There is a corner case that ALSA keeps increasing the hw_ptr but DMA already stop working/updating the position for a long time. In following log we can see the position returned from DMA driver does not move at all but the hw_ptr got increased at some point of time so snd_pcm_avail() will return a large number which seems to be a buffer underrun event from user space program point of view. The program thinks there is space in the buffer and fill more data. [ 418.510086] sound pcmC0D5p: pos 96 hw_ptr 96 appl_ptr 4096 avail 12368 [ 418.510149] sound pcmC0D5p: pos 96 hw_ptr 96 appl_ptr 6910 avail 9554 ... [ 418.681052] sound pcmC0D5p: pos 96 hw_ptr 96 appl_ptr 15102 avail 1362 [ 418.681130] sound pcmC0D5p: pos 96 hw_ptr 96 appl_ptr 16464 avail 0 [ 418.726515] sound pcmC0D5p: pos 96 hw_ptr 16464 appl_ptr 16464 avail 16368 This is because the hw_base will be increased by runtime->buffer_size frames unconditionally if the hw_ptr is not updated for over half of buffer time. As the hw_base increases, so does the hw_ptr increased by the same number. The avail value returned from snd_pcm_avail() could exceed the limit (buffer_size) easily becase the hw_ptr itself got increased by same buffer_size samples when the corner case happens. In following log, the buffer_size is 16368 samples but the avail is 21810 samples so CRAS server complains about it. [ 418.851755] sound pcmC0D5p: pos 96 hw_ptr 16464 appl_ptr 27390 avail 5442 [ 418.926491] sound pcmC0D5p: pos 96 hw_ptr 32832 appl_ptr 27390 avail 21810 cras_server[1907]: pcm_avail returned frames larger than buf_size: sof-glkda7219max: :0,5: 21810 > 16368 By updating runtime->hw_ptr_jiffies each time the HWSYNC is called, the hw_base will keep the same when buffer stall happens at long as the interval between each HWSYNC call is shorter than half of buffer time. Following is a log captured by a patched kernel. The hw_base/hw_ptr value is fixed in this corner case and user space program should be aware of the buffer stall and handle it. [ 293.525543] sound pcmC0D5p: pos 96 hw_ptr 96 appl_ptr 4096 avail 12368 [ 293.525606] sound pcmC0D5p: pos 96 hw_ptr 96 appl_ptr 6880 avail 9584 [ 293.525975] sound pcmC0D5p: pos 96 hw_ptr 96 appl_ptr 10976 avail 5488 [ 293.611178] sound pcmC0D5p: pos 96 hw_ptr 96 appl_ptr 15072 avail 1392 [ 293.696429] sound pcmC0D5p: pos 96 hw_ptr 96 appl_ptr 16464 avail 0 ... [ 381.139517] sound pcmC0D5p: pos 96 hw_ptr 96 appl_ptr 16464 avail 0 Signed-off-by: Brent Lu <brent.lu@intel.com> Reviewed-by: Jaroslav Kysela <perex@perex.cz> Cc: <stable@vger.kernel.org> Link: https://lore.kernel.org/r/1589776238-23877-1-git-send-email-brent.lu@intel.com Signed-off-by: Takashi Iwai <tiwai@suse.de>
2020-01-05ALSA: pcm: More constificationsTakashi Iwai
Apply const prefix to more possible places: the string tables for PCM format and co, the table for the PCM type helpers, etc. Just for minor optimization and no functional changes. Link: https://lore.kernel.org/r/20200105144823.29547-6-tiwai@suse.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2020-01-04ALSA: control: Add verification for kctl accessesTakashi Iwai
The current implementation of ALSA control API fully relies on the callbacks of each driver, and there is no verification of the values passed via API. This patch is an attempt to improve the situation slightly by adding the validation code for the values stored via info and get callbacks. The patch adds a new kconfig, CONFIG_SND_CTL_VALIDATION. It depends on CONFIG_SND_DEBUG and off as default since the validation would require a slight overhead including the additional call of info callback at each get callback invocation. When this config is enabled, the values stored by each info callback invocation are verified, namely: - Whether the info type is valid - Whether the number of enum items is non-zero - Whether the given info count is within the allowed boundary Similarly, the values stored at each get callback are verified as well: - Whether the values are within the given range - Whether the values are aligned with the given step - Whether any further changes are seen in the data array over the given info count The last point helps identifying a possibly invalid data type access, typically a case where the info callback declares the type being SNDRV_CTL_ELEM_TYPE_ENUMERATED while the get/put callbacks store the values in value.integer.value[] array. When a validation fails, the ALSA core logs an error message including the device and the control ID, and the API call also returns an error. So, with the new validation turned on, the driver behavior difference may be visible on user-space, too -- it's intentional, though, so that we can catch an error more clearly. The patch also introduces a new ctl access type, SNDRV_CTL_ELEM_ACCESS_SKIP_CHECK. A driver may pass this flag with other access bits to indicate that the ctl element won't be verified. It's useful when a driver code is specially written to access the data greater than info->count size by some reason. For example, this flag is actually set now in HD-audio HDMI codec driver which needs to clear the data array in the case of the disconnected monitor. Also, the PCM channel-map helper code is slightly modified to avoid the false-positive hit by this validation code, too. Link: https://lore.kernel.org/r/20200104083556.27789-1-tiwai@suse.de Signed-off-by: Takashi Iwai <tiwai@suse.de>
2019-12-17Merge tag 'y2038-alsa-v8-signed' of ↵Takashi Iwai
git://git.kernel.org:/pub/scm/linux/kernel/git/arnd/playground into for-next ALSA: Fix year 2038 issue for sound subsystem This is a series I worked on with Baolin in 2017 and 2018, but we never quite managed to finish up the last pieces. During the ALSA developer meetup at ELC-E 2018 in Edinburgh, a decision was made to go with this approach for keeping best compatibility with existing source code, and then I failed to follow up by resending the patches. Now I have patches for all remaining time_t uses in the kernel, so it's absolutely time to revisit them. I have done more review of the patches myself and found a couple of minor issues that I have fixed up, otherwise the series is still the same as before. Conceptually, the idea of these patches is: - 64-bit applications should see no changes at all, neither compile-time nor run-time. - 32-bit code compiled with a 64-bit time_t currently does not work with ALSA, and requires kernel changes and/or sound/asound.h changes - Most 32-bit code using these interfaces will work correctly on a modified kernel, with or without the uapi header changes. - 32-bit code using SNDRV_TIMER_IOCTL_TREAD requires the updated header file for 64-bit time_t support - 32-bit i386 user space with 64-bit time_t is broken for SNDRV_PCM_IOCTL_STATUS, SNDRV_RAWMIDI_IOCTL_STATUS and SNDRV_PCM_IOCTL_SYNC_PTR because of i386 alignment. This is also addressed by the updated uapi header. - PCM mmap is currently supported on native x86 kernels (both 32-bit and 64-bit) but not for compat mode. This series breaks the 32-bit native mmap support for 32-bit time_t, but instead allows it for 64-bit time_t on both native and compat kernels. This seems to be the best trade-off, as mmap support is optional already, and most 32-bit code runs in compat mode anyway. - I've tried to avoid breaking compilation of 32-bit code as much as possible. Anything that does break however is likely code that is already broken on 64-bit time_t and needs source changes to fix them. [1] https://git.kernel.org/pub/scm/linux/kernel/git/arnd/playground.git y2038-alsa-v8 [2] https://lore.kernel.org/lkml/CAK8P3a2Os66+iwQYf97qh05W2JP8rmWao8zmKoHiXqVHvyYAJA@mail.gmail.com/T/#m6519cb07cfda08adf1dedea6596bb98892b4d5dc Signed-off-by: Arnd Bergmann <arnd@arndb.de> Changes since v7: (Arnd): - Fix a typo found by Ben Hutchings Changes since v6: (Arnd): - Add a patch to update the API versions - Hide a timespec reference in #ifndef __KERNEL__ to remove the last reference to time_t - Use a more readable way to do padding and describe it in the changelog - Rebase to linux-5.5-rc1, changing include/sound/soc-component.h and sound/drivers/aloop.c as needed. Changes since v5 (Arnd): - Rebased to linux-5.4-rc4 - Updated to completely remove timespec and time_t references from alsa - found and fixed a few bugs Changes since v4 (Baolin): - Add patch 5 to change trigger_tstamp member of struct snd_pcm_runtime. - Add patch 8 to change internal timespec. - Add more explanation in commit message. - Use ktime_get_real_ts64() in patch 6. - Split common code out into a separate function in patch 6. - Fix tu->tread bug in patch 6 and remove #if __BITS_PER_LONG == 64 macro. Changes since v3: - Move struct snd_pcm_status32 to pcm.h file. - Modify comments and commit message. - Add new patch2 ~ patch6. Changes since v2: - Renamed all structures to make clear. - Remove CONFIG_X86_X32 macro and introduced new compat_snd_pcm_status64_x86_32. Changes since v1: - Add one macro for struct snd_pcm_status_32 which only active in 32bits kernel. - Convert pcm_compat.c to use struct snd_pcm_status_64. - Convert pcm_native.c to use struct snd_pcm_status_64.
2019-12-14ALSA: control: remove useless assignment in .info callback of PCM chmap elementTakashi Sakamoto
Control elements for PCM chmap return information to userspace abount the maximum number of available PCM channels as the number of values in the element. In current implementation the number is once initialized to zero, then assigned to. This is useless and this commit fixes it. Fixes: 2d3391ec0ecc ("ALSA: PCM: channel mapping API implementation") Signed-off-by: Takashi Sakamoto <o-takashi@sakamocchi.jp> Link: https://lore.kernel.org/r/20191214131351.28950-1-o-takashi@sakamocchi.jp Signed-off-by: Takashi Iwai <tiwai@suse.de>
2019-12-13ALSA: add new 32-bit layout for snd_pcm_mmap_status/controlArnd Bergmann
The snd_pcm_mmap_status and snd_pcm_mmap_control interfaces are one of the trickiest areas to get right when moving to 64-bit time_t in user space. The snd_pcm_mmap_status structure layout is incompatible with user space that uses a 64-bit time_t, so we need a new layout for it. Since the SNDRV_PCM_IOCTL_SYNC_PTR ioctl combines it with snd_pcm_mmap_control into snd_pcm_sync_ptr, we need to change those two as well. Both structures are also exported via an mmap() operation on certain architectures, and this suffers from incompatibility between 32-bit and 64-bit user space. As we have to change both structures anyway, this is a good opportunity to fix the mmap() problem as well, so let's standardize on the existing 64-bit layout of the structure where possible. The downside is that we lose mmap() support for existing 32-bit x86 and powerpc applications, adding that would introduce very noticeable runtime overhead and complexity. My assumption here is that not too many people will miss the removed feature, given that: - Almost all x86 and powerpc users these days are on 64-bit kernels, the majority of today's 32-bit users are on architectures that never supported mmap (ARM, MIPS, ...). - It never worked in compat mode (it was intentionally disabled there) - The application already needs to work with a fallback to SNDRV_PCM_IOCTL_SYNC_PTR, which will keep working with both the old and new structure layout. Both the ioctl() and mmap() based interfaces are changed at the same time, as they are based on the same structures. Unlike other interfaces, we change the uapi header to export both the traditional structure and a version that is portable between 32-bit and 64-bit user space code and that corresponds to the existing 64-bit layout. We further check the __USE_TIME_BITS64 macro that will be defined by future C library versions whenever we use the new time_t definition, so any existing user space source code will not see any changes until it gets rebuilt against a new C library. However, the new structures are all visible in addition to the old ones, allowing applications to explicitly request the new structures. In order to detect the difference between the old snd_pcm_mmap_status and the new __snd_pcm_mmap_status64 structure from the ioctl command number, we rely on one quirk in the structure definition: snd_pcm_mmap_status must be aligned to alignof(time_t), which leads the compiler to insert four bytes of padding in struct snd_pcm_sync_ptr after 'flags' and a corresponding change in the size of snd_pcm_sync_ptr itself. On x86-32 (and only there), the compiler doesn't use 64-bit alignment in structure, so I'm adding an explicit pad in the structure that has no effect on the existing 64-bit architectures but ensures that the layout matches for x86. The snd_pcm_uframes_t type compatibility requires another hack: we can't easily make that 64 bit wide, so I leave the type as 'unsigned long', but add padding before and after it, to ensure that the data is properly aligned to the respective 64-bit field in the in-kernel structure. For the SNDRV_PCM_MMAP_OFFSET_STATUS/CONTROL constants that are used as the virtual file offset in the mmap() function, we also have to introduce new constants that depend on hte __USE_TIME_BITS64 macro: The existing macros are renamed to SNDRV_PCM_MMAP_OFFSET_STATUS_OLD and SNDRV_PCM_MMAP_OFFSET_CONTROL_OLD, they continue to work fine on 64-bit architectures, but stop working on native 32-bit user space. The replacement _NEW constants are now used by default for user space built with __USE_TIME_BITS64, those now work on all new kernels for x86, ppc and alpha (32 and 64 bit, native and compat). It might be a good idea for a future alsa-lib to support both the _OLD and _NEW macros and use the corresponding structures directly. Unmodified alsa-lib source code will retain the current behavior, so it will no longer be able to use mmap() for the status/control structures on 32-bit systems, until either the C library gets updated to 64-bit time_t or alsa-lib gets updated to support both mmap() layouts. Co-developed-with: Baolin Wang <baolin.wang@linaro.org> Signed-off-by: Baolin Wang <baolin.wang@linaro.org> Signed-off-by: Arnd Bergmann <arnd@arndb.de>
2019-12-11ALSA: Replace timespec with timespec64Baolin Wang
Since timespec is not year 2038 safe on 32bit system, and we need to convert all timespec variables to timespec64 type for sound subsystem. This patch is used to do preparation for following patches, that will convert all structures defined in uapi/sound/asound.h to use 64-bit time_t. Signed-off-by: Baolin Wang <baolin.wang@linaro.org> Signed-off-by: Arnd Bergmann <arnd@arndb.de>
2019-11-13ALSA: pcm: Fix stream lock usage in snd_pcm_period_elapsed()paulhsia
If the nullity check for `substream->runtime` is outside of the lock region, it is possible to have a null runtime in the critical section if snd_pcm_detach_substream is called right before the lock. Signed-off-by: paulhsia <paulhsia@chromium.org> Link: https://lore.kernel.org/r/20191112171715.128727-2-paulhsia@chromium.org Signed-off-by: Takashi Iwai <tiwai@suse.de>
2019-05-30treewide: Replace GPLv2 boilerplate/reference with SPDX - rule 156Thomas Gleixner
Based on 1 normalized pattern(s): this program is free software you can redistribute it and or modify it under the terms of the gnu general public license as published by the free software foundation either version 2 of the license or at your option any later version this program is distributed in the hope that it will be useful but without any warranty without even the implied warranty of merchantability or fitness for a particular purpose see the gnu general public license for more details you should have received a copy of the gnu general public license along with this program if not write to the free software foundation inc 59 temple place suite 330 boston ma 02111 1307 usa extracted by the scancode license scanner the SPDX license identifier GPL-2.0-or-later has been chosen to replace the boilerplate/reference in 1334 file(s). Signed-off-by: Thomas Gleixner <tglx@linutronix.de> Reviewed-by: Allison Randal <allison@lohutok.net> Reviewed-by: Richard Fontana <rfontana@redhat.com> Cc: linux-spdx@vger.kernel.org Link: https://lkml.kernel.org/r/20190527070033.113240726@linutronix.de Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
2019-02-13ALSA: pcm: Comment why read blocks when PCM is not runningRicardo Biehl Pasquali
This avoids bringing back the problem introduced by 62ba568f7aef ("ALSA: pcm: Return 0 when size < start_threshold in capture") and fixed in 00a399cad1a0 ("ALSA: pcm: Revert capture stream behavior change in blocking mode"), which prevented the user from starting capture from another thread. Signed-off-by: Ricardo Biehl Pasquali <pasqualirb@gmail.com> Signed-off-by: Takashi Iwai <tiwai@suse.de>
2019-02-13Merge branch 'for-linus' into for-nextTakashi Iwai
Signed-off-by: Takashi Iwai <tiwai@suse.de>
2019-02-08ALSA: pcm: Revert capture stream behavior change in blocking modeTakashi Iwai
In the commit 62ba568f7aef ("ALSA: pcm: Return 0 when size < start_threshold in capture"), we changed the behavior of __snd_pcm_lib_xfer() to return immediately with 0 when a capture stream has a high start_threshold. This was intended to be a correction of the behavior consistency and looked harmless, but this was the culprit of the recent breakage reported by syzkaller, which was fixed by the commit e190161f96b8 ("ALSA: pcm: Fix tight loop of OSS capture stream"). At the time for the OSS fix, I didn't touch the behavior for ALSA native API, as assuming that this behavior actually is good. But this turned out to be also broken actually for a similar deployment, e.g. one thread goes to a write loop in blocking mode while another thread controls the start/stop of the stream manually. Overall, the original commit is harmful, and it brings less merit to keep that behavior. Let's revert it. Fixes: 62ba568f7aef ("ALSA: pcm: Return 0 when size < start_threshold in capture") Fixes: e190161f96b8 ("ALSA: pcm: Fix tight loop of OSS capture stream") Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.de>
2019-01-29Merge branch 'for-linus' into for-nextTakashi Iwai
Pull 5.0 branch for further development of USB-audio quirks Signed-off-by: Takashi Iwai <tiwai@suse.de>
2019-01-25ALSA: pcm: Fix tight loop of OSS capture streamTakashi Iwai
When the trigger=off is passed for a PCM OSS stream, it sets the start_threshold of the given substream to the boundary size, so that it won't be automatically started. This can be problematic for a capture stream, unfortunately, as detected by syzkaller. The scenario is like the following: - In __snd_pcm_lib_xfer() that is invoked from snd_pcm_oss_read() loop, we have a check whether the stream was already started or the stream can be auto-started. - The function at this check returns 0 with trigger=off since we explicitly disable the auto-start. - The loop continues and repeats calling __snd_pcm_lib_xfer() tightly, which may lead to an RCU stall. This patch fixes the bug by simply allowing the wait for non-started stream in the case of OSS capture. For native usages, it's supposed to be done by the caller side (which is user-space), hence it returns zero like before. (In theory, __snd_pcm_lib_xfer() could wait even for the native API usage cases, too; but I'd like to stay in a safer side for not breaking the existing stuff for now.) Reported-by: syzbot+fbe0496f92a0ce7b786c@syzkaller.appspotmail.com Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.de>
2019-01-25ALSA: pcm: Use the common error path in __snd_pcm_lib_xfer()Takashi Iwai
An open-coded error path in __snd_pcm_lib_xfer() can be replaced with the simple goto to the common error path. This also makes the error handling more consistent, i.e. when some samples have been already processed, return that size instead of the error code. Signed-off-by: Takashi Iwai <tiwai@suse.de>
2018-09-10ALSA: pcm: Update hardware pointer before start captureRicardo Biehl Pasquali
This ensures the transfer loop won't waste a run to read the few frames (if any) between start and hw_ptr update. It will wait for the next interrupt with wait_for_avail(). Signed-off-by: Ricardo Biehl Pasquali <pasqualirb@gmail.com> Signed-off-by: Takashi Iwai <tiwai@suse.de>
2018-08-27ALSA: pcm: Return 0 when size < start_threshold in captureRicardo Biehl Pasquali
In __snd_pcm_lib_xfer(), when capture, if state is PREPARED and size is less than start_threshold nothing can be done. As there is no error, 0 is returned. Signed-off-by: Ricardo Biehl Pasquali <pasqualirb@gmail.com> Signed-off-by: Takashi Iwai <tiwai@suse.de>
2018-07-11ALSA: pcm: Fix snd_interval_refine first/last with open min/maxTimo Wischer
Without this commit the following intervals [x y), (x y) were be replaced to (y-1 y) by snd_interval_refine_last(). This was also done if y-1 is part of the previous interval. With this changes it will be replaced with [y-1 y) in case of y-1 is part of the previous interval. A similar behavior will be used for snd_interval_refine_first(). This commit adapts the changes for alsa-lib of commit 9bb985c ("pcm: snd_interval_refine_first/last: exclude value only if also excluded before") Signed-off-by: Timo Wischer <twischer@de.adit-jv.com> Signed-off-by: Takashi Iwai <tiwai@suse.de>
2018-07-06ALSA: pcm: Allow drivers to set R/W wait time.Liam Girdwood
Currently ALSA core blocks userspace for about 10 seconds for PCM R/W IO. This needs to be configurable for modern hardware like DSPs where no pointer update in milliseconds can indicate terminal DSP errors. Add a substream variable to set the wait time in ms. This allows userspace and drivers to recover more quickly from terminal DSP errors. Signed-off-by: Liam Girdwood <liam.r.girdwood@linux.intel.com> Signed-off-by: Takashi Iwai <tiwai@suse.de>
2018-07-04ALSA: pcm: trace XRUN event at injection, tooTakashi Iwai
The PCM xrun injection triggers directly snd_pcm_stop() without the standard xrun handler, hence it's not recorded on the event buffer. Ditto for snd_pcm_stop_xrun() call and SNDRV_PCM_IOCTL_XRUN ioctl. They are inconvenient from the debugging POV. Let's make them to trigger XRUN via the standard helper more consistently. Signed-off-by: Takashi Iwai <tiwai@suse.de>
2018-04-17ALSA: pcm: Clean up with snd_pcm_avail() and snd_pcm_hw_avail() helpersTakashi Iwai
Introduce two new direction-neutral helpers to calculate the avail and hw_avail values, and clean up the code with them. The two separated forward and rewind functions are gathered to the unified functions. No functional change but only code reductions. Reviewed-by: Takashi Sakamoto <o-takashi@sakamocchi.jp> Signed-off-by: Takashi Iwai <tiwai@suse.de>
2018-03-13ALSA: pcm: Use krealloc() for resizing the rules arrayTakashi Iwai
Just a minor simplification. Change from kcalloc() shouldn't matter as each array element is fully initialized. Reviewed-by: Takashi Sakamoto <o-takashi@sakamocchi.jp> Signed-off-by: Takashi Iwai <tiwai@suse.de>
2018-01-15Merge branch 'for-linus' into for-nextTakashi Iwai
Back-merge to the development branch for further fixes of sequencer stuff. Signed-off-by: Takashi Iwai <tiwai@suse.de>
2018-01-11ALSA: pcm: Remove yet superfluous WARN_ON()Takashi Iwai
muldiv32() contains a snd_BUG_ON() (which is morphed as WARN_ON() with debug option) for checking the case of 0 / 0. This would be helpful if this happens only as a logical error; however, since the hw refine is performed with any data set provided by user, the inconsistent values that can trigger such a condition might be passed easily. Actually, syzbot caught this by passing some zero'ed old hw_params ioctl. So, having snd_BUG_ON() there is simply superfluous and rather harmful to give unnecessary confusions. Let's get rid of it. Reported-by: syzbot+7e6ee55011deeebce15d@syzkaller.appspotmail.com Cc: <stable@vger.kernel.org> Signed-off-by: Takashi Iwai <tiwai@suse.de>
2018-01-09Merge branch 'for-linus' into for-nextTakashi Iwai
Back-merge to continue fixing the OSS emulation code. Signed-off-by: Takashi Iwai <tiwai@suse.de>