#include "lint.h"
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include "mtlib.h"
#include "libc.h"
#include "tsd.h"
typedef void (*pfrv_t)(void *);
typedef struct {
void *buf;
size_t size;
pfrv_t destructor;
} tsdent_t;
static void
_free_tsdbuf(void *ptr)
{
tsdent_t *loc = ptr;
pfrv_t destructor;
void *p;
int i;
if (loc != NULL) {
for (i = 0; i < _T_NUM_ENTRIES; i++) {
if ((p = loc[i].buf) != NULL) {
destructor = loc[i].destructor;
if (destructor != NULL)
destructor(p);
lfree(p, loc[i].size);
}
}
lfree(loc, _T_NUM_ENTRIES * sizeof (tsdent_t));
}
}
void *
tsdalloc(__tsd_item_t n, size_t size, pfrv_t destructor)
{
static thread_key_t key = THR_ONCE_KEY;
tsdent_t *loc;
void *p;
int error;
if ((uint_t)n >= _T_NUM_ENTRIES) {
errno = ENOTSUP;
return (NULL);
}
if ((error = thr_keycreate_once(&key, _free_tsdbuf)) != 0) {
errno = error;
return (NULL);
}
if ((loc = pthread_getspecific(key)) != NULL) {
if ((p = loc[n].buf) != NULL)
return (p);
} else {
loc = lmalloc(_T_NUM_ENTRIES * sizeof (tsdent_t));
if (loc == NULL)
return (NULL);
if ((error = thr_setspecific(key, loc)) != 0) {
lfree(loc, _T_NUM_ENTRIES * sizeof (tsdent_t));
errno = error;
return (NULL);
}
}
loc[n].buf = p = lmalloc(size);
loc[n].size = size;
loc[n].destructor = destructor;
return (p);
}