android開發ION內存管理器cache

ION如何實現buffer共享的思路倒是很清晰的,但是深入代碼研究,發現ION是依賴於DMA Mapping的,而DMA mapping模塊對我而言還是挺復雜的,看這個模塊遇到的第一個問題就是cache。既然是DMA mapping,直接將申請的buffer設置為non-cacheable不就行瞭?這樣就可以保證CPU通過DMA讀寫緩沖區的一致性瞭。為什麼還有Consistent DMA mappings 和 Streaming DMA mappings一說呢?下面先介紹一下Cache的概念。

Cache

Cache寫機制:Write-through與Write-back[5]

Cache寫機制分為write through和write back兩種。

Write-through- Write is done synchronously both to the cache and to the backing store.Write-back (or Write-behind) – Writing is done only to the cache. A modified cache block is written back to the store, just before it is replaced.

Write-through(直寫模式)在數據更新時,同時寫入緩存Cache和後端存儲。此模式的優點是操作簡單;缺點是因為數據修改需要同時寫入存儲,數據寫入速度較慢。

Write-back(回寫模式)在數據更新時隻寫入緩存Cache。隻在數據被替換出緩存時,被修改的緩存數據才會被寫到後端存儲。此模式的優點是數據寫入速度快,因為不需要寫存儲;缺點是一旦更新後的數據未被寫入存儲時出現系統掉電的情況,數據將無法找回。

Write-misses寫缺失的處理方式

對於寫操作,存在寫入緩存缺失數據的情況,這時有兩種處理方式:

Write allocate (aka Fetch on write) – Datum at the missed-write location is loaded to cache, followed by a write-hit operation. In this approach, write misses are similar to read-misses.No-write allocate (aka Write-no-allocate, Write around) – Datum at the missed-write location is not loaded to cache, and is written directly to the backing store. In this approach, actually only system reads are being cached.

Write allocate方式將寫入位置讀入緩存,然後采用write-hit(緩存命中寫入)操作。寫缺失操作與讀缺失操作類似。

No-write allocate方式並不將寫入位置讀入緩存,而是直接將數據寫入存儲。這種方式下,隻有讀操作會被緩存。

無論是Write-through還是Write-back都可以使用寫缺失的兩種方式之一。隻是通常Write-back采用Write allocate方式,而Write-through采用No-write allocate方式;因為多次寫入同一緩存時,Write allocate配合Write-back可以提升性能;而對於Write-through則沒有幫助。

Cache的兩個函數

–Flush

把Cache內容寫回Memory,當Cache為Write through,不需要Flush

–Invalidate

把Cache內容直接丟掉不要。

Cache的使用場合

當有DMA在使用memory的時候,一般要用到cache的處理。因為DMA在訪問memory時是不經過cache的。比較典型的比如在Ethernet,wireless,USB等driver裡,DMA會操作descriptors和packet buffers,Driver要做這些處理

–如果driver使用descripter和packet buffer的地址都是cache的地址,那麼

a).Driver在讀descripter裡一些狀態,有沒有收到包時,要對descripter當前結構裡的內容做cache invalidate,收到packet後,也要對packet buffer做cache invalidate

b).Driver在寫descripter裡一些狀態,要發送包時,要對descripter當前結構裡的內容做cache flush,發送packet時,也要對packet buffer做cache flush

–有些driver會對descripter使用uncache 地址,那麼上面兩種情況裡invalidate/flush就不用做瞭。一般很少會對packet buffer也用uncache地址的,因為對packet內容的處理將會很頻繁,使用uncache會很慢。而descripter一般由於結構比較小,如果也使用cache地址的話,做invalidate/flush的時間消耗可能會比uncache的還要多。

下面文字采自於[6]

C B 位的具體含義

0 0 無cache,無寫緩沖(strongly-ordered);任何對memory的讀寫都反映到總線上。對 memory 的操作過程中CPU需要等待。

0 1 無cache,有寫緩沖(shareable device);讀操作直接反映到總線上;寫操作,CPU將數據寫入到寫緩沖後繼續運行,由寫緩沖進行寫回操作。

1 0 有cache,寫通模式(write-through);讀操作首先考慮cache hit;寫操作時直接將數據寫入寫緩沖,如果同時出現cache hit,那麼也更新cache。

1 1 有cache,寫回模式(write-back);讀操作首先考慮cache hit;寫操作也首先考慮cache hit。

處理流程圖

Write-through模式處理流程:

A Write-Through cache with No-Write Allocation

A Write-Through cache with No-Write Allocation

Write-back模式處理流程:

A Write-Back cache with Write Allocation

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *