Per-cpu -3- (동적 할당)

<kernel v5.0>

Per-cpu -3- (동적 할당)

alloc_percpu-1

 

alloc_percpu()

include/linux/percpu.h

1#define alloc_percpu(type)                                              \
2        (typeof(type) __percpu *)__alloc_percpu(sizeof(type),           \
3                                                __alignof__(type))

요청 타입의 per-cpu 메모리를  할당한다.

 

__alloc_percpu()

mm/percpu.c

1/**
2 * __alloc_percpu - allocate dynamic percpu area
3 * @size: size of area to allocate in bytes
4 * @align: alignment of area (max PAGE_SIZE)
5 *
6 * Equivalent to __alloc_percpu_gfp(size, align, %GFP_KERNEL).
7 */
1void __percpu *__alloc_percpu(size_t size, size_t align)
2{
3        return pcpu_alloc(size, align, false, GFP_KERNEL);
4}
5EXPORT_SYMBOL_GPL(__alloc_percpu);

요청 @size 및 @align 값으로 per-cpu 메모리를  할당한다.

 

alloc_percpu_gfp()

include/linux/percpu.h

1#define alloc_percpu_gfp(type, gfp)                                     \
2        (typeof(type) __percpu *)__alloc_percpu_gfp(sizeof(type),       \
3                                                __alignof__(type), gfp)

요청 타입 및 gfp 플래그를 사용하여 per-cpu 메모리를  할당한다.

 

__alloc_percpu_gfp()

mm/percpu.c

01/**
02 * __alloc_percpu_gfp - allocate dynamic percpu area
03 * @size: size of area to allocate in bytes
04 * @align: alignment of area (max PAGE_SIZE)
05 * @gfp: allocation flags
06 *
07 * Allocate zero-filled percpu area of @size bytes aligned at @align.  If
08 * @gfp doesn't contain %GFP_KERNEL, the allocation doesn't block and can
09 * be called from any context but is a lot more likely to fail. If @gfp
10 * has __GFP_NOWARN then no warning will be triggered on invalid or failed
11 * allocation requests.
12 *
13 * RETURNS:
14 * Percpu pointer to the allocated area on success, NULL on failure.
15 */
1void __percpu *__alloc_percpu_gfp(size_t size, size_t align, gfp_t gfp)
2{
3        return pcpu_alloc(size, align, false, gfp);
4}
5EXPORT_SYMBOL_GPL(__alloc_percpu_gfp);

요청 size, align 및 gfp 플래그 값으로 per-cpu 메모리를  할당한다.

 

__alloc_reserved_percpu()

mm/percpu.c

01/**
02 * __alloc_reserved_percpu - allocate reserved percpu area
03 * @size: size of area to allocate in bytes
04 * @align: alignment of area (max PAGE_SIZE)
05 *
06 * Allocate zero-filled percpu area of @size bytes aligned at @align
07 * from reserved percpu area if arch has set it up; otherwise,
08 * allocation is served from the same dynamic area.  Might sleep.
09 * Might trigger writeouts.
10 *
11 * CONTEXT:
12 * Does GFP_KERNEL allocation.
13 *
14 * RETURNS:
15 * Percpu pointer to the allocated area on success, NULL on failure.
16 */
1void __percpu *__alloc_reserved_percpu(size_t size, size_t align)
2{
3        return pcpu_alloc(size, align, true, GFP_KERNEL);
4}

컴파일 타임에 모듈에서 사용된 static per-cpu 데이터 선언 영역들은 곧바로 사용될 수 있는 데이터 공간이 아니다. 이들은 런타임에 모듈이 로드될 때 이 함수가 호출되어 first chunk의 reserved 영역 범위내에서 할당한다.

 

pcpu 동적 할당  메인

pcpu_alloc()

mm/percpu.c -1/3-

