xref: /titanic_44/usr/src/uts/common/fs/smbsrv/smb_alloc.c (revision 8475e04352e630e4bd0f59a283286ee2475a14ce)
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  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <sys/types.h>
29 #include <sys/sunddi.h>
30 #include <sys/kmem.h>
31 #include <sys/sysmacros.h>
32 #include <sys/types.h>
33 
34 #include <smbsrv/alloc.h>
35 
36 #define	MEM_HDR_SIZE	8
37 static uint32_t mem_get_size(void *ptr);
38 
39 void *
40 mem_malloc(uint32_t size)
41 {
42 	uint8_t *p;
43 
44 	size += MEM_HDR_SIZE;
45 	p = kmem_alloc(size, KM_SLEEP);
46 	/*LINTED E_BAD_PTR_CAST_ALIGN*/
47 	*(uint32_t *)p = size;
48 	p += MEM_HDR_SIZE;
49 
50 	return (p);
51 }
52 
53 void *
54 mem_zalloc(uint32_t size)
55 {
56 	uint8_t *p;
57 
58 	p = mem_malloc(size);
59 	(void) memset(p, 0, size);
60 	return (p);
61 }
62 
63 char *
64 mem_strdup(const char *ptr)
65 {
66 	char *p;
67 	size_t size;
68 
69 	size = strlen(ptr) + 1;
70 	p = mem_malloc(size);
71 	(void) memcpy(p, ptr, size);
72 	return (p);
73 }
74 
75 static uint32_t
76 mem_get_size(void *ptr)
77 {
78 	uint32_t *p;
79 
80 	/*LINTED E_BAD_PTR_CAST_ALIGN*/
81 	p = (uint32_t *)((uint8_t *)ptr - MEM_HDR_SIZE);
82 
83 	return (*p);
84 }
85 
86 void *
87 mem_realloc(void *ptr, uint32_t size)
88 {
89 	void *new_ptr;
90 
91 	if (ptr == NULL)
92 		return (mem_malloc(size));
93 
94 	if (size == 0) {
95 		smb_mem_free(ptr);
96 		return (NULL);
97 	}
98 
99 	new_ptr = mem_malloc(size);
100 	(void) memcpy(new_ptr, ptr, mem_get_size(ptr));
101 	smb_mem_free(ptr);
102 
103 	return (new_ptr);
104 }
105 
106 void
107 smb_mem_free(void *ptr)
108 {
109 	uint8_t *p;
110 
111 	if (ptr == 0)
112 		return;
113 
114 	p = (uint8_t *)ptr - MEM_HDR_SIZE;
115 	/*LINTED E_BAD_PTR_CAST_ALIGN*/
116 	kmem_free(p, *(uint32_t *)p);
117 }
118