/*
 *  Copyright (C) 2000-2025, Thomas Maier-Komor
 *
 *  This file is part of mbuffer's source code.
 *
 *  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 3 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, see <http://www.gnu.org/licenses/>.
 */

#ifndef COMMON_H
#define COMMON_H

#include "mbconf.h"

#include <sys/time.h>
#include <pthread.h>

#ifdef __sun
#include <synch.h>
#define sem_t sema_t
#define sem_init(a,b,c) sema_init(a,c,USYNC_THREAD,0)
#define sem_post sema_post
#define sem_getvalue(a,b) ((*(b) = (a)->count), 0)
#if defined(__SunOS_5_8) || defined(__SunOS_5_9)
#define sem_wait SemWait
#else
#define sem_wait sema_wait
#endif
#endif

#ifdef USE_COND_VARS
#ifdef USE_SEMAPHORES
#error infrastructure config error, both variants enabled
#endif
typedef size_t counter_val_t;
typedef struct counter_s {
	counter_val_t value;
	pthread_mutex_t mutex;
	pthread_cond_t cond;
} counter_t;
#elif defined USE_SEMAPHORES	// use semaphores
#include "semaphore.h"
typedef int counter_val_t;
typedef sem_t counter_t;
#else
#error infrastructure variant not set
#endif

int mt_usleep(unsigned long long sleep_usecs);
long long enforceSpeedLimit(unsigned long long limit, long long num, struct timespec *last);
void releaseLock(void *l);
void enable_directio(int fd, const char *fn);
int disable_directio(int fd, const char *fn);
const char *hBytes(unsigned long long v);


#ifdef USE_COND_VARS
/* Condition variable-based counting synchronization (replaces semaphores) */
void counter_init(counter_t *, size_t init_val);
void counter_wait(counter_t *);
void counter_post(counter_t *);
void counter_getvalue(counter_t *, size_t *val);
#elif defined USE_SEMAPHORES
/* use semaphores based infrastrcture */
#define counter_init(a,b) sem_init(a,0,b)
#define counter_wait(a) sem_wait(a)
#define counter_post(a) sem_post(a)
#define counter_getvalue(a,b) sem_getvalue(a,b)
#else
#error infrastructure variant not set
#endif

#endif
