← All reports

libpas background-prefault allocator

Component: libpas / bmalloc | 954ff13

Source/JavaScriptCore/runtime/JSONObject.cpp

- Vector<CharType, dynamicBufferInlineCapacity, CrashOnOverflow, 16, WTF::StringImplMalloc> m_dynamicBuffer;
+ Vector<CharType, dynamicBufferInlineCapacity, CrashOnOverflow, 16, StringImplMallocWithBackgroundPrefault> m_dynamicBuffer;

Source/WTF/wtf/FastMalloc.cpp

+PRESERVE_MOST void* fastMallocWithBackgroundPrefault(size_t size, bmalloc::CompactAllocationMode mode)
+{
+ ...
+ void* result = bmalloc::api::mallocWithBackgroundPrefault(size, mode);
+ ...
+}

libpas는 bmalloc과 WebKit FastMalloc의 기반이 되는 allocator입니다. Large allocation은 새로 확보한 virtual memory 위에 만들어집니다. 이때 kernel은 각 page에 처음 접근하는 시점에야 physical page를 매핑합니다. 그래서 내용이 천천히 채워지는 buffer는 page마다 한 번씩 page fault 비용을 mutator thread에서 부담하게 됩니다. 한편 JSC의 MarkedBlock을 미리 warm up하기 위한 prefault thread는 이전부터 존재했습니다.

이번 commit은 bmalloc_try_allocate_auxiliary_with_background_prefault를 추가해 이 thread를 범용화했습니다. 먼저 large allocation이 고정 크기의 fault-in request slot에 등록됩니다. 그러면 prefault thread가 madvise를 통해 해당 page를 background에서 populate합니다. Large allocation을 해제하는 경로(pas_try_deallocate_known_large, pas_try_deallocate_pgm_large)도 함께 변경되었습니다. 이제 이 경로들은 slot을 scan하여, 대기 중인 request는 등록 해제하고 이미 처리 중인 request는 완료될 때까지 기다립니다. 테스트에는 reallocate 시 request가 취소되는 경우도 포함되었습니다. 첫 적용 대상은 JSON.stringify입니다. 동적 output buffer가 새로운 StringImplMallocWithBackgroundPrefault allocator를 사용하도록 변경되었습니다.

Main thread                      Prefault thread
  ├─ try_allocate_..._prefault(sz)    │
  │   └─► large alloc + request slot ─┤ (slot filled, thread woken)
  ├─ write buffer (slow fill)         ├─ madvise populate chunks (no write)
  ├─ free / realloc(ptr)              │
  │   └─► scan slots for ptr range    │
  │        ├─ queued    → clear slot  │
  │        └─ in-flight → wait ◄──────┤ finish chunk, signal
  └─► release pages to heap           │

크기가 크고 점진적으로 채워지는 buffer에서는, 첫 접근 시 발생하는 page fault 비용이 이번 변경으로 main thread 밖으로 옮겨졌습니다. 그 결과 큰 JSON.stringify 결과를 생성하는 속도가 빨라집니다. Prefault thread가 범용 서비스로 바뀌면서, allocator 내부에 free와 populate 사이의 새로운 동기화 계약이 생겼습니다. 이제 별도의 thread가 heap memory를 다루는데, allocator는 같은 시점에 그 memory를 free하거나 decommit하거나 realloc할 수 있습니다. 따라서 populate request는 대상 allocation보다 오래 살아남아서는 안 됩니다. 또한 mutator가 이미 기록한 내용을 덮어써서도 안 됩니다.

가장 먼저 살펴볼 곳은 cancel/wait protocol입니다. Slot 조회와 madvise 호출 사이에 해당 범위가 해제되고 재사용되는 window가 있는지 확인할 필요가 있습니다. 같은 주소가 새 allocation이나 다른 request에 의해 재사용되는 ABA 상황도 여기에 포함됩니다. 또한 free 경로가 이제 prefault thread를 기다리며 block되므로, lock 순서 역전 가능성도 점검해야 합니다. 대상은 heap lock, scavenger, 그리고 free 도중 잡혀 있는 large allocation bookkeeping lock입니다.

FaultInTakesBackDecommittedPages와 FaultInMarksAgedPagesInUse 테스트를 보면, populate 동작이 page commit 상태와 맞물려 있다는 점이 드러납니다. 그래서 scavenger나 동시에 진행된 free가 막 반환한 page를 populate가 다시 commit하지 않는지 확인해야 합니다. Committed/decommitted accounting이 어긋나지 않는지도 검증이 필요합니다. 한편 pas_page_malloc_fault_in_without_writing이 main thread가 이미 기록한 byte를 덮어쓰지 않는지는 platform별(Darwin vs Linux)로 확인해야 합니다.

범위를 넓히면 다음 항목도 점검할 필요가 있습니다.