mmap:强制执行64K对齐 [英] mmap: enforce 64K alignment

查看:806
本文介绍了mmap:强制执行64K对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将(由我自己)为Windows编写的项目移植到移动平台上.

I'm porting a project written (by me) for Windows to mobile platforms.

我需要等价的VirtualAlloc(+ friends),自然的是mmap.但是,有2个显着差异.

I need an equivalent of VirtualAlloc (+friends), and the natural one is mmap. However there are 2 significant differences.

    确保
  1. VirtualAlloc返回的地址是所谓的分配粒度(dwAllocationGranularity)的倍数.不要与页面大小相混淆,该数字是任意的,并且在大多数Windows系统上是64K.相反,仅保证mmap返回的地址是页面对齐的.

  1. Addresses returned by VirtualAlloc are guaranteed to be multiples of the so-called allocation granularity (dwAllocationGranularity). Not to be confused with the page size, this number is arbitrary, and on most Windows system is 64K. In contrast address returned by mmap is only guaranteed to be page-aligned.

可以通过调用VirtualFree一次释放保留/分配的区域,无需传递分配大小(即,在VirtualAlloc中使用的大小).相反,应为munmap提供要取消映射的确切区域大小,即,它释放给定数量的内存页面,而与它们的分配方式无关.

The reserved/allocated region may be freed at once by a call to VirtualFree, and there's no need to pass the allocation size (that is, the size used in VirtualAlloc). In contrast munmap should be given the exact region size to be unmapped, i.e. it frees the given number of memory pages without any relation about how they were allocated.

这给我带来了问题.虽然我可以忍受(2),但(1)是一个真正的问题.我不想详细介绍,但是假设分配粒度小得多,例如4K,将导致严重的效率下降.这与以下事实有关:我的代码需要在分配的区域内的每个粒度边界处放置一些信息,这会在连续的内存区域内施加间隙".

This imposes problems for me. While I could live with (2), the (1) is a real problem. I don't want to get into details, but assuming the much smaller allocation granularity, such as 4K, will lead to a serious efficiency degradation. This is related to the fact that my code needs to put some information at every granularity boundary within the allocated regions, which impose "gaps" within the contiguous memory region.

我需要解决这个问题.我可以考虑分配增加区域的非常幼稚的方法,以便它们可以对齐64K,并且仍然具有足够的大小.或者,保留虚拟地址空间的巨大区域,然后分配适当对齐的内存区域(即,实现某种对齐的堆).但我想知道是否还有其他选择.例如特殊的API,也许有一些标志,秘密的系统调用等等.

I need to solve this. I can think about pretty naive methods of allocating increased regions, so that they can be 64K-aligned and still have adequate size. Or alternatively reserve huge regions of virtual address space, and then allocating properly-aligned memory regions (i.e. implement a sort of an aligned heap). But I wonder if there are alternatives. Such as special APIs, maybe some flags, secret system calls or whatever.

推荐答案

(1)实际上很容易解决.如您所述,munmap带有一个size参数,这是因为munmap能够 partial 释放.因此,您可以分配比您需要的更大的内存块,然后重新分配未对齐的部分.

(1) is actually quite easy to solve. As you note, munmap takes a size parameter, and this is because munmap is capable of partial deallocation. You can thus allocate a chunk of memory that is bigger than what you need, then deallocate the parts that aren't aligned.

这篇关于mmap:强制执行64K对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