Practical examples

Here are some examples of how you could use typed memory.

Allocating contiguous memory from system RAM

Here's a code snippet that allocates contiguous memory from system RAM:

int fd = posix_typed_mem_open( "/memory/ram/sysram", O_RDWR,
            POSIX_TYPED_MEM_ALLOCATE_CONTIG);

void *vaddr = mmap( NULL, size, PROT_READ | PROT_WRITE,
                    MAP_PRIVATE, fd, 0);

Defining packet memory and allocating from it

Assume you have special memory (say fast SRAM) that you want to use for packet memory. This SRAM isn't put in the global system RAM pool. Instead, in startup, we use as_add() (see the Customizing Image Startup Programs chapter of Building Embedded Systems) to add an asinfo entry for the packet memory:

as_add(phys_addr, phys_addr + size - 1, AS_ATTR_NONE,
       "packet_memory", mem_id);

where phys_addr is the physical address of the SRAM, size is the SRAM size, and mem_id is the ID of the parent (typically memory, which is returned by as_default()).

This code creates an asinfo entry for packet_memory, which you can then use as POSIX typed memory. The following code allows different applications to allocate pages from packet_memory:

int fd = posix_typed_mem_open( "packet_memory", O_RDWR,
            POSIX_TYPED_MEM_ALLOCATE);
void *vaddr = mmap( NULL, size, PROT_READ | PROT_WRITE,
                    MAP_SHARED, fd, 0);

Alternatively, you may want to use the packet memory as direct shared, physical buffers. In this case, applications would use it as follows:

int fd = posix_typed_mem_open( "packet_memory", O_RDWR,
            POSIX_TYPED_MEM_MAP_ALLOCATABLE);
void *vaddr = mmap( NULL, size, PROT_READ | PROT_WRITE,
                    MAP_SHARED, fd, offset);

Defining a DMA-safe region

On some hardware, due to limitations of the chipset or memory controller, it may not be possible to perform DMA to arbitrary addresses in the system. In some cases, the chipset has only the ability to DMA to a subset of all physical RAM. This has traditionally been difficult to solve without statically reserving some portion of RAM of driver DMA buffers (which is potentially wasteful). Typed memory provides a clean abstraction to solve this issue. Here's an example:

In startup, use as_add_containing() (see the Customizing Image Startup Programs chapter of Building Embedded Systems) to define an asinfo entry for DMA-safe memory. Make this entry be a child of ram:

as_add_containing( dma_addr, dma_addr + size - 1,
                   AS_ATTR_RAM, "dma", "ram");

where dma_addr is the start of the DMA-safe RAM, and size is the size of the DMA-safe region.

This code creates an asinfo entry for dma, which is a child of ram. Drivers can then use it to allocate DMA-safe buffers:

int fd = posix_typed_mem_open( "ram/dma", O_RDWR,
            POSIX_TYPED_MEM_ALLOCATE_CONTIG);
void *vaddr = mmap( NULL, size, PROT_READ | PROT_WRITE,
                    MAP_SHARED, fd, 0);