01/**
02 * pcpu_alloc - the percpu allocator
03 * @size: size of area to allocate in bytes
04 * @align: alignment of area (max PAGE_SIZE)
05 * @reserved: allocate from the reserved chunk if available
06 * @gfp: allocation flags
07 *
08 * Allocate percpu area of @size bytes aligned at @align.  If @gfp doesn't
09 * contain %GFP_KERNEL, the allocation is atomic. If @gfp has __GFP_NOWARN
10 * then no warning will be triggered on invalid or failed allocation
11 * requests.
12 *
13 * RETURNS:
14 * Percpu pointer to the allocated area on success, NULL on failure.
15 */
01static void __percpu *pcpu_alloc(size_t size, size_t align, bool reserved,
02                                 gfp_t gfp)
03{
04        /* whitelisted flags that can be passed to the backing allocators */
05        gfp_t pcpu_gfp = gfp & (GFP_KERNEL | __GFP_NORETRY | __GFP_NOWARN);
06        bool is_atomic = (gfp & GFP_KERNEL) != GFP_KERNEL;
07        bool do_warn = !(gfp & __GFP_NOWARN);
08        static int warn_limit = 10;
09        struct pcpu_chunk *chunk;
10        const char *err;
11        int slot, off, cpu, ret;
12        unsigned long flags;
13        void __percpu *ptr;
14        size_t bits, bit_align;
15 
16        /*
17         * There is now a minimum allocation size of PCPU_MIN_ALLOC_SIZE,
18         * therefore alignment must be a minimum of that many bytes.
19         * An allocation may have internal fragmentation from rounding up
20         * of up to PCPU_MIN_ALLOC_SIZE - 1 bytes.
21         */
22        if (unlikely(align < PCPU_MIN_ALLOC_SIZE))
23                align = PCPU_MIN_ALLOC_SIZE;
24 
25        size = ALIGN(size, PCPU_MIN_ALLOC_SIZE);
26        bits = size >> PCPU_MIN_ALLOC_SHIFT;
27        bit_align = align >> PCPU_MIN_ALLOC_SHIFT;
28 
29        if (unlikely(!size || size > PCPU_MIN_UNIT_SIZE || align > PAGE_SIZE ||
30                     !is_power_of_2(align))) {
31                WARN(do_warn, "illegal size (%zu) or align (%zu) for percpu allocation\n",
32                     size, align);
33                return NULL;
34        }
35 
36        if (!is_atomic) {
37                /*
38                 * pcpu_balance_workfn() allocates memory under this mutex,
39                 * and it may wait for memory reclaim. Allow current task
40                 * to become OOM victim, in case of memory pressure.
41                 */
42                if (gfp & __GFP_NOFAIL)
43                        mutex_lock(&pcpu_alloc_mutex);
44                else if (mutex_lock_killable(&pcpu_alloc_mutex))
45                        return NULL;
46        }
47 
48        spin_lock_irqsave(&pcpu_lock, flags);
49 
50        /* serve reserved allocations from the reserved chunk if available */
51        if (reserved && pcpu_reserved_chunk) {
52                chunk = pcpu_reserved_chunk;
53 
54                off = pcpu_find_block_fit(chunk, bits, bit_align, is_atomic);
55                if (off < 0) {
56                        err = "alloc from reserved chunk failed";
57                        goto fail_unlock;
58                }
59 
60                off = pcpu_alloc_area(chunk, bits, bit_align, off);
61                if (off >= 0)
62                        goto area_found;
63 
64                err = "alloc from reserved chunk failed";
65                goto fail_unlock;
66        }

요청 size와 align 값으로 per-cpu 메모리를 동적으로 할당한다. 모듈에서 호출하는 경우 reserved를 true로 호출하여 reserved per-cpu 영역에서 할당하게 한다. 할당받을 공간이 부족한 경우 chunk를 새로 추가하는데, 만일 어토믹 요청인 경우에는 확장하지 않고 실패 처리한다.

  • 코드 라인 6에서 어토믹 요청 여부를 파악한다. GFP_KERNEL 옵션을 사용하지 않으면 어토믹 요청이 온 것이다. alloc_percpu( ) 함수 등을 사용하여 호출하는 경우 항상 GFP_KERNEL 옵션을 사용하므로 어토믹 조건을 사용하지 않는다.
    • 현재 커널에서 alloc_percpu_gfp( ) 함수를 사용하는 경우에는 gfp 옵션을 바꿀 수 있는데, 실제 적용된 코드에는 아직까지 GFP_KERNEL 옵션 이외의 gfp 옵션을 사용한 경우가 없다. 향후 어토믹 조건을 사용하려고 미리 준비해둔 함수다.
    •  어토믹 조건으로 이 함수를 동작시키는 경우 populate된 페이지에서만 per-cpu 데이터를 할당할 수 있게 제한한다. 어토믹 조건이 아닌 경우는 chunk가 부족한 경우 chunk도 생성할 수 있고 unpopulate된 페이지들을 population 과정을 통해 사용할 수 있게 한다.
  • 코드 라인 22~23에서 per-cpu 할당의 최소 정렬 단위를 최소 4바이트로 제한한다.
  • 코드 라인 25~27에서 할당 사이즈는 per-cpu 최소 정렬 단위로 정렬한다. 그리고 산출된 사이즈 및 정렬 단위로 필요 비트 수를 구한다.
    • 예) size=32, align=4
      • bits=8, bit_align=1
  • 코드 라인 29~34에서 사이즈가 0이거나 유닛 사이즈를 초과하거나 align이 페이지 단위를 초과하거나 2의 제곱승 단위를 사용하지 않는 경우 경고 메시지를 출력하고 null을 반환한다.
  • 코드 라인 36~46에서 어토믹 할당 요청이 아닌 경우 OOM 상황에서 per-cpu 할당을 위한 lock을 획득하지 않고 중간에 포기하고 null을 반환할 수 있게 한다.
  • 코드 라인 48에서 할당 준비를 하는동안 interrupt를 막는다.
  • 코드 라인 51~66에서 모듈을 위해 사용된 static per-cpu 할당은 first chunk의 reserved 영역을 사용하여 관리한다. 이 chunk에서 할당 가능한지 공간을 확인한 후 할당을 시도한다. 만일 적당한 공간을 찾은 경우 area_found: 레이블로 이동하고, 적절한 공간을 찾지 못한 경우 할당 실패 사유를 출력하고 함수를 빠져나가기 위해 faile_unlock: 레이블로 이동한다.

 

