]> git.alsa-project.org Git - alsa-lib.git/blob - src/pcm/pcm_direct.c
a08bbe6d93471745be5765afc3f5632d283a3f8c
[alsa-lib.git] / src / pcm / pcm_direct.c
1 /*
2  *  PCM - Direct Stream Mixing
3  *  Copyright (c) 2003 by Jaroslav Kysela <perex@perex.cz>
4  *
5  *
6  *   This library is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU Lesser General Public License as
8  *   published by the Free Software Foundation; either version 2.1 of
9  *   the License, or (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU Lesser General Public License for more details.
15  *
16  *   You should have received a copy of the GNU Lesser General Public
17  *   License along with this library; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #include "pcm_local.h"
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stddef.h>
26 #include <unistd.h>
27 #include <signal.h>
28 #include <string.h>
29 #include <fcntl.h>
30 #include <ctype.h>
31 #include <grp.h>
32 #include <sys/ioctl.h>
33 #include <sys/mman.h>
34 #include <poll.h>
35 #include <sys/shm.h>
36 #include <sys/sem.h>
37 #include <sys/wait.h>
38 #include <sys/socket.h>
39 #include <sys/stat.h>
40 #include <sys/un.h>
41 #include <sys/mman.h>
42 #include "pcm_direct.h"
43
44 /*
45  *
46  */
47
48 #if !defined(__OpenBSD__) && !defined(__DragonFly__) && !defined(__ANDROID__)
49 union semun {
50         int              val;    /* Value for SETVAL */
51         struct semid_ds *buf;    /* Buffer for IPC_STAT, IPC_SET */
52         unsigned short  *array;  /* Array for GETALL, SETALL */
53 #if defined(__linux__)
54         struct seminfo  *__buf;  /* Buffer for IPC_INFO (Linux specific) */
55 #endif
56 };
57 #endif
58
59 /*
60  * FIXME:
61  *  add possibility to use futexes here
62  */
63
64 int snd_pcm_direct_semaphore_create_or_connect(snd_pcm_direct_t *dmix)
65 {
66         union semun s;
67         struct semid_ds buf;
68         int i;
69
70         dmix->semid = semget(dmix->ipc_key, DIRECT_IPC_SEMS,
71                              IPC_CREAT | dmix->ipc_perm);
72         if (dmix->semid < 0)
73                 return -errno;
74         if (dmix->ipc_gid < 0)
75                 return 0;
76         for (i = 0; i < DIRECT_IPC_SEMS; i++) {
77                 s.buf = &buf;
78                 if (semctl(dmix->semid, i, IPC_STAT, s) < 0) {
79                         int err = -errno;
80                         snd_pcm_direct_semaphore_discard(dmix);
81                         return err;
82                 }
83                 buf.sem_perm.gid = dmix->ipc_gid;
84                 s.buf = &buf;
85                 semctl(dmix->semid, i, IPC_SET, s);
86         }
87         return 0;
88 }
89
90 static unsigned int snd_pcm_direct_magic(snd_pcm_direct_t *dmix)
91 {
92         if (!dmix->direct_memory_access)
93                 return 0xa15ad300 + sizeof(snd_pcm_direct_share_t);
94         else
95                 return 0xb15ad300 + sizeof(snd_pcm_direct_share_t);
96 }
97
98 /*
99  *  global shared memory area
100  */
101
102 int snd_pcm_direct_shm_create_or_connect(snd_pcm_direct_t *dmix)
103 {
104         struct shmid_ds buf;
105         int tmpid, err, first_instance = 0;
106
107 retryget:
108         dmix->shmid = shmget(dmix->ipc_key, sizeof(snd_pcm_direct_share_t),
109                              dmix->ipc_perm);
110         if (dmix->shmid < 0 && errno == ENOENT) {
111                 if ((dmix->shmid = shmget(dmix->ipc_key, sizeof(snd_pcm_direct_share_t),
112                                              IPC_CREAT | IPC_EXCL | dmix->ipc_perm)) != -1)
113                         first_instance = 1;
114                 else if (errno == EEXIST)
115                         goto retryget;
116         }
117         err = -errno;
118         if (dmix->shmid < 0) {
119                 if (errno == EINVAL)
120                 if ((tmpid = shmget(dmix->ipc_key, 0, dmix->ipc_perm)) != -1)
121                 if (!shmctl(tmpid, IPC_STAT, &buf))
122                 if (!buf.shm_nattch)
123                 /* no users so destroy the segment */
124                 if (!shmctl(tmpid, IPC_RMID, NULL))
125                     goto retryget;
126                 return err;
127         }
128         dmix->shmptr = shmat(dmix->shmid, 0, 0);
129         if (dmix->shmptr == (void *) -1) {
130                 err = -errno;
131                 snd_pcm_direct_shm_discard(dmix);
132                 return err;
133         }
134         mlock(dmix->shmptr, sizeof(snd_pcm_direct_share_t));
135         if (shmctl(dmix->shmid, IPC_STAT, &buf) < 0) {
136                 err = -errno;
137                 snd_pcm_direct_shm_discard(dmix);
138                 return err;
139         }
140         if (first_instance) {   /* we're the first user, clear the segment */
141                 memset(dmix->shmptr, 0, sizeof(snd_pcm_direct_share_t));
142                 if (dmix->ipc_gid >= 0) {
143                         buf.shm_perm.gid = dmix->ipc_gid;
144                         shmctl(dmix->shmid, IPC_SET, &buf);
145                 }
146                 dmix->shmptr->magic = snd_pcm_direct_magic(dmix);
147                 return 1;
148         } else {
149                 if (dmix->shmptr->magic != snd_pcm_direct_magic(dmix)) {
150                         snd_pcm_direct_shm_discard(dmix);
151                         return -EINVAL;
152                 }
153         }
154         return 0;
155 }
156
157 /* discard shared memory */
158 /*
159  * Define snd_* functions to be used in server.
160  * Since objects referred in a plugin can be released dynamically, a forked
161  * server should have statically linked functions.
162  * (e.g. Novell bugzilla #105772)
163  */
164 static int _snd_pcm_direct_shm_discard(snd_pcm_direct_t *dmix)
165 {
166         struct shmid_ds buf;
167         int ret = 0;
168
169         if (dmix->shmid < 0)
170                 return -EINVAL;
171         if (dmix->shmptr != (void *) -1 && shmdt(dmix->shmptr) < 0)
172                 return -errno;
173         dmix->shmptr = (void *) -1;
174         if (shmctl(dmix->shmid, IPC_STAT, &buf) < 0)
175                 return -errno;
176         if (buf.shm_nattch == 0) {      /* we're the last user, destroy the segment */
177                 if (shmctl(dmix->shmid, IPC_RMID, NULL) < 0)
178                         return -errno;
179                 ret = 1;
180         }
181         dmix->shmid = -1;
182         return ret;
183 }
184
185 /* ... and an exported version */
186 int snd_pcm_direct_shm_discard(snd_pcm_direct_t *dmix)
187 {
188         return _snd_pcm_direct_shm_discard(dmix);
189 }
190
191 /*
192  *  server side
193  */
194
195 static int get_tmp_name(char *filename, size_t size)
196 {
197         struct timeval tv;
198
199         gettimeofday(&tv, NULL);
200         snprintf(filename, size, TMPDIR "/alsa-dmix-%i-%li-%li", (int)getpid(), (long)tv.tv_sec, (long)tv.tv_usec);
201         filename[size-1] = '\0';
202         return 0;
203 }
204
205 static int make_local_socket(const char *filename, int server, mode_t ipc_perm, int ipc_gid)
206 {
207         size_t l = strlen(filename);
208         size_t size = offsetof(struct sockaddr_un, sun_path) + l;
209         struct sockaddr_un *addr = alloca(size);
210         int sock;
211
212         sock = socket(PF_LOCAL, SOCK_STREAM, 0);
213         if (sock < 0) {
214                 int result = -errno;
215                 snd_errornum(PCM, "socket failed");
216                 return result;
217         }
218
219         if (server)
220                 unlink(filename);
221         memset(addr, 0, size); /* make valgrind happy */
222         addr->sun_family = AF_LOCAL;
223         memcpy(addr->sun_path, filename, l);
224
225         if (server) {
226                 if (bind(sock, (struct sockaddr *) addr, size) < 0) {
227                         int result = -errno;
228                         snd_errornum(PCM, "bind failed: %s", filename);
229                         close(sock);
230                         return result;
231                 } else {
232                         if (chmod(filename, ipc_perm) < 0) {
233                                 int result = -errno;
234                                 snd_errornum(PCM, "chmod failed: %s", filename);
235                                 close(sock);
236                                 unlink(filename);
237                                 return result;
238                         }
239                         if (chown(filename, -1, ipc_gid) < 0) {
240 #if 0 /* it's not fatal */
241                                 int result = -errno;
242                                 snd_errornum(PCM, "chown failed: %s", filename);
243                                 close(sock);
244                                 unlink(filename);
245                                 return result;
246 #endif
247                         }
248                 }
249         } else {
250                 if (connect(sock, (struct sockaddr *) addr, size) < 0) {
251                         int result = -errno;
252                         snd_errornum(PCM, "connect failed: %s", filename);
253                         close(sock);
254                         return result;
255                 }
256         }
257         return sock;
258 }
259
260 #if 0
261 #define SERVER_JOB_DEBUG
262 #define server_printf(fmt, args...) printf(fmt, ##args)
263 #else
264 #undef SERVER_JOB_DEBUG
265 #define server_printf(fmt, args...) /* nothing */
266 #endif
267
268 static snd_pcm_direct_t *server_job_dmix;
269
270 static void server_cleanup(snd_pcm_direct_t *dmix)
271 {
272         close(dmix->server_fd);
273         close(dmix->hw_fd);
274         if (dmix->server_free)
275                 dmix->server_free(dmix);
276         unlink(dmix->shmptr->socket_name);
277         _snd_pcm_direct_shm_discard(dmix);
278         snd_pcm_direct_semaphore_discard(dmix);
279 }
280
281 static void server_job_signal(int sig ATTRIBUTE_UNUSED)
282 {
283         snd_pcm_direct_semaphore_down(server_job_dmix, DIRECT_IPC_SEM_CLIENT);
284         server_cleanup(server_job_dmix);
285         server_printf("DIRECT SERVER EXIT - SIGNAL\n");
286         _exit(EXIT_SUCCESS);
287 }
288
289 /* This is a copy from ../socket.c, provided here only for a server job
290  * (see the comment above)
291  */
292 static int _snd_send_fd(int sock, void *data, size_t len, int fd)
293 {
294         int ret;
295         size_t cmsg_len = CMSG_LEN(sizeof(int));
296         struct cmsghdr *cmsg = alloca(cmsg_len);
297         int *fds = (int *) CMSG_DATA(cmsg);
298         struct msghdr msghdr;
299         struct iovec vec;
300
301         vec.iov_base = (void *)&data;
302         vec.iov_len = len;
303
304         cmsg->cmsg_len = cmsg_len;
305         cmsg->cmsg_level = SOL_SOCKET;
306         cmsg->cmsg_type = SCM_RIGHTS;
307         *fds = fd;
308
309         msghdr.msg_name = NULL;
310         msghdr.msg_namelen = 0;
311         msghdr.msg_iov = &vec;
312         msghdr.msg_iovlen = 1;
313         msghdr.msg_control = cmsg;
314         msghdr.msg_controllen = cmsg_len;
315         msghdr.msg_flags = 0;
316
317         ret = sendmsg(sock, &msghdr, 0 );
318         if (ret < 0)
319                 return -errno;
320         return ret;
321 }
322
323 static void server_job(snd_pcm_direct_t *dmix)
324 {
325         int ret, sck, i;
326         int max = 128, current = 0;
327         struct pollfd pfds[max + 1];
328
329         server_job_dmix = dmix;
330         /* don't allow to be killed */
331         signal(SIGHUP, server_job_signal);
332         signal(SIGQUIT, server_job_signal);
333         signal(SIGTERM, server_job_signal);
334         signal(SIGKILL, server_job_signal);
335         /* close all files to free resources */
336         i = sysconf(_SC_OPEN_MAX);
337 #ifdef SERVER_JOB_DEBUG
338         while (--i >= 3) {
339 #else
340         while (--i >= 0) {
341 #endif
342                 if (i != dmix->server_fd && i != dmix->hw_fd)
343                         close(i);
344         }
345
346         /* detach from parent */
347         setsid();
348
349         pfds[0].fd = dmix->server_fd;
350         pfds[0].events = POLLIN | POLLERR | POLLHUP;
351
352         server_printf("DIRECT SERVER STARTED\n");
353         while (1) {
354                 ret = poll(pfds, current + 1, 500);
355                 server_printf("DIRECT SERVER: poll ret = %i, revents[0] = 0x%x, errno = %i\n", ret, pfds[0].revents, errno);
356                 if (ret < 0) {
357                         if (errno == EINTR)
358                                 continue;
359                         /* some error */
360                         break;
361                 }
362                 if (ret == 0 || (pfds[0].revents & (POLLERR | POLLHUP))) {      /* timeout or error? */
363                         struct shmid_ds buf;
364                         snd_pcm_direct_semaphore_down(dmix, DIRECT_IPC_SEM_CLIENT);
365                         if (shmctl(dmix->shmid, IPC_STAT, &buf) < 0) {
366                                 _snd_pcm_direct_shm_discard(dmix);
367                                 snd_pcm_direct_semaphore_up(dmix, DIRECT_IPC_SEM_CLIENT);
368                                 continue;
369                         }
370                         server_printf("DIRECT SERVER: nattch = %i\n", (int)buf.shm_nattch);
371                         if (buf.shm_nattch == 1)        /* server is the last user, exit */
372                                 break;
373                         snd_pcm_direct_semaphore_up(dmix, DIRECT_IPC_SEM_CLIENT);
374                         continue;
375                 }
376                 if (pfds[0].revents & POLLIN) {
377                         ret--;
378                         sck = accept(dmix->server_fd, 0, 0);
379                         if (sck >= 0) {
380                                 server_printf("DIRECT SERVER: new connection %i\n", sck);
381                                 if (current == max) {
382                                         close(sck);
383                                 } else {
384                                         unsigned char buf = 'A';
385                                         pfds[current+1].fd = sck;
386                                         pfds[current+1].events = POLLIN | POLLERR | POLLHUP;
387                                         _snd_send_fd(sck, &buf, 1, dmix->hw_fd);
388                                         server_printf("DIRECT SERVER: fd sent ok\n");
389                                         current++;
390                                 }
391                         }
392                 }
393                 for (i = 0; i < current && ret > 0; i++) {
394                         struct pollfd *pfd = &pfds[i+1];
395                         unsigned char cmd;
396                         server_printf("client %i revents = 0x%x\n", pfd->fd, pfd->revents);
397                         if (pfd->revents & (POLLERR | POLLHUP)) {
398                                 ret--;
399                                 close(pfd->fd);
400                                 pfd->fd = -1;
401                                 continue;
402                         }
403                         if (!(pfd->revents & POLLIN))
404                                 continue;
405                         ret--;
406                         if (read(pfd->fd, &cmd, 1) == 1)
407                                 cmd = 0 /*process command */;
408                 }
409                 for (i = 0; i < current; i++) {
410                         if (pfds[i+1].fd < 0) {
411                                 if (i + 1 != max)
412                                         memcpy(&pfds[i+1], &pfds[i+2], sizeof(struct pollfd) * (max - i - 1));
413                                 current--;
414                         }
415                 }
416         }
417         server_cleanup(dmix);
418         server_printf("DIRECT SERVER EXIT\n");
419 #ifdef SERVER_JOB_DEBUG
420         close(0); close(1); close(2);
421 #endif
422         _exit(EXIT_SUCCESS);
423 }
424
425 int snd_pcm_direct_server_create(snd_pcm_direct_t *dmix)
426 {
427         int ret;
428
429         dmix->server_fd = -1;
430
431         ret = get_tmp_name(dmix->shmptr->socket_name, sizeof(dmix->shmptr->socket_name));
432         if (ret < 0)
433                 return ret;
434
435         ret = make_local_socket(dmix->shmptr->socket_name, 1, dmix->ipc_perm, dmix->ipc_gid);
436         if (ret < 0)
437                 return ret;
438         dmix->server_fd = ret;
439
440         ret = listen(dmix->server_fd, 4);
441         if (ret < 0) {
442                 close(dmix->server_fd);
443                 return ret;
444         }
445
446         ret = fork();
447         if (ret < 0) {
448                 close(dmix->server_fd);
449                 return ret;
450         } else if (ret == 0) {
451                 ret = fork();
452                 if (ret == 0)
453                         server_job(dmix);
454                 _exit(EXIT_SUCCESS);
455         } else {
456                 waitpid(ret, NULL, 0);
457         }
458         dmix->server_pid = ret;
459         dmix->server = 1;
460         return 0;
461 }
462
463 int snd_pcm_direct_server_discard(snd_pcm_direct_t *dmix)
464 {
465         if (dmix->server) {
466                 //kill(dmix->server_pid, SIGTERM);
467                 //waitpid(dmix->server_pid, NULL, 0);
468                 dmix->server_pid = (pid_t)-1;
469         }
470         if (dmix->server_fd > 0) {
471                 close(dmix->server_fd);
472                 dmix->server_fd = -1;
473         }
474         dmix->server = 0;
475         return 0;
476 }
477
478 /*
479  *  client side
480  */
481
482 int snd_pcm_direct_client_connect(snd_pcm_direct_t *dmix)
483 {
484         int ret;
485         unsigned char buf;
486
487         ret = make_local_socket(dmix->shmptr->socket_name, 0, -1, -1);
488         if (ret < 0)
489                 return ret;
490         dmix->comm_fd = ret;
491
492         ret = snd_receive_fd(dmix->comm_fd, &buf, 1, &dmix->hw_fd);
493         if (ret < 1 || buf != 'A') {
494                 close(dmix->comm_fd);
495                 dmix->comm_fd = -1;
496                 return ret;
497         }
498
499         dmix->client = 1;
500         return 0;
501 }
502
503 int snd_pcm_direct_client_discard(snd_pcm_direct_t *dmix)
504 {
505         if (dmix->client) {
506                 close(dmix->comm_fd);
507                 dmix->comm_fd = -1;
508         }
509         return 0;
510 }
511
512 /*
513  *  plugin helpers
514  */
515
516 int snd_pcm_direct_nonblock(snd_pcm_t *pcm ATTRIBUTE_UNUSED, int nonblock ATTRIBUTE_UNUSED)
517 {
518         /* value is cached for us in pcm->mode (SND_PCM_NONBLOCK flag) */
519         return 0;
520 }
521
522 int snd_pcm_direct_async(snd_pcm_t *pcm, int sig, pid_t pid)
523 {
524         snd_pcm_direct_t *dmix = pcm->private_data;
525         return snd_timer_async(dmix->timer, sig, pid);
526 }
527
528 /* empty the timer read queue */
529 int snd_pcm_direct_clear_timer_queue(snd_pcm_direct_t *dmix)
530 {
531         int changed = 0;
532         if (dmix->timer_need_poll) {
533                 while (poll(&dmix->timer_fd, 1, 0) > 0) {
534                         changed++;
535                         /* we don't need the value */
536                         if (dmix->tread) {
537                                 snd_timer_tread_t rbuf[4];
538                                 snd_timer_read(dmix->timer, rbuf, sizeof(rbuf));
539                         } else {
540                                 snd_timer_read_t rbuf;
541                                 snd_timer_read(dmix->timer, &rbuf, sizeof(rbuf));
542                         }
543                 }
544         } else {
545                 if (dmix->tread) {
546                         snd_timer_tread_t rbuf[4];
547                         int len;
548                         while ((len = snd_timer_read(dmix->timer, rbuf,
549                                                      sizeof(rbuf))) > 0
550                                                      && (++changed) &&
551                                len != sizeof(rbuf[0]))
552                                 ;
553                 } else {
554                         snd_timer_read_t rbuf;
555                         while (snd_timer_read(dmix->timer, &rbuf, sizeof(rbuf)) > 0)
556                                 changed++;
557                 }
558         }
559         return changed;
560 }
561
562 int snd_pcm_direct_timer_stop(snd_pcm_direct_t *dmix)
563 {
564         snd_timer_stop(dmix->timer);
565         return 0;
566 }
567
568 #define RECOVERIES_FLAG_SUSPENDED       (1U << 31)
569 #define RECOVERIES_MASK                 ((1U << 31) - 1)
570
571 /*
572  * Recover slave on XRUN or SUSPENDED.
573  * Even if direct plugins disable xrun detection, there might be an xrun
574  * raised directly by some drivers.
575  * The first client recovers slave pcm.
576  * Each client needs to execute sw xrun handling afterwards
577  */
578 int snd_pcm_direct_slave_recover(snd_pcm_direct_t *direct)
579 {
580         unsigned int recoveries;
581         int state;
582         int ret;
583         int semerr;
584
585         semerr = snd_pcm_direct_semaphore_down(direct,
586                                                    DIRECT_IPC_SEM_CLIENT);
587         if (semerr < 0) {
588                 snd_error(PCM, "SEMDOWN FAILED with err %d", semerr);
589                 return semerr;
590         }
591
592         state = snd_pcm_state(direct->spcm);
593         if (state != SND_PCM_STATE_XRUN && state != SND_PCM_STATE_SUSPENDED) {
594                 /* ignore... someone else already did recovery */
595                 semerr = snd_pcm_direct_semaphore_up(direct,
596                                                      DIRECT_IPC_SEM_CLIENT);
597                 if (semerr < 0) {
598                         snd_error(PCM, "SEMUP FAILED with err %d", semerr);
599                         return semerr;
600                 }
601                 return 0;
602         }
603
604         recoveries = direct->shmptr->s.recoveries;
605         recoveries = (recoveries + 1) & RECOVERIES_MASK;
606         if (state == SND_PCM_STATE_SUSPENDED)
607                 recoveries |= RECOVERIES_FLAG_SUSPENDED;
608         direct->shmptr->s.recoveries = recoveries;
609
610         /* some buggy drivers require the device resumed before prepared;
611          * when a device has RESUME flag and is in SUSPENDED state, resume
612          * here but immediately drop to bring it to a sane active state.
613          */
614         if (state == SND_PCM_STATE_SUSPENDED &&
615             (direct->spcm->info & SND_PCM_INFO_RESUME)) {
616                 snd_pcm_resume(direct->spcm);
617                 snd_pcm_drop(direct->spcm);
618                 snd_pcm_direct_timer_stop(direct);
619                 snd_pcm_direct_clear_timer_queue(direct);
620         }
621
622         ret = snd_pcm_prepare(direct->spcm);
623         if (ret < 0) {
624                 snd_error(PCM, "recover: unable to prepare slave");
625                 semerr = snd_pcm_direct_semaphore_up(direct,
626                                                      DIRECT_IPC_SEM_CLIENT);
627                 if (semerr < 0) {
628                         snd_error(PCM, "SEMUP FAILED with err %d", semerr);
629                         return semerr;
630                 }
631                 return ret;
632         }
633
634         if (direct->type == SND_PCM_TYPE_DSHARE) {
635                 const snd_pcm_channel_area_t *dst_areas;
636                 dst_areas = snd_pcm_mmap_areas(direct->spcm);
637                 snd_pcm_areas_silence(dst_areas, 0, direct->spcm->channels,
638                                       direct->spcm->buffer_size,
639                                       direct->spcm->format);
640         }
641
642         ret = snd_pcm_start(direct->spcm);
643         if (ret < 0) {
644                 snd_error(PCM, "recover: unable to start slave");
645                 semerr = snd_pcm_direct_semaphore_up(direct,
646                                                      DIRECT_IPC_SEM_CLIENT);
647                 if (semerr < 0) {
648                         snd_error(PCM, "SEMUP FAILED with err %d", semerr);
649                         return semerr;
650                 }
651                 return ret;
652         }
653         semerr = snd_pcm_direct_semaphore_up(direct,
654                                                  DIRECT_IPC_SEM_CLIENT);
655         if (semerr < 0) {
656                 snd_error(PCM, "SEMUP FAILED with err %d", semerr);
657                 return semerr;
658         }
659         return 0;
660 }
661
662 /*
663  * enter xrun or suspended state, if slave xrun occurred or suspended
664  * @return: 0 for no xrun/suspend or a negative error code for xrun/suspend
665  */
666 int snd_pcm_direct_check_xrun(snd_pcm_direct_t *direct, snd_pcm_t *pcm)
667 {
668         int err;
669
670         switch (snd_pcm_state(direct->spcm)) {
671         case SND_PCM_STATE_DISCONNECTED:
672                 direct->state = SNDRV_PCM_STATE_DISCONNECTED;
673                 return -ENODEV;
674         case SND_PCM_STATE_XRUN:
675         case SND_PCM_STATE_SUSPENDED:
676                 if ((err = snd_pcm_direct_slave_recover(direct)) < 0)
677                         return err;
678                 break;
679         default:
680                 break;
681         }
682
683         if (direct->state == SND_PCM_STATE_XRUN)
684                 return -EPIPE;
685         else if (direct->state == SND_PCM_STATE_SUSPENDED)
686                 return -ESTRPIPE;
687         if (direct->shmptr->s.recoveries != direct->recoveries) {
688                 /* no matter how many xruns we missed -
689                  * so don't increment but just update to actual counter
690                  */
691                 direct->recoveries = direct->shmptr->s.recoveries;
692                 pcm->fast_ops->drop(pcm->fast_op_arg);
693                 /* trigger_tstamp update is missing in drop callbacks */
694                 gettimestamp(&direct->trigger_tstamp, pcm->tstamp_type);
695                 /* no timer clear:
696                  * if slave already entered xrun again the event is lost.
697                  * snd_pcm_direct_clear_timer_queue(direct);
698                  */
699                 if (direct->recoveries & RECOVERIES_FLAG_SUSPENDED) {
700                         direct->state = SND_PCM_STATE_SUSPENDED;
701                         return -ESTRPIPE;
702                 } else {
703                         direct->state = SND_PCM_STATE_XRUN;
704                         return -EPIPE;
705                 }
706         }
707         return 0;
708 }
709
710 /*
711  * This is the only operation guaranteed to be called before entering poll().
712  * Direct plugins use fd of snd_timer to poll on, these timers do NOT check
713  * state of substream in kernel by intention.
714  * Only the enter to xrun might be notified once (SND_TIMER_EVENT_MSTOP).
715  * If xrun event was not correctly handled or was ignored it will never be
716  * evaluated again afterwards.
717  * This will result in snd_pcm_wait() always returning timeout.
718  * In contrast poll() on pcm hardware checks ALSA state and will immediately
719  * return POLLERR on XRUN.
720  *
721  * To prevent timeout and applications endlessly spinning without xrun
722  * detected we add a state check here which may trigger the xrun sequence.
723  *
724  * return count of filled descriptors or negative error code
725  */
726 int snd_pcm_direct_poll_descriptors(snd_pcm_t *pcm, struct pollfd *pfds,
727                                     unsigned int space)
728 {
729         if (pcm->poll_fd < 0) {
730                 snd_check(PCM, "poll_fd < 0");
731                 return -EIO;
732         }
733         if (space >= 1 && pfds) {
734                 pfds->fd = pcm->poll_fd;
735                 pfds->events = pcm->poll_events | POLLERR | POLLNVAL;
736         } else {
737                 return 0;
738         }
739
740         /* this will also evaluate slave state and enter xrun if necessary */
741         /* using __snd_pcm_state() since this function is called inside lock */
742         switch (__snd_pcm_state(pcm)) {
743         case SND_PCM_STATE_XRUN:
744                 return -EPIPE;
745         default:
746                 break;
747         }
748         return 1;
749 }
750
751 int snd_pcm_direct_poll_revents(snd_pcm_t *pcm, struct pollfd *pfds, unsigned int nfds, unsigned short *revents)
752 {
753         snd_pcm_direct_t *dmix = pcm->private_data;
754         unsigned short events;
755         int empty = 0;
756
757         assert(pfds && nfds == 1 && revents);
758
759 timer_changed:
760         events = pfds[0].revents;
761         if (events & POLLIN) {
762                 snd_pcm_uframes_t avail;
763                 __snd_pcm_avail_update(pcm);
764                 if (pcm->stream == SND_PCM_STREAM_PLAYBACK) {
765                         events |= POLLOUT;
766                         events &= ~POLLIN;
767                         avail = snd_pcm_mmap_playback_avail(pcm);
768                 } else {
769                         avail = snd_pcm_mmap_capture_avail(pcm);
770                 }
771                 empty = avail < pcm->avail_min;
772         }
773
774         if (snd_pcm_direct_check_xrun(dmix, pcm) < 0 ||
775             snd_pcm_state(dmix->spcm) == SND_PCM_STATE_SETUP) {
776                 events |= POLLERR;
777         } else {
778                 if (empty) {
779                         /* here we have a race condition:
780                          * if period event arrived after the avail_update call
781                          * above we might clear this event with the following
782                          * clear_timer_queue.
783                          * There is no way to do this in atomic manner, so we
784                          * need to recheck avail_update if we successfully
785                          * cleared a poll event.
786                          */
787                         if (snd_pcm_direct_clear_timer_queue(dmix))
788                                 goto timer_changed;
789                         events &= ~(POLLOUT|POLLIN);
790                         /* additional check */
791                         switch (__snd_pcm_state(pcm)) {
792                         case SND_PCM_STATE_XRUN:
793                         case SND_PCM_STATE_SUSPENDED:
794                         case SND_PCM_STATE_SETUP:
795                                 events |= POLLERR;
796                                 break;
797                         default:
798                                 break;
799                         }
800                 }
801         }
802         *revents = events;
803         return 0;
804 }
805
806 int snd_pcm_direct_info(snd_pcm_t *pcm, snd_pcm_info_t * info)
807 {
808         snd_pcm_direct_t *dmix = pcm->private_data;
809
810         if (dmix->spcm && !dmix->shmptr->use_server)
811                 return snd_pcm_info(dmix->spcm, info);
812
813         memset(info, 0, sizeof(*info));
814         info->stream = pcm->stream;
815         info->card = -1;
816         /* FIXME: fill this with something more useful: we know the hardware name */
817         if (pcm->name) {
818                 snd_strlcpy((char *)info->id, pcm->name, sizeof(info->id));
819                 snd_strlcpy((char *)info->name, pcm->name, sizeof(info->name));
820                 snd_strlcpy((char *)info->subname, pcm->name, sizeof(info->subname));
821         }
822         info->subdevices_count = 1;
823         return 0;
824 }
825
826 static inline snd_mask_t *hw_param_mask(snd_pcm_hw_params_t *params,
827                                         snd_pcm_hw_param_t var)
828 {
829         return &params->masks[var - SND_PCM_HW_PARAM_FIRST_MASK];
830 }
831
832 static inline snd_interval_t *hw_param_interval(snd_pcm_hw_params_t *params,
833                                                 snd_pcm_hw_param_t var)
834 {
835         return &params->intervals[var - SND_PCM_HW_PARAM_FIRST_INTERVAL];
836 }
837
838 static int hw_param_interval_refine_one(snd_pcm_hw_params_t *params,
839                                         snd_pcm_hw_param_t var,
840                                         snd_interval_t *src)
841 {
842         snd_interval_t *i;
843
844         if (!(params->rmask & (1<<var)))        /* nothing to do? */
845                 return 0;
846         i = hw_param_interval(params, var);
847         if (snd_interval_empty(i)) {
848                 snd_error(PCM, "dshare interval %i empty?", (int)var);
849                 return -EINVAL;
850         }
851         if (snd_interval_refine(i, src))
852                 params->cmask |= 1<<var;
853         return 0;
854 }
855
856 static int hw_param_interval_refine_minmax(snd_pcm_hw_params_t *params,
857                                            snd_pcm_hw_param_t var,
858                                            unsigned int imin,
859                                            unsigned int imax)
860 {
861         snd_interval_t t;
862
863         memset(&t, 0, sizeof(t));
864         snd_interval_set_minmax(&t, imin, imax);
865         t.integer = 1;
866         return hw_param_interval_refine_one(params, var, &t);
867 }
868
869 /* this code is used 'as-is' from the alsa kernel code */
870 static int snd_interval_step(struct snd_interval *i, unsigned int min,
871                              unsigned int step)
872 {
873         unsigned int n;
874         int changed = 0;
875         n = (i->min - min) % step;
876         if (n != 0 || i->openmin) {
877                 i->min += step - n;
878                 changed = 1;
879         }
880         n = (i->max - min) % step;
881         if (n != 0 || i->openmax) {
882                 i->max -= n;
883                 changed = 1;
884         }
885         if (snd_interval_checkempty(i)) {
886                 i->empty = 1;
887                 return -EINVAL;
888         }
889         return changed;
890 }
891
892 #undef REFINE_DEBUG
893
894 int snd_pcm_direct_hw_refine(snd_pcm_t *pcm, snd_pcm_hw_params_t *params)
895 {
896         snd_pcm_direct_t *dshare = pcm->private_data;
897         static const snd_mask_t access = { .bits = {
898                                         (1<<SNDRV_PCM_ACCESS_MMAP_INTERLEAVED) |
899                                         (1<<SNDRV_PCM_ACCESS_MMAP_NONINTERLEAVED) |
900                                         (1<<SNDRV_PCM_ACCESS_RW_INTERLEAVED) |
901                                         (1<<SNDRV_PCM_ACCESS_RW_NONINTERLEAVED),
902                                         0, 0, 0 } };
903         int err;
904
905 #ifdef REFINE_DEBUG
906         snd_output_t *log;
907         snd_output_stdio_attach(&log, stderr, 0);
908         snd_output_puts(log, "DMIX REFINE (begin):\n");
909         snd_pcm_hw_params_dump(params, log);
910 #endif
911         if (params->rmask & (1<<SND_PCM_HW_PARAM_ACCESS)) {
912                 if (snd_mask_empty(hw_param_mask(params, SND_PCM_HW_PARAM_ACCESS))) {
913                         snd_error(PCM, "dshare access mask empty?");
914                         return -EINVAL;
915                 }
916                 if (snd_mask_refine(hw_param_mask(params, SND_PCM_HW_PARAM_ACCESS), &access))
917                         params->cmask |= 1<<SND_PCM_HW_PARAM_ACCESS;
918         }
919         if (params->rmask & (1<<SND_PCM_HW_PARAM_FORMAT)) {
920                 if (snd_mask_empty(hw_param_mask(params, SND_PCM_HW_PARAM_FORMAT))) {
921                         snd_error(PCM, "dshare format mask empty?");
922                         return -EINVAL;
923                 }
924                 if (snd_mask_refine_set(hw_param_mask(params, SND_PCM_HW_PARAM_FORMAT),
925                                         dshare->shmptr->hw.format))
926                         params->cmask |= 1<<SND_PCM_HW_PARAM_FORMAT;
927         }
928         //snd_mask_none(hw_param_mask(params, SND_PCM_HW_PARAM_SUBFORMAT));
929         if (params->rmask & (1<<SND_PCM_HW_PARAM_CHANNELS)) {
930                 if (snd_interval_empty(hw_param_interval(params, SND_PCM_HW_PARAM_CHANNELS))) {
931                         snd_error(PCM, "dshare channels mask empty?");
932                         return -EINVAL;
933                 }
934                 err = snd_interval_refine_set(hw_param_interval(params, SND_PCM_HW_PARAM_CHANNELS), dshare->channels);
935                 if (err < 0)
936                         return err;
937         }
938         err = hw_param_interval_refine_one(params, SND_PCM_HW_PARAM_RATE,
939                                            &dshare->shmptr->hw.rate);
940         if (err < 0)
941                 return err;
942
943         if (dshare->max_periods < 0) {
944                 err = hw_param_interval_refine_one(params, SND_PCM_HW_PARAM_PERIOD_SIZE,
945                                                    &dshare->shmptr->hw.period_size);
946                 if (err < 0)
947                         return err;
948                 err = hw_param_interval_refine_one(params, SND_PCM_HW_PARAM_PERIOD_TIME,
949                                                    &dshare->shmptr->hw.period_time);
950                 if (err < 0)
951                         return err;
952                 err = hw_param_interval_refine_one(params, SND_PCM_HW_PARAM_BUFFER_SIZE,
953                                                    &dshare->shmptr->hw.buffer_size);
954                 if (err < 0)
955                         return err;
956                 err = hw_param_interval_refine_one(params, SND_PCM_HW_PARAM_BUFFER_TIME,
957                                                    &dshare->shmptr->hw.buffer_time);
958                 if (err < 0)
959                         return err;
960         } else if (params->rmask & ((1<<SND_PCM_HW_PARAM_PERIODS)|
961                                     (1<<SND_PCM_HW_PARAM_BUFFER_BYTES)|
962                                     (1<<SND_PCM_HW_PARAM_BUFFER_SIZE)|
963                                     (1<<SND_PCM_HW_PARAM_BUFFER_TIME)|
964                                     (1<<SND_PCM_HW_PARAM_PERIOD_TIME)|
965                                     (1<<SND_PCM_HW_PARAM_PERIOD_SIZE)|
966                                     (1<<SND_PCM_HW_PARAM_PERIOD_BYTES))) {
967                 snd_interval_t period_size = dshare->shmptr->hw.period_size;
968                 snd_interval_t period_time = dshare->shmptr->hw.period_time;
969                 int changed;
970                 unsigned int max_periods = dshare->max_periods;
971                 if (max_periods < 2)
972                         max_periods = dshare->slave_buffer_size / dshare->slave_period_size;
973
974                 /* make sure buffer size does not exceed slave buffer size */
975                 err = hw_param_interval_refine_minmax(params, SND_PCM_HW_PARAM_BUFFER_SIZE,
976                                         2 * dshare->slave_period_size, dshare->slave_buffer_size);
977                 if (err < 0)
978                         return err;
979                 if (dshare->var_periodsize) {
980                         /* more tolerant settings... */
981                         if (dshare->shmptr->hw.buffer_size.max / 2 > period_size.max) {
982                                 period_size.max = dshare->shmptr->hw.buffer_size.max / 2;
983                                 period_size.openmax = dshare->shmptr->hw.buffer_size.openmax;
984                         }
985                         if (dshare->shmptr->hw.buffer_time.max / 2 > period_time.max) {
986                                 period_time.max = dshare->shmptr->hw.buffer_time.max / 2;
987                                 period_time.openmax = dshare->shmptr->hw.buffer_time.openmax;
988                         }
989                 }
990
991                 err = hw_param_interval_refine_one(params, SND_PCM_HW_PARAM_PERIOD_SIZE,
992                                                    &period_size);
993                 if (err < 0)
994                         return err;
995                 err = hw_param_interval_refine_one(params, SND_PCM_HW_PARAM_PERIOD_TIME,
996                                                    &period_time);
997                 if (err < 0)
998                         return err;
999                 do {
1000                         changed = 0;
1001                         err = hw_param_interval_refine_minmax(params, SND_PCM_HW_PARAM_PERIODS,
1002                                                               2, max_periods);
1003                         if (err < 0)
1004                                 return err;
1005                         changed |= err;
1006                         err = snd_pcm_hw_refine_soft(pcm, params);
1007                         if (err < 0)
1008                                 return err;
1009                         changed |= err;
1010                         err = snd_interval_step(hw_param_interval(params, SND_PCM_HW_PARAM_PERIOD_SIZE),
1011                                                                 0, dshare->slave_period_size);
1012                         if (err < 0)
1013                                 return err;
1014                         changed |= err;
1015                         if (err)
1016                                 params->rmask |= (1 << SND_PCM_HW_PARAM_PERIOD_SIZE);
1017                 } while (changed);
1018         }
1019         dshare->timer_ticks = hw_param_interval(params, SND_PCM_HW_PARAM_PERIOD_SIZE)->max / dshare->slave_period_size;
1020         params->info = dshare->shmptr->s.info;
1021         params->info &= ~(SND_PCM_INFO_RESUME | SND_PCM_INFO_PAUSE);
1022 #ifdef REFINE_DEBUG
1023         snd_output_puts(log, "DMIX REFINE (end):\n");
1024         snd_pcm_hw_params_dump(params, log);
1025         snd_output_close(log);
1026 #endif
1027         return 0;
1028 }
1029
1030 int snd_pcm_direct_hw_params(snd_pcm_t *pcm, snd_pcm_hw_params_t * params)
1031 {
1032         snd_pcm_direct_t *dmix = pcm->private_data;
1033
1034         params->info = dmix->shmptr->s.info;
1035         params->info &= ~(SND_PCM_INFO_RESUME | SND_PCM_INFO_PAUSE);
1036         params->rate_num = dmix->shmptr->s.rate;
1037         params->rate_den = 1;
1038         params->fifo_size = 0;
1039         params->msbits = dmix->shmptr->s.msbits;
1040         return 0;
1041 }
1042
1043 int snd_pcm_direct_hw_free(snd_pcm_t *pcm ATTRIBUTE_UNUSED)
1044 {
1045         /* values are cached in the pcm structure */
1046         return 0;
1047 }
1048
1049 int snd_pcm_direct_sw_params(snd_pcm_t *pcm, snd_pcm_sw_params_t *params)
1050 {
1051         if (params->tstamp_type != pcm->tstamp_type)
1052                 return -EINVAL;
1053
1054         /* values are cached in the pcm structure */
1055         return 0;
1056 }
1057
1058 int snd_pcm_direct_channel_info(snd_pcm_t *pcm, snd_pcm_channel_info_t * info)
1059 {
1060         return snd_pcm_channel_info_shm(pcm, info, -1);
1061 }
1062
1063 int snd_pcm_direct_mmap(snd_pcm_t *pcm ATTRIBUTE_UNUSED)
1064 {
1065         return 0;
1066 }
1067
1068 int snd_pcm_direct_munmap(snd_pcm_t *pcm ATTRIBUTE_UNUSED)
1069 {
1070         return 0;
1071 }
1072
1073 snd_pcm_chmap_query_t **snd_pcm_direct_query_chmaps(snd_pcm_t *pcm)
1074 {
1075         snd_pcm_direct_t *dmix = pcm->private_data;
1076         snd_pcm_chmap_query_t **smaps, **maps;
1077         unsigned int i, j;
1078
1079         if (dmix->bindings == NULL)
1080                 return snd_pcm_query_chmaps(dmix->spcm);
1081
1082         maps = calloc(2, sizeof(*maps));
1083         if (!maps)
1084                 return NULL;
1085         maps[0] = calloc(dmix->channels + 2, sizeof(int *));
1086         if (!maps[0]) {
1087                 free(maps);
1088                 return NULL;
1089         }
1090         smaps = snd_pcm_query_chmaps(dmix->spcm);
1091         if (smaps == NULL) {
1092                 snd_pcm_free_chmaps(maps);
1093                 return NULL;
1094         }
1095         maps[0]->type = SND_CHMAP_TYPE_FIXED;
1096         maps[0]->map.channels = dmix->channels;
1097         for (i = 0; i < dmix->channels; i++) {
1098                 j = dmix->bindings[i];
1099                 if (j == UINT_MAX || smaps[0]->map.channels < j)
1100                         continue;
1101                 maps[0]->map.pos[i] = smaps[0]->map.pos[j];
1102         }
1103         return maps;
1104 }
1105
1106 snd_pcm_chmap_t *snd_pcm_direct_get_chmap(snd_pcm_t *pcm)
1107 {
1108         snd_pcm_direct_t *dmix = pcm->private_data;
1109         return snd_pcm_get_chmap(dmix->spcm);
1110 }
1111
1112 int snd_pcm_direct_set_chmap(snd_pcm_t *pcm, const snd_pcm_chmap_t *map)
1113 {
1114         snd_pcm_direct_t *dmix = pcm->private_data;
1115         return snd_pcm_set_chmap(dmix->spcm, map);
1116 }
1117
1118 int snd_pcm_direct_prepare(snd_pcm_t *pcm)
1119 {
1120         snd_pcm_direct_t *dmix = pcm->private_data;
1121         int err;
1122
1123         switch (snd_pcm_state(dmix->spcm)) {
1124         case SND_PCM_STATE_SETUP:
1125         case SND_PCM_STATE_XRUN:
1126         case SND_PCM_STATE_SUSPENDED:
1127                 err = snd_pcm_prepare(dmix->spcm);
1128                 if (err < 0)
1129                         return err;
1130                 snd_pcm_start(dmix->spcm);
1131                 break;
1132         case SND_PCM_STATE_OPEN:
1133         case SND_PCM_STATE_DISCONNECTED:
1134                 return -EBADFD;
1135         default:
1136                 break;
1137         }
1138         snd_pcm_direct_check_interleave(dmix, pcm);
1139         dmix->state = SND_PCM_STATE_PREPARED;
1140         dmix->appl_ptr = dmix->last_appl_ptr = 0;
1141         dmix->hw_ptr = 0;
1142         return snd_pcm_direct_set_timer_params(dmix);
1143 }
1144
1145 int snd_pcm_direct_resume(snd_pcm_t *pcm)
1146 {
1147         snd_pcm_direct_t *dmix = pcm->private_data;
1148         int err;
1149
1150         err = snd_pcm_direct_slave_recover(dmix);
1151         return err < 0 ? err : -ENOSYS;
1152 }
1153
1154 #define COPY_SLAVE(field) (dmix->shmptr->s.field = spcm->field)
1155
1156 /* copy the slave setting */
1157 static void save_slave_setting(snd_pcm_direct_t *dmix, snd_pcm_t *spcm)
1158 {
1159         COPY_SLAVE(access);
1160         COPY_SLAVE(format);
1161         COPY_SLAVE(subformat);
1162         COPY_SLAVE(channels);
1163         COPY_SLAVE(rate);
1164         COPY_SLAVE(period_size);
1165         COPY_SLAVE(period_time);
1166         COPY_SLAVE(periods);
1167         COPY_SLAVE(tstamp_mode);
1168         COPY_SLAVE(tstamp_type);
1169         COPY_SLAVE(period_step);
1170         COPY_SLAVE(avail_min);
1171         COPY_SLAVE(start_threshold);
1172         COPY_SLAVE(stop_threshold);
1173         COPY_SLAVE(silence_threshold);
1174         COPY_SLAVE(silence_size);
1175         COPY_SLAVE(boundary);
1176         COPY_SLAVE(info);
1177         COPY_SLAVE(msbits);
1178         COPY_SLAVE(rate_num);
1179         COPY_SLAVE(rate_den);
1180         COPY_SLAVE(hw_flags);
1181         COPY_SLAVE(fifo_size);
1182         COPY_SLAVE(buffer_size);
1183         COPY_SLAVE(buffer_time);
1184         COPY_SLAVE(sample_bits);
1185         COPY_SLAVE(frame_bits);
1186 }
1187
1188 #undef COPY_SLAVE
1189
1190 /*
1191  * this function initializes hardware and starts playback operation with
1192  * no stop threshold (it operates all time without xrun checking)
1193  * also, the driver silences the unused ring buffer areas for us
1194  */
1195 int snd_pcm_direct_initialize_slave(snd_pcm_direct_t *dmix, snd_pcm_t *spcm, struct slave_params *params)
1196 {
1197         snd_pcm_hw_params_t hw_params = {0};
1198         snd_pcm_sw_params_t sw_params = {0};
1199         int ret, buffer_is_not_initialized;
1200         snd_pcm_uframes_t boundary;
1201         struct pollfd fd;
1202         int loops = 10;
1203
1204       __again:
1205         if (loops-- <= 0) {
1206                 snd_error(PCM, "unable to find a valid configuration for slave");
1207                 return -EINVAL;
1208         }
1209         ret = snd_pcm_hw_params_any(spcm, &hw_params);
1210         if (ret < 0) {
1211                 snd_error(PCM, "snd_pcm_hw_params_any failed");
1212                 return ret;
1213         }
1214         ret = snd_pcm_hw_params_set_access(spcm, &hw_params,
1215                                            SND_PCM_ACCESS_MMAP_INTERLEAVED);
1216         if (ret < 0) {
1217                 ret = snd_pcm_hw_params_set_access(spcm, &hw_params,
1218                                         SND_PCM_ACCESS_MMAP_NONINTERLEAVED);
1219                 if (ret < 0) {
1220                         snd_error(PCM, "slave plugin does not support mmap interleaved or mmap noninterleaved access");
1221                         return ret;
1222                 }
1223         }
1224         if (params->format == SND_PCM_FORMAT_UNKNOWN)
1225                 ret = -EINVAL;
1226         else
1227                 ret = snd_pcm_hw_params_set_format(spcm, &hw_params,
1228                                                    params->format);
1229         if (ret < 0) {
1230                 static const snd_pcm_format_t dmix_formats[] = {
1231                         SND_PCM_FORMAT_S32,
1232                         SND_PCM_FORMAT_S32 ^ SND_PCM_FORMAT_S32_LE ^
1233                                                         SND_PCM_FORMAT_S32_BE,
1234                         SND_PCM_FORMAT_S16,
1235                         SND_PCM_FORMAT_S16 ^ SND_PCM_FORMAT_S16_LE ^
1236                                                         SND_PCM_FORMAT_S16_BE,
1237                         SND_PCM_FORMAT_S24_LE,
1238                         SND_PCM_FORMAT_S24_3LE,
1239                         SND_PCM_FORMAT_U8,
1240                 };
1241                 snd_pcm_format_t format;
1242                 unsigned int i;
1243
1244                 for (i = 0; i < ARRAY_SIZE(dmix_formats); ++i) {
1245                         format = dmix_formats[i];
1246                         ret = snd_pcm_hw_params_set_format(spcm, &hw_params,
1247                                                            format);
1248                         if (ret >= 0)
1249                                 break;
1250                 }
1251                 if (ret < 0 && dmix->type != SND_PCM_TYPE_DMIX) {
1252                         /* TODO: try to choose a good format */
1253                         ret = INTERNAL(snd_pcm_hw_params_set_format_first)(spcm,
1254                                                         &hw_params, &format);
1255                 }
1256                 if (ret < 0) {
1257                         snd_error(PCM, "requested or auto-format is not available");
1258                         return ret;
1259                 }
1260                 params->format = format;
1261         }
1262         ret = INTERNAL(snd_pcm_hw_params_set_channels_near)(spcm, &hw_params,
1263                                         (unsigned int *)&params->channels);
1264         if (ret < 0) {
1265                 snd_error(PCM, "requested count of channels is not available");
1266                 return ret;
1267         }
1268         ret = INTERNAL(snd_pcm_hw_params_set_rate_near)(spcm, &hw_params,
1269                                         (unsigned int *)&params->rate, 0);
1270         if (ret < 0) {
1271                 snd_error(PCM, "requested rate is not available");
1272                 return ret;
1273         }
1274
1275         buffer_is_not_initialized = 0;
1276         if (params->buffer_time > 0) {
1277                 ret = INTERNAL(snd_pcm_hw_params_set_buffer_time_near)(spcm,
1278                         &hw_params, (unsigned int *)&params->buffer_time, 0);
1279                 if (ret < 0) {
1280                         snd_error(PCM, "unable to set buffer time");
1281                         return ret;
1282                 }
1283         } else if (params->buffer_size > 0) {
1284                 ret = INTERNAL(snd_pcm_hw_params_set_buffer_size_near)(spcm,
1285                         &hw_params, (snd_pcm_uframes_t *)&params->buffer_size);
1286                 if (ret < 0) {
1287                         snd_error(PCM, "unable to set buffer size");
1288                         return ret;
1289                 }
1290         } else {
1291                 buffer_is_not_initialized = 1;
1292         }
1293
1294         if (params->period_time > 0) {
1295                 ret = INTERNAL(snd_pcm_hw_params_set_period_time_near)(spcm,
1296                         &hw_params, (unsigned int *)&params->period_time, 0);
1297                 if (ret < 0) {
1298                         snd_error(PCM, "unable to set period_time");
1299                         return ret;
1300                 }
1301         } else if (params->period_size > 0) {
1302                 ret = INTERNAL(snd_pcm_hw_params_set_period_size_near)(spcm,
1303                         &hw_params, (snd_pcm_uframes_t *)&params->period_size,
1304                         0);
1305                 if (ret < 0) {
1306                         snd_error(PCM, "unable to set period_size");
1307                         return ret;
1308                 }
1309         }
1310
1311         if (buffer_is_not_initialized && params->periods > 0) {
1312                 unsigned int periods = params->periods;
1313                 ret = INTERNAL(snd_pcm_hw_params_set_periods_near)(spcm,
1314                                         &hw_params, &params->periods, 0);
1315                 if (ret < 0) {
1316                         snd_error(PCM, "unable to set requested periods");
1317                         return ret;
1318                 }
1319                 if (params->periods == 1) {
1320                         params->periods = periods;
1321                         if (params->period_time > 0) {
1322                                 params->period_time /= 2;
1323                                 goto __again;
1324                         } else if (params->period_size > 0) {
1325                                 params->period_size /= 2;
1326                                 goto __again;
1327                         }
1328                         snd_error(PCM, "unable to use stream with periods == 1");
1329                         return ret;
1330                 }
1331         }
1332
1333         ret = snd_pcm_hw_params(spcm, &hw_params);
1334         if (ret < 0) {
1335                 snd_error(PCM, "unable to install hw params");
1336                 return ret;
1337         }
1338
1339         /* store some hw_params values to shared info */
1340         dmix->shmptr->hw.format =
1341                 snd_mask_value(hw_param_mask(&hw_params,
1342                                              SND_PCM_HW_PARAM_FORMAT));
1343         dmix->shmptr->hw.rate =
1344                 *hw_param_interval(&hw_params, SND_PCM_HW_PARAM_RATE);
1345         dmix->shmptr->hw.buffer_size =
1346                 *hw_param_interval(&hw_params, SND_PCM_HW_PARAM_BUFFER_SIZE);
1347         dmix->shmptr->hw.buffer_time =
1348                 *hw_param_interval(&hw_params, SND_PCM_HW_PARAM_BUFFER_TIME);
1349         dmix->shmptr->hw.period_size =
1350                 *hw_param_interval(&hw_params, SND_PCM_HW_PARAM_PERIOD_SIZE);
1351         dmix->shmptr->hw.period_time =
1352                 *hw_param_interval(&hw_params, SND_PCM_HW_PARAM_PERIOD_TIME);
1353         dmix->shmptr->hw.periods =
1354                 *hw_param_interval(&hw_params, SND_PCM_HW_PARAM_PERIODS);
1355
1356
1357         ret = snd_pcm_sw_params_current(spcm, &sw_params);
1358         if (ret < 0) {
1359                 snd_error(PCM, "unable to get current sw_params");
1360                 return ret;
1361         }
1362
1363         ret = snd_pcm_sw_params_get_boundary(&sw_params, &boundary);
1364         if (ret < 0) {
1365                 snd_error(PCM, "unable to get boundary");
1366                 return ret;
1367         }
1368         ret = snd_pcm_sw_params_set_stop_threshold(spcm, &sw_params, boundary);
1369         if (ret < 0) {
1370                 snd_error(PCM, "unable to set stop threshold");
1371                 return ret;
1372         }
1373
1374         /* set timestamp mode to MMAP
1375          * the slave timestamp is copied appropriately in dsnoop/dmix/dshare
1376          * based on the tstamp_mode of each client
1377          */
1378         ret = snd_pcm_sw_params_set_tstamp_mode(spcm, &sw_params,
1379                                                 SND_PCM_TSTAMP_ENABLE);
1380         if (ret < 0) {
1381                 snd_error(PCM, "unable to tstamp mode MMAP");
1382                 return ret;
1383         }
1384
1385         if (dmix->tstamp_type != -1) {
1386                 ret = snd_pcm_sw_params_set_tstamp_type(spcm, &sw_params,
1387                                                         dmix->tstamp_type);
1388                 if (ret < 0) {
1389                         snd_error(PCM, "unable to set tstamp type");
1390                         return ret;
1391                 }
1392         }
1393
1394         if (dmix->type != SND_PCM_TYPE_DMIX &&
1395             dmix->type != SND_PCM_TYPE_DSHARE)
1396                 goto __skip_silencing;
1397
1398         ret = snd_pcm_sw_params_set_silence_threshold(spcm, &sw_params, 0);
1399         if (ret < 0) {
1400                 snd_error(PCM, "unable to set silence threshold");
1401                 return ret;
1402         }
1403         ret = snd_pcm_sw_params_set_silence_size(spcm, &sw_params, boundary);
1404         if (ret < 0) {
1405                 snd_error(PCM, "unable to set silence threshold (please upgrade to 0.9.0rc8+ driver)");
1406                 return ret;
1407         }
1408
1409       __skip_silencing:
1410
1411         ret = snd_pcm_sw_params(spcm, &sw_params);
1412         if (ret < 0) {
1413                 snd_error(PCM, "unable to install sw params (please upgrade to 0.9.0rc8+ driver)");
1414                 return ret;
1415         }
1416
1417         if (dmix->type == SND_PCM_TYPE_DSHARE) {
1418                 const snd_pcm_channel_area_t *dst_areas;
1419                 dst_areas = snd_pcm_mmap_areas(spcm);
1420                 snd_pcm_areas_silence(dst_areas, 0, spcm->channels,
1421                                       spcm->buffer_size, spcm->format);
1422         }
1423
1424         ret = snd_pcm_start(spcm);
1425         if (ret < 0) {
1426                 snd_error(PCM, "unable to start PCM stream");
1427                 return ret;
1428         }
1429
1430         if (snd_pcm_poll_descriptors_count(spcm) != 1) {
1431                 snd_error(PCM, "unable to use hardware pcm with fd more than one!!!");
1432                 return ret;
1433         }
1434         snd_pcm_poll_descriptors(spcm, &fd, 1);
1435         dmix->hw_fd = fd.fd;
1436
1437         save_slave_setting(dmix, spcm);
1438
1439         /* Currently, we assume that each dmix client has the same
1440          * hw_params setting.
1441          * If the arbitrary hw_parmas is supported in future,
1442          * boundary has to be taken from the slave config but
1443          * recalculated for the native boundary size (for 32bit
1444          * emulation on 64bit arch).
1445          */
1446         dmix->slave_buffer_size = spcm->buffer_size;
1447         dmix->slave_period_size = spcm->period_size;
1448         dmix->slave_boundary = spcm->boundary;
1449
1450         spcm->donot_close = 1;
1451
1452         {
1453                 int ver = 0;
1454                 ioctl(spcm->poll_fd, SNDRV_PCM_IOCTL_PVERSION, &ver);
1455                 if (ver < SNDRV_PROTOCOL_VERSION(2, 0, 8))
1456                         dmix->shmptr->use_server = 1;
1457         }
1458
1459         return 0;
1460 }
1461
1462 /*
1463  * the trick is used here; we cannot use effectively the hardware handle because
1464  * we cannot drive multiple accesses to appl_ptr; so we use slave timer of given
1465  * PCM hardware handle; it's not this easy and cheap?
1466  */
1467 int snd_pcm_direct_initialize_poll_fd(snd_pcm_direct_t *dmix)
1468 {
1469         int ret;
1470         snd_pcm_info_t info = {0};
1471         char name[128];
1472         int capture = dmix->type == SND_PCM_TYPE_DSNOOP ? 1 : 0;
1473
1474         dmix->tread = 1;
1475         dmix->timer_need_poll = 0;
1476         dmix->timer_ticks = 1;
1477         ret = snd_pcm_info(dmix->spcm, &info);
1478         if (ret < 0) {
1479                 snd_error(PCM, "unable to info for slave pcm");
1480                 return ret;
1481         }
1482         sprintf(name, "hw:CLASS=%i,SCLASS=0,CARD=%i,DEV=%i,SUBDEV=%i",
1483                 (int)SND_TIMER_CLASS_PCM,
1484                 snd_pcm_info_get_card(&info),
1485                 snd_pcm_info_get_device(&info),
1486                 snd_pcm_info_get_subdevice(&info) * 2 + capture);
1487         ret = snd_timer_open(&dmix->timer, name,
1488                              SND_TIMER_OPEN_NONBLOCK | SND_TIMER_OPEN_TREAD);
1489         if (ret < 0) {
1490                 dmix->tread = 0;
1491                 ret = snd_timer_open(&dmix->timer, name,
1492                                      SND_TIMER_OPEN_NONBLOCK);
1493                 if (ret < 0) {
1494                         snd_error(PCM, "unable to open timer '%s'", name);
1495                         return ret;
1496                 }
1497         }
1498
1499         if (snd_timer_poll_descriptors_count(dmix->timer) != 1) {
1500                 snd_error(PCM, "unable to use timer '%s' with more than one fd!", name);
1501                 return ret;
1502         }
1503         snd_timer_poll_descriptors(dmix->timer, &dmix->timer_fd, 1);
1504         dmix->poll_fd = dmix->timer_fd.fd;
1505
1506         dmix->timer_events = (1<<SND_TIMER_EVENT_MSUSPEND) |
1507                              (1<<SND_TIMER_EVENT_MRESUME) |
1508                              (1<<SND_TIMER_EVENT_MSTOP) |
1509                              (1<<SND_TIMER_EVENT_STOP);
1510
1511         /*
1512          * Some hacks for older kernel drivers
1513          */
1514         {
1515                 int ver = 0;
1516                 ioctl(dmix->poll_fd, SNDRV_TIMER_IOCTL_PVERSION, &ver);
1517                 /* In older versions, check via poll before read() is needed
1518                  * because of the confliction between TIMER_START and
1519                  * FIONBIO ioctls.
1520                  */
1521                 if (ver < SNDRV_PROTOCOL_VERSION(2, 0, 4))
1522                         dmix->timer_need_poll = 1;
1523                 /*
1524                  * In older versions, timer uses pause events instead
1525                  * suspend/resume events.
1526                  */
1527                 if (ver < SNDRV_PROTOCOL_VERSION(2, 0, 5)) {
1528                         dmix->timer_events &= ~((1<<SND_TIMER_EVENT_MSUSPEND) |
1529                                                 (1<<SND_TIMER_EVENT_MRESUME));
1530                         dmix->timer_events |= (1<<SND_TIMER_EVENT_MPAUSE) |
1531                                               (1<<SND_TIMER_EVENT_MCONTINUE);
1532                 }
1533                 /* In older versions, use SND_TIMER_EVENT_START too.
1534                  */
1535                 if (ver < SNDRV_PROTOCOL_VERSION(2, 0, 6))
1536                         dmix->timer_events |= 1<<SND_TIMER_EVENT_START;
1537         }
1538         return 0;
1539 }
1540
1541 static snd_pcm_uframes_t recalc_boundary_size(unsigned long long bsize, snd_pcm_uframes_t buffer_size)
1542 {
1543         if (bsize > LONG_MAX) {
1544                 bsize = buffer_size;
1545                 while (bsize * 2 <= LONG_MAX - buffer_size)
1546                         bsize *= 2;
1547         }
1548         return (snd_pcm_uframes_t)bsize;
1549 }
1550
1551 #define COPY_SLAVE(field) (spcm->field = dmix->shmptr->s.field)
1552
1553 /* copy the slave setting */
1554 static void copy_slave_setting(snd_pcm_direct_t *dmix, snd_pcm_t *spcm)
1555 {
1556         COPY_SLAVE(access);
1557         COPY_SLAVE(format);
1558         COPY_SLAVE(subformat);
1559         COPY_SLAVE(channels);
1560         COPY_SLAVE(rate);
1561         COPY_SLAVE(period_size);
1562         COPY_SLAVE(period_time);
1563         COPY_SLAVE(periods);
1564         COPY_SLAVE(tstamp_mode);
1565         COPY_SLAVE(tstamp_type);
1566         COPY_SLAVE(period_step);
1567         COPY_SLAVE(avail_min);
1568         COPY_SLAVE(start_threshold);
1569         COPY_SLAVE(stop_threshold);
1570         COPY_SLAVE(silence_threshold);
1571         COPY_SLAVE(silence_size);
1572         COPY_SLAVE(boundary);
1573         COPY_SLAVE(info);
1574         COPY_SLAVE(msbits);
1575         COPY_SLAVE(rate_num);
1576         COPY_SLAVE(rate_den);
1577         COPY_SLAVE(hw_flags);
1578         COPY_SLAVE(fifo_size);
1579         COPY_SLAVE(buffer_size);
1580         COPY_SLAVE(buffer_time);
1581         COPY_SLAVE(sample_bits);
1582         COPY_SLAVE(frame_bits);
1583
1584         spcm->info &= ~SND_PCM_INFO_PAUSE;
1585         spcm->boundary = recalc_boundary_size(dmix->shmptr->s.boundary, spcm->buffer_size);
1586 }
1587
1588 #undef COPY_SLAVE
1589
1590
1591 /*
1592  * open a slave PCM as secondary client (dup'ed fd)
1593  */
1594 int snd_pcm_direct_open_secondary_client(snd_pcm_t **spcmp, snd_pcm_direct_t *dmix, const char *client_name)
1595 {
1596         int ret;
1597         snd_pcm_t *spcm;
1598
1599         ret = snd_pcm_hw_open_fd(spcmp, client_name, dmix->hw_fd, 0);
1600         if (ret < 0) {
1601                 snd_error(PCM, "unable to open hardware");
1602                 return ret;
1603         }
1604
1605         spcm = *spcmp;
1606         spcm->donot_close = 1;
1607         spcm->setup = 1;
1608
1609         copy_slave_setting(dmix, spcm);
1610
1611         /* Use the slave setting as SPCM, so far */
1612         dmix->slave_buffer_size = spcm->buffer_size;
1613         dmix->slave_period_size = dmix->shmptr->s.period_size;
1614         dmix->slave_boundary = spcm->boundary;
1615         dmix->recoveries = dmix->shmptr->s.recoveries;
1616
1617         ret = snd_pcm_mmap(spcm);
1618         if (ret < 0) {
1619                 snd_error(PCM, "unable to mmap channels");
1620                 return ret;
1621         }
1622         return 0;
1623 }
1624
1625 /*
1626  * open a slave PCM as secondary client (dup'ed fd)
1627  */
1628 int snd_pcm_direct_initialize_secondary_slave(snd_pcm_direct_t *dmix,
1629                                               snd_pcm_t *spcm,
1630                                               struct slave_params *params ATTRIBUTE_UNUSED)
1631 {
1632         int ret;
1633
1634         spcm->donot_close = 1;
1635         spcm->setup = 1;
1636
1637         copy_slave_setting(dmix, spcm);
1638
1639         /* Use the slave setting as SPCM, so far */
1640         dmix->slave_buffer_size = spcm->buffer_size;
1641         dmix->slave_period_size = dmix->shmptr->s.period_size;
1642         dmix->slave_boundary = spcm->boundary;
1643
1644         ret = snd_pcm_mmap(spcm);
1645         if (ret < 0) {
1646                 snd_error(PCM, "unable to mmap channels");
1647                 return ret;
1648         }
1649         return 0;
1650 }
1651
1652 int snd_pcm_direct_set_timer_params(snd_pcm_direct_t *dmix)
1653 {
1654         snd_timer_params_t params = {0};
1655         unsigned int filter;
1656         int ret;
1657
1658         snd_timer_params_set_auto_start(&params, 1);
1659         if (dmix->type != SND_PCM_TYPE_DSNOOP)
1660                 snd_timer_params_set_early_event(&params, 1);
1661         snd_timer_params_set_ticks(&params, dmix->timer_ticks);
1662         if (dmix->tread) {
1663                 filter = (1<<SND_TIMER_EVENT_TICK) |
1664                          dmix->timer_events;
1665                 INTERNAL(snd_timer_params_set_filter)(&params, filter);
1666         }
1667         ret = snd_timer_params(dmix->timer, &params);
1668         if (ret < 0) {
1669                 snd_error(PCM, "unable to set timer parameters");
1670                 return ret;
1671         }
1672         return 0;
1673 }
1674
1675 /*
1676  *  ring buffer operation
1677  */
1678 int snd_pcm_direct_check_interleave(snd_pcm_direct_t *dmix, snd_pcm_t *pcm)
1679 {
1680         unsigned int chn, channels;
1681         int bits;
1682         const snd_pcm_channel_area_t *dst_areas;
1683         const snd_pcm_channel_area_t *src_areas;
1684
1685         bits = snd_pcm_format_physical_width(pcm->format);
1686         if ((bits % 8) != 0)
1687                 goto __nointerleaved;
1688         channels = dmix->channels;
1689         if (channels != dmix->spcm->channels)
1690                 goto __nointerleaved;
1691         dst_areas = snd_pcm_mmap_areas(dmix->spcm);
1692         src_areas = snd_pcm_mmap_areas(pcm);
1693         for (chn = 1; chn < channels; chn++) {
1694                 if (dst_areas[chn-1].addr != dst_areas[chn].addr)
1695                         goto __nointerleaved;
1696                 if (src_areas[chn-1].addr != src_areas[chn].addr)
1697                         goto __nointerleaved;
1698         }
1699         for (chn = 0; chn < channels; chn++) {
1700                 if (dmix->bindings && dmix->bindings[chn] != chn)
1701                         goto __nointerleaved;
1702                 if (dst_areas[chn].first != chn * bits ||
1703                     dst_areas[chn].step != channels * bits)
1704                         goto __nointerleaved;
1705                 if (src_areas[chn].first != chn * bits ||
1706                     src_areas[chn].step != channels * bits)
1707                         goto __nointerleaved;
1708         }
1709         return dmix->interleaved = 1;
1710 __nointerleaved:
1711         return dmix->interleaved = 0;
1712 }
1713
1714 /*
1715  * parse the channel map
1716  * id == client channel
1717  * value == slave's channel
1718  */
1719 int snd_pcm_direct_parse_bindings(snd_pcm_direct_t *dmix,
1720                                   struct slave_params *params,
1721                                   snd_config_t *cfg)
1722 {
1723         snd_config_iterator_t i, next;
1724         unsigned int chn, chn1, count = 0;
1725         unsigned int *bindings;
1726         int err;
1727
1728         dmix->channels = UINT_MAX;
1729         if (cfg == NULL)
1730                 return 0;
1731         if (snd_config_get_type(cfg) != SND_CONFIG_TYPE_COMPOUND) {
1732                 snd_error(PCM, "invalid type for bindings");
1733                 return -EINVAL;
1734         }
1735         snd_config_for_each(i, next, cfg) {
1736                 snd_config_t *n = snd_config_iterator_entry(i);
1737                 const char *id;
1738                 long cchannel;
1739                 if (snd_config_get_id(n, &id) < 0)
1740                         continue;
1741                 err = safe_strtol(id, &cchannel);
1742                 if (err < 0 || cchannel < 0) {
1743                         snd_error(PCM, "invalid client channel in binding: %s", id);
1744                         return -EINVAL;
1745                 }
1746                 if ((unsigned)cchannel >= count)
1747                         count = cchannel + 1;
1748         }
1749         if (count == 0)
1750                 return 0;
1751         if (count > 1024) {
1752                 snd_error(PCM, "client channel out of range");
1753                 return -EINVAL;
1754         }
1755         bindings = malloc(count * sizeof(unsigned int));
1756         if (bindings == NULL)
1757                 return -ENOMEM;
1758         for (chn = 0; chn < count; chn++)
1759                 bindings[chn] = UINT_MAX;               /* don't route */
1760         snd_config_for_each(i, next, cfg) {
1761                 snd_config_t *n = snd_config_iterator_entry(i);
1762                 const char *id;
1763                 long cchannel, schannel;
1764                 if (snd_config_get_id(n, &id) < 0)
1765                         continue;
1766                 err = safe_strtol(id, &cchannel);
1767                 if (err < 0) {
1768                         free(bindings);
1769                         return -EINVAL;
1770                 }
1771                 if (snd_config_get_integer(n, &schannel) < 0) {
1772                         snd_error(PCM, "unable to get slave channel (should be integer type) in binding: %s", id);
1773                         free(bindings);
1774                         return -EINVAL;
1775                 }
1776                 if (schannel < 0 || schannel >= params->channels) {
1777                         snd_error(PCM, "invalid slave channel number %ld in binding to %ld",
1778                                        schannel, cchannel);
1779
1780                         free(bindings);
1781                         return -EINVAL;
1782                 }
1783                 bindings[cchannel] = schannel;
1784         }
1785         if (dmix->type == SND_PCM_TYPE_DSNOOP ||
1786             ! dmix->bindings)
1787                 goto __skip_same_dst;
1788         for (chn = 0; chn < count; chn++) {
1789                 for (chn1 = 0; chn1 < count; chn1++) {
1790                         if (chn == chn1)
1791                                 continue;
1792                         if (bindings[chn] == dmix->bindings[chn1]) {
1793                                 snd_error(PCM, "unable to route channels %d,%d to same destination %d", chn, chn1, bindings[chn]);
1794                                 free(bindings);
1795                                 return -EINVAL;
1796                         }
1797                 }
1798         }
1799       __skip_same_dst:
1800         dmix->bindings = bindings;
1801         dmix->channels = count;
1802         return 0;
1803 }
1804
1805 /*
1806  * parse slave config and calculate the ipc_key offset
1807  */
1808
1809 static int _snd_pcm_direct_get_slave_ipc_offset(snd_config_t *root,
1810                                                 snd_config_t *sconf,
1811                                                 int direction,
1812                                                 int hop)
1813 {
1814         snd_config_iterator_t i, next;
1815         snd_config_t *pcm_conf, *pcm_conf2;
1816         int err;
1817         long card = 0, device = 0, subdevice = 0;
1818         const char *str;
1819
1820         if (snd_config_get_string(sconf, &str) >= 0) {
1821                 if (hop > SND_CONF_MAX_HOPS) {
1822                         snd_error(PCM, "Too many definition levels (looped?)");
1823                         return -EINVAL;
1824                 }
1825                 err = snd_config_search_definition(root, "pcm", str, &pcm_conf);
1826                 if (err < 0) {
1827                         snd_error(PCM, "Unknown slave PCM %s", str);
1828                         return err;
1829                 }
1830                 err = _snd_pcm_direct_get_slave_ipc_offset(root, pcm_conf,
1831                                                            direction,
1832                                                            hop + 1);
1833                 snd_config_delete(pcm_conf);
1834                 return err;
1835         }
1836
1837 #if 0   /* for debug purposes */
1838         {
1839                 snd_output_t *out;
1840                 snd_output_stdio_attach(&out, stderr, 0);
1841                 snd_config_save(sconf, out);
1842                 snd_output_close(out);
1843         }
1844 #endif
1845
1846         if (snd_config_search(sconf, "slave", &pcm_conf) >= 0) {
1847                 if (snd_config_search(pcm_conf, "pcm", &pcm_conf) >= 0) {
1848                         return _snd_pcm_direct_get_slave_ipc_offset(root,
1849                                                                    pcm_conf,
1850                                                                    direction,
1851                                                                    hop + 1);
1852                 } else {
1853                         if (snd_config_get_string(pcm_conf, &str) >= 0 &&
1854                             snd_config_search_definition(root, "pcm_slave",
1855                                                     str, &pcm_conf) >= 0) {
1856                                 if (snd_config_search(pcm_conf, "pcm",
1857                                                         &pcm_conf2) >= 0) {
1858                                         err =
1859                                          _snd_pcm_direct_get_slave_ipc_offset(
1860                                              root, pcm_conf2, direction, hop + 1);
1861                                         snd_config_delete(pcm_conf);
1862                                         return err;
1863                                 }
1864                                 snd_config_delete(pcm_conf);
1865                         }
1866                 }
1867         }
1868
1869         snd_config_for_each(i, next, sconf) {
1870                 snd_config_t *n = snd_config_iterator_entry(i);
1871                 const char *id, *str;
1872                 if (snd_config_get_id(n, &id) < 0)
1873                         continue;
1874                 if (strcmp(id, "type") == 0) {
1875                         err = snd_config_get_string(n, &str);
1876                         if (err < 0) {
1877                                 snd_error(PCM, "Invalid value for PCM type definition");
1878                                 return -EINVAL;
1879                         }
1880                         if (strcmp(str, "hw")) {
1881                                 snd_error(PCM, "Invalid type '%s' for slave PCM", str);
1882                                 return -EINVAL;
1883                         }
1884                         continue;
1885                 }
1886                 if (strcmp(id, "card") == 0) {
1887                         err = snd_config_get_card(n);
1888                         if (err < 0)
1889                                 return err;
1890                         card = err;
1891                         continue;
1892                 }
1893                 if (strcmp(id, "device") == 0) {
1894                         err = snd_config_get_integer(n, &device);
1895                         if (err < 0) {
1896                                 snd_error(PCM, "Invalid type for %s", id);
1897                                 return err;
1898                         }
1899                         continue;
1900                 }
1901                 if (strcmp(id, "subdevice") == 0) {
1902                         err = snd_config_get_integer(n, &subdevice);
1903                         if (err < 0) {
1904                                 snd_error(PCM, "Invalid type for %s", id);
1905                                 return err;
1906                         }
1907                         continue;
1908                 }
1909         }
1910         if (device < 0)
1911                 device = 0;
1912         if (subdevice < 0)
1913                 subdevice = 0;
1914         if (card < 0 || card >= (1 << (31 - 12 - 1)))
1915                 return -EOVERFLOW;
1916         if (device >= (1 << 6))
1917                 return -EOVERFLOW;
1918         if (subdevice >= (1 << 4))
1919                 return -EOVERFLOW;
1920         if (direction < 0 || direction > 1)
1921                 return -EOVERFLOW;
1922         return (direction << 1) + (device << 2) + (subdevice << 8) + (card << 12);
1923 }
1924
1925 static int snd_pcm_direct_get_slave_ipc_offset(snd_config_t *root,
1926                                         snd_config_t *sconf,
1927                                         int direction)
1928 {
1929         return _snd_pcm_direct_get_slave_ipc_offset(root, sconf, direction, 0);
1930 }
1931
1932 int snd_pcm_direct_parse_open_conf(snd_config_t *root, snd_config_t *conf,
1933                                    int stream, struct snd_pcm_direct_open_conf *rec)
1934 {
1935         snd_config_iterator_t i, next;
1936         int ipc_key_add_uid = 0;
1937         snd_config_t *n;
1938         int err;
1939
1940         rec->slave = NULL;
1941         rec->bindings = NULL;
1942         rec->ipc_key = 0;
1943         rec->ipc_perm = 0600;
1944         rec->ipc_gid = -1;
1945         rec->slowptr = 1;
1946         rec->max_periods = 0;
1947         rec->var_periodsize = 0;
1948 #ifdef LOCKLESS_DMIX_DEFAULT
1949         rec->direct_memory_access = 1;
1950 #else
1951         rec->direct_memory_access = 0;
1952 #endif
1953         rec->hw_ptr_alignment = SND_PCM_HW_PTR_ALIGNMENT_AUTO;
1954         rec->tstamp_type = -1;
1955
1956         /* read defaults */
1957         if (snd_config_search(root, "defaults.pcm.dmix_max_periods", &n) >= 0) {
1958                 long val;
1959                 err = snd_config_get_integer(n, &val);
1960                 if (err >= 0)
1961                         rec->max_periods = val;
1962         }
1963
1964         snd_config_for_each(i, next, conf) {
1965                 const char *id;
1966                 n = snd_config_iterator_entry(i);
1967                 if (snd_config_get_id(n, &id) < 0)
1968                         continue;
1969                 if (snd_pcm_conf_generic_id(id))
1970                         continue;
1971                 if (strcmp(id, "ipc_key") == 0) {
1972                         long key;
1973                         err = snd_config_get_integer(n, &key);
1974                         if (err < 0) {
1975                                 snd_error(PCM, "The field ipc_key must be an integer type");
1976
1977                                 return err;
1978                         }
1979                         rec->ipc_key = key;
1980                         continue;
1981                 }
1982                 if (strcmp(id, "ipc_perm") == 0) {
1983                         long perm;
1984                         err = snd_config_get_integer(n, &perm);
1985                         if (err < 0) {
1986                                 snd_error(PCM, "Invalid type for %s", id);
1987                                 return err;
1988                         }
1989                         if ((perm & ~0777) != 0) {
1990                                 snd_error(PCM, "The field ipc_perm must be a valid file permission");
1991                                 return -EINVAL;
1992                         }
1993                         rec->ipc_perm = perm;
1994                         continue;
1995                 }
1996                 if (strcmp(id, "hw_ptr_alignment") == 0) {
1997                         const char *str;
1998                         err = snd_config_get_string(n, &str);
1999                         if (err < 0) {
2000                                 snd_error(PCM, "Invalid type for %s", id);
2001                                 return -EINVAL;
2002                         }
2003                         if (strcmp(str, "no") == 0 || strcmp(str, "off") == 0)
2004                                 rec->hw_ptr_alignment = SND_PCM_HW_PTR_ALIGNMENT_NO;
2005                         else if (strcmp(str, "roundup") == 0)
2006                                 rec->hw_ptr_alignment = SND_PCM_HW_PTR_ALIGNMENT_ROUNDUP;
2007                         else if (strcmp(str, "rounddown") == 0)
2008                                 rec->hw_ptr_alignment = SND_PCM_HW_PTR_ALIGNMENT_ROUNDDOWN;
2009                         else if (strcmp(str, "auto") == 0)
2010                                 rec->hw_ptr_alignment = SND_PCM_HW_PTR_ALIGNMENT_AUTO;
2011                         else {
2012                                 snd_error(PCM, "The field hw_ptr_alignment is invalid : %s", str);
2013                                 return -EINVAL;
2014                         }
2015
2016                         continue;
2017                 }
2018                 if (strcmp(id, "tstamp_type") == 0) {
2019                         const char *str;
2020                         err = snd_config_get_string(n, &str);
2021                         if (err < 0) {
2022                                 snd_error(PCM, "Invalid type for %s", id);
2023                                 return -EINVAL;
2024                         }
2025                         if (strcmp(str, "default") == 0)
2026                                 rec->tstamp_type = -1;
2027                         else if (strcmp(str, "gettimeofday") == 0)
2028                                 rec->tstamp_type = SND_PCM_TSTAMP_TYPE_GETTIMEOFDAY;
2029                         else if (strcmp(str, "monotonic") == 0)
2030                                 rec->tstamp_type = SND_PCM_TSTAMP_TYPE_MONOTONIC;
2031                         else if (strcmp(str, "monotonic_raw") == 0)
2032                                 rec->tstamp_type = SND_PCM_TSTAMP_TYPE_MONOTONIC_RAW;
2033                         else {
2034                                 snd_error(PCM, "The field tstamp_type is invalid : %s", str);
2035                                 return -EINVAL;
2036                         }
2037                         continue;
2038                 }
2039                 if (strcmp(id, "ipc_gid") == 0) {
2040                         char *group;
2041                         char *endp;
2042                         err = snd_config_get_ascii(n, &group);
2043                         if (err < 0) {
2044                                 snd_error(PCM, "The field ipc_gid must be a valid group");
2045                                 return err;
2046                         }
2047                         if (! *group) {
2048                                 rec->ipc_gid = -1;
2049                                 free(group);
2050                                 continue;
2051                         }
2052                         if (isdigit(*group) == 0) {
2053                                 long clen = sysconf(_SC_GETGR_R_SIZE_MAX);
2054                                 size_t len = (clen == -1) ? 1024 : (size_t)clen;
2055                                 struct group grp, *pgrp;
2056                                 char *buffer = (char *)malloc(len);
2057                                 if (buffer == NULL)
2058                                         return -ENOMEM;
2059                                 int st = getgrnam_r(group, &grp, buffer, len, &pgrp);
2060                                 if (st != 0 || !pgrp) {
2061                                         snd_error(PCM, "The field ipc_gid must be a valid group (create group %s)", group);
2062                                         free(buffer);
2063                                         return -EINVAL;
2064                                 }
2065                                 rec->ipc_gid = pgrp->gr_gid;
2066                                 free(buffer);
2067                         } else {
2068                                 rec->ipc_gid = strtol(group, &endp, 10);
2069                         }
2070                         free(group);
2071                         continue;
2072                 }
2073                 if (strcmp(id, "ipc_key_add_uid") == 0) {
2074                         if ((err = snd_config_get_bool(n)) < 0) {
2075                                 snd_error(PCM, "The field ipc_key_add_uid must be a boolean type");
2076                                 return err;
2077                         }
2078                         ipc_key_add_uid = err;
2079                         continue;
2080                 }
2081                 if (strcmp(id, "slave") == 0) {
2082                         rec->slave = n;
2083                         continue;
2084                 }
2085                 if (strcmp(id, "bindings") == 0) {
2086                         rec->bindings = n;
2087                         continue;
2088                 }
2089                 if (strcmp(id, "slowptr") == 0) {
2090                         err = snd_config_get_bool(n);
2091                         if (err < 0)
2092                                 return err;
2093                         rec->slowptr = err;
2094                         continue;
2095                 }
2096                 if (strcmp(id, "max_periods") == 0) {
2097                         long val;
2098                         err = snd_config_get_integer(n, &val);
2099                         if (err < 0)
2100                                 return err;
2101                         rec->max_periods = val;
2102                         continue;
2103                 }
2104                 if (strcmp(id, "var_periodsize") == 0) {
2105                         err = snd_config_get_bool(n);
2106                         if (err < 0)
2107                                 return err;
2108                         rec->var_periodsize = err;
2109                         continue;
2110                 }
2111                 if (strcmp(id, "direct_memory_access") == 0) {
2112                         err = snd_config_get_bool(n);
2113                         if (err < 0)
2114                                 return err;
2115                         rec->direct_memory_access = err;
2116                         continue;
2117                 }
2118                 snd_error(PCM, "Unknown field %s", id);
2119                 return -EINVAL;
2120         }
2121         if (!rec->slave) {
2122                 snd_error(PCM, "slave is not defined");
2123                 return -EINVAL;
2124         }
2125         if (!rec->ipc_key) {
2126                 snd_error(PCM, "Unique IPC key is not defined");
2127                 return -EINVAL;
2128         }
2129         if (ipc_key_add_uid)
2130                 rec->ipc_key += getuid();
2131         err = snd_pcm_direct_get_slave_ipc_offset(root, conf, stream);
2132         if (err < 0)
2133                 return err;
2134         rec->ipc_key += err;
2135
2136         return 0;
2137 }
2138
2139 void snd_pcm_direct_reset_slave_ptr(snd_pcm_t *pcm, snd_pcm_direct_t *dmix,
2140                                     snd_pcm_uframes_t hw_ptr)
2141 {
2142         dmix->slave_appl_ptr = dmix->slave_hw_ptr = hw_ptr;
2143         if (dmix->hw_ptr_alignment == SND_PCM_HW_PTR_ALIGNMENT_ROUNDUP ||
2144             (dmix->hw_ptr_alignment == SND_PCM_HW_PTR_ALIGNMENT_AUTO &&
2145              pcm->buffer_size <= pcm->period_size * 2))
2146                 dmix->slave_appl_ptr =
2147                         ((dmix->slave_appl_ptr + dmix->slave_period_size - 1) /
2148                                         dmix->slave_period_size) * dmix->slave_period_size;
2149         else if (dmix->hw_ptr_alignment == SND_PCM_HW_PTR_ALIGNMENT_ROUNDDOWN ||
2150                  (dmix->hw_ptr_alignment == SND_PCM_HW_PTR_ALIGNMENT_AUTO &&
2151                   ((dmix->slave_period_size * SEC_TO_MS) / pcm->rate) < LOW_LATENCY_PERIOD_TIME))
2152                 dmix->slave_appl_ptr = dmix->slave_hw_ptr =
2153                         ((dmix->slave_hw_ptr / dmix->slave_period_size) *
2154                                                         dmix->slave_period_size);
2155 }
2156
2157 int _snd_pcm_direct_new(snd_pcm_t **pcmp, snd_pcm_direct_t **_dmix, int type,
2158                         const char *name, struct snd_pcm_direct_open_conf *opts,
2159                         struct slave_params *params, snd_pcm_stream_t stream, int mode)
2160 {
2161         snd_pcm_direct_t *dmix;
2162         int fail_sem_loop = 10;
2163         int ret;
2164
2165         dmix = calloc(1, sizeof(snd_pcm_direct_t));
2166         if (!dmix)
2167                 return -ENOMEM;
2168
2169         ret = snd_pcm_direct_parse_bindings(dmix, params, opts->bindings);
2170         if (ret < 0) {
2171                 free(dmix);
2172                 return ret;
2173         }
2174
2175         dmix->ipc_key = opts->ipc_key;
2176         dmix->ipc_perm = opts->ipc_perm;
2177         dmix->ipc_gid = opts->ipc_gid;
2178         dmix->tstamp_type = opts->tstamp_type;
2179         dmix->semid = -1;
2180         dmix->shmid = -1;
2181         dmix->shmptr = (void *) -1;
2182         dmix->type = type;
2183
2184         ret = snd_pcm_new(pcmp, type, name, stream, mode);
2185         if (ret < 0)
2186                 goto _err_nosem;
2187
2188         while (1) {
2189                 ret = snd_pcm_direct_semaphore_create_or_connect(dmix);
2190                 if (ret < 0) {
2191                         snd_error(PCM, "unable to create IPC semaphore");
2192                         goto _err_nosem_free;
2193                 }
2194                 ret = snd_pcm_direct_semaphore_down(dmix, DIRECT_IPC_SEM_CLIENT);
2195                 if (ret < 0) {
2196                         snd_pcm_direct_semaphore_discard(dmix);
2197                         if (--fail_sem_loop <= 0)
2198                                 goto _err_nosem_free;
2199                         continue;
2200                 }
2201                 break;
2202         }
2203
2204         ret = snd_pcm_direct_shm_create_or_connect(dmix);
2205         if (ret < 0) {
2206                 snd_error(PCM, "unable to create IPC shm instance");
2207                 snd_pcm_direct_semaphore_up(dmix, DIRECT_IPC_SEM_CLIENT);
2208                 goto _err_nosem_free;
2209         } else {
2210                 *_dmix = dmix;
2211         }
2212
2213         return ret;
2214 _err_nosem_free:
2215         snd_pcm_free(*pcmp);
2216         *pcmp = NULL;
2217 _err_nosem:
2218         free(dmix->bindings);
2219         free(dmix);
2220         return ret;
2221 }