xref: /netbsd-src/lib/libc/stdlib/aligned_alloc.c (revision e5014a45d857e6639905eec7f40943a207fed007)
1 /* $NetBSD: aligned_alloc.c,v 1.2 2018/07/27 13:08:47 maya 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 <errno.h>
36 #include <stdlib.h>
37 
38 void *
39 aligned_alloc(size_t alignment, size_t size)
40 {
41         void *memptr;
42         int err;
43 
44         /*
45          * Check that alignment is a power of 2.
46          */
47         if (alignment == 0 || ((alignment - 1) & alignment) != 0) {
48                 errno = EINVAL;
49                 return NULL;
50         }
51 
52         /*
53          * Adjust alignment to satisfy posix_memalign,
54          * larger alignments satisfy smaller alignments.
55          */
56         while (alignment < sizeof(void *)) {
57                 alignment <<= 1;
58         }
59 
60         err = posix_memalign(&memptr, alignment, size);
61 
62         if (err) {
63                 errno = err;
64                 return NULL;
65         }
66 
67         return memptr;
68 }
69