mm/percpu.c -2/3-

01restart:
02        /* search through normal chunks */
03        for (slot = pcpu_size_to_slot(size); slot < pcpu_nr_slots; slot++) {
04                list_for_each_entry(chunk, &pcpu_slot[slot], list) {
05                        off = pcpu_find_block_fit(chunk, bits, bit_align,
06                                                  is_atomic);
07                        if (off < 0)
08                                continue;
09 
10                        off = pcpu_alloc_area(chunk, bits, bit_align, off);
11                        if (off >= 0)
12                                goto area_found;
13 
14                }
15        }
16 
17        spin_unlock_irqrestore(&pcpu_lock, flags);
18 
19        /*
20         * No space left.  Create a new chunk.  We don't want multiple
21         * tasks to create chunks simultaneously.  Serialize and create iff
22         * there's still no empty chunk after grabbing the mutex.
23         */
24        if (is_atomic) {
25                err = "atomic alloc failed, no space left";
26                goto fail;
27        }
28 
29        if (list_empty(&pcpu_slot[pcpu_nr_slots - 1])) {
30                chunk = pcpu_create_chunk(pcpu_gfp);
31                if (!chunk) {
32                        err = "failed to allocate new chunk";
33                        goto fail;
34                }
35 
36                spin_lock_irqsave(&pcpu_lock, flags);
37                pcpu_chunk_relocate(chunk, -1);
38        } else {
39                spin_lock_irqsave(&pcpu_lock, flags);
40        }
41 
42        goto restart;

restart: 레이블에서는 dynamic per-cpu 할당에 대한 처리를 수행한다.

  • 코드 라인 3에서 적절한 chunk를 먼저 찾기 위해 할당할 사이즈에 해당하는 슬롯 부터 최상위 슬롯까지 순회한다.
    • pcpu_size_to_slot()은 size 범위에 해당되는 슬롯 번호를 리턴한다.
      • 예) size가 44K이라면 13번 슬롯을 리턴한다.
  • 코드 라인 4~8에서 해당 슬롯의 chunk 리스트를 순회하며 할당할 사이즈보다 큰 free 공간이 없으면 skip 한다.
  • 코드 라인 10~12에서 할당 요청한 사이즈 만큼 할당된 경우 area_found; 레이블로 이동한다.
  • 코드 라인 24~27에서 atomic 요청된 경우 재시도를 하지 않고 fail: 레이블로 이동한다.
  • 코드 라인 29~42에서 최상위 슬롯에는 항상 빈 chunk가 있어야 한다. 만일 없는 경우에는 빈 chunk를 생성하고, 최상위 슬롯에 위치시키고 재시도를 하기 위해 restart: 레이블로 이동한다.

 

mm/percpu.c -3/3-

01area_found:
02        pcpu_stats_area_alloc(chunk, size);
03        spin_unlock_irqrestore(&pcpu_lock, flags);
04 
05        /* populate if not all pages are already there */
06        if (!is_atomic) {
07                int page_start, page_end, rs, re;
08 
09                page_start = PFN_DOWN(off);
10                page_end = PFN_UP(off + size);
11 
12                pcpu_for_each_unpop_region(chunk->populated, rs, re,
13                                           page_start, page_end) {
14                        WARN_ON(chunk->immutable);
15 
16                        ret = pcpu_populate_chunk(chunk, rs, re, pcpu_gfp);
17 
18                        spin_lock_irqsave(&pcpu_lock, flags);
19                        if (ret) {
20                                pcpu_free_area(chunk, off);
21                                err = "failed to populate";
22                                goto fail_unlock;
23                        }
24                        pcpu_chunk_populated(chunk, rs, re, true);
25                        spin_unlock_irqrestore(&pcpu_lock, flags);
26                }
27 
28                mutex_unlock(&pcpu_alloc_mutex);
29        }
30 
31        if (pcpu_nr_empty_pop_pages < PCPU_EMPTY_POP_PAGES_LOW)
32                pcpu_schedule_balance_work();
33 
34        /* clear the areas and return address relative to base address */
35        for_each_possible_cpu(cpu)
36                memset((void *)pcpu_chunk_addr(chunk, cpu, 0) + off, 0, size);
37 
38        ptr = __addr_to_pcpu_ptr(chunk->base_addr + off);
39        kmemleak_alloc_percpu(ptr, size, gfp);
40 
41        trace_percpu_alloc_percpu(reserved, is_atomic, size, align,
42                        chunk->base_addr, off, ptr);
43 
44        return ptr;
45 
46fail_unlock:
47        spin_unlock_irqrestore(&pcpu_lock, flags);
48fail:
49        trace_percpu_alloc_percpu_fail(reserved, is_atomic, size, align);
50 
51        if (!is_atomic && do_warn && warn_limit) {
52                pr_warn("allocation failed, size=%zu align=%zu atomic=%d, %s\n",
53                        size, align, is_atomic, err);
54                dump_stack();
55                if (!--warn_limit)
56                        pr_info("limit reached, disable warning\n");
57        }
58        if (is_atomic) {
59                /* see the flag handling in pcpu_blance_workfn() */
60                pcpu_atomic_alloc_failed = true;
61                pcpu_schedule_balance_work();
62        } else {
63                mutex_unlock(&pcpu_alloc_mutex);
64        }
65        return NULL;
66}

