#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <pthread.h>
#include <semaphore.h>
#define FATAL do { fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n", \
  __LINE__, __FILE__, errno, strerror(errno)); exit(1); } while(0)
int fd_dsp;
#define MAILBOX_IOC_MAGIC  'k'
#define MAILBOX_DSP1_START    _IOWR(MAILBOX_IOC_MAGIC, 0,int)
#define MAILBOX_SENDMSG_DSP1      _IOWR(MAILBOX_IOC_MAGIC,1,int)
#define MAILBOX_RECVMSG      _IOWR(MAILBOX_IOC_MAGIC,2,int)
#define MAILBOX_DSP2_START    _IOWR(MAILBOX_IOC_MAGIC, 3,int)
#define MAILBOX_SENDMSG_DSP2      _IOWR(MAILBOX_IOC_MAGIC,4,int)

#define MAP_MASK 4096

sem_t sem_id;
#if 0
void fill_memory(int address)
{
	int fd,i,ret;
	volatile void* mmap_addr;
	volatile unsigned int* add;
	if((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1) FATAL;
    printf("/dev/mem opened.\n"); 
	mmap_addr = mmap(0, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, address & ~MAP_MASK);
	printf("address 0x%x,mmap_addr 0x%x\n",address,mmap_addr);
	add = mmap_addr;
	for(i=0;i<1024;i++)
	{
		*add = i;
	//	printf("add 0x%x, value 0x%x\n",add,*add);
		add++;
	}
	ret = msync(mmap_addr,4096,MS_SYNC);
	printf("ret = 0x%x\n",ret);
	munmap(mmap_addr,4096);
	close(fd);	
}
#endif
void send_message_dsp1()
{
	int argv,ret,addr;
	int i=1;
	if((fd_dsp = open("/dev/dsp_mailbox", O_RDWR | O_SYNC)) == -1) FATAL;
	do{
	//	addr = 0x90000000+i*0x10000;
	//	if(addr >= 0xa0000000)
	//	{
	//		printf("thread send message return\n");
	//		return;
	//	}
	//	fill_memory(addr);
	//	argv = addr;
		printf("send msg to dsp1 0x%x\n",i);
		ret = ioctl(fd_dsp,MAILBOX_SENDMSG_DSP1, &i);
		if(ret == -1) FATAL;
		sem_wait(&sem_id);  
		i++;
	}while(1);
	close(fd_dsp);
}
void send_message_dsp2()
{
	int argv,ret,addr;
	int i=0x10000000;
	if((fd_dsp = open("/dev/dsp_mailbox", O_RDWR | O_SYNC)) == -1) FATAL;
	do{
		printf("send msg to dsp2 0x%x\n",i);
		ret = ioctl(fd_dsp,MAILBOX_SENDMSG_DSP2, &i);
		if(ret == -1) FATAL;
		sem_wait(&sem_id);  
		i--;
	}while(1);
	close(fd_dsp);
}
void recv_message()
{
	int argv,ret;
	if((fd_dsp = open("/dev/dsp_mailbox", O_RDWR | O_SYNC)) == -1) FATAL;
	do{
	ret = ioctl(fd_dsp,MAILBOX_RECVMSG, &argv);
	if(ret == -1) FATAL;
	printf("recv msg 0x%x\n",argv);
	sem_post(&sem_id);  
	}while(1);
	close(fd_dsp);
}

/*END OF GEMSS PRCM Definition*/ 
int main(int argc, char **argv) {
	pthread_t send_dsp1,send_dsp2,recv;
	sem_init(&sem_id,0,0);  
	pthread_create(&send_dsp1,NULL,(void *)send_message_dsp1,NULL);
//	pthread_create(&send_dsp2,NULL,(void *)send_message_dsp2,NULL);	
    pthread_create(&recv,NULL,(void *)recv_message,NULL);
	pthread_join(send_dsp1,NULL);
//	pthread_join(send_dsp2,NULL);
    pthread_join(recv,NULL);
    return 0;
}

