aligned_alloc.c revision 1.1
11.1Snros/* $NetBSD: aligned_alloc.c,v 1.1 2015/11/07 16:21:42 nros Exp $ */ 21.1Snros 31.1Snros/*- 41.1Snros * Copyright (C) 2015 The NetBSD Foundation, Inc. 51.1Snros * All rights reserved. 61.1Snros * 71.1Snros * This code is derived from software contributed to The NetBSD Foundation 81.1Snros * by Niclas Rosenvik. 91.1Snros * 101.1Snros * Redistribution and use in source and binary forms, with or without 111.1Snros * modification, are permitted provided that the following conditions 121.1Snros * are met: 131.1Snros * 1. Redistributions of source code must retain the above copyright 141.1Snros * notice(s), this list of conditions and the following disclaimer as 151.1Snros * the first lines of this file unmodified other than the possible 161.1Snros * addition of one or more copyright notices. 171.1Snros * 2. Redistributions in binary form must reproduce the above copyright 181.1Snros * notice(s), this list of conditions and the following disclaimer in 191.1Snros * the documentation and/or other materials provided with the 201.1Snros * distribution. 211.1Snros * 221.1Snros * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY 231.1Snros * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 241.1Snros * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 251.1Snros * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE 261.1Snros * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 271.1Snros * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 281.1Snros * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 291.1Snros * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 301.1Snros * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 311.1Snros * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 321.1Snros * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 331.1Snros */ 341.1Snros 351.1Snros#include <errno.h> 361.1Snros#include <stdlib.h> 371.1Snros 381.1Snrosvoid * 391.1Snrosaligned_alloc(size_t alignment, size_t size) 401.1Snros{ 411.1Snros void *memptr; 421.1Snros int err; 431.1Snros 441.1Snros /* 451.1Snros * Check that alignment is a power of 2 461.1Snros * and that size is an integer multiple of alignment. 471.1Snros */ 481.1Snros if (alignment == 0 || ((alignment - 1) & alignment) != 0 || 491.1Snros (size & (alignment-1)) != 0) { 501.1Snros errno = EINVAL; 511.1Snros return NULL; 521.1Snros } 531.1Snros 541.1Snros /* 551.1Snros * Adjust alignment to satisfy posix_memalign, 561.1Snros * larger alignments satisfy smaller alignments. 571.1Snros */ 581.1Snros while (alignment < sizeof(void *)) { 591.1Snros alignment <<= 1; 601.1Snros } 611.1Snros 621.1Snros err = posix_memalign(&memptr, alignment, size); 631.1Snros 641.1Snros if (err) { 651.1Snros errno = err; 661.1Snros return NULL; 671.1Snros } 681.1Snros 691.1Snros return memptr; 701.1Snros} 71