area_found: 레이블에서는 per-cpu 할당이 성공한 경우 후속 처리를 위한 루틴이 있고, fail: 레이블에는 할당이 실패한 경우 원인에 대한 에러 출력을 수행한 후 null을 반환한다.

  • 코드 라인 2에서 per-cpu 할당에 대한 stat들을 증가 및 갱신한다.
  • 코드 라인 6~29에서 어토믹 처리 요청 중이 아니면 스케줄러를 이용할 필요가 없으므로 즉시 활성화 처리를 한다. 할당받은 페이지의 시작 pfn에서 끝 pfn까지 chunk 내 un-populated 영역의 시작(rs) 주소와 끝(re) 주소들을 알아와서 해당 chunk의 지정된 영역을 populate 한다. 이때 할당된 실제 페이지를 지정된 vmalloc 영역에 매핑한다. 페이지 번호들은 모두 페이지 기준의 PFN이 아니고 chunk의 첫 유닛을 기준으로 한다. 그리고 pcpu_chunk_populated() 함수를 통해 chunk에 해당 영역이 populate되었다는 정보를 비트맵 방식으로 기록한다.
  • 코드 라인 31~32에서 빈 populated 페이지 수가 2개 미만이면 populate를 하기 위해 백그라운드에서 워크큐를 통해 pcpu_balance_workfn( )을 호출하게 하여 하나의 빈 chunk에 어토믹 할당이 가능하도록 populated free pages를 PCPU_EMPTY_POP_PAGES_LOW(2)~HIGH(4)까지 확보한다. 어토믹 연산을 위해 미리 populate된 페이지를 확보해둔다.
  • 코드 라인 35~36에서 할당된 사이즈의 영역을 깨끗이 0으로 청소한다.
  • 코드 라인 38에서 주어진 주소로 per-cpu 포인터 주소로의 변환을 하여 리턴한다. per-cpu 포인터 주소는 유닛 0에 해당하는 실제 데이터의 주소가 아니라 그 주소에서 delta를 뺀 주소를 가리킨다. 실제 사용 시에는 이 값에 해당 cpu가 저장하고 있는 TPIDRPRW 값을 더해 사용한다.
    • TPIDRPRW에는 first chunk의 처음 설정 시 cpu에 해당하는 유닛 offset + delta 값이 보관되어 있으며, 이 값은 향후 바뀌지 않는다.
    • delta 값은 first chunk를 처음 설정할 때 계산된 가장 낮은 노드(그룹)의 base offset에서 per-cpu 섹션의 시작 주소를 뺀 가상의 주소다.
    • 실제 static 변수의 경우 per-cpu 섹션에 컴파일 타임에 만들어진 주소를 가지며, 동적 할당에서는 그 delta 값을 고려하여 미리 감소시킨 값을 가리킨다. 따라서 어떠한 경우에도 per-cpu 포인터 값을 액세스하면 안 된다. static per-cpu 데이터, 동적으로 할당되어 사용하는 per-cpu 데이터 상관없이 동일한 this_cpu_ptr( ) 등의 API 함수를 사용하게 하기 위해 고려되었다.
  • 코드 라인 39~44에서 메모리 누수 감시를 위해 객체를 등록하고 성공했으므로 함수를 빠져나간다.
  • 코드 라인 46~57에서 할당에 실패한 경우 이 루틴으로 진입한다. 어토믹 할당 요청을 받은 경우가 아니면 경고를 출력한다.
  • 코드 라인 58~65에서 어토믹 할당 요청을 받은 경우 pcpu_schedule_balance_work( ) 루틴을 호출하여 워크큐에서 별도로 스케줄 할당을 받아 populated된 free 페이지의 할당을 준비한다.

 


chunk 내 필요 free 공간 검색

pcpu_find_block_fit()

mm/percpu.c

