KVMALLOC()


 리눅스 커널 코드에서 메모리 할당에 관련된 패턴중 필요에 의해 만들어진 핼퍼 함수 이다. 이 함수는 아래와 같은 패턴의 메모리 할당에 대해 교체 지원한다.


memory = kmalloc(allocation_size, GFP_KERNEL);
    if (!memory)
        memory = vmalloc(allocation_size);


kvmalloc() 은 내부적으로 kmalloc() 호출을 시도한다. 이는 slab allocator 를 이용한 메모리 압박이 없다면 빠른 메모리 할당을 지원한다. 또한 slab 은 PAGE_SIZE(32비트에서는 4KB) 보다 작은 메모리 할당을 위해 사용하고, 그보다 큰경우에는 물리적으로 연속적인 메모리를 할당하려고 한다. 하지만, 시스템을 운영하다 보면, 할당할 수 있는 메모리 공간은 있지만, 단편화로 인해 물리적으로 연속적인 공간은 할당 받지 못하는 경우가 있다. 물론, 연속적인 공간 확보를 위한 compaction 등의 feature 로 노력은 하지만 연속적인 공간 요청이 크다면 힘들 수도 있다.


 이런 경우 가상주소 공간에서 연속적인 메모리 할당을 vmalloc() 으로 가능하게 한다. vmalloc() 은 가상 주소 공간에서 연속적이지만, 실제 물리적으로는 흩어진 메모리를 관리한다. 이런 할당은 페이지 테이블의 수정이 생기고, TLB cache 의 invalidation 을 갖게 된다.(페이지 폴트) 또한 PAGE_SIZE 보다 작은 메모리 할당은 align 되어 PAGE_SIZE  만큼 할당할 것이다.


 이제 kvmalloc() 내부를 보자.


/**
 * kvmalloc_node - attempt to allocate physically contiguous memory, but upon
 * failure, fall back to non-contiguous (vmalloc) allocation.
 * @size: size of the request.
 * @flags: gfp mask for the allocation - must be compatible (superset) with GFP_KERNEL.
 * @node: numa node to allocate from
 *
 * Uses kmalloc to get the memory but if the allocation fails then falls back
 * to the vmalloc allocator. Use kvfree for freeing the memory.
 *
 * Reclaim modifiers - __GFP_NORETRY and __GFP_NOFAIL are not supported. __GFP_REPEAT
 * is supported only for large (>32kB) allocations, and it should be used only if
 * kmalloc is preferable to the vmalloc fallback, due to visible performance drawbacks.
 *
 * Any use of gfp flags outside of GFP_KERNEL should be consulted with mm people.
 */
void *kvmalloc_node(size_t size, gfp_t flags, int node)
{
    gfp_t kmalloc_flags = flags;
    void *ret;

    /*
     * vmalloc uses GFP_KERNEL for some internal allocations (e.g page tables)
     * so the given set of flags has to be compatible.
     */
    WARN_ON_ONCE((flags & GFP_KERNEL) != GFP_KERNEL);

    /*
     * Make sure that larger requests are not too disruptive - no OOM
     * killer and no allocation failure warnings as we have a fallback
     */
    if (size > PAGE_SIZE) {
        kmalloc_flags |= __GFP_NOWARN;

        /*
         * We have to override __GFP_REPEAT by __GFP_NORETRY for !costly
         * requests because there is no other way to tell the allocator
         * that we want to fail rather than retry endlessly.
         */
        if (!(kmalloc_flags & __GFP_REPEAT) ||
                (size <= PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER))
            kmalloc_flags |= __GFP_NORETRY;
    }

    ret = kmalloc_node(size, kmalloc_flags, node);

    /*
     * It doesn't really make sense to fallback to vmalloc for sub page
     * requests
     */
    if (ret || size <= PAGE_SIZE)
        return ret;

    return __vmalloc_node_flags(size, node, flags);
}
EXPORT_SYMBOL(kvmalloc_node);

간단히, 메모리 할당이 8 개 페이지 크기보다 같거나 작다면, vmalloc() 은 쓰지 않을 것이다. 그냥 될때까지(oom killer 도 돌고 요청완료할 때까지) 진행을 하고, 그 크기보다 클때는 vmalloc() 으로 메모리 할당을 대체 하겠다는 것이다.


이와 관련된 헬퍼 함수는 다음과 같다.

void *kvmalloc(size_t size, gfp_t flags); void *kvzalloc(size_t size, gfp_t flags); void *kvmalloc_node(size_t size, gfp_t flags, int node); void *kvzalloc_node(size_t size, gfp_t flags, int node);

 커널 코드를 보다가 이 헬퍼 함수로 교체 가능한 코드가 있다면 수정 하면 좋겠다.


 개발자로 살다보면, 어느 시점에는 내가 실력이 있는 건가 하는 고민을 한다. 사실 Open source project 에 참가하다보면 이렇게 잘하는 사람들이 넘치는데서 Software 개발을 하는 것이 맞는 일인지도 잘 모르겠다. 그래서 이런 저런 고민을 하고 찾다보니, 어디에서 연결된 페이지인지는 기억나진 않지만, 재미있는 Github project 를 발견했다.


 https://github.com/jwasham/coding-interview-university 여기에 가면, 작성하신 분이 Google 에 입사하기 위해 공부했던 내용의 리스트들을 만날 수 있다. 이런 공부를 통해 Google / Facebook / Amazon 이런 곳에 입사하면야 좋겠지만, 이런 공부들을 조금씩 하다보면 좋은 개발자라는 소릴 어디선가는 듣지 않을까하는 생각이다. 그리고 각종 언어로 번역중에 있다.(물론 한국어도 진행하시는 분이 있긴 하다.)


 개인적인 생각은 원래 그 사이트를 번역만 할 것이 아니라 한글 책 소개 / 한글 자막 영상/ 한국어 설명 영상이 있는 것이 링크 및 업데이트를 위해서 개인적으로 fork 해서 한글화 번역을 마무리 했다.(잘 되었다고 할 순 없지만, 답답하지 않을 정도 일 것이다.) https://github.com/daeseokyoun/google-interview-university [한글 번역]


원본을 보시면 더욱더 좋고, 더 잘 하신분의 번역을(완료가 되면-아직 작업중인 것으로 보인다) 보셔도 된다. 


원본: https://github.com/jwasham/coding-interview-university

번역[개인 저장소] : https://github.com/daeseokyoun/google-interview-university



'Open Source Project' 카테고리의 다른 글

Mozilla open source project 찾기  (0) 2016.12.01

What Can I Do For Mozilla


"What Can I Do For Mozilla" 라는 이름의 사이트가 있다.


https://www.whatcanidoformozilla.org/#!/progornoprog/teach


입장을 하면, 각종 질문이 주어지는데 그 카테고리에 맞는 Mozilla open source project 를 소개 해준다.

자신에 입맞에 맞는 open source project 를 찾아보고 싶다면 한번 이용해 보면 좋겠다.



'Open Source Project' 카테고리의 다른 글

Better Software Engineer(?)  (1) 2017.03.05

+ Recent posts