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., 59 Temple Place, Suite 330, Boston, MA  02111-1307 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 <sys/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
47union 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
59int 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
85#define SND_PCM_DIRECT_MAGIC	(0xa15ad300 + sizeof(snd_pcm_direct_share_t))
86
87/*
88 *  global shared memory area
89 */
90
91int snd_pcm_direct_shm_create_or_connect(snd_pcm_direct_t *dmix)
92{
93	struct shmid_ds buf;
94	int tmpid, err;
95
96retryget:
97	dmix->shmid = shmget(dmix->ipc_key, sizeof(snd_pcm_direct_share_t),
98			     IPC_CREAT | dmix->ipc_perm);
99	err = -errno;
100	if (dmix->shmid < 0){
101		if (errno == EINVAL)
102		if ((tmpid = shmget(dmix->ipc_key, 0, dmix->ipc_perm)) != -1)
103		if (!shmctl(tmpid, IPC_STAT, &buf))
104		if (!buf.shm_nattch)
105	    	/* no users so destroy the segment */
106		if (!shmctl(tmpid, IPC_RMID, NULL))
107		    goto retryget;
108		return err;
109	}
110	dmix->shmptr = shmat(dmix->shmid, 0, 0);
111	if (dmix->shmptr == (void *) -1) {
112		err = -errno;
113		snd_pcm_direct_shm_discard(dmix);
114		return err;
115	}
116	mlock(dmix->shmptr, sizeof(snd_pcm_direct_share_t));
117	if (shmctl(dmix->shmid, IPC_STAT, &buf) < 0) {
118		err = -errno;
119		snd_pcm_direct_shm_discard(dmix);
120		return err;
121	}
122	if (buf.shm_nattch == 1) {	/* we're the first user, clear the segment */
123		memset(dmix->shmptr, 0, sizeof(snd_pcm_direct_share_t));
124		if (dmix->ipc_gid >= 0) {
125			buf.shm_perm.gid = dmix->ipc_gid;
126			shmctl(dmix->shmid, IPC_SET, &buf);
127		}
128		dmix->shmptr->magic = SND_PCM_DIRECT_MAGIC;
129		return 1;
130	} else {
131		if (dmix->shmptr->magic != SND_PCM_DIRECT_MAGIC) {
132			snd_pcm_direct_shm_discard(dmix);
133			return -EINVAL;
134		}
135	}
136	return 0;
137}
138
139/* discard shared memory */
140/*
141 * Define snd_* functions to be used in server.
142 * Since objects referred in a plugin can be released dynamically, a forked
143 * server should have statically linked functions.
144 * (e.g. Novell bugzilla #105772)
145 */
146static int _snd_pcm_direct_shm_discard(snd_pcm_direct_t *dmix)
147{
148	struct shmid_ds buf;
149	int ret = 0;
150
151	if (dmix->shmid < 0)
152		return -EINVAL;
153	if (dmix->shmptr != (void *) -1 && shmdt(dmix->shmptr) < 0)
154		return -errno;
155	dmix->shmptr = (void *) -1;
156	if (shmctl(dmix->shmid, IPC_STAT, &buf) < 0)
157		return -errno;
158	if (buf.shm_nattch == 0) {	/* we're the last user, destroy the segment */
159		if (shmctl(dmix->shmid, IPC_RMID, NULL) < 0)
160			return -errno;
161		ret = 1;
162	}
163	dmix->shmid = -1;
164	return ret;
165}
166
167/* ... and an exported version */
168int snd_pcm_direct_shm_discard(snd_pcm_direct_t *dmix)
169{
170	return _snd_pcm_direct_shm_discard(dmix);
171}
172
173/*
174 *  server side
175 */
176
177static int get_tmp_name(char *filename, size_t size)
178{
179	struct timeval tv;
180
181	gettimeofday(&tv, NULL);
182	snprintf(filename, size, TMPDIR "/alsa-dmix-%i-%li-%li", (int)getpid(), (long)tv.tv_sec, (long)tv.tv_usec);
183	filename[size-1] = '\0';
184	return 0;
185}
186
187static int make_local_socket(const char *filename, int server, mode_t ipc_perm, int ipc_gid)
188{
189	size_t l = strlen(filename);
190	size_t size = offsetof(struct sockaddr_un, sun_path) + l;
191	struct sockaddr_un *addr = alloca(size);
192	int sock;
193
194	sock = socket(PF_LOCAL, SOCK_STREAM, 0);
195	if (sock < 0) {
196		int result = -errno;
197		SYSERR("socket failed");
198		return result;
199	}
200
201	if (server)
202		unlink(filename);
203	memset(addr, 0, size); /* make valgrind happy */
204	addr->sun_family = AF_LOCAL;
205	memcpy(addr->sun_path, filename, l);
206
207	if (server) {
208		if (bind(sock, (struct sockaddr *) addr, size) < 0) {
209			int result = -errno;
210			SYSERR("bind failed: %s", filename);
211			close(sock);
212			return result;
213		} else {
214			if (chmod(filename, ipc_perm) < 0) {
215				int result = -errno;
216				SYSERR("chmod failed: %s", filename);
217				close(sock);
218				unlink(filename);
219				return result;
220			}
221			if (chown(filename, -1, ipc_gid) < 0) {
222#if 0 /* it's not fatal */
223				int result = -errno;
224				SYSERR("chown failed: %s", filename);
225				close(sock);
226				unlink(filename);
227				return result;
228#endif
229			}
230		}
231	} else {
232		if (connect(sock, (struct sockaddr *) addr, size) < 0) {
233			int result = -errno;
234			SYSERR("connect failed: %s", filename);
235			close(sock);
236			return result;
237		}
238	}
239	return sock;
240}
241
242#if 0
243#define SERVER_JOB_DEBUG
244#define server_printf(fmt, args...) printf(fmt, ##args)
245#else
246#undef SERVER_JOB_DEBUG
247#define server_printf(fmt, args...) /* nothing */
248#endif
249
250static snd_pcm_direct_t *server_job_dmix;
251
252static void server_cleanup(snd_pcm_direct_t *dmix)
253{
254	close(dmix->server_fd);
255	close(dmix->hw_fd);
256	if (dmix->server_free)
257		dmix->server_free(dmix);
258	unlink(dmix->shmptr->socket_name);
259	_snd_pcm_direct_shm_discard(dmix);
260	snd_pcm_direct_semaphore_discard(dmix);
261}
262
263static void server_job_signal(int sig ATTRIBUTE_UNUSED)
264{
265	snd_pcm_direct_semaphore_down(server_job_dmix, DIRECT_IPC_SEM_CLIENT);
266	server_cleanup(server_job_dmix);
267	server_printf("DIRECT SERVER EXIT - SIGNAL\n");
268	_exit(EXIT_SUCCESS);
269}
270
271/* This is a copy from ../socket.c, provided here only for a server job
272 * (see the comment above)
273 */
274static int _snd_send_fd(int sock, void *data, size_t len, int fd)
275{
276	int ret;
277	size_t cmsg_len = CMSG_LEN(sizeof(int));
278	struct cmsghdr *cmsg = alloca(cmsg_len);
279	int *fds = (int *) CMSG_DATA(cmsg);
280	struct msghdr msghdr;
281	struct iovec vec;
282
283	vec.iov_base = (void *)&data;
284	vec.iov_len = len;
285
286	cmsg->cmsg_len = cmsg_len;
287	cmsg->cmsg_level = SOL_SOCKET;
288	cmsg->cmsg_type = SCM_RIGHTS;
289	*fds = fd;
290
291	msghdr.msg_name = NULL;
292	msghdr.msg_namelen = 0;
293	msghdr.msg_iov = &vec;
294 	msghdr.msg_iovlen = 1;
295	msghdr.msg_control = cmsg;
296	msghdr.msg_controllen = cmsg_len;
297	msghdr.msg_flags = 0;
298
299	ret = sendmsg(sock, &msghdr, 0 );
300	if (ret < 0)
301		return -errno;
302	return ret;
303}
304
305static void server_job(snd_pcm_direct_t *dmix)
306{
307	int ret, sck, i;
308	int max = 128, current = 0;
309	struct pollfd pfds[max + 1];
310
311	server_job_dmix = dmix;
312	/* don't allow to be killed */
313	signal(SIGHUP, server_job_signal);
314	signal(SIGQUIT, server_job_signal);
315	signal(SIGTERM, server_job_signal);
316	signal(SIGKILL, server_job_signal);
317	/* close all files to free resources */
318	i = sysconf(_SC_OPEN_MAX);
319#ifdef SERVER_JOB_DEBUG
320	while (--i >= 3) {
321#else
322	while (--i >= 0) {
323#endif
324		if (i != dmix->server_fd && i != dmix->hw_fd)
325			close(i);
326	}
327
328	/* detach from parent */
329	setsid();
330
331	pfds[0].fd = dmix->server_fd;
332	pfds[0].events = POLLIN | POLLERR | POLLHUP;
333
334	server_printf("DIRECT SERVER STARTED\n");
335	while (1) {
336		ret = poll(pfds, current + 1, 500);
337		server_printf("DIRECT SERVER: poll ret = %i, revents[0] = 0x%x, errno = %i\n", ret, pfds[0].revents, errno);
338		if (ret < 0) {
339			if (errno == EINTR)
340				continue;
341			/* some error */
342			break;
343		}
344		if (ret == 0 || (pfds[0].revents & (POLLERR | POLLHUP))) {	/* timeout or error? */
345			struct shmid_ds buf;
346			snd_pcm_direct_semaphore_down(dmix, DIRECT_IPC_SEM_CLIENT);
347			if (shmctl(dmix->shmid, IPC_STAT, &buf) < 0) {
348				_snd_pcm_direct_shm_discard(dmix);
349				snd_pcm_direct_semaphore_up(dmix, DIRECT_IPC_SEM_CLIENT);
350				continue;
351			}
352			server_printf("DIRECT SERVER: nattch = %i\n", (int)buf.shm_nattch);
353			if (buf.shm_nattch == 1)	/* server is the last user, exit */
354				break;
355			snd_pcm_direct_semaphore_up(dmix, DIRECT_IPC_SEM_CLIENT);
356			continue;
357		}
358		if (pfds[0].revents & POLLIN) {
359			ret--;
360			sck = accept(dmix->server_fd, 0, 0);
361			if (sck >= 0) {
362				server_printf("DIRECT SERVER: new connection %i\n", sck);
363				if (current == max) {
364					close(sck);
365				} else {
366					unsigned char buf = 'A';
367					pfds[current+1].fd = sck;
368					pfds[current+1].events = POLLIN | POLLERR | POLLHUP;
369					_snd_send_fd(sck, &buf, 1, dmix->hw_fd);
370					server_printf("DIRECT SERVER: fd sent ok\n");
371					current++;
372				}
373			}
374		}
375		for (i = 0; i < current && ret > 0; i++) {
376			struct pollfd *pfd = &pfds[i+1];
377			unsigned char cmd;
378			server_printf("client %i revents = 0x%x\n", pfd->fd, pfd->revents);
379			if (pfd->revents & (POLLERR | POLLHUP)) {
380				ret--;
381				close(pfd->fd);
382				pfd->fd = -1;
383				continue;
384			}
385			if (!(pfd->revents & POLLIN))
386				continue;
387			ret--;
388			if (read(pfd->fd, &cmd, 1) == 1)
389				cmd = 0 /*process command */;
390		}
391		for (i = 0; i < current; i++) {
392			if (pfds[i+1].fd < 0) {
393				if (i + 1 != max)
394					memcpy(&pfds[i+1], &pfds[i+2], sizeof(struct pollfd) * (max - i - 1));
395				current--;
396			}
397		}
398	}
399	server_cleanup(dmix);
400	server_printf("DIRECT SERVER EXIT\n");
401#ifdef SERVER_JOB_DEBUG
402	close(0); close(1); close(2);
403#endif
404	_exit(EXIT_SUCCESS);
405}
406
407int snd_pcm_direct_server_create(snd_pcm_direct_t *dmix)
408{
409	int ret;
410
411	dmix->server_fd = -1;
412
413	ret = get_tmp_name(dmix->shmptr->socket_name, sizeof(dmix->shmptr->socket_name));
414	if (ret < 0)
415		return ret;
416
417	ret = make_local_socket(dmix->shmptr->socket_name, 1, dmix->ipc_perm, dmix->ipc_gid);
418	if (ret < 0)
419		return ret;
420	dmix->server_fd = ret;
421
422	ret = listen(dmix->server_fd, 4);
423	if (ret < 0) {
424		close(dmix->server_fd);
425		return ret;
426	}
427
428	ret = fork();
429	if (ret < 0) {
430		close(dmix->server_fd);
431		return ret;
432	} else if (ret == 0) {
433		ret = fork();
434		if (ret == 0)
435			server_job(dmix);
436		_exit(EXIT_SUCCESS);
437	} else {
438		waitpid(ret, NULL, 0);
439	}
440	dmix->server_pid = ret;
441	dmix->server = 1;
442	return 0;
443}
444
445int snd_pcm_direct_server_discard(snd_pcm_direct_t *dmix)
446{
447	if (dmix->server) {
448		//kill(dmix->server_pid, SIGTERM);
449		//waitpid(dmix->server_pid, NULL, 0);
450		dmix->server_pid = (pid_t)-1;
451	}
452	if (dmix->server_fd > 0) {
453		close(dmix->server_fd);
454		dmix->server_fd = -1;
455	}
456	dmix->server = 0;
457	return 0;
458}
459
460/*
461 *  client side
462 */
463
464int snd_pcm_direct_client_connect(snd_pcm_direct_t *dmix)
465{
466	int ret;
467	unsigned char buf;
468
469	ret = make_local_socket(dmix->shmptr->socket_name, 0, -1, -1);
470	if (ret < 0)
471		return ret;
472	dmix->comm_fd = ret;
473
474	ret = snd_receive_fd(dmix->comm_fd, &buf, 1, &dmix->hw_fd);
475	if (ret < 1 || buf != 'A') {
476		close(dmix->comm_fd);
477		dmix->comm_fd = -1;
478		return ret;
479	}
480
481	dmix->client = 1;
482	return 0;
483}
484
485int snd_pcm_direct_client_discard(snd_pcm_direct_t *dmix)
486{
487	if (dmix->client) {
488		close(dmix->comm_fd);
489		dmix->comm_fd = -1;
490	}
491	return 0;
492}
493
494/*
495 *  plugin helpers
496 */
497
498int snd_pcm_direct_nonblock(snd_pcm_t *pcm ATTRIBUTE_UNUSED, int nonblock ATTRIBUTE_UNUSED)
499{
500	/* value is cached for us in pcm->mode (SND_PCM_NONBLOCK flag) */
501	return 0;
502}
503
504int snd_pcm_direct_async(snd_pcm_t *pcm, int sig, pid_t pid)
505{
506	snd_pcm_direct_t *dmix = pcm->private_data;
507	return snd_timer_async(dmix->timer, sig, pid);
508}
509
510/* empty the timer read queue */
511void snd_pcm_direct_clear_timer_queue(snd_pcm_direct_t *dmix)
512{
513	if (dmix->timer_need_poll) {
514		while (poll(&dmix->timer_fd, 1, 0) > 0) {
515			/* we don't need the value */
516			if (dmix->tread) {
517				snd_timer_tread_t rbuf[4];
518				snd_timer_read(dmix->timer, rbuf, sizeof(rbuf));
519			} else {
520				snd_timer_read_t rbuf;
521				snd_timer_read(dmix->timer, &rbuf, sizeof(rbuf));
522			}
523		}
524	} else {
525		if (dmix->tread) {
526			snd_timer_tread_t rbuf[4];
527			int len;
528			while ((len = snd_timer_read(dmix->timer, rbuf,
529						     sizeof(rbuf))) > 0 &&
530			       len != sizeof(rbuf[0]))
531				;
532		} else {
533			snd_timer_read_t rbuf;
534			while (snd_timer_read(dmix->timer, &rbuf, sizeof(rbuf)) > 0)
535				;
536		}
537	}
538}
539
540int snd_pcm_direct_timer_stop(snd_pcm_direct_t *dmix)
541{
542	snd_timer_stop(dmix->timer);
543	return 0;
544}
545
546int snd_pcm_direct_poll_revents(snd_pcm_t *pcm, struct pollfd *pfds, unsigned int nfds, unsigned short *revents)
547{
548	snd_pcm_direct_t *dmix = pcm->private_data;
549	unsigned short events;
550	int empty = 0;
551
552	assert(pfds && nfds == 1 && revents);
553	events = pfds[0].revents;
554	if (events & POLLIN) {
555		snd_pcm_uframes_t avail;
556		snd_pcm_avail_update(pcm);
557		if (pcm->stream == SND_PCM_STREAM_PLAYBACK) {
558			events |= POLLOUT;
559			events &= ~POLLIN;
560			avail = snd_pcm_mmap_playback_avail(pcm);
561		} else {
562			avail = snd_pcm_mmap_capture_avail(pcm);
563		}
564		empty = avail < pcm->avail_min;
565	}
566	switch (snd_pcm_state(dmix->spcm)) {
567	case SND_PCM_STATE_XRUN:
568	case SND_PCM_STATE_SUSPENDED:
569	case SND_PCM_STATE_SETUP:
570		events |= POLLERR;
571		break;
572	default:
573		if (empty) {
574			snd_pcm_direct_clear_timer_queue(dmix);
575			events &= ~(POLLOUT|POLLIN);
576			/* additional check */
577			switch (snd_pcm_state(pcm)) {
578			case SND_PCM_STATE_XRUN:
579			case SND_PCM_STATE_SUSPENDED:
580			case SND_PCM_STATE_SETUP:
581				events |= POLLERR;
582				break;
583			default:
584				break;
585			}
586		}
587		break;
588	}
589	*revents = events;
590	return 0;
591}
592
593int snd_pcm_direct_info(snd_pcm_t *pcm, snd_pcm_info_t * info)
594{
595	snd_pcm_direct_t *dmix = pcm->private_data;
596
597	if (dmix->spcm && !dmix->shmptr->use_server)
598		return snd_pcm_info(dmix->spcm, info);
599
600	memset(info, 0, sizeof(*info));
601	info->stream = pcm->stream;
602	info->card = -1;
603	/* FIXME: fill this with something more useful: we know the hardware name */
604	if (pcm->name) {
605		strncpy((char *)info->id, pcm->name, sizeof(info->id));
606		strncpy((char *)info->name, pcm->name, sizeof(info->name));
607		strncpy((char *)info->subname, pcm->name, sizeof(info->subname));
608	}
609	info->subdevices_count = 1;
610	return 0;
611}
612
613static inline snd_mask_t *hw_param_mask(snd_pcm_hw_params_t *params,
614					snd_pcm_hw_param_t var)
615{
616	return &params->masks[var - SND_PCM_HW_PARAM_FIRST_MASK];
617}
618
619static inline snd_interval_t *hw_param_interval(snd_pcm_hw_params_t *params,
620						snd_pcm_hw_param_t var)
621{
622	return &params->intervals[var - SND_PCM_HW_PARAM_FIRST_INTERVAL];
623}
624
625static int hw_param_interval_refine_one(snd_pcm_hw_params_t *params,
626					snd_pcm_hw_param_t var,
627					snd_interval_t *src)
628{
629	snd_interval_t *i;
630
631	if (!(params->rmask & (1<<var)))	/* nothing to do? */
632		return 0;
633	i = hw_param_interval(params, var);
634	if (snd_interval_empty(i)) {
635		SNDERR("dshare interval %i empty?", (int)var);
636		return -EINVAL;
637	}
638	if (snd_interval_refine(i, src))
639		params->cmask |= 1<<var;
640	return 0;
641}
642
643static int hw_param_interval_refine_minmax(snd_pcm_hw_params_t *params,
644					   snd_pcm_hw_param_t var,
645					   unsigned int imin,
646					   unsigned int imax)
647{
648	snd_interval_t t;
649
650	memset(&t, 0, sizeof(t));
651	snd_interval_set_minmax(&t, imin, imax);
652	t.integer = 1;
653	return hw_param_interval_refine_one(params, var, &t);
654}
655
656#undef REFINE_DEBUG
657
658int snd_pcm_direct_hw_refine(snd_pcm_t *pcm, snd_pcm_hw_params_t *params)
659{
660	snd_pcm_direct_t *dshare = pcm->private_data;
661	static const snd_mask_t access = { .bits = {
662					(1<<SNDRV_PCM_ACCESS_MMAP_INTERLEAVED) |
663					(1<<SNDRV_PCM_ACCESS_MMAP_NONINTERLEAVED) |
664					(1<<SNDRV_PCM_ACCESS_RW_INTERLEAVED) |
665					(1<<SNDRV_PCM_ACCESS_RW_NONINTERLEAVED),
666					0, 0, 0 } };
667	int err;
668
669#ifdef REFINE_DEBUG
670	snd_output_t *log;
671	snd_output_stdio_attach(&log, stderr, 0);
672	snd_output_puts(log, "DMIX REFINE (begin):\n");
673	snd_pcm_hw_params_dump(params, log);
674#endif
675	if (params->rmask & (1<<SND_PCM_HW_PARAM_ACCESS)) {
676		if (snd_mask_empty(hw_param_mask(params, SND_PCM_HW_PARAM_ACCESS))) {
677			SNDERR("dshare access mask empty?");
678			return -EINVAL;
679		}
680		if (snd_mask_refine(hw_param_mask(params, SND_PCM_HW_PARAM_ACCESS), &access))
681			params->cmask |= 1<<SND_PCM_HW_PARAM_ACCESS;
682	}
683	if (params->rmask & (1<<SND_PCM_HW_PARAM_FORMAT)) {
684		if (snd_mask_empty(hw_param_mask(params, SND_PCM_HW_PARAM_FORMAT))) {
685			SNDERR("dshare format mask empty?");
686			return -EINVAL;
687		}
688		if (snd_mask_refine_set(hw_param_mask(params, SND_PCM_HW_PARAM_FORMAT),
689					dshare->shmptr->hw.format))
690			params->cmask |= 1<<SND_PCM_HW_PARAM_FORMAT;
691	}
692	//snd_mask_none(hw_param_mask(params, SND_PCM_HW_PARAM_SUBFORMAT));
693	if (params->rmask & (1<<SND_PCM_HW_PARAM_CHANNELS)) {
694		if (snd_interval_empty(hw_param_interval(params, SND_PCM_HW_PARAM_CHANNELS))) {
695			SNDERR("dshare channels mask empty?");
696			return -EINVAL;
697		}
698		err = snd_interval_refine_set(hw_param_interval(params, SND_PCM_HW_PARAM_CHANNELS), dshare->channels);
699		if (err < 0)
700			return err;
701	}
702	err = hw_param_interval_refine_one(params, SND_PCM_HW_PARAM_RATE,
703					   &dshare->shmptr->hw.rate);
704	if (err < 0)
705		return err;
706	err = hw_param_interval_refine_one(params, SND_PCM_HW_PARAM_PERIOD_SIZE,
707					   &dshare->shmptr->hw.period_size);
708	if (err < 0)
709		return err;
710	err = hw_param_interval_refine_one(params, SND_PCM_HW_PARAM_PERIOD_TIME,
711					   &dshare->shmptr->hw.period_time);
712	if (err < 0)
713		return err;
714	if (dshare->max_periods < 0) {
715		err = hw_param_interval_refine_one(params, SND_PCM_HW_PARAM_BUFFER_SIZE,
716						   &dshare->shmptr->hw.buffer_size);
717		if (err < 0)
718			return err;
719		err = hw_param_interval_refine_one(params, SND_PCM_HW_PARAM_BUFFER_TIME,
720						   &dshare->shmptr->hw.buffer_time);
721		if (err < 0)
722			return err;
723	} else if (params->rmask & ((1<<SND_PCM_HW_PARAM_PERIODS)|
724				    (1<<SND_PCM_HW_PARAM_BUFFER_BYTES)|
725				    (1<<SND_PCM_HW_PARAM_BUFFER_SIZE)|
726				    (1<<SND_PCM_HW_PARAM_BUFFER_TIME))) {
727		int changed;
728		unsigned int max_periods = dshare->max_periods;
729		if (max_periods < 2)
730			max_periods = dshare->slave_buffer_size / dshare->slave_period_size;
731		do {
732			changed = 0;
733			err = hw_param_interval_refine_minmax(params, SND_PCM_HW_PARAM_PERIODS,
734							      2, max_periods);
735			if (err < 0)
736				return err;
737			changed |= err;
738			err = snd_pcm_hw_refine_soft(pcm, params);
739			if (err < 0)
740				return err;
741			changed |= err;
742		} while (changed);
743	}
744	params->info = dshare->shmptr->s.info;
745#ifdef REFINE_DEBUG
746	snd_output_puts(log, "DMIX REFINE (end):\n");
747	snd_pcm_hw_params_dump(params, log);
748	snd_output_close(log);
749#endif
750	return 0;
751}
752
753int snd_pcm_direct_hw_params(snd_pcm_t *pcm, snd_pcm_hw_params_t * params)
754{
755	snd_pcm_direct_t *dmix = pcm->private_data;
756
757	params->info = dmix->shmptr->s.info;
758	params->rate_num = dmix->shmptr->s.rate;
759	params->rate_den = 1;
760	params->fifo_size = 0;
761	params->msbits = dmix->shmptr->s.msbits;
762	return 0;
763}
764
765int snd_pcm_direct_hw_free(snd_pcm_t *pcm ATTRIBUTE_UNUSED)
766{
767	/* values are cached in the pcm structure */
768	return 0;
769}
770
771int snd_pcm_direct_sw_params(snd_pcm_t *pcm ATTRIBUTE_UNUSED, snd_pcm_sw_params_t * params ATTRIBUTE_UNUSED)
772{
773	/* values are cached in the pcm structure */
774	return 0;
775}
776
777int snd_pcm_direct_channel_info(snd_pcm_t *pcm, snd_pcm_channel_info_t * info)
778{
779        return snd_pcm_channel_info_shm(pcm, info, -1);
780}
781
782int snd_pcm_direct_mmap(snd_pcm_t *pcm ATTRIBUTE_UNUSED)
783{
784	return 0;
785}
786
787int snd_pcm_direct_munmap(snd_pcm_t *pcm ATTRIBUTE_UNUSED)
788{
789	return 0;
790}
791
792int snd_pcm_direct_resume(snd_pcm_t *pcm)
793{
794	snd_pcm_direct_t *dmix = pcm->private_data;
795	int err;
796
797	snd_pcm_direct_semaphore_down(dmix, DIRECT_IPC_SEM_CLIENT);
798	err = snd_pcm_resume(dmix->spcm);
799	if (err == -ENOSYS) {
800		/* FIXME: error handling? */
801		snd_pcm_prepare(dmix->spcm);
802		snd_pcm_start(dmix->spcm);
803		err = 0;
804	}
805	snd_pcm_direct_semaphore_up(dmix, DIRECT_IPC_SEM_CLIENT);
806	return err;
807}
808
809#define COPY_SLAVE(field) (dmix->shmptr->s.field = spcm->field)
810
811/* copy the slave setting */
812static void save_slave_setting(snd_pcm_direct_t *dmix, snd_pcm_t *spcm)
813{
814	spcm->info &= ~SND_PCM_INFO_PAUSE;
815
816	COPY_SLAVE(access);
817	COPY_SLAVE(format);
818	COPY_SLAVE(subformat);
819	COPY_SLAVE(channels);
820	COPY_SLAVE(rate);
821	COPY_SLAVE(period_size);
822	COPY_SLAVE(period_time);
823	COPY_SLAVE(periods);
824	COPY_SLAVE(tstamp_mode);
825	COPY_SLAVE(period_step);
826	COPY_SLAVE(avail_min);
827	COPY_SLAVE(start_threshold);
828	COPY_SLAVE(stop_threshold);
829	COPY_SLAVE(silence_threshold);
830	COPY_SLAVE(silence_size);
831	COPY_SLAVE(boundary);
832	COPY_SLAVE(info);
833	COPY_SLAVE(msbits);
834	COPY_SLAVE(rate_num);
835	COPY_SLAVE(rate_den);
836	COPY_SLAVE(hw_flags);
837	COPY_SLAVE(fifo_size);
838	COPY_SLAVE(buffer_size);
839	COPY_SLAVE(buffer_time);
840	COPY_SLAVE(sample_bits);
841	COPY_SLAVE(frame_bits);
842}
843
844#undef COPY_SLAVE
845
846/*
847 * this function initializes hardware and starts playback operation with
848 * no stop threshold (it operates all time without xrun checking)
849 * also, the driver silences the unused ring buffer areas for us
850 */
851int snd_pcm_direct_initialize_slave(snd_pcm_direct_t *dmix, snd_pcm_t *spcm, struct slave_params *params)
852{
853	snd_pcm_hw_params_t *hw_params;
854	snd_pcm_sw_params_t *sw_params;
855	int ret, buffer_is_not_initialized;
856	snd_pcm_uframes_t boundary;
857	struct pollfd fd;
858	int loops = 10;
859
860	snd_pcm_hw_params_alloca(&hw_params);
861	snd_pcm_sw_params_alloca(&sw_params);
862
863      __again:
864      	if (loops-- <= 0) {
865      		SNDERR("unable to find a valid configuration for slave");
866      		return -EINVAL;
867      	}
868	ret = snd_pcm_hw_params_any(spcm, hw_params);
869	if (ret < 0) {
870		SNDERR("snd_pcm_hw_params_any failed");
871		return ret;
872	}
873	ret = snd_pcm_hw_params_set_access(spcm, hw_params, SND_PCM_ACCESS_MMAP_INTERLEAVED);
874	if (ret < 0) {
875		ret = snd_pcm_hw_params_set_access(spcm, hw_params, SND_PCM_ACCESS_MMAP_NONINTERLEAVED);
876		if (ret < 0) {
877			SNDERR("slave plugin does not support mmap interleaved or mmap noninterleaved access");
878			return ret;
879		}
880	}
881	if (params->format == SND_PCM_FORMAT_UNKNOWN)
882		ret = -EINVAL;
883	else
884		ret = snd_pcm_hw_params_set_format(spcm, hw_params,
885						   params->format);
886	if (ret < 0) {
887		static const snd_pcm_format_t dmix_formats[] = {
888			SND_PCM_FORMAT_S32,
889			SND_PCM_FORMAT_S32 ^ SND_PCM_FORMAT_S32_LE ^ SND_PCM_FORMAT_S32_BE,
890			SND_PCM_FORMAT_S16,
891			SND_PCM_FORMAT_S16 ^ SND_PCM_FORMAT_S16_LE ^ SND_PCM_FORMAT_S16_BE,
892			SND_PCM_FORMAT_S24_LE,
893			SND_PCM_FORMAT_S24_3LE,
894			SND_PCM_FORMAT_U8,
895		};
896		snd_pcm_format_t format;
897		unsigned int i;
898
899		for (i = 0; i < sizeof dmix_formats / sizeof dmix_formats[0]; ++i) {
900			format = dmix_formats[i];
901			ret = snd_pcm_hw_params_set_format(spcm, hw_params, format);
902			if (ret >= 0)
903				break;
904		}
905		if (ret < 0 && dmix->type != SND_PCM_TYPE_DMIX) {
906			/* TODO: try to choose a good format */
907			ret = INTERNAL(snd_pcm_hw_params_set_format_first)(spcm, hw_params, &format);
908		}
909		if (ret < 0) {
910			SNDERR("requested or auto-format is not available");
911			return ret;
912		}
913		params->format = format;
914	}
915	ret = INTERNAL(snd_pcm_hw_params_set_channels_near)(spcm, hw_params, (unsigned int *)&params->channels);
916	if (ret < 0) {
917		SNDERR("requested count of channels is not available");
918		return ret;
919	}
920	ret = INTERNAL(snd_pcm_hw_params_set_rate_near)(spcm, hw_params, (unsigned int *)&params->rate, 0);
921	if (ret < 0) {
922		SNDERR("requested rate is not available");
923		return ret;
924	}
925
926	buffer_is_not_initialized = 0;
927	if (params->buffer_time > 0) {
928		ret = INTERNAL(snd_pcm_hw_params_set_buffer_time_near)(spcm, hw_params, (unsigned int *)&params->buffer_time, 0);
929		if (ret < 0) {
930			SNDERR("unable to set buffer time");
931			return ret;
932		}
933	} else if (params->buffer_size > 0) {
934		ret = INTERNAL(snd_pcm_hw_params_set_buffer_size_near)(spcm, hw_params, (snd_pcm_uframes_t *)&params->buffer_size);
935		if (ret < 0) {
936			SNDERR("unable to set buffer size");
937			return ret;
938		}
939	} else {
940		buffer_is_not_initialized = 1;
941	}
942
943	if (params->period_time > 0) {
944		ret = INTERNAL(snd_pcm_hw_params_set_period_time_near)(spcm, hw_params, (unsigned int *)&params->period_time, 0);
945		if (ret < 0) {
946			SNDERR("unable to set period_time");
947			return ret;
948		}
949	} else if (params->period_size > 0) {
950		ret = INTERNAL(snd_pcm_hw_params_set_period_size_near)(spcm, hw_params, (snd_pcm_uframes_t *)&params->period_size, 0);
951		if (ret < 0) {
952			SNDERR("unable to set period_size");
953			return ret;
954		}
955	}
956
957	if (buffer_is_not_initialized && params->periods > 0) {
958		unsigned int periods = params->periods;
959		ret = INTERNAL(snd_pcm_hw_params_set_periods_near)(spcm, hw_params, &params->periods, 0);
960		if (ret < 0) {
961			SNDERR("unable to set requested periods");
962			return ret;
963		}
964		if (params->periods == 1) {
965			params->periods = periods;
966			if (params->period_time > 0) {
967				params->period_time /= 2;
968				goto __again;
969			} else if (params->period_size > 0) {
970				params->period_size /= 2;
971				goto __again;
972			}
973			SNDERR("unable to use stream with periods == 1");
974			return ret;
975		}
976	}
977
978	ret = snd_pcm_hw_params(spcm, hw_params);
979	if (ret < 0) {
980		SNDERR("unable to install hw params");
981		return ret;
982	}
983
984	/* store some hw_params values to shared info */
985	dmix->shmptr->hw.format = snd_mask_value(hw_param_mask(hw_params, SND_PCM_HW_PARAM_FORMAT));
986	dmix->shmptr->hw.rate = *hw_param_interval(hw_params, SND_PCM_HW_PARAM_RATE);
987	dmix->shmptr->hw.buffer_size = *hw_param_interval(hw_params, SND_PCM_HW_PARAM_BUFFER_SIZE);
988	dmix->shmptr->hw.buffer_time = *hw_param_interval(hw_params, SND_PCM_HW_PARAM_BUFFER_TIME);
989	dmix->shmptr->hw.period_size = *hw_param_interval(hw_params, SND_PCM_HW_PARAM_PERIOD_SIZE);
990	dmix->shmptr->hw.period_time = *hw_param_interval(hw_params, SND_PCM_HW_PARAM_PERIOD_TIME);
991	dmix->shmptr->hw.periods = *hw_param_interval(hw_params, SND_PCM_HW_PARAM_PERIODS);
992
993
994	ret = snd_pcm_sw_params_current(spcm, sw_params);
995	if (ret < 0) {
996		SNDERR("unable to get current sw_params");
997		return ret;
998	}
999
1000	ret = snd_pcm_sw_params_get_boundary(sw_params, &boundary);
1001	if (ret < 0) {
1002		SNDERR("unable to get boundary");
1003		return ret;
1004	}
1005	ret = snd_pcm_sw_params_set_stop_threshold(spcm, sw_params, boundary);
1006	if (ret < 0) {
1007		SNDERR("unable to set stop threshold");
1008		return ret;
1009	}
1010
1011	/* set timestamp mode to MMAP
1012	 * the slave timestamp is copied appropriately in dsnoop/dmix/dshare
1013	 * based on the tstamp_mode of each client
1014	 */
1015	ret = snd_pcm_sw_params_set_tstamp_mode(spcm, sw_params,
1016						SND_PCM_TSTAMP_ENABLE);
1017	if (ret < 0) {
1018		SNDERR("unable to tstamp mode MMAP");
1019		return ret;
1020	}
1021
1022	if (dmix->type != SND_PCM_TYPE_DMIX)
1023		goto __skip_silencing;
1024
1025	ret = snd_pcm_sw_params_set_silence_threshold(spcm, sw_params, 0);
1026	if (ret < 0) {
1027		SNDERR("unable to set silence threshold");
1028		return ret;
1029	}
1030	ret = snd_pcm_sw_params_set_silence_size(spcm, sw_params, boundary);
1031	if (ret < 0) {
1032		SNDERR("unable to set silence threshold (please upgrade to 0.9.0rc8+ driver)");
1033		return ret;
1034	}
1035
1036      __skip_silencing:
1037
1038	ret = snd_pcm_sw_params(spcm, sw_params);
1039	if (ret < 0) {
1040		SNDERR("unable to install sw params (please upgrade to 0.9.0rc8+ driver)");
1041		return ret;
1042	}
1043
1044	if (dmix->type == SND_PCM_TYPE_DSHARE) {
1045		const snd_pcm_channel_area_t *dst_areas;
1046		dst_areas = snd_pcm_mmap_areas(spcm);
1047		snd_pcm_areas_silence(dst_areas, 0, spcm->channels, spcm->buffer_size, spcm->format);
1048	}
1049
1050	ret = snd_pcm_start(spcm);
1051	if (ret < 0) {
1052		SNDERR("unable to start PCM stream");
1053		return ret;
1054	}
1055
1056	if (snd_pcm_poll_descriptors_count(spcm) != 1) {
1057		SNDERR("unable to use hardware pcm with fd more than one!!!");
1058		return ret;
1059	}
1060	snd_pcm_poll_descriptors(spcm, &fd, 1);
1061	dmix->hw_fd = fd.fd;
1062
1063	save_slave_setting(dmix, spcm);
1064
1065	/* Currently, we assume that each dmix client has the same
1066	 * hw_params setting.
1067	 * If the arbitrary hw_parmas is supported in future,
1068	 * boundary has to be taken from the slave config but
1069	 * recalculated for the native boundary size (for 32bit
1070	 * emulation on 64bit arch).
1071	 */
1072	dmix->slave_buffer_size = spcm->buffer_size;
1073	dmix->slave_period_size = spcm->period_size;
1074	dmix->slave_boundary = spcm->boundary;
1075
1076	spcm->donot_close = 1;
1077
1078	{
1079		int ver = 0;
1080		ioctl(spcm->poll_fd, SNDRV_PCM_IOCTL_PVERSION, &ver);
1081		if (ver < SNDRV_PROTOCOL_VERSION(2, 0, 8))
1082			dmix->shmptr->use_server = 1;
1083	}
1084
1085	return 0;
1086}
1087
1088/*
1089 * the trick is used here; we cannot use effectively the hardware handle because
1090 * we cannot drive multiple accesses to appl_ptr; so we use slave timer of given
1091 * PCM hardware handle; it's not this easy and cheap?
1092 */
1093int snd_pcm_direct_initialize_poll_fd(snd_pcm_direct_t *dmix)
1094{
1095	int ret;
1096	snd_pcm_info_t *info;
1097	char name[128];
1098	int capture = dmix->type == SND_PCM_TYPE_DSNOOP ? 1 : 0;
1099
1100	dmix->tread = 1;
1101	dmix->timer_need_poll = 0;
1102	snd_pcm_info_alloca(&info);
1103	ret = snd_pcm_info(dmix->spcm, info);
1104	if (ret < 0) {
1105		SNDERR("unable to info for slave pcm");
1106		return ret;
1107	}
1108	sprintf(name, "hw:CLASS=%i,SCLASS=0,CARD=%i,DEV=%i,SUBDEV=%i",
1109				(int)SND_TIMER_CLASS_PCM,
1110				snd_pcm_info_get_card(info),
1111				snd_pcm_info_get_device(info),
1112				snd_pcm_info_get_subdevice(info) * 2 + capture);
1113	ret = snd_timer_open(&dmix->timer, name, SND_TIMER_OPEN_NONBLOCK | SND_TIMER_OPEN_TREAD);
1114	if (ret < 0) {
1115		dmix->tread = 0;
1116		ret = snd_timer_open(&dmix->timer, name, SND_TIMER_OPEN_NONBLOCK);
1117		if (ret < 0) {
1118			SNDERR("unable to open timer '%s'", name);
1119			return ret;
1120		}
1121	}
1122
1123	if (snd_timer_poll_descriptors_count(dmix->timer) != 1) {
1124		SNDERR("unable to use timer '%s' with more than one fd!", name);
1125		return ret;
1126	}
1127	snd_timer_poll_descriptors(dmix->timer, &dmix->timer_fd, 1);
1128	dmix->poll_fd = dmix->timer_fd.fd;
1129
1130	dmix->timer_events = (1<<SND_TIMER_EVENT_MSUSPEND) |
1131			     (1<<SND_TIMER_EVENT_MRESUME) |
1132			     (1<<SND_TIMER_EVENT_STOP);
1133
1134	/*
1135	 * Some hacks for older kernel drivers
1136	 */
1137	{
1138		int ver = 0;
1139		ioctl(dmix->poll_fd, SNDRV_TIMER_IOCTL_PVERSION, &ver);
1140		/* In older versions, check via poll before read() is needed
1141		 * because of the confliction between TIMER_START and
1142		 * FIONBIO ioctls.
1143		 */
1144		if (ver < SNDRV_PROTOCOL_VERSION(2, 0, 4))
1145			dmix->timer_need_poll = 1;
1146		/*
1147		 * In older versions, timer uses pause events instead
1148		 * suspend/resume events.
1149		 */
1150		if (ver < SNDRV_PROTOCOL_VERSION(2, 0, 5)) {
1151			dmix->timer_events &= ~((1<<SND_TIMER_EVENT_MSUSPEND) |
1152						(1<<SND_TIMER_EVENT_MRESUME));
1153			dmix->timer_events |= (1<<SND_TIMER_EVENT_MPAUSE) |
1154					      (1<<SND_TIMER_EVENT_MCONTINUE);
1155		}
1156		/* In older versions, use SND_TIMER_EVENT_START too.
1157		 */
1158		if (ver < SNDRV_PROTOCOL_VERSION(2, 0, 6))
1159			dmix->timer_events |= 1<<SND_TIMER_EVENT_START;
1160	}
1161	return 0;
1162}
1163
1164static snd_pcm_uframes_t recalc_boundary_size(unsigned long long bsize, snd_pcm_uframes_t buffer_size)
1165{
1166	if (bsize > LONG_MAX) {
1167		bsize = buffer_size;
1168		while (bsize * 2 <= LONG_MAX - buffer_size)
1169			bsize *= 2;
1170	}
1171	return (snd_pcm_uframes_t)bsize;
1172}
1173
1174#define COPY_SLAVE(field) (spcm->field = dmix->shmptr->s.field)
1175
1176/* copy the slave setting */
1177static void copy_slave_setting(snd_pcm_direct_t *dmix, snd_pcm_t *spcm)
1178{
1179	COPY_SLAVE(access);
1180	COPY_SLAVE(format);
1181	COPY_SLAVE(subformat);
1182	COPY_SLAVE(channels);
1183	COPY_SLAVE(rate);
1184	COPY_SLAVE(period_size);
1185	COPY_SLAVE(period_time);
1186	COPY_SLAVE(periods);
1187	COPY_SLAVE(tstamp_mode);
1188	COPY_SLAVE(period_step);
1189	COPY_SLAVE(avail_min);
1190	COPY_SLAVE(start_threshold);
1191	COPY_SLAVE(stop_threshold);
1192	COPY_SLAVE(silence_threshold);
1193	COPY_SLAVE(silence_size);
1194	COPY_SLAVE(boundary);
1195	COPY_SLAVE(info);
1196	COPY_SLAVE(msbits);
1197	COPY_SLAVE(rate_num);
1198	COPY_SLAVE(rate_den);
1199	COPY_SLAVE(hw_flags);
1200	COPY_SLAVE(fifo_size);
1201	COPY_SLAVE(buffer_size);
1202	COPY_SLAVE(buffer_time);
1203	COPY_SLAVE(sample_bits);
1204	COPY_SLAVE(frame_bits);
1205
1206	spcm->info &= ~SND_PCM_INFO_PAUSE;
1207	spcm->boundary = recalc_boundary_size(dmix->shmptr->s.boundary, spcm->buffer_size);
1208}
1209
1210#undef COPY_SLAVE
1211
1212
1213/*
1214 * open a slave PCM as secondary client (dup'ed fd)
1215 */
1216int snd_pcm_direct_open_secondary_client(snd_pcm_t **spcmp, snd_pcm_direct_t *dmix, const char *client_name)
1217{
1218	int ret;
1219	snd_pcm_t *spcm;
1220
1221	ret = snd_pcm_hw_open_fd(spcmp, client_name, dmix->hw_fd, 0, 0);
1222	if (ret < 0) {
1223		SNDERR("unable to open hardware");
1224		return ret;
1225	}
1226
1227	spcm = *spcmp;
1228	spcm->donot_close = 1;
1229	spcm->setup = 1;
1230
1231	copy_slave_setting(dmix, spcm);
1232
1233	/* Use the slave setting as SPCM, so far */
1234	dmix->slave_buffer_size = spcm->buffer_size;
1235	dmix->slave_period_size = dmix->shmptr->s.period_size;
1236	dmix->slave_boundary = spcm->boundary;
1237
1238	ret = snd_pcm_mmap(spcm);
1239	if (ret < 0) {
1240		SNDERR("unable to mmap channels");
1241		return ret;
1242	}
1243	return 0;
1244}
1245
1246/*
1247 * open a slave PCM as secondary client (dup'ed fd)
1248 */
1249int snd_pcm_direct_initialize_secondary_slave(snd_pcm_direct_t *dmix,
1250					      snd_pcm_t *spcm,
1251					      struct slave_params *params ATTRIBUTE_UNUSED)
1252{
1253	int ret;
1254
1255	spcm->donot_close = 1;
1256	spcm->setup = 1;
1257
1258	copy_slave_setting(dmix, spcm);
1259
1260	/* Use the slave setting as SPCM, so far */
1261	dmix->slave_buffer_size = spcm->buffer_size;
1262	dmix->slave_period_size = dmix->shmptr->s.period_size;
1263	dmix->slave_boundary = spcm->boundary;
1264
1265	ret = snd_pcm_mmap(spcm);
1266	if (ret < 0) {
1267		SNDERR("unable to mmap channels");
1268		return ret;
1269	}
1270	return 0;
1271}
1272
1273int snd_pcm_direct_set_timer_params(snd_pcm_direct_t *dmix)
1274{
1275	snd_timer_params_t *params;
1276	unsigned int filter;
1277	int ret;
1278
1279	snd_timer_params_alloca(&params);
1280	snd_timer_params_set_auto_start(params, 1);
1281	if (dmix->type != SND_PCM_TYPE_DSNOOP)
1282		snd_timer_params_set_early_event(params, 1);
1283	snd_timer_params_set_ticks(params, 1);
1284	if (dmix->tread) {
1285		filter = (1<<SND_TIMER_EVENT_TICK) |
1286			 dmix->timer_events;
1287		snd_timer_params_set_filter(params, filter);
1288	}
1289	ret = snd_timer_params(dmix->timer, params);
1290	if (ret < 0) {
1291		SNDERR("unable to set timer parameters");
1292                return ret;
1293	}
1294	return 0;
1295}
1296
1297/*
1298 *  ring buffer operation
1299 */
1300int snd_pcm_direct_check_interleave(snd_pcm_direct_t *dmix, snd_pcm_t *pcm)
1301{
1302	unsigned int chn, channels;
1303	int bits, interleaved = 1;
1304	const snd_pcm_channel_area_t *dst_areas;
1305	const snd_pcm_channel_area_t *src_areas;
1306
1307	bits = snd_pcm_format_physical_width(pcm->format);
1308	if ((bits % 8) != 0)
1309		interleaved = 0;
1310	channels = dmix->channels;
1311	dst_areas = snd_pcm_mmap_areas(dmix->spcm);
1312	src_areas = snd_pcm_mmap_areas(pcm);
1313	for (chn = 1; chn < channels; chn++) {
1314		if (dst_areas[chn-1].addr != dst_areas[chn].addr) {
1315			interleaved = 0;
1316			break;
1317		}
1318		if (src_areas[chn-1].addr != src_areas[chn].addr) {
1319			interleaved = 0;
1320			break;
1321		}
1322	}
1323	for (chn = 0; chn < channels; chn++) {
1324		if (dmix->bindings && dmix->bindings[chn] != chn) {
1325			interleaved = 0;
1326			break;
1327		}
1328		if (dst_areas[chn].first != chn * bits ||
1329		    dst_areas[chn].step != channels * bits) {
1330			interleaved = 0;
1331			break;
1332		}
1333		if (src_areas[chn].first != chn * bits ||
1334		    src_areas[chn].step != channels * bits) {
1335			interleaved = 0;
1336			break;
1337		}
1338	}
1339	return dmix->interleaved = interleaved;
1340}
1341
1342/*
1343 * parse the channel map
1344 * id == client channel
1345 * value == slave's channel
1346 */
1347int snd_pcm_direct_parse_bindings(snd_pcm_direct_t *dmix,
1348				  struct slave_params *params,
1349				  snd_config_t *cfg)
1350{
1351	snd_config_iterator_t i, next;
1352	unsigned int chn, chn1, count = 0;
1353	unsigned int *bindings;
1354	int err;
1355
1356	dmix->channels = UINT_MAX;
1357	if (cfg == NULL)
1358		return 0;
1359	if (snd_config_get_type(cfg) != SND_CONFIG_TYPE_COMPOUND) {
1360		SNDERR("invalid type for bindings");
1361		return -EINVAL;
1362	}
1363	snd_config_for_each(i, next, cfg) {
1364		snd_config_t *n = snd_config_iterator_entry(i);
1365		const char *id;
1366		long cchannel;
1367		if (snd_config_get_id(n, &id) < 0)
1368			continue;
1369		err = safe_strtol(id, &cchannel);
1370		if (err < 0 || cchannel < 0) {
1371			SNDERR("invalid client channel in binding: %s\n", id);
1372			return -EINVAL;
1373		}
1374		if ((unsigned)cchannel >= count)
1375			count = cchannel + 1;
1376	}
1377	if (count == 0)
1378		return 0;
1379	if (count > 1024) {
1380		SNDERR("client channel out of range");
1381		return -EINVAL;
1382	}
1383	bindings = malloc(count * sizeof(unsigned int));
1384	if (bindings == NULL)
1385		return -ENOMEM;
1386	for (chn = 0; chn < count; chn++)
1387		bindings[chn] = UINT_MAX;		/* don't route */
1388	snd_config_for_each(i, next, cfg) {
1389		snd_config_t *n = snd_config_iterator_entry(i);
1390		const char *id;
1391		long cchannel, schannel;
1392		if (snd_config_get_id(n, &id) < 0)
1393			continue;
1394		safe_strtol(id, &cchannel);
1395		if (snd_config_get_integer(n, &schannel) < 0) {
1396			SNDERR("unable to get slave channel (should be integer type) in binding: %s\n", id);
1397			free(bindings);
1398			return -EINVAL;
1399		}
1400		if (schannel < 0 || schannel >= params->channels) {
1401			SNDERR("invalid slave channel number %ld in binding to %ld",
1402			       schannel, cchannel);
1403			free(bindings);
1404			return -EINVAL;
1405		}
1406		bindings[cchannel] = schannel;
1407	}
1408	if (dmix->type == SND_PCM_TYPE_DSNOOP ||
1409	    ! dmix->bindings)
1410		goto __skip_same_dst;
1411	for (chn = 0; chn < count; chn++) {
1412		for (chn1 = 0; chn1 < count; chn1++) {
1413			if (chn == chn1)
1414				continue;
1415			if (bindings[chn] == dmix->bindings[chn1]) {
1416				SNDERR("unable to route channels %d,%d to same destination %d", chn, chn1, bindings[chn]);
1417				free(bindings);
1418				return -EINVAL;
1419			}
1420		}
1421	}
1422      __skip_same_dst:
1423	dmix->bindings = bindings;
1424	dmix->channels = count;
1425	return 0;
1426}
1427
1428/*
1429 * parse slave config and calculate the ipc_key offset
1430 */
1431
1432static int _snd_pcm_direct_get_slave_ipc_offset(snd_config_t *root,
1433						snd_config_t *sconf,
1434						int direction,
1435						int hop)
1436{
1437	snd_config_iterator_t i, next;
1438	snd_config_t *pcm_conf;
1439	int err;
1440	long card = 0, device = 0, subdevice = 0;
1441	const char *str;
1442
1443	if (snd_config_get_string(sconf, &str) >= 0) {
1444		if (hop > SND_CONF_MAX_HOPS) {
1445			SNDERR("Too many definition levels (looped?)");
1446			return -EINVAL;
1447		}
1448		err = snd_config_search_definition(root, "pcm", str, &pcm_conf);
1449		if (err < 0) {
1450			SNDERR("Unknown slave PCM %s", str);
1451			return err;
1452		}
1453		err = _snd_pcm_direct_get_slave_ipc_offset(root, pcm_conf,
1454							   direction,
1455							   hop + 1);
1456		snd_config_delete(pcm_conf);
1457		return err;
1458	}
1459
1460#if 0	/* for debug purposes */
1461	{
1462		snd_output_t *out;
1463		snd_output_stdio_attach(&out, stderr, 0);
1464		snd_config_save(sconf, out);
1465		snd_output_close(out);
1466	}
1467#endif
1468
1469	if (snd_config_search(sconf, "slave", &pcm_conf) >= 0 &&
1470	    (snd_config_search(pcm_conf, "pcm", &pcm_conf) >= 0 ||
1471	    (snd_config_get_string(pcm_conf, &str) >= 0 &&
1472	    snd_config_search_definition(root, "pcm_slave", str, &pcm_conf) >= 0 &&
1473	    snd_config_search(pcm_conf, "pcm", &pcm_conf) >= 0)))
1474		return _snd_pcm_direct_get_slave_ipc_offset(root, pcm_conf,
1475							    direction,
1476							    hop + 1);
1477
1478	snd_config_for_each(i, next, sconf) {
1479		snd_config_t *n = snd_config_iterator_entry(i);
1480		const char *id, *str;
1481		if (snd_config_get_id(n, &id) < 0)
1482			continue;
1483		if (strcmp(id, "type") == 0) {
1484			err = snd_config_get_string(n, &str);
1485			if (err < 0) {
1486				SNDERR("Invalid value for PCM type definition\n");
1487				return -EINVAL;
1488			}
1489			if (strcmp(str, "hw")) {
1490				SNDERR("Invalid type '%s' for slave PCM\n", str);
1491				return -EINVAL;
1492			}
1493			continue;
1494		}
1495		if (strcmp(id, "card") == 0) {
1496			err = snd_config_get_integer(n, &card);
1497			if (err < 0) {
1498				err = snd_config_get_string(n, &str);
1499				if (err < 0) {
1500					SNDERR("Invalid type for %s", id);
1501					return -EINVAL;
1502				}
1503				card = snd_card_get_index(str);
1504				if (card < 0) {
1505					SNDERR("Invalid value for %s", id);
1506					return card;
1507				}
1508			}
1509			continue;
1510		}
1511		if (strcmp(id, "device") == 0) {
1512			err = snd_config_get_integer(n, &device);
1513			if (err < 0) {
1514				SNDERR("Invalid type for %s", id);
1515				return err;
1516			}
1517			continue;
1518		}
1519		if (strcmp(id, "subdevice") == 0) {
1520			err = snd_config_get_integer(n, &subdevice);
1521			if (err < 0) {
1522				SNDERR("Invalid type for %s", id);
1523				return err;
1524			}
1525			continue;
1526		}
1527	}
1528	if (card < 0)
1529		card = 0;
1530	if (device < 0)
1531		device = 0;
1532	if (subdevice < 0)
1533		subdevice = 0;
1534	return (direction << 1) + (device << 2) + (subdevice << 8) + (card << 12);
1535}
1536
1537static int snd_pcm_direct_get_slave_ipc_offset(snd_config_t *root,
1538					snd_config_t *sconf,
1539					int direction)
1540{
1541	return _snd_pcm_direct_get_slave_ipc_offset(root, sconf, direction, 0);
1542}
1543
1544int snd_pcm_direct_parse_open_conf(snd_config_t *root, snd_config_t *conf,
1545				   int stream, struct snd_pcm_direct_open_conf *rec)
1546{
1547	snd_config_iterator_t i, next;
1548	int ipc_key_add_uid = 0;
1549	snd_config_t *n;
1550	int err;
1551
1552	rec->slave = NULL;
1553	rec->bindings = NULL;
1554	rec->ipc_key = 0;
1555	rec->ipc_perm = 0600;
1556	rec->ipc_gid = -1;
1557	rec->slowptr = 1;
1558	rec->max_periods = 0;
1559
1560	/* read defaults */
1561	if (snd_config_search(root, "defaults.pcm.dmix_max_periods", &n) >= 0) {
1562		long val;
1563		err = snd_config_get_integer(n, &val);
1564		if (err >= 0)
1565			rec->max_periods = val;
1566	}
1567
1568	snd_config_for_each(i, next, conf) {
1569		const char *id;
1570		n = snd_config_iterator_entry(i);
1571		if (snd_config_get_id(n, &id) < 0)
1572			continue;
1573		if (snd_pcm_conf_generic_id(id))
1574			continue;
1575		if (strcmp(id, "ipc_key") == 0) {
1576			long key;
1577			err = snd_config_get_integer(n, &key);
1578			if (err < 0) {
1579				SNDERR("The field ipc_key must be an integer type");
1580
1581				return err;
1582			}
1583			rec->ipc_key = key;
1584			continue;
1585		}
1586		if (strcmp(id, "ipc_perm") == 0) {
1587			long perm;
1588			err = snd_config_get_integer(n, &perm);
1589			if (err < 0) {
1590				SNDERR("Invalid type for %s", id);
1591				return err;
1592			}
1593			if ((perm & ~0777) != 0) {
1594				SNDERR("The field ipc_perm must be a valid file permission");
1595				return -EINVAL;
1596			}
1597			rec->ipc_perm = perm;
1598			continue;
1599		}
1600		if (strcmp(id, "ipc_gid") == 0) {
1601			char *group;
1602			char *endp;
1603			err = snd_config_get_ascii(n, &group);
1604			if (err < 0) {
1605				SNDERR("The field ipc_gid must be a valid group");
1606				return err;
1607			}
1608			if (! *group) {
1609				rec->ipc_gid = -1;
1610				free(group);
1611				continue;
1612			}
1613			if (isdigit(*group) == 0) {
1614				struct group *grp = getgrnam(group);
1615				if (grp == NULL) {
1616					SNDERR("The field ipc_gid must be a valid group (create group %s)", group);
1617					free(group);
1618					return -EINVAL;
1619				}
1620				rec->ipc_gid = grp->gr_gid;
1621			} else {
1622				rec->ipc_gid = strtol(group, &endp, 10);
1623			}
1624			free(group);
1625			continue;
1626		}
1627		if (strcmp(id, "ipc_key_add_uid") == 0) {
1628			if ((err = snd_config_get_bool(n)) < 0) {
1629				SNDERR("The field ipc_key_add_uid must be a boolean type");
1630				return err;
1631			}
1632			ipc_key_add_uid = err;
1633			continue;
1634		}
1635		if (strcmp(id, "slave") == 0) {
1636			rec->slave = n;
1637			continue;
1638		}
1639		if (strcmp(id, "bindings") == 0) {
1640			rec->bindings = n;
1641			continue;
1642		}
1643		if (strcmp(id, "slowptr") == 0) {
1644			err = snd_config_get_bool(n);
1645			if (err < 0)
1646				return err;
1647			rec->slowptr = err;
1648			continue;
1649		}
1650		if (strcmp(id, "max_periods") == 0) {
1651			long val;
1652			err = snd_config_get_integer(n, &val);
1653			if (err < 0)
1654				return err;
1655			rec->max_periods = val;
1656			continue;
1657		}
1658		SNDERR("Unknown field %s", id);
1659		return -EINVAL;
1660	}
1661	if (!rec->slave) {
1662		SNDERR("slave is not defined");
1663		return -EINVAL;
1664	}
1665	if (!rec->ipc_key) {
1666		SNDERR("Unique IPC key is not defined");
1667		return -EINVAL;
1668	}
1669	if (ipc_key_add_uid)
1670		rec->ipc_key += getuid();
1671	err = snd_pcm_direct_get_slave_ipc_offset(root, conf, stream);
1672	if (err < 0)
1673		return err;
1674	rec->ipc_key += err;
1675
1676	return 0;
1677}
1678