01/**
02 * pcpu_find_block_fit - finds the block index to start searching
03 * @chunk: chunk of interest
04 * @alloc_bits: size of request in allocation units
05 * @align: alignment of area (max PAGE_SIZE bytes)
06 * @pop_only: use populated regions only
07 *
08 * Given a chunk and an allocation spec, find the offset to begin searching
09 * for a free region.  This iterates over the bitmap metadata blocks to
10 * find an offset that will be guaranteed to fit the requirements.  It is
11 * not quite first fit as if the allocation does not fit in the contig hint
12 * of a block or chunk, it is skipped.  This errs on the side of caution
13 * to prevent excess iteration.  Poor alignment can cause the allocator to
14 * skip over blocks and chunks that have valid free areas.
15 *
16 * RETURNS:
17 * The offset in the bitmap to begin searching.
18 * -1 if no offset is found.
19 */
01static int pcpu_find_block_fit(struct pcpu_chunk *chunk, int alloc_bits,
02                               size_t align, bool pop_only)
03{
04        int bit_off, bits, next_off;
05 
06        /*
07         * Check to see if the allocation can fit in the chunk's contig hint.
08         * This is an optimization to prevent scanning by assuming if it
09         * cannot fit in the global hint, there is memory pressure and creating
10         * a new chunk would happen soon.
11         */
12        bit_off = ALIGN(chunk->contig_bits_start, align) -
13                  chunk->contig_bits_start;
14        if (bit_off + alloc_bits > chunk->contig_bits)
15                return -1;
16 
17        bit_off = chunk->first_bit;
18        bits = 0;
19        pcpu_for_each_fit_region(chunk, alloc_bits, align, bit_off, bits) {
20                if (!pop_only || pcpu_is_populated(chunk, bit_off, bits,
21                                                   &next_off))
22                        break;
23 
24                bit_off = next_off;
25                bits = 0;
26        }
27 
28        if (bit_off == pcpu_chunk_map_bits(chunk))
29                return -1;
30 
31        return bit_off;
32}

@chunk 내에서 적절한 빈 공간을 찾아 chunk 기준 bit_off 값을 반환한다. @pop_only가 1로 주어진 경우 populate 페이지 들에서만 검색한다.

  • 코드 라인 12~15에서 최대 연속된 free 공간을 보고 @align 정렬 단위로 @alloc_bits 만큼 할당할 공간이 없으면 -1을 반환한다.
  • 코드 라인 17~19에서 bit_off 위치부터 시작하여 bits 단위로 순회하며 align 조건이 만족하는 빈 공간을 찾아 bit_off를 구한다.
  • 코드 라인 20~22에서 @pop_only가 0인 경우 처음 찾은 위치가 확정된다. 그렇지 않고 @pop_only가 1로 설정된 경우 @bit_off 부터 bits 만큼의 공간이 populate된 공간인지를 확인하여 확정한다. 만일 populate 공간이 아니면 next_off에 다음 populate 페이지의 시작 비트를 가리키는 값을 반환한다.
  •  코드라인24~26에서 다음 populate 페이지의 시작 비트를 next_off로 가져왔으므로 이를 bit_off에 넣고 계속 루프를 반복한다.
  • 코드 라인 28~31에서 할당이 실패한 경우 -1을 반환하고, 성공한 경우 bit_off를 반환한다.

 

pcpu_for_each_fit_region()

mm/percpu.c

1#define pcpu_for_each_fit_region(chunk, alloc_bits, align, bit_off, bits)     \
2        for (pcpu_next_fit_region((chunk), (alloc_bits), (align), &(bit_off), \
3                                  &(bits));                                   \
4             (bit_off) < pcpu_chunk_map_bits((chunk));                        \
5             (bit_off) += (bits),                                             \
6             pcpu_next_fit_region((chunk), (alloc_bits), (align), &(bit_off), \
7                                  &(bits)))

@chunk 내에서 입출력인자 @bit_off부터 시작하여 @align 단위로 @alloc_bits 만큼 free 공간이 확보 가능한 영역을 찾아 입출력 인자 @bit_off에 비트 오프셋 위치와, 출력 인자 @bits에 free 영역의 사이즈를 반환한다. 참고로 각 비트는 4바이트 단위의 할당 상태를 표시한다.

 

pcpu_next_fit_region()

mm/percpu.c

