xref: /netbsd-src/lib/libc/stdlib/aligned_alloc.c (revision a928bc806116f599aeedad4ccd547b082d4b6267)
1 /* $NetBSD: aligned_alloc.c,v 1.3 2024/08/18 18:47:20 riastradh Exp $ */
2 
3 /*-
4  * Copyright (C) 2015 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Niclas Rosenvik.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice(s), this list of conditions and the following disclaimer as
15  *    the first lines of this file unmodified other than the possible
16  *    addition of one or more copyright notices.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice(s), this list of conditions and the following disclaimer in
19  *    the documentation and/or other materials provided with the
20  *    distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
23  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE
26  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
29  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
30  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
31  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
32  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 __RCSID("$NetBSD: aligned_alloc.c,v 1.3 2024/08/18 18:47:20 riastradh Exp $");
37 
38 #include <errno.h>
39 #include <stdlib.h>
40 
41 void *
42 aligned_alloc(size_t alignment, size_t size)
43 {
44         void *memptr;
45         int err;
46 
47         /*
48          * Check that alignment is a power of 2.
49          */
50         if (alignment == 0 || ((alignment - 1) & alignment) != 0) {
51                 errno = EINVAL;
52                 return NULL;
53         }
54 
55         /*
56          * Adjust alignment to satisfy posix_memalign,
57          * larger alignments satisfy smaller alignments.
58          */
59         while (alignment < sizeof(void *)) {
60                 alignment <<= 1;
61         }
62 
63         err = posix_memalign(&memptr, alignment, size);
64         if (err) {
65                 errno = err;
66                 return NULL;
67         }
68 
69         return memptr;
70 }
71