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