01/**
02 * pcpu_next_fit_region - finds fit areas for a given allocation request
03 * @chunk: chunk of interest
04 * @alloc_bits: size of allocation
05 * @align: alignment of area (max PAGE_SIZE)
06 * @bit_off: chunk offset
07 * @bits: size of free area
08 *
09 * Finds the next free region that is viable for use with a given size and
10 * alignment.  This only returns if there is a valid area to be used for this
11 * allocation.  block->first_free is returned if the allocation request fits
12 * within the block to see if the request can be fulfilled prior to the contig
13 * hint.
14 */
01static void pcpu_next_fit_region(struct pcpu_chunk *chunk, int alloc_bits,
02                                 int align, int *bit_off, int *bits)
03{
04        int i = pcpu_off_to_block_index(*bit_off);
05        int block_off = pcpu_off_to_block_off(*bit_off);
06        struct pcpu_block_md *block;
07 
08        *bits = 0;
09        for (block = chunk->md_blocks + i; i < pcpu_chunk_nr_blocks(chunk);
10             block++, i++) {
11                /* handles contig area across blocks */
12                if (*bits) {
13                        *bits += block->left_free;
14                        if (*bits >= alloc_bits)
15                                return;
16                        if (block->left_free == PCPU_BITMAP_BLOCK_BITS)
17                                continue;
18                }
19 
20                /* check block->contig_hint */
21                *bits = ALIGN(block->contig_hint_start, align) -
22                        block->contig_hint_start;
23                /*
24                 * This uses the block offset to determine if this has been
25                 * checked in the prior iteration.
26                 */
27                if (block->contig_hint &&
28                    block->contig_hint_start >= block_off &&
29                    block->contig_hint >= *bits + alloc_bits) {
30                        *bits += alloc_bits + block->contig_hint_start -
31                                 block->first_free;
32                        *bit_off = pcpu_block_off_to_off(i, block->first_free);
33                        return;
34                }
35                /* reset to satisfy the second predicate above */
36                block_off = 0;
37 
38                *bit_off = ALIGN(PCPU_BITMAP_BLOCK_BITS - block->right_free,
39                                 align);
40                *bits = PCPU_BITMAP_BLOCK_BITS - *bit_off;
41                *bit_off = pcpu_block_off_to_off(i, *bit_off);
42                if (*bits >= alloc_bits)
43                        return;
44        }
45 
46        /* no valid offsets were found - fail condition */
47        *bit_off = pcpu_chunk_map_bits(chunk);
48}

@chunk 내에서 입출력 인자 @bit_off부터 시작하여 @align 단위로 @alloc_bits 만큼 free 공간이 확보 가능한 영역을 찾는다. 그런 후 입출력 인자 @bit_off에 찾은 free 영역의 시작 비트 오프셋 위치와, 출력 인자 @bits에 free 영역의 사이즈를 반환한다. 참고로 각 비트는 4바이트 단위의 할당 상태를 표시한다.

  • 코드 라인 9~18에서 청크에서 pcpu 블럭(페이지) 수 만큼 순회하며 처음 호출되어 @bits가 0인 경우 가장 첫 free 공간에서 할당 가능하면 @bits를 갱신하여 함수를 빠져나오고, 그렇지 않고 free 공간의 중간 블럭인 경우 skip 한다.
  • 코드 라인 21~34에서 free 공간에서 할당 가능하면 그 위치와 사이즈를 산출하여 반환한다.
  • 코드 라인 36~43에서 가장 우측 free 공간에서 할당 가능한 경우 그 위치와 사이즈를 산출하여 반환한다.
  • 코드 라인 47에서 더 이상 찾지 못한 경우 함수 밖에 있는 루프를 끝내기 위해 @bit_off에 마지막 값을 담는다.

 


할당한 영역을 비트맵에 표기

pcpu_alloc_area()

mm/percpu.c

01/**
02 * pcpu_alloc_area - allocates an area from a pcpu_chunk
03 * @chunk: chunk of interest
04 * @alloc_bits: size of request in allocation units
05 * @align: alignment of area (max PAGE_SIZE)
06 * @start: bit_off to start searching
07 *
08 * This function takes in a @start offset to begin searching to fit an
09 * allocation of @alloc_bits with alignment @align.  It needs to scan
10 * the allocation map because if it fits within the block's contig hint,
11 * @start will be block->first_free. This is an attempt to fill the
12 * allocation prior to breaking the contig hint.  The allocation and
13 * boundary maps are updated accordingly if it confirms a valid
14 * free area.
15 *
16 * RETURNS:
17 * Allocated addr offset in @chunk on success.
18 * -1 if no matching area is found.
19 */
01static int pcpu_alloc_area(struct pcpu_chunk *chunk, int alloc_bits,
02                           size_t align, int start)
03{
04        size_t align_mask = (align) ? (align - 1) : 0;
05        int bit_off, end, oslot;
06 
07        lockdep_assert_held(&pcpu_lock);
08 
09        oslot = pcpu_chunk_slot(chunk);
10 
11        /*
12         * Search to find a fit.
13         */
14        end = start + alloc_bits + PCPU_BITMAP_BLOCK_BITS;
15        bit_off = bitmap_find_next_zero_area(chunk->alloc_map, end, start,
16                                             alloc_bits, align_mask);
17        if (bit_off >= end)
18                return -1;
19 
20        /* update alloc map */
21        bitmap_set(chunk->alloc_map, bit_off, alloc_bits);
22 
23        /* update boundary map */
24        set_bit(bit_off, chunk->bound_map);
25        bitmap_clear(chunk->bound_map, bit_off + 1, alloc_bits - 1);
26        set_bit(bit_off + alloc_bits, chunk->bound_map);
27 
28        chunk->free_bytes -= alloc_bits * PCPU_MIN_ALLOC_SIZE;
29 
30        /* update first free bit */
31        if (bit_off == chunk->first_bit)
32                chunk->first_bit = find_next_zero_bit(
33                                        chunk->alloc_map,
34                                        pcpu_chunk_map_bits(chunk),
35                                        bit_off + alloc_bits);
36 
37        pcpu_block_update_hint_alloc(chunk, bit_off, alloc_bits);
38 
39        pcpu_chunk_relocate(chunk, oslot);
40 
41        return bit_off * PCPU_MIN_ALLOC_SIZE;
42}

