xref: /linux/sound/virtio/virtio_pcm.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 <linux/moduleparam.h>
7 #include <linux/virtio_config.h>
8 
9 #include "virtio_card.h"
10 
11 static u32 pcm_buffer_ms = 160;
12 module_param(pcm_buffer_ms, uint, 0644);
13 MODULE_PARM_DESC(pcm_buffer_ms, "PCM substream buffer time in milliseconds");
14 
15 static u32 pcm_periods_min = 2;
16 module_param(pcm_periods_min, uint, 0644);
17 MODULE_PARM_DESC(pcm_periods_min, "Minimum number of PCM periods");
18 
19 static u32 pcm_periods_max = 16;
20 module_param(pcm_periods_max, uint, 0644);
21 MODULE_PARM_DESC(pcm_periods_max, "Maximum number of PCM periods");
22 
23 static u32 pcm_period_ms_min = 10;
24 module_param(pcm_period_ms_min, uint, 0644);
25 MODULE_PARM_DESC(pcm_period_ms_min, "Minimum PCM period time in milliseconds");
26 
27 static u32 pcm_period_ms_max = 80;
28 module_param(pcm_period_ms_max, uint, 0644);
29 MODULE_PARM_DESC(pcm_period_ms_max, "Maximum PCM period time in milliseconds");
30 
31 /* Map for converting VirtIO format to ALSA format. */
32 static const snd_pcm_format_t g_v2a_format_map[] = {
33 	[VIRTIO_SND_PCM_FMT_IMA_ADPCM] = SNDRV_PCM_FORMAT_IMA_ADPCM,
34 	[VIRTIO_SND_PCM_FMT_MU_LAW] = SNDRV_PCM_FORMAT_MU_LAW,
35 	[VIRTIO_SND_PCM_FMT_A_LAW] = SNDRV_PCM_FORMAT_A_LAW,
36 	[VIRTIO_SND_PCM_FMT_S8] = SNDRV_PCM_FORMAT_S8,
37 	[VIRTIO_SND_PCM_FMT_U8] = SNDRV_PCM_FORMAT_U8,
38 	[VIRTIO_SND_PCM_FMT_S16] = SNDRV_PCM_FORMAT_S16_LE,
39 	[VIRTIO_SND_PCM_FMT_U16] = SNDRV_PCM_FORMAT_U16_LE,
40 	[VIRTIO_SND_PCM_FMT_S18_3] = SNDRV_PCM_FORMAT_S18_3LE,
41 	[VIRTIO_SND_PCM_FMT_U18_3] = SNDRV_PCM_FORMAT_U18_3LE,
42 	[VIRTIO_SND_PCM_FMT_S20_3] = SNDRV_PCM_FORMAT_S20_3LE,
43 	[VIRTIO_SND_PCM_FMT_U20_3] = SNDRV_PCM_FORMAT_U20_3LE,
44 	[VIRTIO_SND_PCM_FMT_S24_3] = SNDRV_PCM_FORMAT_S24_3LE,
45 	[VIRTIO_SND_PCM_FMT_U24_3] = SNDRV_PCM_FORMAT_U24_3LE,
46 	[VIRTIO_SND_PCM_FMT_S20] = SNDRV_PCM_FORMAT_S20_LE,
47 	[VIRTIO_SND_PCM_FMT_U20] = SNDRV_PCM_FORMAT_U20_LE,
48 	[VIRTIO_SND_PCM_FMT_S24] = SNDRV_PCM_FORMAT_S24_LE,
49 	[VIRTIO_SND_PCM_FMT_U24] = SNDRV_PCM_FORMAT_U24_LE,
50 	[VIRTIO_SND_PCM_FMT_S32] = SNDRV_PCM_FORMAT_S32_LE,
51 	[VIRTIO_SND_PCM_FMT_U32] = SNDRV_PCM_FORMAT_U32_LE,
52 	[VIRTIO_SND_PCM_FMT_FLOAT] = SNDRV_PCM_FORMAT_FLOAT_LE,
53 	[VIRTIO_SND_PCM_FMT_FLOAT64] = SNDRV_PCM_FORMAT_FLOAT64_LE,
54 	[VIRTIO_SND_PCM_FMT_DSD_U8] = SNDRV_PCM_FORMAT_DSD_U8,
55 	[VIRTIO_SND_PCM_FMT_DSD_U16] = SNDRV_PCM_FORMAT_DSD_U16_LE,
56 	[VIRTIO_SND_PCM_FMT_DSD_U32] = SNDRV_PCM_FORMAT_DSD_U32_LE,
57 	[VIRTIO_SND_PCM_FMT_IEC958_SUBFRAME] =
58 		SNDRV_PCM_FORMAT_IEC958_SUBFRAME_LE
59 };
60 
61 /* Map for converting VirtIO frame rate to ALSA frame rate. */
62 struct virtsnd_v2a_rate {
63 	unsigned int alsa_bit;
64 	unsigned int rate;
65 };
66 
67 static const struct virtsnd_v2a_rate g_v2a_rate_map[] = {
68 	[VIRTIO_SND_PCM_RATE_5512] = { SNDRV_PCM_RATE_5512, 5512 },
69 	[VIRTIO_SND_PCM_RATE_8000] = { SNDRV_PCM_RATE_8000, 8000 },
70 	[VIRTIO_SND_PCM_RATE_11025] = { SNDRV_PCM_RATE_11025, 11025 },
71 	[VIRTIO_SND_PCM_RATE_16000] = { SNDRV_PCM_RATE_16000, 16000 },
72 	[VIRTIO_SND_PCM_RATE_22050] = { SNDRV_PCM_RATE_22050, 22050 },
73 	[VIRTIO_SND_PCM_RATE_32000] = { SNDRV_PCM_RATE_32000, 32000 },
74 	[VIRTIO_SND_PCM_RATE_44100] = { SNDRV_PCM_RATE_44100, 44100 },
75 	[VIRTIO_SND_PCM_RATE_48000] = { SNDRV_PCM_RATE_48000, 48000 },
76 	[VIRTIO_SND_PCM_RATE_64000] = { SNDRV_PCM_RATE_64000, 64000 },
77 	[VIRTIO_SND_PCM_RATE_88200] = { SNDRV_PCM_RATE_88200, 88200 },
78 	[VIRTIO_SND_PCM_RATE_96000] = { SNDRV_PCM_RATE_96000, 96000 },
79 	[VIRTIO_SND_PCM_RATE_176400] = { SNDRV_PCM_RATE_176400, 176400 },
80 	[VIRTIO_SND_PCM_RATE_192000] = { SNDRV_PCM_RATE_192000, 192000 },
81 	[VIRTIO_SND_PCM_RATE_384000] = { SNDRV_PCM_RATE_384000, 384000 }
82 };
83 
84 /**
85  * virtsnd_pcm_build_hw() - Parse substream config and build HW descriptor.
86  * @vss: VirtIO substream.
87  * @info: VirtIO substream information entry.
88  *
89  * Context: Any context.
90  * Return: 0 on success, -EINVAL if configuration is invalid.
91  */
92 static int virtsnd_pcm_build_hw(struct virtio_pcm_substream *vss,
93 				struct virtio_snd_pcm_info *info)
94 {
95 	struct virtio_device *vdev = vss->snd->vdev;
96 	unsigned int i;
97 	u64 values;
98 	size_t sample_max = 0;
99 	size_t sample_min = 0;
100 
101 	vss->features = le32_to_cpu(info->features);
102 
103 	/*
104 	 * TODO: set SNDRV_PCM_INFO_{BATCH,BLOCK_TRANSFER} if device supports
105 	 * only message-based transport.
106 	 */
107 	vss->hw.info =
108 		SNDRV_PCM_INFO_MMAP |
109 		SNDRV_PCM_INFO_MMAP_VALID |
110 		SNDRV_PCM_INFO_BATCH |
111 		SNDRV_PCM_INFO_BLOCK_TRANSFER |
112 		SNDRV_PCM_INFO_INTERLEAVED |
113 		SNDRV_PCM_INFO_PAUSE |
114 		SNDRV_PCM_INFO_NO_REWINDS |
115 		SNDRV_PCM_INFO_SYNC_APPLPTR;
116 
117 	if (!info->channels_min || info->channels_min > info->channels_max) {
118 		dev_err(&vdev->dev,
119 			"SID %u: invalid channel range [%u %u]\n",
120 			vss->sid, info->channels_min, info->channels_max);
121 		return -EINVAL;
122 	}
123 
124 	vss->hw.channels_min = info->channels_min;
125 	vss->hw.channels_max = info->channels_max;
126 
127 	values = le64_to_cpu(info->formats);
128 
129 	vss->hw.formats = 0;
130 
131 	for (i = 0; i < ARRAY_SIZE(g_v2a_format_map); ++i)
132 		if (values & (1ULL << i)) {
133 			snd_pcm_format_t alsa_fmt = g_v2a_format_map[i];
134 			int bytes = snd_pcm_format_physical_width(alsa_fmt) / 8;
135 
136 			if (!sample_min || sample_min > bytes)
137 				sample_min = bytes;
138 
139 			if (sample_max < bytes)
140 				sample_max = bytes;
141 
142 			vss->hw.formats |= pcm_format_to_bits(alsa_fmt);
143 		}
144 
145 	if (!vss->hw.formats) {
146 		dev_err(&vdev->dev,
147 			"SID %u: no supported PCM sample formats found\n",
148 			vss->sid);
149 		return -EINVAL;
150 	}
151 
152 	values = le64_to_cpu(info->rates);
153 
154 	vss->hw.rates = 0;
155 
156 	for (i = 0; i < ARRAY_SIZE(g_v2a_rate_map); ++i)
157 		if (values & (1ULL << i)) {
158 			if (!vss->hw.rate_min ||
159 			    vss->hw.rate_min > g_v2a_rate_map[i].rate)
160 				vss->hw.rate_min = g_v2a_rate_map[i].rate;
161 
162 			if (vss->hw.rate_max < g_v2a_rate_map[i].rate)
163 				vss->hw.rate_max = g_v2a_rate_map[i].rate;
164 
165 			vss->hw.rates |= g_v2a_rate_map[i].alsa_bit;
166 		}
167 
168 	if (!vss->hw.rates) {
169 		dev_err(&vdev->dev,
170 			"SID %u: no supported PCM frame rates found\n",
171 			vss->sid);
172 		return -EINVAL;
173 	}
174 
175 	vss->hw.periods_min = pcm_periods_min;
176 	vss->hw.periods_max = pcm_periods_max;
177 
178 	/*
179 	 * We must ensure that there is enough space in the buffer to store
180 	 * pcm_buffer_ms ms for the combination (Cmax, Smax, Rmax), where:
181 	 *   Cmax = maximum supported number of channels,
182 	 *   Smax = maximum supported sample size in bytes,
183 	 *   Rmax = maximum supported frame rate.
184 	 */
185 	vss->hw.buffer_bytes_max =
186 		PAGE_ALIGN(sample_max * vss->hw.channels_max * pcm_buffer_ms *
187 			   (vss->hw.rate_max / MSEC_PER_SEC));
188 
189 	/*
190 	 * We must ensure that the minimum period size is enough to store
191 	 * pcm_period_ms_min ms for the combination (Cmin, Smin, Rmin), where:
192 	 *   Cmin = minimum supported number of channels,
193 	 *   Smin = minimum supported sample size in bytes,
194 	 *   Rmin = minimum supported frame rate.
195 	 */
196 	vss->hw.period_bytes_min =
197 		sample_min * vss->hw.channels_min * pcm_period_ms_min *
198 		(vss->hw.rate_min / MSEC_PER_SEC);
199 
200 	/*
201 	 * We must ensure that the maximum period size is enough to store
202 	 * pcm_period_ms_max ms for the combination (Cmax, Smax, Rmax).
203 	 */
204 	vss->hw.period_bytes_max =
205 		sample_max * vss->hw.channels_max * pcm_period_ms_max *
206 		(vss->hw.rate_max / MSEC_PER_SEC);
207 
208 	return 0;
209 }
210 
211 /**
212  * virtsnd_pcm_find() - Find the PCM device for the specified node ID.
213  * @snd: VirtIO sound device.
214  * @nid: Function node ID.
215  *
216  * Context: Any context.
217  * Return: a pointer to the PCM device or ERR_PTR(-ENOENT).
218  */
219 struct virtio_pcm *virtsnd_pcm_find(struct virtio_snd *snd, u32 nid)
220 {
221 	struct virtio_pcm *vpcm;
222 
223 	list_for_each_entry(vpcm, &snd->pcm_list, list)
224 		if (vpcm->nid == nid)
225 			return vpcm;
226 
227 	return ERR_PTR(-ENOENT);
228 }
229 
230 /**
231  * virtsnd_pcm_find_or_create() - Find or create the PCM device for the
232  *                                specified node ID.
233  * @snd: VirtIO sound device.
234  * @nid: Function node ID.
235  *
236  * Context: Any context that permits to sleep.
237  * Return: a pointer to the PCM device or ERR_PTR(-errno).
238  */
239 struct virtio_pcm *virtsnd_pcm_find_or_create(struct virtio_snd *snd, u32 nid)
240 {
241 	struct virtio_device *vdev = snd->vdev;
242 	struct virtio_pcm *vpcm;
243 
244 	vpcm = virtsnd_pcm_find(snd, nid);
245 	if (!IS_ERR(vpcm))
246 		return vpcm;
247 
248 	vpcm = devm_kzalloc(&vdev->dev, sizeof(*vpcm), GFP_KERNEL);
249 	if (!vpcm)
250 		return ERR_PTR(-ENOMEM);
251 
252 	vpcm->nid = nid;
253 	list_add_tail(&vpcm->list, &snd->pcm_list);
254 
255 	return vpcm;
256 }
257 
258 /**
259  * virtsnd_pcm_validate() - Validate if the device can be started.
260  * @vdev: VirtIO parent device.
261  *
262  * Context: Any context.
263  * Return: 0 on success, -EINVAL on failure.
264  */
265 int virtsnd_pcm_validate(struct virtio_device *vdev)
266 {
267 	if (pcm_periods_min < 2 || pcm_periods_min > pcm_periods_max) {
268 		dev_err(&vdev->dev,
269 			"invalid range [%u %u] of the number of PCM periods\n",
270 			pcm_periods_min, pcm_periods_max);
271 		return -EINVAL;
272 	}
273 
274 	if (!pcm_period_ms_min || pcm_period_ms_min > pcm_period_ms_max) {
275 		dev_err(&vdev->dev,
276 			"invalid range [%u %u] of the size of the PCM period\n",
277 			pcm_period_ms_min, pcm_period_ms_max);
278 		return -EINVAL;
279 	}
280 
281 	if (pcm_buffer_ms < pcm_periods_min * pcm_period_ms_min) {
282 		dev_err(&vdev->dev,
283 			"pcm_buffer_ms(=%u) value cannot be < %u ms\n",
284 			pcm_buffer_ms, pcm_periods_min * pcm_period_ms_min);
285 		return -EINVAL;
286 	}
287 
288 	if (pcm_period_ms_max > pcm_buffer_ms / 2) {
289 		dev_err(&vdev->dev,
290 			"pcm_period_ms_max(=%u) value cannot be > %u ms\n",
291 			pcm_period_ms_max, pcm_buffer_ms / 2);
292 		return -EINVAL;
293 	}
294 
295 	return 0;
296 }
297 
298 /**
299  * virtsnd_pcm_period_elapsed() - Kernel work function to handle the elapsed
300  *                                period state.
301  * @work: Elapsed period work.
302  *
303  * The main purpose of this function is to call snd_pcm_period_elapsed() in
304  * a process context, not in an interrupt context. This is necessary because PCM
305  * devices operate in non-atomic mode.
306  *
307  * Context: Process context.
308  */
309 static void virtsnd_pcm_period_elapsed(struct work_struct *work)
310 {
311 	struct virtio_pcm_substream *vss =
312 		container_of(work, struct virtio_pcm_substream, elapsed_period);
313 
314 	snd_pcm_period_elapsed(vss->substream);
315 }
316 
317 /**
318  * virtsnd_pcm_parse_cfg() - Parse the stream configuration.
319  * @snd: VirtIO sound device.
320  *
321  * This function is called during initial device initialization.
322  *
323  * Context: Any context that permits to sleep.
324  * Return: 0 on success, -errno on failure.
325  */
326 int virtsnd_pcm_parse_cfg(struct virtio_snd *snd)
327 {
328 	struct virtio_device *vdev = snd->vdev;
329 	struct virtio_snd_pcm_info *info;
330 	u32 i;
331 	int rc;
332 
333 	virtio_cread_le(vdev, struct virtio_snd_config, streams,
334 			&snd->nsubstreams);
335 	if (!snd->nsubstreams)
336 		return 0;
337 
338 	snd->substreams = devm_kcalloc(&vdev->dev, snd->nsubstreams,
339 				       sizeof(*snd->substreams), GFP_KERNEL);
340 	if (!snd->substreams)
341 		return -ENOMEM;
342 
343 	/*
344 	 * Initialize critical substream fields early in case we hit an
345 	 * error path and end up trying to clean up uninitialized structures
346 	 * elsewhere.
347 	 */
348 	for (i = 0; i < snd->nsubstreams; ++i) {
349 		struct virtio_pcm_substream *vss = &snd->substreams[i];
350 
351 		vss->snd = snd;
352 		vss->sid = i;
353 		INIT_WORK(&vss->elapsed_period, virtsnd_pcm_period_elapsed);
354 		init_waitqueue_head(&vss->msg_empty);
355 		spin_lock_init(&vss->lock);
356 	}
357 
358 	info = kzalloc_objs(*info, snd->nsubstreams);
359 	if (!info)
360 		return -ENOMEM;
361 
362 	rc = virtsnd_ctl_query_info(snd, VIRTIO_SND_R_PCM_INFO, 0,
363 				    snd->nsubstreams, sizeof(*info), info);
364 	if (rc)
365 		goto on_exit;
366 
367 	for (i = 0; i < snd->nsubstreams; ++i) {
368 		struct virtio_pcm_substream *vss = &snd->substreams[i];
369 		struct virtio_pcm *vpcm;
370 
371 		rc = virtsnd_pcm_build_hw(vss, &info[i]);
372 		if (rc)
373 			goto on_exit;
374 
375 		vss->nid = le32_to_cpu(info[i].hdr.hda_fn_nid);
376 
377 		vpcm = virtsnd_pcm_find_or_create(snd, vss->nid);
378 		if (IS_ERR(vpcm)) {
379 			rc = PTR_ERR(vpcm);
380 			goto on_exit;
381 		}
382 
383 		switch (info[i].direction) {
384 		case VIRTIO_SND_D_OUTPUT:
385 			vss->direction = SNDRV_PCM_STREAM_PLAYBACK;
386 			break;
387 		case VIRTIO_SND_D_INPUT:
388 			vss->direction = SNDRV_PCM_STREAM_CAPTURE;
389 			break;
390 		default:
391 			dev_err(&vdev->dev, "SID %u: unknown direction (%u)\n",
392 				vss->sid, info[i].direction);
393 			rc = -EINVAL;
394 			goto on_exit;
395 		}
396 
397 		vpcm->streams[vss->direction].nsubstreams++;
398 	}
399 
400 on_exit:
401 	kfree(info);
402 
403 	return rc;
404 }
405 
406 /**
407  * virtsnd_pcm_build_devs() - Build ALSA PCM devices.
408  * @snd: VirtIO sound device.
409  *
410  * Context: Any context that permits to sleep.
411  * Return: 0 on success, -errno on failure.
412  */
413 int virtsnd_pcm_build_devs(struct virtio_snd *snd)
414 {
415 	struct virtio_device *vdev = snd->vdev;
416 	struct virtio_pcm *vpcm;
417 	u32 i;
418 	int rc;
419 
420 	list_for_each_entry(vpcm, &snd->pcm_list, list) {
421 		unsigned int npbs =
422 			vpcm->streams[SNDRV_PCM_STREAM_PLAYBACK].nsubstreams;
423 		unsigned int ncps =
424 			vpcm->streams[SNDRV_PCM_STREAM_CAPTURE].nsubstreams;
425 
426 		if (!npbs && !ncps)
427 			continue;
428 
429 		rc = snd_pcm_new(snd->card, VIRTIO_SND_CARD_DRIVER, vpcm->nid,
430 				 npbs, ncps, &vpcm->pcm);
431 		if (rc) {
432 			dev_err(&vdev->dev, "snd_pcm_new[%u] failed: %d\n",
433 				vpcm->nid, rc);
434 			return rc;
435 		}
436 
437 		vpcm->pcm->info_flags = 0;
438 		vpcm->pcm->dev_class = SNDRV_PCM_CLASS_GENERIC;
439 		vpcm->pcm->dev_subclass = SNDRV_PCM_SUBCLASS_GENERIC_MIX;
440 		snprintf(vpcm->pcm->name, sizeof(vpcm->pcm->name),
441 			 VIRTIO_SND_PCM_NAME " %u", vpcm->pcm->device);
442 		vpcm->pcm->private_data = vpcm;
443 		vpcm->pcm->nonatomic = true;
444 
445 		for (i = 0; i < ARRAY_SIZE(vpcm->streams); ++i) {
446 			struct virtio_pcm_stream *stream = &vpcm->streams[i];
447 
448 			if (!stream->nsubstreams)
449 				continue;
450 
451 			stream->substreams =
452 				devm_kcalloc(&vdev->dev, stream->nsubstreams,
453 					     sizeof(*stream->substreams),
454 					     GFP_KERNEL);
455 			if (!stream->substreams)
456 				return -ENOMEM;
457 
458 			stream->nsubstreams = 0;
459 		}
460 	}
461 
462 	for (i = 0; i < snd->nsubstreams; ++i) {
463 		struct virtio_pcm_stream *vs;
464 		struct virtio_pcm_substream *vss = &snd->substreams[i];
465 
466 		vpcm = virtsnd_pcm_find(snd, vss->nid);
467 		if (IS_ERR(vpcm))
468 			return PTR_ERR(vpcm);
469 
470 		vs = &vpcm->streams[vss->direction];
471 		vs->substreams[vs->nsubstreams++] = vss;
472 	}
473 
474 	list_for_each_entry(vpcm, &snd->pcm_list, list) {
475 		for (i = 0; i < ARRAY_SIZE(vpcm->streams); ++i) {
476 			struct virtio_pcm_stream *vs = &vpcm->streams[i];
477 			struct snd_pcm_str *ks = &vpcm->pcm->streams[i];
478 			struct snd_pcm_substream *kss;
479 
480 			if (!vs->nsubstreams)
481 				continue;
482 
483 			for (kss = ks->substream; kss; kss = kss->next)
484 				vs->substreams[kss->number]->substream = kss;
485 
486 			snd_pcm_set_ops(vpcm->pcm, i, &virtsnd_pcm_ops[i]);
487 		}
488 
489 		snd_pcm_set_managed_buffer_all(vpcm->pcm,
490 					       SNDRV_DMA_TYPE_VMALLOC, NULL,
491 					       0, 0);
492 	}
493 
494 	return 0;
495 }
496 
497 /**
498  * virtsnd_pcm_event() - Handle the PCM device event notification.
499  * @snd: VirtIO sound device.
500  * @event: VirtIO sound event.
501  *
502  * Context: Interrupt context.
503  */
504 void virtsnd_pcm_event(struct virtio_snd *snd, struct virtio_snd_event *event)
505 {
506 	struct virtio_pcm_substream *vss;
507 	u32 sid = le32_to_cpu(event->data);
508 
509 	if (sid >= snd->nsubstreams)
510 		return;
511 
512 	vss = &snd->substreams[sid];
513 
514 	switch (le32_to_cpu(event->hdr.code)) {
515 	case VIRTIO_SND_EVT_PCM_PERIOD_ELAPSED:
516 		/* TODO: deal with shmem elapsed period */
517 		break;
518 	case VIRTIO_SND_EVT_PCM_XRUN:
519 		scoped_guard(spinlock, &vss->lock) {
520 			if (vss->xfer_enabled)
521 				vss->xfer_xrun = true;
522 		}
523 		break;
524 	}
525 }
526