/* Copyright (C) 2003 Datapark corp. All rights reserved.
   Copyright (C) 2000-2002 Lavtech.com corp. All rights reserved.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
*/

#ifndef _DPS_MUTEX_H
#define _DPS_MUTEX_H


#include <sys/types.h>
#ifdef HAVE_SYS_SYSCTL_H
#include <sys/sysctl.h>
#endif


#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_PTHREAD
#include <pthread.h>
#define dps_mutex_t		pthread_mutex_t
#define InitMutex(x)		pthread_mutex_init(x,NULL)
#define DestroyMutex(x)		pthread_mutex_destroy(x)
#define DPS_MUTEX_LOCK(x)	pthread_mutex_lock(x)
#define DPS_MUTEX_UNLOCK(x)	pthread_mutex_unlock(x)
#else

#ifdef HAVE_SEMAPHORE_H
#include <semaphore.h>
#define dps_mutex_t             sem_t*
void InitMutex(dps_mutex_t *);
#define DestroyMutex(x)         sem_close(x)
#define DPS_MUTEX_LOCK(x)       sem_wait(x)
#define DPS_MUTEX_UNLOCK(x)     sem_post(x)

#elif HAVE_SYS_SEM_H
#include <sys/ipc.h>
#include <sys/sem.h>
#define dps_mutex_t             int
void InitMutex(dps_mutex_t *);
void DPS_MUTEX_LOCK(dps_mutex_t *x);
void DPS_MUTEX_UNLOCK(dps_mutex_t *x);

#else
#define dps_mutex_t		int
#define InitMutex(x)		*(x)=0
#define DestroyMutex(x)
#define DPS_MUTEX_LOCK(x)
#define DPS_MUTEX_UNLOCK(x)
#endif

#endif


typedef struct {
  int handle;
  int cnt;
  dps_mutex_t mutex;
} DPS_MUTEX;


#define DPS_LOCK_CACHED_N(n)  ((DpsNsems == DPS_LOCK_MAX) ? DPS_LOCK_CACHED : (DPS_LOCK_MAX + (n % (DpsNsems - DPS_LOCK_MAX))))


/* MUTEX stuff to lock dangerous places in multi-threaded mode */

extern __C_LINK int __DPSCALL DpsSetLockProc(DPS_ENV * Conf,
		void (*proc)(DPS_AGENT *A, int command, size_t type, const char *fname, int lineno));
extern __C_LINK void __DPSCALL DpsLockProc(DPS_AGENT *A, int command, size_t type, const char *fn, int ln);

extern __C_LINK void __DPSCALL DpsInitMutexes(void);
extern __C_LINK void __DPSCALL DpsDestroyMutexes(void);


extern size_t DpsNsems;

#define DPS_GETLOCK(A,mutex)		if(A->Conf->LockProc)A->Conf->LockProc(A,DPS_LOCK,mutex,__FILE__,__LINE__)
#define DPS_RELEASELOCK(A,mutex)	if(A->Conf->LockProc)A->Conf->LockProc(A,DPS_UNLOCK,mutex,__FILE__,__LINE__)

/* Locking commands */
#define DPS_LOCK		1
#define DPS_UNLOCK		2


#endif