per-cpu 할당 영역에 대한 비트맵, 블럭 메타데이터들 및 각종 관련 정보들을 갱신한다.

  • 코드 라인 9에서 할당 영역 갱신으로 인해 슬롯 이동이 될 수 있으므로 현재 슬롯 번호를 알아온다.
  • 코드 라인 14~18에서 범위내 @align 정렬 단위로 @alloc_bits 만큼의 free 영역을 찾는다. 적합한 free 영역이 없는 경우 -1을 반환한다.
  • 코드 라인 21에서 할당 범위의 할당맵을 모두 1로 채운다.
  • 코드 라인 24~26에서 할당 범위의 경계 맵을 모두 클리어하고 시작과 끝+1 비트만 1로 설정한다.
  • 코드 라인 28에서 남은 free 바이트를 갱신한다.
  • 코드 라인 31~35에서 만일 할당한 영역이 첫 번째 free 공간인 경우 첫 번째 free 공간 비트 위치를 갱신한다.
  • 코드 라인 37에서 chunk내의 per-cpu 블럭 메타데이터들을 갱신한다.
  • 코드 라인 39에서 슬롯의 이동이 필요한 경우 갱신한다.
  • 코드 라인 41에서 할당이 성공한 경우이다. 할당된 영역의 비트 offset을 반환한다.

 


할당 페이지 범위 활성화

pcpu_populate_chunk()

mm/percpu-vm.c

01/**
02 * pcpu_populate_chunk - populate and map an area of a pcpu_chunk
03 * @chunk: chunk of interest
04 * @page_start: the start page
05 * @page_end: the end page
06 * For each cpu, populate and map pages [@page_start,@page_end) into
07 *
08 * For each cpu, populate and map pages [@page_start,@page_end) into
09 * @chunk.
10 *
11 * CONTEXT:
12 * pcpu_alloc_mutex, does GFP_KERNEL allocation.
13 */
01static int pcpu_populate_chunk(struct pcpu_chunk *chunk,
02                               int page_start, int page_end, gfp_t gfp)
03{
04        struct page **pages;
05 
06        pages = pcpu_get_pages();
07        if (!pages)
08                return -ENOMEM;
09 
10        if (pcpu_alloc_pages(chunk, pages, page_start, page_end, gfp))
11                return -ENOMEM;
12 
13        if (pcpu_map_pages(chunk, pages, page_start, page_end)) {
14                pcpu_free_pages(chunk, pages, page_start, page_end);
15                return -ENOMEM;
16        }
17        pcpu_post_map_flush(chunk, page_start, page_end);
18 
19        return 0;
20}

chunk의 요청 페이지 범위에 대해 활성화(population)한다.

  • 코드 라인 6~8에서 필요 page descriptor 만큼 할당을 받는다. 할당 실패시 -ENOMEM으로 반환한다.
  • 코드 라인 10~11에서 필요 페이지 범위를 cpu 수 만큼 할당 받는다. 할당 실패시 -ENOMEM으로 반환한다.
  • 코드 라인 13~16에서 할당받은 영역 페이지들을 vmalloc 공간에 매핑시킨다.
  • 코드 라인 17에서 매핑이 완료되면 TLB 캐시를 flush 한다.

 

pcpu_get_pages()

mm/percpu-vm.c

01/**
02 * pcpu_get_pages - get temp pages array
03 * @chunk: chunk of interest
04 *
05 * Returns pointer to array of pointers to struct page which can be indexed
06 * with pcpu_page_idx().  Note that there is only one array and accesses
07 * should be serialized by pcpu_alloc_mutex.
08 *
09 * RETURNS:
10 * Pointer to temp pages array on success.
11 */
01static struct page **pcpu_get_pages(void)
02{
03        static struct page **pages;
04        size_t pages_size = pcpu_nr_units * pcpu_unit_pages * sizeof(pages[0]);
05 
06        lockdep_assert_held(&pcpu_alloc_mutex);
07 
08        if (!pages)
09                pages = pcpu_mem_zalloc(pages_size, GFP_KERNEL);
10        return pages;
11}

chunk 할당을 위해 전체 per-cpu 유닛에 필요한 page descriptor 사이즈 만큼 메모리 할당을 받아온다.

 

pcpu_map_pages()

mm/percpu-vm.c

