xref: /titanic_44/usr/src/lib/libc/port/gen/tsdalloc.c (revision 67e3a03ed4a2813074d36330f062ed6e593a4937)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include "synonyms.h"
30 #include <stdlib.h>
31 #include <errno.h>
32 #include "mtlib.h"
33 #include "libc.h"
34 #include "tsd.h"
35 
36 typedef void (*pfrv_t)(void *);
37 
38 typedef struct {
39 	void	*buf;
40 	size_t	size;
41 	pfrv_t	destructor;
42 } tsdent_t;
43 
44 static void
45 _free_tsdbuf(void *ptr)
46 {
47 	tsdent_t *loc = ptr;
48 	pfrv_t destructor;
49 	void *p;
50 	int i;
51 
52 	if (loc != NULL) {
53 		for (i = 0; i < _T_NUM_ENTRIES; i++) {
54 			if ((p = loc[i].buf) != NULL) {
55 				destructor = loc[i].destructor;
56 				if (destructor != NULL)
57 					destructor(p);
58 				lfree(p, loc[i].size);
59 			}
60 		}
61 		lfree(loc, _T_NUM_ENTRIES * sizeof (tsdent_t));
62 	}
63 }
64 
65 void *
66 tsdalloc(__tsd_item_t n, size_t size, pfrv_t destructor)
67 {
68 	static thread_key_t	key = THR_ONCE_KEY;
69 	tsdent_t		*loc;
70 	void			*p;
71 	int			error;
72 
73 	if ((uint_t)n >= _T_NUM_ENTRIES) {
74 		errno = ENOTSUP;
75 		return (NULL);
76 	}
77 
78 	if ((error = _thr_keycreate_once(&key, _free_tsdbuf)) != 0) {
79 		errno = error;
80 		return (NULL);
81 	}
82 
83 	if ((loc = _pthread_getspecific(key)) != NULL) {
84 		if ((p = loc[n].buf) != NULL)
85 			return (p);
86 	} else {
87 		/* allocate our array of pointers */
88 		loc = lmalloc(_T_NUM_ENTRIES * sizeof (tsdent_t));
89 		if (loc == NULL)
90 			return (NULL);
91 		if ((error = _thr_setspecific(key, loc)) != 0) {
92 			lfree(loc, _T_NUM_ENTRIES * sizeof (tsdent_t));
93 			errno = error;
94 			return (NULL);
95 		}
96 	}
97 
98 	/* allocate item n */
99 	loc[n].buf = p = lmalloc(size);
100 	loc[n].size = size;
101 	loc[n].destructor = destructor;
102 	return (p);
103 }
104