xref: /netbsd-src/lib/libc/stdlib/aligned_alloc.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /* $NetBSD: aligned_alloc.c,v 1.1 2015/11/07 16:21:42 nros 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          * and that size is an integer multiple of alignment.
47          */
48         if (alignment == 0 || ((alignment - 1) & alignment) != 0 ||
49             (size & (alignment-1)) != 0) {
50                 errno = EINVAL;
51                 return NULL;
52         }
53 
54         /*
55          * Adjust alignment to satisfy posix_memalign,
56          * larger alignments satisfy smaller alignments.
57          */
58         while (alignment < sizeof(void *)) {
59                 alignment <<= 1;
60         }
61 
62         err = posix_memalign(&memptr, alignment, size);
63 
64         if (err) {
65                 errno = err;
66                 return NULL;
67         }
68 
69         return memptr;
70 }
71