01/**
02 * pcpu_map_pages - map pages into a pcpu_chunk
03 * @chunk: chunk of interest
04 * @pages: pages array containing pages to be mapped
05 * @page_start: page index of the first page to map
06 * @page_end: page index of the last page to map + 1
07 *
08 * For each cpu, map pages [@page_start,@page_end) into @chunk.  The
09 * caller is responsible for calling pcpu_post_map_flush() after all
10 * mappings are complete.
11 *
12 * This function is responsible for setting up whatever is necessary for
13 * reverse lookup (addr -> chunk).
14 */
01static int pcpu_map_pages(struct pcpu_chunk *chunk,
02                          struct page **pages, int page_start, int page_end)
03{
04        unsigned int cpu, tcpu;
05        int i, err;
06 
07        for_each_possible_cpu(cpu) {
08                err = __pcpu_map_pages(pcpu_chunk_addr(chunk, cpu, page_start),
09                                       &pages[pcpu_page_idx(cpu, page_start)],
10                                       page_end - page_start);
11                if (err < 0)
12                        goto err;
13 
14                for (i = page_start; i < page_end; i++)
15                        pcpu_set_page_chunk(pages[pcpu_page_idx(cpu, i)],
16                                            chunk);
17        }
18        return 0;
19err:
20        for_each_possible_cpu(tcpu) {
21                if (tcpu == cpu)
22                        break;
23                __pcpu_unmap_pages(pcpu_chunk_addr(chunk, tcpu, page_start),
24                                   page_end - page_start);
25        }
26        pcpu_post_unmap_tlb_flush(chunk, page_start, page_end);
27        return err;
28}

할당받은 영역 페이지들을 vmalloc 공간에 매핑시킨다

  • 코드 라인 7~12에서 possible cpu 수 만큼 루프를 돌며 per-cpu chunk를 vmalloc 공간에 매핑한다.
  • 코드 라인 14~16에서 각 페이지(page->index)들이 pcpu_chunk를 가리키도록 설정한다.

 

__pcpu_map_pages()

mm/percpu-vm.c

1static int __pcpu_map_pages(unsigned long addr, struct page **pages,
2                            int nr_pages)
3{
4        return map_kernel_range_noflush(addr, nr_pages << PAGE_SHIFT,
5                                        PAGE_KERNEL, pages);
6}

할당받은 영역 페이지들을 요청 vmalloc 가상 주소 공간에 매핑시킨다

 

map_kernel_range_noflush()

mm/vmalloc.c

01/**
02 * map_kernel_range_noflush - map kernel VM area with the specified pages
03 * @addr: start of the VM area to map
04 * @size: size of the VM area to map
05 * @prot: page protection flags to use
06 * @pages: pages to map
07 *
08 * Map PFN_UP(@size) pages at @addr.  The VM area @addr and @size
09 * specify should have been allocated using get_vm_area() and its
10 * friends.
11 *                         
12 * NOTE:                               
13 * This function does NOT do any cache flushing.  The caller is
14 * responsible for calling flush_cache_vmap() on to-be-mapped areas
15 * before calling this function.
16 *
17 * RETURNS:
18 * The number of pages mapped on success, -errno on failure.
19 */
1int map_kernel_range_noflush(unsigned long addr, unsigned long size,
2                             pgprot_t prot, struct page **pages)
3{
4        return vmap_page_range_noflush(addr, addr + size, prot, pages);
5}

할당받은 영역 페이지들을 요청 vmalloc 가상 주소 공간에 vmap 매핑시킨다

 

범위의 활성화 여부

pcpu_is_populated()

mm/percpu.c

01/**
02 * pcpu_is_populated - determines if the region is populated
03 * @chunk: chunk of interest
04 * @bit_off: chunk offset
05 * @bits: size of area
06 * @next_off: return value for the next offset to start searching
07 *
08 * For atomic allocations, check if the backing pages are populated.
09 *
10 * RETURNS:
11 * Bool if the backing pages are populated.
12 * next_index is to skip over unpopulated blocks in pcpu_find_block_fit.
13 */
01static bool pcpu_is_populated(struct pcpu_chunk *chunk, int bit_off, int bits,
02                              int *next_off)
03{
04        int page_start, page_end, rs, re;
05 
06        page_start = PFN_DOWN(bit_off * PCPU_MIN_ALLOC_SIZE);
07        page_end = PFN_UP((bit_off + bits) * PCPU_MIN_ALLOC_SIZE);
08 
09        rs = page_start;
10        pcpu_next_unpop(chunk->populated, &rs, &re, page_end);
11        if (rs >= page_end)
12                return true;
13 
14        *next_off = re * PAGE_SIZE / PCPU_MIN_ALLOC_SIZE;
15        return false;
16}

@chunk에서 @bit_off부터 @bits 까지의 공간이 활성화(populate)된 상태인지 여부를 반환한다. 출력 인자 @next_off에는 다음 검색을 시작할 offset 위치가 담긴다.

 

pcpu_next_unpop()

mm/percpu.c

1static void pcpu_next_unpop(unsigned long *bitmap, int *rs, int *re, int end)
2{
3        *rs = find_next_zero_bit(bitmap, end, *rs);
4        *re = find_next_bit(bitmap, end, *rs + 1);
5}

@end 까지의 per-cpu 페이지 중 활성화되지 않은 페이지의 시작 @rs과 끝 @re를 산출한다.

 

참고

댓글 남기기