xref: /openbmc/qemu/hw/audio/virtio-snd.c (revision 13af3af1)
1 /*
2  * VIRTIO Sound Device conforming to
3  *
4  * "Virtual I/O Device (VIRTIO) Version 1.2
5  * Committee Specification Draft 01
6  * 09 May 2022"
7  *
8  * <https://docs.oasis-open.org/virtio/virtio/v1.2/csd01/virtio-v1.2-csd01.html#x1-52900014>
9  *
10  * Copyright (c) 2023 Emmanouil Pitsidianakis <manos.pitsidianakis@linaro.org>
11  * Copyright (C) 2019 OpenSynergy GmbH
12  *
13  * This work is licensed under the terms of the GNU GPL, version 2 or
14  * (at your option) any later version.  See the COPYING file in the
15  * top-level directory.
16  */
17 
18 #include "qemu/osdep.h"
19 #include "qemu/iov.h"
20 #include "qemu/log.h"
21 #include "qemu/error-report.h"
22 #include "include/qemu/lockable.h"
23 #include "sysemu/runstate.h"
24 #include "trace.h"
25 #include "qapi/error.h"
26 #include "hw/audio/virtio-snd.h"
27 #include "hw/core/cpu.h"
28 
29 #define VIRTIO_SOUND_VM_VERSION 1
30 #define VIRTIO_SOUND_JACK_DEFAULT 0
31 #define VIRTIO_SOUND_STREAM_DEFAULT 2
32 #define VIRTIO_SOUND_CHMAP_DEFAULT 0
33 #define VIRTIO_SOUND_HDA_FN_NID 0
34 
35 static void virtio_snd_pcm_out_cb(void *data, int available);
36 static void virtio_snd_process_cmdq(VirtIOSound *s);
37 static void virtio_snd_pcm_flush(VirtIOSoundPCMStream *stream);
38 static void virtio_snd_pcm_in_cb(void *data, int available);
39 static void virtio_snd_unrealize(DeviceState *dev);
40 
41 static uint32_t supported_formats = BIT(VIRTIO_SND_PCM_FMT_S8)
42                                   | BIT(VIRTIO_SND_PCM_FMT_U8)
43                                   | BIT(VIRTIO_SND_PCM_FMT_S16)
44                                   | BIT(VIRTIO_SND_PCM_FMT_U16)
45                                   | BIT(VIRTIO_SND_PCM_FMT_S32)
46                                   | BIT(VIRTIO_SND_PCM_FMT_U32)
47                                   | BIT(VIRTIO_SND_PCM_FMT_FLOAT);
48 
49 static uint32_t supported_rates = BIT(VIRTIO_SND_PCM_RATE_5512)
50                                 | BIT(VIRTIO_SND_PCM_RATE_8000)
51                                 | BIT(VIRTIO_SND_PCM_RATE_11025)
52                                 | BIT(VIRTIO_SND_PCM_RATE_16000)
53                                 | BIT(VIRTIO_SND_PCM_RATE_22050)
54                                 | BIT(VIRTIO_SND_PCM_RATE_32000)
55                                 | BIT(VIRTIO_SND_PCM_RATE_44100)
56                                 | BIT(VIRTIO_SND_PCM_RATE_48000)
57                                 | BIT(VIRTIO_SND_PCM_RATE_64000)
58                                 | BIT(VIRTIO_SND_PCM_RATE_88200)
59                                 | BIT(VIRTIO_SND_PCM_RATE_96000)
60                                 | BIT(VIRTIO_SND_PCM_RATE_176400)
61                                 | BIT(VIRTIO_SND_PCM_RATE_192000)
62                                 | BIT(VIRTIO_SND_PCM_RATE_384000);
63 
64 static const VMStateDescription vmstate_virtio_snd_device = {
65     .name = TYPE_VIRTIO_SND,
66     .version_id = VIRTIO_SOUND_VM_VERSION,
67     .minimum_version_id = VIRTIO_SOUND_VM_VERSION,
68 };
69 
70 static const VMStateDescription vmstate_virtio_snd = {
71     .name = TYPE_VIRTIO_SND,
72     .unmigratable = 1,
73     .minimum_version_id = VIRTIO_SOUND_VM_VERSION,
74     .version_id = VIRTIO_SOUND_VM_VERSION,
75     .fields = (const VMStateField[]) {
76         VMSTATE_VIRTIO_DEVICE,
77         VMSTATE_END_OF_LIST()
78     },
79 };
80 
81 static Property virtio_snd_properties[] = {
82     DEFINE_AUDIO_PROPERTIES(VirtIOSound, card),
83     DEFINE_PROP_UINT32("jacks", VirtIOSound, snd_conf.jacks,
84                        VIRTIO_SOUND_JACK_DEFAULT),
85     DEFINE_PROP_UINT32("streams", VirtIOSound, snd_conf.streams,
86                        VIRTIO_SOUND_STREAM_DEFAULT),
87     DEFINE_PROP_UINT32("chmaps", VirtIOSound, snd_conf.chmaps,
88                        VIRTIO_SOUND_CHMAP_DEFAULT),
89     DEFINE_PROP_END_OF_LIST(),
90 };
91 
92 static void
93 virtio_snd_get_config(VirtIODevice *vdev, uint8_t *config)
94 {
95     VirtIOSound *s = VIRTIO_SND(vdev);
96     virtio_snd_config *sndconfig =
97         (virtio_snd_config *)config;
98     trace_virtio_snd_get_config(vdev,
99                                 s->snd_conf.jacks,
100                                 s->snd_conf.streams,
101                                 s->snd_conf.chmaps);
102 
103     memcpy(sndconfig, &s->snd_conf, sizeof(s->snd_conf));
104     cpu_to_le32s(&sndconfig->jacks);
105     cpu_to_le32s(&sndconfig->streams);
106     cpu_to_le32s(&sndconfig->chmaps);
107 
108 }
109 
110 static void
111 virtio_snd_set_config(VirtIODevice *vdev, const uint8_t *config)
112 {
113     VirtIOSound *s = VIRTIO_SND(vdev);
114     const virtio_snd_config *sndconfig =
115         (const virtio_snd_config *)config;
116 
117 
118    trace_virtio_snd_set_config(vdev,
119                                s->snd_conf.jacks,
120                                sndconfig->jacks,
121                                s->snd_conf.streams,
122                                sndconfig->streams,
123                                s->snd_conf.chmaps,
124                                sndconfig->chmaps);
125 
126     memcpy(&s->snd_conf, sndconfig, sizeof(virtio_snd_config));
127     le32_to_cpus(&s->snd_conf.jacks);
128     le32_to_cpus(&s->snd_conf.streams);
129     le32_to_cpus(&s->snd_conf.chmaps);
130 
131 }
132 
133 static void
134 virtio_snd_pcm_buffer_free(VirtIOSoundPCMBuffer *buffer)
135 {
136     g_free(buffer->elem);
137     g_free(buffer);
138 }
139 
140 static void
141 virtio_snd_ctrl_cmd_free(virtio_snd_ctrl_command *cmd)
142 {
143     g_free(cmd->elem);
144     g_free(cmd);
145 }
146 
147 /*
148  * Get a specific stream from the virtio sound card device.
149  * Returns NULL if @stream_id is invalid or not allocated.
150  *
151  * @s: VirtIOSound device
152  * @stream_id: stream id
153  */
154 static VirtIOSoundPCMStream *virtio_snd_pcm_get_stream(VirtIOSound *s,
155                                                        uint32_t stream_id)
156 {
157     return stream_id >= s->snd_conf.streams ? NULL :
158         s->pcm->streams[stream_id];
159 }
160 
161 /*
162  * Get params for a specific stream.
163  *
164  * @s: VirtIOSound device
165  * @stream_id: stream id
166  */
167 static virtio_snd_pcm_set_params *virtio_snd_pcm_get_params(VirtIOSound *s,
168                                                             uint32_t stream_id)
169 {
170     return stream_id >= s->snd_conf.streams ? NULL
171         : &s->pcm->pcm_params[stream_id];
172 }
173 
174 /*
175  * Handle the VIRTIO_SND_R_PCM_INFO request.
176  * The function writes the info structs to the request element.
177  *
178  * @s: VirtIOSound device
179  * @cmd: The request command queue element from VirtIOSound cmdq field
180  */
181 static void virtio_snd_handle_pcm_info(VirtIOSound *s,
182                                        virtio_snd_ctrl_command *cmd)
183 {
184     uint32_t stream_id, start_id, count, size;
185     virtio_snd_pcm_info val;
186     virtio_snd_query_info req;
187     VirtIOSoundPCMStream *stream = NULL;
188     g_autofree virtio_snd_pcm_info *pcm_info = NULL;
189     size_t msg_sz = iov_to_buf(cmd->elem->out_sg,
190                                cmd->elem->out_num,
191                                0,
192                                &req,
193                                sizeof(virtio_snd_query_info));
194 
195     if (msg_sz != sizeof(virtio_snd_query_info)) {
196         /*
197          * TODO: do we need to set DEVICE_NEEDS_RESET?
198          */
199         qemu_log_mask(LOG_GUEST_ERROR,
200                 "%s: virtio-snd command size incorrect %zu vs \
201                 %zu\n", __func__, msg_sz, sizeof(virtio_snd_query_info));
202         cmd->resp.code = cpu_to_le32(VIRTIO_SND_S_BAD_MSG);
203         return;
204     }
205 
206     start_id = le32_to_cpu(req.start_id);
207     count = le32_to_cpu(req.count);
208     size = le32_to_cpu(req.size);
209 
210     if (iov_size(cmd->elem->in_sg, cmd->elem->in_num) <
211         sizeof(virtio_snd_hdr) + size * count) {
212         /*
213          * TODO: do we need to set DEVICE_NEEDS_RESET?
214          */
215         error_report("pcm info: buffer too small, got: %zu, needed: %zu",
216                 iov_size(cmd->elem->in_sg, cmd->elem->in_num),
217                 sizeof(virtio_snd_pcm_info));
218         cmd->resp.code = cpu_to_le32(VIRTIO_SND_S_BAD_MSG);
219         return;
220     }
221 
222     pcm_info = g_new0(virtio_snd_pcm_info, count);
223     for (uint32_t i = 0; i < count; i++) {
224         stream_id = i + start_id;
225         trace_virtio_snd_handle_pcm_info(stream_id);
226         stream = virtio_snd_pcm_get_stream(s, stream_id);
227         if (!stream) {
228             error_report("Invalid stream id: %"PRIu32, stream_id);
229             cmd->resp.code = cpu_to_le32(VIRTIO_SND_S_BAD_MSG);
230             return;
231         }
232         val = stream->info;
233         val.hdr.hda_fn_nid = cpu_to_le32(val.hdr.hda_fn_nid);
234         val.features = cpu_to_le32(val.features);
235         val.formats = cpu_to_le64(val.formats);
236         val.rates = cpu_to_le64(val.rates);
237         /*
238          * 5.14.6.6.2.1 Device Requirements: Stream Information The device MUST
239          * NOT set undefined feature, format, rate and direction values. The
240          * device MUST initialize the padding bytes to 0.
241          */
242         pcm_info[i] = val;
243         memset(&pcm_info[i].padding, 0, 5);
244     }
245 
246     cmd->payload_size = sizeof(virtio_snd_pcm_info) * count;
247     cmd->resp.code = cpu_to_le32(VIRTIO_SND_S_OK);
248     iov_from_buf(cmd->elem->in_sg,
249                  cmd->elem->in_num,
250                  sizeof(virtio_snd_hdr),
251                  pcm_info,
252                  cmd->payload_size);
253 }
254 
255 /*
256  * Set the given stream params.
257  * Called by both virtio_snd_handle_pcm_set_params and during device
258  * initialization.
259  * Returns the response status code. (VIRTIO_SND_S_*).
260  *
261  * @s: VirtIOSound device
262  * @params: The PCM params as defined in the virtio specification
263  */
264 static
265 uint32_t virtio_snd_set_pcm_params(VirtIOSound *s,
266                                    uint32_t stream_id,
267                                    virtio_snd_pcm_set_params *params)
268 {
269     virtio_snd_pcm_set_params *st_params;
270 
271     if (stream_id >= s->snd_conf.streams || s->pcm->pcm_params == NULL) {
272         /*
273          * TODO: do we need to set DEVICE_NEEDS_RESET?
274          */
275         virtio_error(VIRTIO_DEVICE(s), "Streams have not been initialized.\n");
276         return cpu_to_le32(VIRTIO_SND_S_BAD_MSG);
277     }
278 
279     st_params = virtio_snd_pcm_get_params(s, stream_id);
280 
281     if (params->channels < 1 || params->channels > AUDIO_MAX_CHANNELS) {
282         error_report("Number of channels is not supported.");
283         return cpu_to_le32(VIRTIO_SND_S_NOT_SUPP);
284     }
285     if (!(supported_formats & BIT(params->format))) {
286         error_report("Stream format is not supported.");
287         return cpu_to_le32(VIRTIO_SND_S_NOT_SUPP);
288     }
289     if (!(supported_rates & BIT(params->rate))) {
290         error_report("Stream rate is not supported.");
291         return cpu_to_le32(VIRTIO_SND_S_NOT_SUPP);
292     }
293 
294     st_params->buffer_bytes = le32_to_cpu(params->buffer_bytes);
295     st_params->period_bytes = le32_to_cpu(params->period_bytes);
296     st_params->features = le32_to_cpu(params->features);
297     /* the following are uint8_t, so there's no need to bswap the values. */
298     st_params->channels = params->channels;
299     st_params->format = params->format;
300     st_params->rate = params->rate;
301 
302     return cpu_to_le32(VIRTIO_SND_S_OK);
303 }
304 
305 /*
306  * Handles the VIRTIO_SND_R_PCM_SET_PARAMS request.
307  *
308  * @s: VirtIOSound device
309  * @cmd: The request command queue element from VirtIOSound cmdq field
310  */
311 static void virtio_snd_handle_pcm_set_params(VirtIOSound *s,
312                                              virtio_snd_ctrl_command *cmd)
313 {
314     virtio_snd_pcm_set_params req = { 0 };
315     uint32_t stream_id;
316     size_t msg_sz = iov_to_buf(cmd->elem->out_sg,
317                                cmd->elem->out_num,
318                                0,
319                                &req,
320                                sizeof(virtio_snd_pcm_set_params));
321 
322     if (msg_sz != sizeof(virtio_snd_pcm_set_params)) {
323         /*
324          * TODO: do we need to set DEVICE_NEEDS_RESET?
325          */
326         qemu_log_mask(LOG_GUEST_ERROR,
327                 "%s: virtio-snd command size incorrect %zu vs \
328                 %zu\n", __func__, msg_sz, sizeof(virtio_snd_pcm_set_params));
329         cmd->resp.code = cpu_to_le32(VIRTIO_SND_S_BAD_MSG);
330         return;
331     }
332     stream_id = le32_to_cpu(req.hdr.stream_id);
333     trace_virtio_snd_handle_pcm_set_params(stream_id);
334     cmd->resp.code = virtio_snd_set_pcm_params(s, stream_id, &req);
335 }
336 
337 /*
338  * Get a QEMU Audiosystem compatible format value from a VIRTIO_SND_PCM_FMT_*
339  */
340 static AudioFormat virtio_snd_get_qemu_format(uint32_t format)
341 {
342     #define CASE(FMT)               \
343     case VIRTIO_SND_PCM_FMT_##FMT:  \
344         return AUDIO_FORMAT_##FMT;
345 
346     switch (format) {
347     CASE(U8)
348     CASE(S8)
349     CASE(U16)
350     CASE(S16)
351     CASE(U32)
352     CASE(S32)
353     case VIRTIO_SND_PCM_FMT_FLOAT:
354         return AUDIO_FORMAT_F32;
355     default:
356         g_assert_not_reached();
357     }
358 
359     #undef CASE
360 }
361 
362 /*
363  * Get a QEMU Audiosystem compatible frequency value from a
364  * VIRTIO_SND_PCM_RATE_*
365  */
366 static uint32_t virtio_snd_get_qemu_freq(uint32_t rate)
367 {
368     #define CASE(RATE)               \
369     case VIRTIO_SND_PCM_RATE_##RATE: \
370         return RATE;
371 
372     switch (rate) {
373     CASE(5512)
374     CASE(8000)
375     CASE(11025)
376     CASE(16000)
377     CASE(22050)
378     CASE(32000)
379     CASE(44100)
380     CASE(48000)
381     CASE(64000)
382     CASE(88200)
383     CASE(96000)
384     CASE(176400)
385     CASE(192000)
386     CASE(384000)
387     default:
388         g_assert_not_reached();
389     }
390 
391     #undef CASE
392 }
393 
394 /*
395  * Get QEMU Audiosystem compatible audsettings from virtio based pcm stream
396  * params.
397  */
398 static void virtio_snd_get_qemu_audsettings(audsettings *as,
399                                             virtio_snd_pcm_set_params *params)
400 {
401     as->nchannels = MIN(AUDIO_MAX_CHANNELS, params->channels);
402     as->fmt = virtio_snd_get_qemu_format(params->format);
403     as->freq = virtio_snd_get_qemu_freq(params->rate);
404     as->endianness = target_words_bigendian() ? 1 : 0;
405 }
406 
407 /*
408  * Close a stream and free all its resources.
409  *
410  * @stream: VirtIOSoundPCMStream *stream
411  */
412 static void virtio_snd_pcm_close(VirtIOSoundPCMStream *stream)
413 {
414     if (stream) {
415         virtio_snd_pcm_flush(stream);
416         if (stream->info.direction == VIRTIO_SND_D_OUTPUT) {
417             AUD_close_out(&stream->pcm->snd->card, stream->voice.out);
418             stream->voice.out = NULL;
419         } else if (stream->info.direction == VIRTIO_SND_D_INPUT) {
420             AUD_close_in(&stream->pcm->snd->card, stream->voice.in);
421             stream->voice.in = NULL;
422         }
423     }
424 }
425 
426 /*
427  * Prepares a VirtIOSound card stream.
428  * Returns the response status code. (VIRTIO_SND_S_*).
429  *
430  * @s: VirtIOSound device
431  * @stream_id: stream id
432  */
433 static uint32_t virtio_snd_pcm_prepare(VirtIOSound *s, uint32_t stream_id)
434 {
435     audsettings as;
436     virtio_snd_pcm_set_params *params;
437     VirtIOSoundPCMStream *stream;
438 
439     if (s->pcm->streams == NULL ||
440         s->pcm->pcm_params == NULL ||
441         stream_id >= s->snd_conf.streams) {
442         return cpu_to_le32(VIRTIO_SND_S_BAD_MSG);
443     }
444 
445     params = virtio_snd_pcm_get_params(s, stream_id);
446     if (params == NULL) {
447         return cpu_to_le32(VIRTIO_SND_S_BAD_MSG);
448     }
449 
450     stream = virtio_snd_pcm_get_stream(s, stream_id);
451     if (stream == NULL) {
452         stream = g_new0(VirtIOSoundPCMStream, 1);
453         stream->active = false;
454         stream->id = stream_id;
455         stream->pcm = s->pcm;
456         stream->s = s;
457         qemu_mutex_init(&stream->queue_mutex);
458         QSIMPLEQ_INIT(&stream->queue);
459         QSIMPLEQ_INIT(&stream->invalid);
460 
461         /*
462          * stream_id >= s->snd_conf.streams was checked before so this is
463          * in-bounds
464          */
465         s->pcm->streams[stream_id] = stream;
466     }
467 
468     virtio_snd_get_qemu_audsettings(&as, params);
469     stream->info.direction = stream_id < s->snd_conf.streams / 2 +
470         (s->snd_conf.streams & 1) ? VIRTIO_SND_D_OUTPUT : VIRTIO_SND_D_INPUT;
471     stream->info.hdr.hda_fn_nid = VIRTIO_SOUND_HDA_FN_NID;
472     stream->info.features = 0;
473     stream->info.channels_min = 1;
474     stream->info.channels_max = as.nchannels;
475     stream->info.formats = supported_formats;
476     stream->info.rates = supported_rates;
477     stream->params = *params;
478 
479     stream->positions[0] = VIRTIO_SND_CHMAP_FL;
480     stream->positions[1] = VIRTIO_SND_CHMAP_FR;
481     stream->as = as;
482 
483     if (stream->info.direction == VIRTIO_SND_D_OUTPUT) {
484         stream->voice.out = AUD_open_out(&s->card,
485                                          stream->voice.out,
486                                          "virtio-sound.out",
487                                          stream,
488                                          virtio_snd_pcm_out_cb,
489                                          &as);
490         AUD_set_volume_out(stream->voice.out, 0, 255, 255);
491     } else {
492         stream->voice.in = AUD_open_in(&s->card,
493                                         stream->voice.in,
494                                         "virtio-sound.in",
495                                         stream,
496                                         virtio_snd_pcm_in_cb,
497                                         &as);
498         AUD_set_volume_in(stream->voice.in, 0, 255, 255);
499     }
500 
501     return cpu_to_le32(VIRTIO_SND_S_OK);
502 }
503 
504 static const char *print_code(uint32_t code)
505 {
506     #define CASE(CODE)            \
507     case VIRTIO_SND_R_##CODE:     \
508         return "VIRTIO_SND_R_"#CODE
509 
510     switch (code) {
511     CASE(JACK_INFO);
512     CASE(JACK_REMAP);
513     CASE(PCM_INFO);
514     CASE(PCM_SET_PARAMS);
515     CASE(PCM_PREPARE);
516     CASE(PCM_RELEASE);
517     CASE(PCM_START);
518     CASE(PCM_STOP);
519     CASE(CHMAP_INFO);
520     default:
521         return "invalid code";
522     }
523 
524     #undef CASE
525 };
526 
527 /*
528  * Handles VIRTIO_SND_R_PCM_PREPARE.
529  *
530  * @s: VirtIOSound device
531  * @cmd: The request command queue element from VirtIOSound cmdq field
532  */
533 static void virtio_snd_handle_pcm_prepare(VirtIOSound *s,
534                                           virtio_snd_ctrl_command *cmd)
535 {
536     uint32_t stream_id;
537     size_t msg_sz = iov_to_buf(cmd->elem->out_sg,
538                                cmd->elem->out_num,
539                                sizeof(virtio_snd_hdr),
540                                &stream_id,
541                                sizeof(stream_id));
542 
543     stream_id = le32_to_cpu(stream_id);
544     cmd->resp.code = msg_sz == sizeof(stream_id)
545                    ? virtio_snd_pcm_prepare(s, stream_id)
546                    : cpu_to_le32(VIRTIO_SND_S_BAD_MSG);
547 }
548 
549 /*
550  * Handles VIRTIO_SND_R_PCM_START.
551  *
552  * @s: VirtIOSound device
553  * @cmd: The request command queue element from VirtIOSound cmdq field
554  * @start: whether to start or stop the device
555  */
556 static void virtio_snd_handle_pcm_start_stop(VirtIOSound *s,
557                                              virtio_snd_ctrl_command *cmd,
558                                              bool start)
559 {
560     VirtIOSoundPCMStream *stream;
561     virtio_snd_pcm_hdr req;
562     uint32_t stream_id;
563     size_t msg_sz = iov_to_buf(cmd->elem->out_sg,
564                                cmd->elem->out_num,
565                                0,
566                                &req,
567                                sizeof(virtio_snd_pcm_hdr));
568 
569     if (msg_sz != sizeof(virtio_snd_pcm_hdr)) {
570         qemu_log_mask(LOG_GUEST_ERROR,
571                 "%s: virtio-snd command size incorrect %zu vs \
572                 %zu\n", __func__, msg_sz, sizeof(virtio_snd_pcm_hdr));
573         cmd->resp.code = cpu_to_le32(VIRTIO_SND_S_BAD_MSG);
574         return;
575     }
576 
577     stream_id = le32_to_cpu(req.stream_id);
578     cmd->resp.code = cpu_to_le32(VIRTIO_SND_S_OK);
579     trace_virtio_snd_handle_pcm_start_stop(start ? "VIRTIO_SND_R_PCM_START" :
580             "VIRTIO_SND_R_PCM_STOP", stream_id);
581 
582     stream = virtio_snd_pcm_get_stream(s, stream_id);
583     if (stream) {
584         WITH_QEMU_LOCK_GUARD(&stream->queue_mutex) {
585             stream->active = start;
586         }
587         if (stream->info.direction == VIRTIO_SND_D_OUTPUT) {
588             AUD_set_active_out(stream->voice.out, start);
589         } else {
590             AUD_set_active_in(stream->voice.in, start);
591         }
592     } else {
593         error_report("Invalid stream id: %"PRIu32, stream_id);
594         cmd->resp.code = cpu_to_le32(VIRTIO_SND_S_BAD_MSG);
595         return;
596     }
597     stream->active = start;
598 }
599 
600 /*
601  * Returns the number of I/O messages that are being processed.
602  *
603  * @stream: VirtIOSoundPCMStream
604  */
605 static size_t virtio_snd_pcm_get_io_msgs_count(VirtIOSoundPCMStream *stream)
606 {
607     VirtIOSoundPCMBuffer *buffer, *next;
608     size_t count = 0;
609 
610     WITH_QEMU_LOCK_GUARD(&stream->queue_mutex) {
611         QSIMPLEQ_FOREACH_SAFE(buffer, &stream->queue, entry, next) {
612             count += 1;
613         }
614         QSIMPLEQ_FOREACH_SAFE(buffer, &stream->invalid, entry, next) {
615             count += 1;
616         }
617     }
618     return count;
619 }
620 
621 /*
622  * Handles VIRTIO_SND_R_PCM_RELEASE.
623  *
624  * @s: VirtIOSound device
625  * @cmd: The request command queue element from VirtIOSound cmdq field
626  */
627 static void virtio_snd_handle_pcm_release(VirtIOSound *s,
628                                           virtio_snd_ctrl_command *cmd)
629 {
630     uint32_t stream_id;
631     VirtIOSoundPCMStream *stream;
632     size_t msg_sz = iov_to_buf(cmd->elem->out_sg,
633                                cmd->elem->out_num,
634                                sizeof(virtio_snd_hdr),
635                                &stream_id,
636                                sizeof(stream_id));
637 
638     if (msg_sz != sizeof(stream_id)) {
639         /*
640          * TODO: do we need to set DEVICE_NEEDS_RESET?
641          */
642         qemu_log_mask(LOG_GUEST_ERROR,
643                 "%s: virtio-snd command size incorrect %zu vs \
644                 %zu\n", __func__, msg_sz, sizeof(stream_id));
645         cmd->resp.code = cpu_to_le32(VIRTIO_SND_S_BAD_MSG);
646         return;
647     }
648 
649     stream_id = le32_to_cpu(stream_id);
650     trace_virtio_snd_handle_pcm_release(stream_id);
651     stream = virtio_snd_pcm_get_stream(s, stream_id);
652     if (stream == NULL) {
653         /*
654          * TODO: do we need to set DEVICE_NEEDS_RESET?
655          */
656         error_report("already released stream %"PRIu32, stream_id);
657         virtio_error(VIRTIO_DEVICE(s),
658                      "already released stream %"PRIu32,
659                      stream_id);
660         cmd->resp.code = cpu_to_le32(VIRTIO_SND_S_BAD_MSG);
661         return;
662     }
663 
664     if (virtio_snd_pcm_get_io_msgs_count(stream)) {
665         /*
666          * virtio-v1.2-csd01, 5.14.6.6.5.1,
667          * Device Requirements: Stream Release
668          *
669          * - The device MUST complete all pending I/O messages for the
670          *   specified stream ID.
671          * - The device MUST NOT complete the control request while there
672          *   are pending I/O messages for the specified stream ID.
673          */
674         trace_virtio_snd_pcm_stream_flush(stream_id);
675         virtio_snd_pcm_flush(stream);
676     }
677 
678     cmd->resp.code = cpu_to_le32(VIRTIO_SND_S_OK);
679 }
680 
681 /*
682  * The actual processing done in virtio_snd_process_cmdq().
683  *
684  * @s: VirtIOSound device
685  * @cmd: control command request
686  */
687 static inline void
688 process_cmd(VirtIOSound *s, virtio_snd_ctrl_command *cmd)
689 {
690     uint32_t code;
691     size_t msg_sz = iov_to_buf(cmd->elem->out_sg,
692                                cmd->elem->out_num,
693                                0,
694                                &cmd->ctrl,
695                                sizeof(virtio_snd_hdr));
696 
697     if (msg_sz != sizeof(virtio_snd_hdr)) {
698         /*
699          * TODO: do we need to set DEVICE_NEEDS_RESET?
700          */
701         qemu_log_mask(LOG_GUEST_ERROR,
702                 "%s: virtio-snd command size incorrect %zu vs \
703                 %zu\n", __func__, msg_sz, sizeof(virtio_snd_hdr));
704         return;
705     }
706 
707     code = le32_to_cpu(cmd->ctrl.code);
708 
709     trace_virtio_snd_handle_code(code, print_code(code));
710 
711     switch (code) {
712     case VIRTIO_SND_R_JACK_INFO:
713     case VIRTIO_SND_R_JACK_REMAP:
714         qemu_log_mask(LOG_UNIMP,
715                      "virtio_snd: jack functionality is unimplemented.\n");
716         cmd->resp.code = cpu_to_le32(VIRTIO_SND_S_NOT_SUPP);
717         break;
718     case VIRTIO_SND_R_PCM_INFO:
719         virtio_snd_handle_pcm_info(s, cmd);
720         break;
721     case VIRTIO_SND_R_PCM_START:
722         virtio_snd_handle_pcm_start_stop(s, cmd, true);
723         break;
724     case VIRTIO_SND_R_PCM_STOP:
725         virtio_snd_handle_pcm_start_stop(s, cmd, false);
726         break;
727     case VIRTIO_SND_R_PCM_SET_PARAMS:
728         virtio_snd_handle_pcm_set_params(s, cmd);
729         break;
730     case VIRTIO_SND_R_PCM_PREPARE:
731         virtio_snd_handle_pcm_prepare(s, cmd);
732         break;
733     case VIRTIO_SND_R_PCM_RELEASE:
734         virtio_snd_handle_pcm_release(s, cmd);
735         break;
736     case VIRTIO_SND_R_CHMAP_INFO:
737         qemu_log_mask(LOG_UNIMP,
738                      "virtio_snd: chmap info functionality is unimplemented.\n");
739         trace_virtio_snd_handle_chmap_info();
740         cmd->resp.code = cpu_to_le32(VIRTIO_SND_S_NOT_SUPP);
741         break;
742     default:
743         /* error */
744         error_report("virtio snd header not recognized: %"PRIu32, code);
745         cmd->resp.code = cpu_to_le32(VIRTIO_SND_S_BAD_MSG);
746     }
747 
748     iov_from_buf(cmd->elem->in_sg,
749                  cmd->elem->in_num,
750                  0,
751                  &cmd->resp,
752                  sizeof(virtio_snd_hdr));
753     virtqueue_push(cmd->vq, cmd->elem,
754                    sizeof(virtio_snd_hdr) + cmd->payload_size);
755     virtio_notify(VIRTIO_DEVICE(s), cmd->vq);
756 }
757 
758 /*
759  * Consume all elements in command queue.
760  *
761  * @s: VirtIOSound device
762  */
763 static void virtio_snd_process_cmdq(VirtIOSound *s)
764 {
765     virtio_snd_ctrl_command *cmd;
766 
767     if (unlikely(qatomic_read(&s->processing_cmdq))) {
768         return;
769     }
770 
771     WITH_QEMU_LOCK_GUARD(&s->cmdq_mutex) {
772         qatomic_set(&s->processing_cmdq, true);
773         while (!QTAILQ_EMPTY(&s->cmdq)) {
774             cmd = QTAILQ_FIRST(&s->cmdq);
775 
776             /* process command */
777             process_cmd(s, cmd);
778 
779             QTAILQ_REMOVE(&s->cmdq, cmd, next);
780 
781             virtio_snd_ctrl_cmd_free(cmd);
782         }
783         qatomic_set(&s->processing_cmdq, false);
784     }
785 }
786 
787 /*
788  * The control message handler. Pops an element from the control virtqueue,
789  * and stores them to VirtIOSound's cmdq queue and finally calls
790  * virtio_snd_process_cmdq() for processing.
791  *
792  * @vdev: VirtIOSound device
793  * @vq: Control virtqueue
794  */
795 static void virtio_snd_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq)
796 {
797     VirtIOSound *s = VIRTIO_SND(vdev);
798     VirtQueueElement *elem;
799     virtio_snd_ctrl_command *cmd;
800 
801     trace_virtio_snd_handle_ctrl(vdev, vq);
802 
803     if (!virtio_queue_ready(vq)) {
804         return;
805     }
806 
807     elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
808     while (elem) {
809         cmd = g_new0(virtio_snd_ctrl_command, 1);
810         cmd->elem = elem;
811         cmd->vq = vq;
812         cmd->resp.code = cpu_to_le32(VIRTIO_SND_S_OK);
813         /* implicit cmd->payload_size = 0; */
814         QTAILQ_INSERT_TAIL(&s->cmdq, cmd, next);
815         elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
816     }
817 
818     virtio_snd_process_cmdq(s);
819 }
820 
821 /*
822  * The event virtqueue handler.
823  * Not implemented yet.
824  *
825  * @vdev: VirtIOSound device
826  * @vq: event vq
827  */
828 static void virtio_snd_handle_event(VirtIODevice *vdev, VirtQueue *vq)
829 {
830     qemu_log_mask(LOG_UNIMP, "virtio_snd: event queue is unimplemented.\n");
831     trace_virtio_snd_handle_event();
832 }
833 
834 static inline void empty_invalid_queue(VirtIODevice *vdev, VirtQueue *vq)
835 {
836     VirtIOSoundPCMBuffer *buffer = NULL;
837     VirtIOSoundPCMStream *stream = NULL;
838     virtio_snd_pcm_status resp = { 0 };
839     VirtIOSound *vsnd = VIRTIO_SND(vdev);
840     bool any = false;
841 
842     for (uint32_t i = 0; i < vsnd->snd_conf.streams; i++) {
843         stream = vsnd->pcm->streams[i];
844         if (stream) {
845             any = false;
846             WITH_QEMU_LOCK_GUARD(&stream->queue_mutex) {
847                 while (!QSIMPLEQ_EMPTY(&stream->invalid)) {
848                     buffer = QSIMPLEQ_FIRST(&stream->invalid);
849                     if (buffer->vq != vq) {
850                         break;
851                     }
852                     any = true;
853                     resp.status = cpu_to_le32(VIRTIO_SND_S_BAD_MSG);
854                     iov_from_buf(buffer->elem->in_sg,
855                                  buffer->elem->in_num,
856                                  0,
857                                  &resp,
858                                  sizeof(virtio_snd_pcm_status));
859                     virtqueue_push(vq,
860                                    buffer->elem,
861                                    sizeof(virtio_snd_pcm_status));
862                     QSIMPLEQ_REMOVE_HEAD(&stream->invalid, entry);
863                     virtio_snd_pcm_buffer_free(buffer);
864                 }
865                 if (any) {
866                     /*
867                      * Notify vq about virtio_snd_pcm_status responses.
868                      * Buffer responses must be notified separately later.
869                      */
870                     virtio_notify(vdev, vq);
871                 }
872             }
873         }
874     }
875 }
876 
877 /*
878  * The tx virtqueue handler. Makes the buffers available to their respective
879  * streams for consumption.
880  *
881  * @vdev: VirtIOSound device
882  * @vq: tx virtqueue
883  */
884 static void virtio_snd_handle_tx_xfer(VirtIODevice *vdev, VirtQueue *vq)
885 {
886     VirtIOSound *s = VIRTIO_SND(vdev);
887     VirtIOSoundPCMStream *stream = NULL;
888     VirtIOSoundPCMBuffer *buffer;
889     VirtQueueElement *elem;
890     size_t msg_sz, size;
891     virtio_snd_pcm_xfer hdr;
892     uint32_t stream_id;
893     /*
894      * If any of the I/O messages are invalid, put them in stream->invalid and
895      * return them after the for loop.
896      */
897     bool must_empty_invalid_queue = false;
898 
899     if (!virtio_queue_ready(vq)) {
900         return;
901     }
902     trace_virtio_snd_handle_tx_xfer();
903 
904     for (;;) {
905         elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
906         if (!elem) {
907             break;
908         }
909         /* get the message hdr object */
910         msg_sz = iov_to_buf(elem->out_sg,
911                             elem->out_num,
912                             0,
913                             &hdr,
914                             sizeof(virtio_snd_pcm_xfer));
915         if (msg_sz != sizeof(virtio_snd_pcm_xfer)) {
916             goto tx_err;
917         }
918         stream_id = le32_to_cpu(hdr.stream_id);
919 
920         if (stream_id >= s->snd_conf.streams
921             || s->pcm->streams[stream_id] == NULL) {
922             goto tx_err;
923         }
924 
925         stream = s->pcm->streams[stream_id];
926         if (stream->info.direction != VIRTIO_SND_D_OUTPUT) {
927             goto tx_err;
928         }
929 
930         WITH_QEMU_LOCK_GUARD(&stream->queue_mutex) {
931             size = iov_size(elem->out_sg, elem->out_num) - msg_sz;
932 
933             buffer = g_malloc0(sizeof(VirtIOSoundPCMBuffer) + size);
934             buffer->elem = elem;
935             buffer->populated = false;
936             buffer->vq = vq;
937             buffer->size = size;
938             buffer->offset = 0;
939 
940             QSIMPLEQ_INSERT_TAIL(&stream->queue, buffer, entry);
941         }
942         continue;
943 
944 tx_err:
945         WITH_QEMU_LOCK_GUARD(&stream->queue_mutex) {
946             must_empty_invalid_queue = true;
947             buffer = g_malloc0(sizeof(VirtIOSoundPCMBuffer));
948             buffer->elem = elem;
949             buffer->vq = vq;
950             QSIMPLEQ_INSERT_TAIL(&stream->invalid, buffer, entry);
951         }
952     }
953 
954     if (must_empty_invalid_queue) {
955         empty_invalid_queue(vdev, vq);
956     }
957 }
958 
959 /*
960  * The rx virtqueue handler. Makes the buffers available to their respective
961  * streams for consumption.
962  *
963  * @vdev: VirtIOSound device
964  * @vq: rx virtqueue
965  */
966 static void virtio_snd_handle_rx_xfer(VirtIODevice *vdev, VirtQueue *vq)
967 {
968     VirtIOSound *s = VIRTIO_SND(vdev);
969     VirtIOSoundPCMStream *stream = NULL;
970     VirtIOSoundPCMBuffer *buffer;
971     VirtQueueElement *elem;
972     size_t msg_sz, size;
973     virtio_snd_pcm_xfer hdr;
974     uint32_t stream_id;
975     /*
976      * if any of the I/O messages are invalid, put them in stream->invalid and
977      * return them after the for loop.
978      */
979     bool must_empty_invalid_queue = false;
980 
981     if (!virtio_queue_ready(vq)) {
982         return;
983     }
984     trace_virtio_snd_handle_rx_xfer();
985 
986     for (;;) {
987         elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
988         if (!elem) {
989             break;
990         }
991         /* get the message hdr object */
992         msg_sz = iov_to_buf(elem->out_sg,
993                             elem->out_num,
994                             0,
995                             &hdr,
996                             sizeof(virtio_snd_pcm_xfer));
997         if (msg_sz != sizeof(virtio_snd_pcm_xfer)) {
998             goto rx_err;
999         }
1000         stream_id = le32_to_cpu(hdr.stream_id);
1001 
1002         if (stream_id >= s->snd_conf.streams
1003             || !s->pcm->streams[stream_id]) {
1004             goto rx_err;
1005         }
1006 
1007         stream = s->pcm->streams[stream_id];
1008         if (stream == NULL || stream->info.direction != VIRTIO_SND_D_INPUT) {
1009             goto rx_err;
1010         }
1011         WITH_QEMU_LOCK_GUARD(&stream->queue_mutex) {
1012             size = iov_size(elem->in_sg, elem->in_num) -
1013                 sizeof(virtio_snd_pcm_status);
1014             buffer = g_malloc0(sizeof(VirtIOSoundPCMBuffer) + size);
1015             buffer->elem = elem;
1016             buffer->vq = vq;
1017             buffer->size = 0;
1018             buffer->offset = 0;
1019             QSIMPLEQ_INSERT_TAIL(&stream->queue, buffer, entry);
1020         }
1021         continue;
1022 
1023 rx_err:
1024         WITH_QEMU_LOCK_GUARD(&stream->queue_mutex) {
1025             must_empty_invalid_queue = true;
1026             buffer = g_malloc0(sizeof(VirtIOSoundPCMBuffer));
1027             buffer->elem = elem;
1028             buffer->vq = vq;
1029             QSIMPLEQ_INSERT_TAIL(&stream->invalid, buffer, entry);
1030         }
1031     }
1032 
1033     if (must_empty_invalid_queue) {
1034         empty_invalid_queue(vdev, vq);
1035     }
1036 }
1037 
1038 static uint64_t get_features(VirtIODevice *vdev, uint64_t features,
1039                              Error **errp)
1040 {
1041     /*
1042      * virtio-v1.2-csd01, 5.14.3,
1043      * Feature Bits
1044      * None currently defined.
1045      */
1046     VirtIOSound *s = VIRTIO_SND(vdev);
1047     features |= s->features;
1048 
1049     trace_virtio_snd_get_features(vdev, features);
1050 
1051     return features;
1052 }
1053 
1054 static void
1055 virtio_snd_vm_state_change(void *opaque, bool running,
1056                                        RunState state)
1057 {
1058     if (running) {
1059         trace_virtio_snd_vm_state_running();
1060     } else {
1061         trace_virtio_snd_vm_state_stopped();
1062     }
1063 }
1064 
1065 static void virtio_snd_realize(DeviceState *dev, Error **errp)
1066 {
1067     ERRP_GUARD();
1068     VirtIOSound *vsnd = VIRTIO_SND(dev);
1069     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1070     virtio_snd_pcm_set_params default_params = { 0 };
1071     uint32_t status;
1072 
1073     trace_virtio_snd_realize(vsnd);
1074 
1075     /* check number of jacks and streams */
1076     if (vsnd->snd_conf.jacks > 8) {
1077         error_setg(errp,
1078                    "Invalid number of jacks: %"PRIu32,
1079                    vsnd->snd_conf.jacks);
1080         return;
1081     }
1082     if (vsnd->snd_conf.streams < 1 || vsnd->snd_conf.streams > 10) {
1083         error_setg(errp,
1084                    "Invalid number of streams: %"PRIu32,
1085                     vsnd->snd_conf.streams);
1086         return;
1087     }
1088 
1089     if (vsnd->snd_conf.chmaps > VIRTIO_SND_CHMAP_MAX_SIZE) {
1090         error_setg(errp,
1091                    "Invalid number of channel maps: %"PRIu32,
1092                    vsnd->snd_conf.chmaps);
1093         return;
1094     }
1095 
1096     if (!AUD_register_card("virtio-sound", &vsnd->card, errp)) {
1097         return;
1098     }
1099 
1100     vsnd->vmstate =
1101         qemu_add_vm_change_state_handler(virtio_snd_vm_state_change, vsnd);
1102 
1103     vsnd->pcm = g_new0(VirtIOSoundPCM, 1);
1104     vsnd->pcm->snd = vsnd;
1105     vsnd->pcm->streams =
1106         g_new0(VirtIOSoundPCMStream *, vsnd->snd_conf.streams);
1107     vsnd->pcm->pcm_params =
1108         g_new0(virtio_snd_pcm_set_params, vsnd->snd_conf.streams);
1109 
1110     virtio_init(vdev, VIRTIO_ID_SOUND, sizeof(virtio_snd_config));
1111     virtio_add_feature(&vsnd->features, VIRTIO_F_VERSION_1);
1112 
1113     /* set default params for all streams */
1114     default_params.features = 0;
1115     default_params.buffer_bytes = cpu_to_le32(8192);
1116     default_params.period_bytes = cpu_to_le32(2048);
1117     default_params.channels = 2;
1118     default_params.format = VIRTIO_SND_PCM_FMT_S16;
1119     default_params.rate = VIRTIO_SND_PCM_RATE_48000;
1120     vsnd->queues[VIRTIO_SND_VQ_CONTROL] =
1121         virtio_add_queue(vdev, 64, virtio_snd_handle_ctrl);
1122     vsnd->queues[VIRTIO_SND_VQ_EVENT] =
1123         virtio_add_queue(vdev, 64, virtio_snd_handle_event);
1124     vsnd->queues[VIRTIO_SND_VQ_TX] =
1125         virtio_add_queue(vdev, 64, virtio_snd_handle_tx_xfer);
1126     vsnd->queues[VIRTIO_SND_VQ_RX] =
1127         virtio_add_queue(vdev, 64, virtio_snd_handle_rx_xfer);
1128     qemu_mutex_init(&vsnd->cmdq_mutex);
1129     QTAILQ_INIT(&vsnd->cmdq);
1130 
1131     for (uint32_t i = 0; i < vsnd->snd_conf.streams; i++) {
1132         status = virtio_snd_set_pcm_params(vsnd, i, &default_params);
1133         if (status != cpu_to_le32(VIRTIO_SND_S_OK)) {
1134             error_setg(errp,
1135                        "Can't initialize stream params, device responded with %s.",
1136                        print_code(status));
1137             goto error_cleanup;
1138         }
1139         status = virtio_snd_pcm_prepare(vsnd, i);
1140         if (status != cpu_to_le32(VIRTIO_SND_S_OK)) {
1141             error_setg(errp,
1142                        "Can't prepare streams, device responded with %s.",
1143                        print_code(status));
1144             goto error_cleanup;
1145         }
1146     }
1147 
1148     return;
1149 
1150 error_cleanup:
1151     virtio_snd_unrealize(dev);
1152 }
1153 
1154 static inline void return_tx_buffer(VirtIOSoundPCMStream *stream,
1155                                     VirtIOSoundPCMBuffer *buffer)
1156 {
1157     virtio_snd_pcm_status resp = { 0 };
1158     resp.status = cpu_to_le32(VIRTIO_SND_S_OK);
1159     resp.latency_bytes = cpu_to_le32((uint32_t)buffer->size);
1160     iov_from_buf(buffer->elem->in_sg,
1161                  buffer->elem->in_num,
1162                  0,
1163                  &resp,
1164                  sizeof(virtio_snd_pcm_status));
1165     virtqueue_push(buffer->vq,
1166                    buffer->elem,
1167                    sizeof(virtio_snd_pcm_status));
1168     virtio_notify(VIRTIO_DEVICE(stream->s), buffer->vq);
1169     QSIMPLEQ_REMOVE(&stream->queue,
1170                     buffer,
1171                     VirtIOSoundPCMBuffer,
1172                     entry);
1173     virtio_snd_pcm_buffer_free(buffer);
1174 }
1175 
1176 /*
1177  * AUD_* output callback.
1178  *
1179  * @data: VirtIOSoundPCMStream stream
1180  * @available: number of bytes that can be written with AUD_write()
1181  */
1182 static void virtio_snd_pcm_out_cb(void *data, int available)
1183 {
1184     VirtIOSoundPCMStream *stream = data;
1185     VirtIOSoundPCMBuffer *buffer;
1186     size_t size;
1187 
1188     WITH_QEMU_LOCK_GUARD(&stream->queue_mutex) {
1189         while (!QSIMPLEQ_EMPTY(&stream->queue)) {
1190             buffer = QSIMPLEQ_FIRST(&stream->queue);
1191             if (!virtio_queue_ready(buffer->vq)) {
1192                 return;
1193             }
1194             if (!stream->active) {
1195                 /* Stream has stopped, so do not perform AUD_write. */
1196                 return_tx_buffer(stream, buffer);
1197                 continue;
1198             }
1199             if (!buffer->populated) {
1200                 iov_to_buf(buffer->elem->out_sg,
1201                            buffer->elem->out_num,
1202                            sizeof(virtio_snd_pcm_xfer),
1203                            buffer->data,
1204                            buffer->size);
1205                 buffer->populated = true;
1206             }
1207             for (;;) {
1208                 size = AUD_write(stream->voice.out,
1209                                  buffer->data + buffer->offset,
1210                                  MIN(buffer->size, available));
1211                 assert(size <= MIN(buffer->size, available));
1212                 if (size == 0) {
1213                     /* break out of both loops */
1214                     available = 0;
1215                     break;
1216                 }
1217                 buffer->size -= size;
1218                 buffer->offset += size;
1219                 available -= size;
1220                 if (buffer->size < 1) {
1221                     return_tx_buffer(stream, buffer);
1222                     break;
1223                 }
1224                 if (!available) {
1225                     break;
1226                 }
1227             }
1228             if (!available) {
1229                 break;
1230             }
1231         }
1232     }
1233 }
1234 
1235 /*
1236  * Flush all buffer data from this input stream's queue into the driver's
1237  * virtual queue.
1238  *
1239  * @stream: VirtIOSoundPCMStream *stream
1240  */
1241 static inline void return_rx_buffer(VirtIOSoundPCMStream *stream,
1242                                     VirtIOSoundPCMBuffer *buffer)
1243 {
1244     virtio_snd_pcm_status resp = { 0 };
1245     resp.status = cpu_to_le32(VIRTIO_SND_S_OK);
1246     resp.latency_bytes = 0;
1247     /* Copy data -if any- to guest */
1248     iov_from_buf(buffer->elem->in_sg,
1249                  buffer->elem->in_num,
1250                  0,
1251                  buffer->data,
1252                  buffer->size);
1253     iov_from_buf(buffer->elem->in_sg,
1254                  buffer->elem->in_num,
1255                  buffer->size,
1256                  &resp,
1257                  sizeof(virtio_snd_pcm_status));
1258     virtqueue_push(buffer->vq,
1259                    buffer->elem,
1260                    sizeof(virtio_snd_pcm_status) + buffer->size);
1261     virtio_notify(VIRTIO_DEVICE(stream->s), buffer->vq);
1262     QSIMPLEQ_REMOVE(&stream->queue,
1263                     buffer,
1264                     VirtIOSoundPCMBuffer,
1265                     entry);
1266     virtio_snd_pcm_buffer_free(buffer);
1267 }
1268 
1269 
1270 /*
1271  * AUD_* input callback.
1272  *
1273  * @data: VirtIOSoundPCMStream stream
1274  * @available: number of bytes that can be read with AUD_read()
1275  */
1276 static void virtio_snd_pcm_in_cb(void *data, int available)
1277 {
1278     VirtIOSoundPCMStream *stream = data;
1279     VirtIOSoundPCMBuffer *buffer;
1280     size_t size;
1281 
1282     WITH_QEMU_LOCK_GUARD(&stream->queue_mutex) {
1283         while (!QSIMPLEQ_EMPTY(&stream->queue)) {
1284             buffer = QSIMPLEQ_FIRST(&stream->queue);
1285             if (!virtio_queue_ready(buffer->vq)) {
1286                 return;
1287             }
1288             if (!stream->active) {
1289                 /* Stream has stopped, so do not perform AUD_read. */
1290                 return_rx_buffer(stream, buffer);
1291                 continue;
1292             }
1293 
1294             for (;;) {
1295                 size = AUD_read(stream->voice.in,
1296                         buffer->data + buffer->size,
1297                         MIN(available, (stream->params.period_bytes -
1298                                         buffer->size)));
1299                 if (!size) {
1300                     available = 0;
1301                     break;
1302                 }
1303                 buffer->size += size;
1304                 available -= size;
1305                 if (buffer->size >= stream->params.period_bytes) {
1306                     return_rx_buffer(stream, buffer);
1307                     break;
1308                 }
1309                 if (!available) {
1310                     break;
1311                 }
1312             }
1313             if (!available) {
1314                 break;
1315             }
1316         }
1317     }
1318 }
1319 
1320 /*
1321  * Flush all buffer data from this output stream's queue into the driver's
1322  * virtual queue.
1323  *
1324  * @stream: VirtIOSoundPCMStream *stream
1325  */
1326 static inline void virtio_snd_pcm_flush(VirtIOSoundPCMStream *stream)
1327 {
1328     VirtIOSoundPCMBuffer *buffer;
1329     void (*cb)(VirtIOSoundPCMStream *, VirtIOSoundPCMBuffer *) =
1330         (stream->info.direction == VIRTIO_SND_D_OUTPUT) ? return_tx_buffer :
1331         return_rx_buffer;
1332 
1333     WITH_QEMU_LOCK_GUARD(&stream->queue_mutex) {
1334         while (!QSIMPLEQ_EMPTY(&stream->queue)) {
1335             buffer = QSIMPLEQ_FIRST(&stream->queue);
1336             cb(stream, buffer);
1337         }
1338     }
1339 }
1340 
1341 static void virtio_snd_unrealize(DeviceState *dev)
1342 {
1343     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1344     VirtIOSound *vsnd = VIRTIO_SND(dev);
1345     VirtIOSoundPCMStream *stream;
1346 
1347     qemu_del_vm_change_state_handler(vsnd->vmstate);
1348     trace_virtio_snd_unrealize(vsnd);
1349 
1350     if (vsnd->pcm) {
1351         if (vsnd->pcm->streams) {
1352             for (uint32_t i = 0; i < vsnd->snd_conf.streams; i++) {
1353                 stream = vsnd->pcm->streams[i];
1354                 if (stream) {
1355                     virtio_snd_process_cmdq(stream->s);
1356                     virtio_snd_pcm_close(stream);
1357                     qemu_mutex_destroy(&stream->queue_mutex);
1358                     g_free(stream);
1359                 }
1360             }
1361             g_free(vsnd->pcm->streams);
1362         }
1363         g_free(vsnd->pcm->pcm_params);
1364         g_free(vsnd->pcm);
1365         vsnd->pcm = NULL;
1366     }
1367     AUD_remove_card(&vsnd->card);
1368     qemu_mutex_destroy(&vsnd->cmdq_mutex);
1369     virtio_delete_queue(vsnd->queues[VIRTIO_SND_VQ_CONTROL]);
1370     virtio_delete_queue(vsnd->queues[VIRTIO_SND_VQ_EVENT]);
1371     virtio_delete_queue(vsnd->queues[VIRTIO_SND_VQ_TX]);
1372     virtio_delete_queue(vsnd->queues[VIRTIO_SND_VQ_RX]);
1373     virtio_cleanup(vdev);
1374 }
1375 
1376 
1377 static void virtio_snd_reset(VirtIODevice *vdev)
1378 {
1379     VirtIOSound *s = VIRTIO_SND(vdev);
1380     virtio_snd_ctrl_command *cmd;
1381 
1382     WITH_QEMU_LOCK_GUARD(&s->cmdq_mutex) {
1383         while (!QTAILQ_EMPTY(&s->cmdq)) {
1384             cmd = QTAILQ_FIRST(&s->cmdq);
1385             QTAILQ_REMOVE(&s->cmdq, cmd, next);
1386             virtio_snd_ctrl_cmd_free(cmd);
1387         }
1388     }
1389 }
1390 
1391 static void virtio_snd_class_init(ObjectClass *klass, void *data)
1392 {
1393     DeviceClass *dc = DEVICE_CLASS(klass);
1394     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
1395 
1396 
1397     set_bit(DEVICE_CATEGORY_SOUND, dc->categories);
1398     device_class_set_props(dc, virtio_snd_properties);
1399 
1400     dc->vmsd = &vmstate_virtio_snd;
1401     vdc->vmsd = &vmstate_virtio_snd_device;
1402     vdc->realize = virtio_snd_realize;
1403     vdc->unrealize = virtio_snd_unrealize;
1404     vdc->get_config = virtio_snd_get_config;
1405     vdc->set_config = virtio_snd_set_config;
1406     vdc->get_features = get_features;
1407     vdc->reset = virtio_snd_reset;
1408     vdc->legacy_features = 0;
1409 }
1410 
1411 static const TypeInfo virtio_snd_types[] = {
1412     {
1413       .name          = TYPE_VIRTIO_SND,
1414       .parent        = TYPE_VIRTIO_DEVICE,
1415       .instance_size = sizeof(VirtIOSound),
1416       .class_init    = virtio_snd_class_init,
1417     }
1418 };
1419 
1420 DEFINE_TYPES(virtio_snd_types)
1421