xref: /linux/sound/virtio/virtio_pcm_ops.c (revision 83fbbcb7935ec6d2c8ba3bc133e8a0ead2ab0b2d)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * virtio-snd: Virtio sound device
4  * Copyright (C) 2021 OpenSynergy GmbH
5  */
6 #include <sound/pcm_params.h>
7 
8 #include "virtio_card.h"
9 
10 /*
11  * I/O messages lifetime
12  * ---------------------
13  *
14  * Allocation:
15  *   Messages are initially allocated in the ops->hw_params() after the size and
16  *   number of periods have been successfully negotiated.
17  *
18  * Freeing:
19  *   Messages can be safely freed after the queue has been successfully flushed
20  *   (RELEASE command in the ops->sync_stop()) and the ops->hw_free() has been
21  *   called.
22  *
23  *   When the substream stops, the ops->sync_stop() waits until the device has
24  *   completed all pending messages. This wait can be interrupted either by a
25  *   signal or due to a timeout. In this case, the device can still access
26  *   messages even after calling ops->hw_free(). It can also issue an interrupt,
27  *   and the interrupt handler will also try to access message structures.
28  *
29  *   Therefore, freeing of already allocated messages occurs:
30  *
31  *   - in ops->hw_params(), if this operator was called several times in a row,
32  *     or if ops->hw_free() failed to free messages previously;
33  *
34  *   - in ops->hw_free(), if the queue has been successfully flushed;
35  *
36  *   - in dev->release().
37  */
38 
39 /* Map for converting ALSA format to VirtIO format. */
40 struct virtsnd_a2v_format {
41 	snd_pcm_format_t alsa_bit;
42 	unsigned int vio_bit;
43 };
44 
45 static const struct virtsnd_a2v_format g_a2v_format_map[] = {
46 	{ SNDRV_PCM_FORMAT_IMA_ADPCM, VIRTIO_SND_PCM_FMT_IMA_ADPCM },
47 	{ SNDRV_PCM_FORMAT_MU_LAW, VIRTIO_SND_PCM_FMT_MU_LAW },
48 	{ SNDRV_PCM_FORMAT_A_LAW, VIRTIO_SND_PCM_FMT_A_LAW },
49 	{ SNDRV_PCM_FORMAT_S8, VIRTIO_SND_PCM_FMT_S8 },
50 	{ SNDRV_PCM_FORMAT_U8, VIRTIO_SND_PCM_FMT_U8 },
51 	{ SNDRV_PCM_FORMAT_S16_LE, VIRTIO_SND_PCM_FMT_S16 },
52 	{ SNDRV_PCM_FORMAT_U16_LE, VIRTIO_SND_PCM_FMT_U16 },
53 	{ SNDRV_PCM_FORMAT_S18_3LE, VIRTIO_SND_PCM_FMT_S18_3 },
54 	{ SNDRV_PCM_FORMAT_U18_3LE, VIRTIO_SND_PCM_FMT_U18_3 },
55 	{ SNDRV_PCM_FORMAT_S20_3LE, VIRTIO_SND_PCM_FMT_S20_3 },
56 	{ SNDRV_PCM_FORMAT_U20_3LE, VIRTIO_SND_PCM_FMT_U20_3 },
57 	{ SNDRV_PCM_FORMAT_S24_3LE, VIRTIO_SND_PCM_FMT_S24_3 },
58 	{ SNDRV_PCM_FORMAT_U24_3LE, VIRTIO_SND_PCM_FMT_U24_3 },
59 	{ SNDRV_PCM_FORMAT_S20_LE, VIRTIO_SND_PCM_FMT_S20 },
60 	{ SNDRV_PCM_FORMAT_U20_LE, VIRTIO_SND_PCM_FMT_U20 },
61 	{ SNDRV_PCM_FORMAT_S24_LE, VIRTIO_SND_PCM_FMT_S24 },
62 	{ SNDRV_PCM_FORMAT_U24_LE, VIRTIO_SND_PCM_FMT_U24 },
63 	{ SNDRV_PCM_FORMAT_S32_LE, VIRTIO_SND_PCM_FMT_S32 },
64 	{ SNDRV_PCM_FORMAT_U32_LE, VIRTIO_SND_PCM_FMT_U32 },
65 	{ SNDRV_PCM_FORMAT_FLOAT_LE, VIRTIO_SND_PCM_FMT_FLOAT },
66 	{ SNDRV_PCM_FORMAT_FLOAT64_LE, VIRTIO_SND_PCM_FMT_FLOAT64 },
67 	{ SNDRV_PCM_FORMAT_DSD_U8, VIRTIO_SND_PCM_FMT_DSD_U8 },
68 	{ SNDRV_PCM_FORMAT_DSD_U16_LE, VIRTIO_SND_PCM_FMT_DSD_U16 },
69 	{ SNDRV_PCM_FORMAT_DSD_U32_LE, VIRTIO_SND_PCM_FMT_DSD_U32 },
70 	{ SNDRV_PCM_FORMAT_IEC958_SUBFRAME_LE,
71 	  VIRTIO_SND_PCM_FMT_IEC958_SUBFRAME }
72 };
73 
74 /* Map for converting ALSA frame rate to VirtIO frame rate. */
75 struct virtsnd_a2v_rate {
76 	unsigned int rate;
77 	unsigned int vio_bit;
78 };
79 
80 static const struct virtsnd_a2v_rate g_a2v_rate_map[] = {
81 	{ 5512, VIRTIO_SND_PCM_RATE_5512 },
82 	{ 8000, VIRTIO_SND_PCM_RATE_8000 },
83 	{ 11025, VIRTIO_SND_PCM_RATE_11025 },
84 	{ 16000, VIRTIO_SND_PCM_RATE_16000 },
85 	{ 22050, VIRTIO_SND_PCM_RATE_22050 },
86 	{ 32000, VIRTIO_SND_PCM_RATE_32000 },
87 	{ 44100, VIRTIO_SND_PCM_RATE_44100 },
88 	{ 48000, VIRTIO_SND_PCM_RATE_48000 },
89 	{ 64000, VIRTIO_SND_PCM_RATE_64000 },
90 	{ 88200, VIRTIO_SND_PCM_RATE_88200 },
91 	{ 96000, VIRTIO_SND_PCM_RATE_96000 },
92 	{ 176400, VIRTIO_SND_PCM_RATE_176400 },
93 	{ 192000, VIRTIO_SND_PCM_RATE_192000 },
94 	{ 384000, VIRTIO_SND_PCM_RATE_384000 }
95 };
96 
97 static int virtsnd_pcm_sync_stop(struct snd_pcm_substream *substream);
98 
99 /**
100  * virtsnd_pcm_open() - Open the PCM substream.
101  * @substream: Kernel ALSA substream.
102  *
103  * Context: Process context.
104  * Return: 0 on success, -errno on failure.
105  */
106 static int virtsnd_pcm_open(struct snd_pcm_substream *substream)
107 {
108 	struct virtio_pcm *vpcm = snd_pcm_substream_chip(substream);
109 	struct virtio_pcm_stream *vs = &vpcm->streams[substream->stream];
110 	struct virtio_pcm_substream *vss = vs->substreams[substream->number];
111 
112 	substream->runtime->hw = vss->hw;
113 	substream->private_data = vss;
114 
115 	snd_pcm_hw_constraint_integer(substream->runtime,
116 				      SNDRV_PCM_HW_PARAM_PERIODS);
117 
118 	vss->stopped = !!virtsnd_pcm_msg_pending_num(vss);
119 	vss->suspended = false;
120 
121 	/*
122 	 * If the substream has already been used, then the I/O queue may be in
123 	 * an invalid state. Just in case, we do a check and try to return the
124 	 * queue to its original state, if necessary.
125 	 */
126 	return virtsnd_pcm_sync_stop(substream);
127 }
128 
129 /**
130  * virtsnd_pcm_close() - Close the PCM substream.
131  * @substream: Kernel ALSA substream.
132  *
133  * Context: Process context.
134  * Return: 0.
135  */
136 static int virtsnd_pcm_close(struct snd_pcm_substream *substream)
137 {
138 	return 0;
139 }
140 
141 /**
142  * virtsnd_pcm_dev_set_params() - Set the parameters of the PCM substream on
143  *                                the device side.
144  * @vss: VirtIO PCM substream.
145  * @buffer_bytes: Size of the hardware buffer.
146  * @period_bytes: Size of the hardware period.
147  * @channels: Selected number of channels.
148  * @format: Selected sample format (SNDRV_PCM_FORMAT_XXX).
149  * @rate: Selected frame rate.
150  *
151  * Context: Any context that permits to sleep.
152  * Return: 0 on success, -errno on failure.
153  */
154 static int virtsnd_pcm_dev_set_params(struct virtio_pcm_substream *vss,
155 				      unsigned int buffer_bytes,
156 				      unsigned int period_bytes,
157 				      unsigned int channels,
158 				      snd_pcm_format_t format,
159 				      unsigned int rate)
160 {
161 	struct virtio_snd_msg *msg;
162 	struct virtio_snd_pcm_set_params *request;
163 	unsigned int i;
164 	int vformat = -1;
165 	int vrate = -1;
166 
167 	for (i = 0; i < ARRAY_SIZE(g_a2v_format_map); ++i)
168 		if (g_a2v_format_map[i].alsa_bit == format) {
169 			vformat = g_a2v_format_map[i].vio_bit;
170 
171 			break;
172 		}
173 
174 	for (i = 0; i < ARRAY_SIZE(g_a2v_rate_map); ++i)
175 		if (g_a2v_rate_map[i].rate == rate) {
176 			vrate = g_a2v_rate_map[i].vio_bit;
177 
178 			break;
179 		}
180 
181 	if (vformat == -1 || vrate == -1)
182 		return -EINVAL;
183 
184 	msg = virtsnd_pcm_ctl_msg_alloc(vss, VIRTIO_SND_R_PCM_SET_PARAMS,
185 					GFP_KERNEL);
186 	if (!msg)
187 		return -ENOMEM;
188 
189 	request = virtsnd_ctl_msg_request(msg);
190 	request->buffer_bytes = cpu_to_le32(buffer_bytes);
191 	request->period_bytes = cpu_to_le32(period_bytes);
192 	request->channels = channels;
193 	request->format = vformat;
194 	request->rate = vrate;
195 
196 	if (vss->features & (1U << VIRTIO_SND_PCM_F_MSG_POLLING))
197 		request->features |=
198 			cpu_to_le32(1U << VIRTIO_SND_PCM_F_MSG_POLLING);
199 
200 	if (vss->features & (1U << VIRTIO_SND_PCM_F_EVT_XRUNS))
201 		request->features |=
202 			cpu_to_le32(1U << VIRTIO_SND_PCM_F_EVT_XRUNS);
203 
204 	return virtsnd_ctl_msg_send_sync(vss->snd, msg);
205 }
206 
207 /**
208  * virtsnd_pcm_hw_params() - Set the parameters of the PCM substream.
209  * @substream: Kernel ALSA substream.
210  * @hw_params: Hardware parameters.
211  *
212  * Context: Process context.
213  * Return: 0 on success, -errno on failure.
214  */
215 static int virtsnd_pcm_hw_params(struct snd_pcm_substream *substream,
216 				 struct snd_pcm_hw_params *hw_params)
217 {
218 	struct virtio_pcm_substream *vss = snd_pcm_substream_chip(substream);
219 	struct virtio_device *vdev = vss->snd->vdev;
220 	int rc;
221 
222 	if (virtsnd_pcm_msg_pending_num(vss)) {
223 		dev_err(&vdev->dev, "SID %u: invalid I/O queue state\n",
224 			vss->sid);
225 		return -EBADFD;
226 	}
227 
228 	rc = virtsnd_pcm_dev_set_params(vss, params_buffer_bytes(hw_params),
229 					params_period_bytes(hw_params),
230 					params_channels(hw_params),
231 					params_format(hw_params),
232 					params_rate(hw_params));
233 	if (rc)
234 		return rc;
235 
236 	/*
237 	 * Free previously allocated messages if ops->hw_params() is called
238 	 * several times in a row, or if ops->hw_free() failed to free messages.
239 	 */
240 	virtsnd_pcm_msg_free(vss);
241 
242 	return virtsnd_pcm_msg_alloc(vss, params_periods(hw_params),
243 				     params_period_bytes(hw_params));
244 }
245 
246 /**
247  * virtsnd_pcm_hw_free() - Reset the parameters of the PCM substream.
248  * @substream: Kernel ALSA substream.
249  *
250  * Context: Process context.
251  * Return: 0
252  */
253 static int virtsnd_pcm_hw_free(struct snd_pcm_substream *substream)
254 {
255 	struct virtio_pcm_substream *vss = snd_pcm_substream_chip(substream);
256 
257 	/* If the queue is flushed, we can safely free the messages here. */
258 	if (!virtsnd_pcm_msg_pending_num(vss))
259 		virtsnd_pcm_msg_free(vss);
260 
261 	return 0;
262 }
263 
264 /**
265  * virtsnd_pcm_prepare() - Prepare the PCM substream.
266  * @substream: Kernel ALSA substream.
267  *
268  * Context: Process context.
269  * Return: 0 on success, -errno on failure.
270  */
271 static int virtsnd_pcm_prepare(struct snd_pcm_substream *substream)
272 {
273 	struct virtio_pcm_substream *vss = snd_pcm_substream_chip(substream);
274 	struct virtio_device *vdev = vss->snd->vdev;
275 	struct virtio_snd_msg *msg;
276 
277 	if (!vss->suspended) {
278 		if (virtsnd_pcm_msg_pending_num(vss)) {
279 			dev_err(&vdev->dev, "SID %u: invalid I/O queue state\n",
280 				vss->sid);
281 			return -EBADFD;
282 		}
283 
284 		vss->buffer_bytes = snd_pcm_lib_buffer_bytes(substream);
285 		vss->hw_ptr = 0;
286 	} else {
287 		struct snd_pcm_runtime *runtime = substream->runtime;
288 		unsigned int buffer_bytes = snd_pcm_lib_buffer_bytes(substream);
289 		unsigned int period_bytes = snd_pcm_lib_period_bytes(substream);
290 		int rc;
291 
292 		rc = virtsnd_pcm_dev_set_params(vss, buffer_bytes, period_bytes,
293 						runtime->channels,
294 						runtime->format, runtime->rate);
295 		if (rc)
296 			return rc;
297 	}
298 
299 	vss->xfer_xrun = false;
300 	vss->suspended = false;
301 	vss->msg_count = 0;
302 
303 	memset(&vss->pcm_indirect, 0, sizeof(vss->pcm_indirect));
304 	vss->pcm_indirect.sw_buffer_size =
305 		vss->pcm_indirect.hw_buffer_size =
306 		snd_pcm_lib_buffer_bytes(substream);
307 
308 	msg = virtsnd_pcm_ctl_msg_alloc(vss, VIRTIO_SND_R_PCM_PREPARE,
309 					GFP_KERNEL);
310 	if (!msg)
311 		return -ENOMEM;
312 
313 	return virtsnd_ctl_msg_send_sync(vss->snd, msg);
314 }
315 
316 /**
317  * virtsnd_pcm_trigger() - Process command for the PCM substream.
318  * @substream: Kernel ALSA substream.
319  * @command: Substream command (SNDRV_PCM_TRIGGER_XXX).
320  *
321  * Context: Any context. Takes and releases the VirtIO substream spinlock.
322  *          May take and release the tx/rx queue spinlock.
323  * Return: 0 on success, -errno on failure.
324  */
325 static int virtsnd_pcm_trigger(struct snd_pcm_substream *substream, int command)
326 {
327 	struct virtio_pcm_substream *vss = snd_pcm_substream_chip(substream);
328 	struct virtio_snd *snd = vss->snd;
329 	struct virtio_snd_queue *queue;
330 	struct virtio_snd_msg *msg;
331 	int rc = 0;
332 
333 	switch (command) {
334 	case SNDRV_PCM_TRIGGER_START:
335 	case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
336 		queue = virtsnd_pcm_queue(vss);
337 
338 		scoped_guard(spinlock_irqsave, &queue->lock) {
339 			guard(spinlock)(&vss->lock);
340 			if (vss->direction == SNDRV_PCM_STREAM_CAPTURE)
341 				rc = virtsnd_pcm_msg_send(vss, 0, vss->buffer_bytes);
342 			if (rc)
343 				return rc;
344 			vss->xfer_enabled = true;
345 		}
346 
347 		msg = virtsnd_pcm_ctl_msg_alloc(vss, VIRTIO_SND_R_PCM_START,
348 						GFP_KERNEL);
349 		if (!msg) {
350 			guard(spinlock_irqsave)(&vss->lock);
351 			vss->xfer_enabled = false;
352 
353 			return -ENOMEM;
354 		}
355 
356 		return virtsnd_ctl_msg_send_sync(snd, msg);
357 	case SNDRV_PCM_TRIGGER_SUSPEND:
358 		vss->suspended = true;
359 		fallthrough;
360 	case SNDRV_PCM_TRIGGER_STOP:
361 		vss->stopped = true;
362 		fallthrough;
363 	case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
364 		scoped_guard(spinlock_irqsave, &vss->lock) {
365 			vss->xfer_enabled = false;
366 		}
367 
368 		msg = virtsnd_pcm_ctl_msg_alloc(vss, VIRTIO_SND_R_PCM_STOP,
369 						GFP_KERNEL);
370 		if (!msg)
371 			return -ENOMEM;
372 
373 		return virtsnd_ctl_msg_send_sync(snd, msg);
374 	default:
375 		return -EINVAL;
376 	}
377 }
378 
379 /**
380  * virtsnd_pcm_sync_stop() - Synchronous PCM substream stop.
381  * @substream: Kernel ALSA substream.
382  *
383  * The function can be called both from the upper level or from the driver
384  * itself.
385  *
386  * Context: Process context. Takes and releases the VirtIO substream spinlock.
387  * Return: 0 on success, -errno on failure.
388  */
389 static int virtsnd_pcm_sync_stop(struct snd_pcm_substream *substream)
390 {
391 	struct virtio_pcm_substream *vss = snd_pcm_substream_chip(substream);
392 	struct virtio_snd *snd = vss->snd;
393 	struct virtio_snd_msg *msg;
394 	unsigned int js = msecs_to_jiffies(virtsnd_msg_timeout_ms);
395 	int rc;
396 
397 	cancel_work_sync(&vss->elapsed_period);
398 
399 	if (!vss->stopped)
400 		return 0;
401 
402 	msg = virtsnd_pcm_ctl_msg_alloc(vss, VIRTIO_SND_R_PCM_RELEASE,
403 					GFP_KERNEL);
404 	if (!msg)
405 		return -ENOMEM;
406 
407 	rc = virtsnd_ctl_msg_send_sync(snd, msg);
408 	if (rc)
409 		return rc;
410 
411 	/*
412 	 * The spec states that upon receipt of the RELEASE command "the device
413 	 * MUST complete all pending I/O messages for the specified stream ID".
414 	 * Thus, we consider the absence of I/O messages in the queue as an
415 	 * indication that the substream has been released.
416 	 */
417 	rc = wait_event_interruptible_timeout(vss->msg_empty,
418 					      !virtsnd_pcm_msg_pending_num(vss),
419 					      js);
420 	if (rc <= 0) {
421 		dev_warn(&snd->vdev->dev, "SID %u: failed to flush I/O queue\n",
422 			 vss->sid);
423 
424 		return !rc ? -ETIMEDOUT : rc;
425 	}
426 
427 	vss->stopped = false;
428 
429 	return 0;
430 }
431 
432 /**
433  * virtsnd_pcm_pb_pointer() - Get the current hardware position for the PCM
434  *                         substream for playback.
435  * @substream: Kernel ALSA substream.
436  *
437  * Context: Any context.
438  * Return: Hardware position in frames inside [0 ... buffer_size) range.
439  */
440 static snd_pcm_uframes_t
441 virtsnd_pcm_pb_pointer(struct snd_pcm_substream *substream)
442 {
443 	struct virtio_pcm_substream *vss = snd_pcm_substream_chip(substream);
444 
445 	return snd_pcm_indirect_playback_pointer(substream,
446 		&vss->pcm_indirect,
447 		vss->hw_ptr);
448 }
449 
450 /**
451  * virtsnd_pcm_cp_pointer() - Get the current hardware position for the PCM
452  *                         substream for capture.
453  * @substream: Kernel ALSA substream.
454  *
455  * Context: Any context.
456  * Return: Hardware position in frames inside [0 ... buffer_size) range.
457  */
458 static snd_pcm_uframes_t
459 virtsnd_pcm_cp_pointer(struct snd_pcm_substream *substream)
460 {
461 	struct virtio_pcm_substream *vss = snd_pcm_substream_chip(substream);
462 
463 	return snd_pcm_indirect_capture_pointer(substream,
464 		&vss->pcm_indirect,
465 		vss->hw_ptr);
466 }
467 
468 static void virtsnd_pcm_trans_copy(struct snd_pcm_substream *substream,
469 				   struct snd_pcm_indirect *rec, size_t bytes)
470 {
471 	struct virtio_pcm_substream *vss = snd_pcm_substream_chip(substream);
472 
473 	virtsnd_pcm_msg_send(vss, rec->sw_data, bytes);
474 }
475 
476 static int virtsnd_pcm_pb_ack(struct snd_pcm_substream *substream)
477 {
478 	struct virtio_pcm_substream *vss = snd_pcm_substream_chip(substream);
479 	struct virtio_snd_queue *queue = virtsnd_pcm_queue(vss);
480 
481 	guard(spinlock_irqsave)(&queue->lock);
482 	guard(spinlock)(&vss->lock);
483 
484 	return snd_pcm_indirect_playback_transfer(substream, &vss->pcm_indirect,
485 						  virtsnd_pcm_trans_copy);
486 }
487 
488 static int virtsnd_pcm_cp_ack(struct snd_pcm_substream *substream)
489 {
490 	struct virtio_pcm_substream *vss = snd_pcm_substream_chip(substream);
491 	struct virtio_snd_queue *queue = virtsnd_pcm_queue(vss);
492 
493 	guard(spinlock_irqsave)(&queue->lock);
494 	guard(spinlock)(&vss->lock);
495 
496 	return snd_pcm_indirect_capture_transfer(substream, &vss->pcm_indirect,
497 						 virtsnd_pcm_trans_copy);
498 }
499 
500 /* PCM substream operators map. */
501 const struct snd_pcm_ops virtsnd_pcm_ops[] = {
502 	{
503 		.open = virtsnd_pcm_open,
504 		.close = virtsnd_pcm_close,
505 		.ioctl = snd_pcm_lib_ioctl,
506 		.hw_params = virtsnd_pcm_hw_params,
507 		.hw_free = virtsnd_pcm_hw_free,
508 		.prepare = virtsnd_pcm_prepare,
509 		.trigger = virtsnd_pcm_trigger,
510 		.sync_stop = virtsnd_pcm_sync_stop,
511 		.pointer = virtsnd_pcm_pb_pointer,
512 		.ack = virtsnd_pcm_pb_ack,
513 	},
514 	{
515 		.open = virtsnd_pcm_open,
516 		.close = virtsnd_pcm_close,
517 		.ioctl = snd_pcm_lib_ioctl,
518 		.hw_params = virtsnd_pcm_hw_params,
519 		.hw_free = virtsnd_pcm_hw_free,
520 		.prepare = virtsnd_pcm_prepare,
521 		.trigger = virtsnd_pcm_trigger,
522 		.sync_stop = virtsnd_pcm_sync_stop,
523 		.pointer = virtsnd_pcm_cp_pointer,
524 		.ack = virtsnd_pcm_cp_ack,
525 	},
526 };
527