Network · Linux 6.18.37 LTS · source + diagram note

RX path

최신 LTS 기준: kernel.org longterm 6.18.37 기준으로 파일 위치와 링크를 맞춘 원본 코드 분석 노트입니다. NAPI, GRO, protocol stack 진입.

전체 흐름

network stack은 sk_buff가 driver, NAPI, protocol stack, socket, qdisc 사이를 이동하는 data-plane이다. throughput만 보면 안 되고, drop attribution과 CPU affinity를 같이 봐야 한다.

핵심 확인 사항

함수의 입력과 처리 결과를 먼저 확인한다. 구조체를 생성하고 연결하는 시점, 다른 코드에서 사용할 수 있게 하는 시점, 더 이상 사용하지 않아 회수하는 시점을 구분한다.

오류 처리 확인

정상 처리와 오류 처리를 함께 확인한다. 오류 복구, 장치의 실행 중 연결·분리(hotplug), 자원 해제 과정에서도 상태가 올바르게 정리되는지 점검한다.

그림 1. RX path 이 kernel 안에서 놓이는 위치
NIC / driverRX ring, TX completion, IRQ
→
NAPI / softirqpoll budget, GRO, backlog
→
protocol stackL2/L3/L4 dispatch
→
socket / qdiscuserspace queue and TX policy

왼쪽부터 처리 단계를 나열했다. 각 코드 조각에서 바뀌는 상태를 해당 단계와 대조한다.

소스 코드 위치

먼저 확인할 Linux 6.18.37 LTS 소스 파일

원본 코드:
Linux 6.18.37 LTS: net/core/dev.c
Linux 6.18.37 LTS: net/core/gro.c
Linux 6.18.37 LTS: net/ipv4/ip_input.c

설명: 진입 함수가 있는 파일과 구조체 정의, 아키텍처별 연결 코드, 콜백 구현을 함께 확인한다. 여러 파일을 대조해야 호출 관계와 각 코드의 역할을 알 수 있다.

대표 코드

__netif_receive_skb_core

원본 코드: net/core/dev.c:5888-6108 · v6.18.37 · 로컬 원문
__netif_receive_skb_core 함수 전체 (221줄)
static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
				    struct packet_type **ppt_prev)
{
	enum skb_drop_reason drop_reason = SKB_DROP_REASON_UNHANDLED_PROTO;
	struct packet_type *ptype, *pt_prev;
	rx_handler_func_t *rx_handler;
	struct sk_buff *skb = *pskb;
	struct net_device *orig_dev;
	bool deliver_exact = false;
	int ret = NET_RX_DROP;
	__be16 type;

	net_timestamp_check(!READ_ONCE(net_hotdata.tstamp_prequeue), skb);

	trace_netif_receive_skb(skb);

	orig_dev = skb->dev;

	skb_reset_network_header(skb);
#if !defined(CONFIG_DEBUG_NET)
	/* We plan to no longer reset the transport header here.
	 * Give some time to fuzzers and dev build to catch bugs
	 * in network stacks.
	 */
	if (!skb_transport_header_was_set(skb))
		skb_reset_transport_header(skb);
#endif
	skb_reset_mac_len(skb);

	pt_prev = NULL;

another_round:
	skb->skb_iif = skb->dev->ifindex;

	__this_cpu_inc(softnet_data.processed);

	if (static_branch_unlikely(&generic_xdp_needed_key)) {
		int ret2;

		migrate_disable();
		ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog),
				      &skb);
		migrate_enable();

		if (ret2 != XDP_PASS) {
			ret = NET_RX_DROP;
			goto out;
		}
	}

	if (eth_type_vlan(skb->protocol)) {
		skb = skb_vlan_untag(skb);
		if (unlikely(!skb))
			goto out;
	}

	if (skb_skip_tc_classify(skb))
		goto skip_classify;

	if (pfmemalloc)
		goto skip_taps;

	list_for_each_entry_rcu(ptype, &dev_net_rcu(skb->dev)->ptype_all,
				list) {
		if (pt_prev)
			ret = deliver_skb(skb, pt_prev, orig_dev);
		pt_prev = ptype;
	}

	list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
		if (pt_prev)
			ret = deliver_skb(skb, pt_prev, orig_dev);
		pt_prev = ptype;
	}

skip_taps:
#ifdef CONFIG_NET_INGRESS
	if (static_branch_unlikely(&ingress_needed_key)) {
		bool another = false;

		nf_skip_egress(skb, true);
		skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
					 &another);
		if (another)
			goto another_round;
		if (!skb)
			goto out;

		nf_skip_egress(skb, false);
		if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
			goto out;
	}
#endif
	skb_reset_redirect(skb);
skip_classify:
	if (pfmemalloc && !skb_pfmemalloc_protocol(skb)) {
		drop_reason = SKB_DROP_REASON_PFMEMALLOC;
		goto drop;
	}

	if (skb_vlan_tag_present(skb)) {
		if (pt_prev) {
			ret = deliver_skb(skb, pt_prev, orig_dev);
			pt_prev = NULL;
		}
		if (vlan_do_receive(&skb))
			goto another_round;
		else if (unlikely(!skb))
			goto out;
	}

	rx_handler = rcu_dereference(skb->dev->rx_handler);
	if (rx_handler) {
		if (pt_prev) {
			ret = deliver_skb(skb, pt_prev, orig_dev);
			pt_prev = NULL;
		}
		switch (rx_handler(&skb)) {
		case RX_HANDLER_CONSUMED:
			ret = NET_RX_SUCCESS;
			goto out;
		case RX_HANDLER_ANOTHER:
			goto another_round;
		case RX_HANDLER_EXACT:
			deliver_exact = true;
			break;
		case RX_HANDLER_PASS:
			break;
		default:
			BUG();
		}
	}

	if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
check_vlan_id:
		if (skb_vlan_tag_get_id(skb)) {
			/* Vlan id is non 0 and vlan_do_receive() above couldn't
			 * find vlan device.
			 */
			skb->pkt_type = PACKET_OTHERHOST;
		} else if (eth_type_vlan(skb->protocol)) {
			/* Outer header is 802.1P with vlan 0, inner header is
			 * 802.1Q or 802.1AD and vlan_do_receive() above could
			 * not find vlan dev for vlan id 0.
			 */
			__vlan_hwaccel_clear_tag(skb);
			skb = skb_vlan_untag(skb);
			if (unlikely(!skb))
				goto out;
			if (vlan_do_receive(&skb))
				/* After stripping off 802.1P header with vlan 0
				 * vlan dev is found for inner header.
				 */
				goto another_round;
			else if (unlikely(!skb))
				goto out;
			else
				/* We have stripped outer 802.1P vlan 0 header.
				 * But could not find vlan dev.
				 * check again for vlan id to set OTHERHOST.
				 */
				goto check_vlan_id;
		}
		/* Note: we might in the future use prio bits
		 * and set skb->priority like in vlan_do_receive()
		 * For the time being, just ignore Priority Code Point
		 */
		__vlan_hwaccel_clear_tag(skb);
	}

	type = skb->protocol;

	/* deliver only exact match when indicated */
	if (likely(!deliver_exact)) {
		deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
				       &ptype_base[ntohs(type) &
						   PTYPE_HASH_MASK]);

		/* orig_dev and skb->dev could belong to different netns;
		 * Even in such case we need to traverse only the list
		 * coming from skb->dev, as the ptype owner (packet socket)
		 * will use dev_net(skb->dev) to do namespace filtering.
		 */
		deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
				       &dev_net_rcu(skb->dev)->ptype_specific);
	}

	deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
			       &orig_dev->ptype_specific);

	if (unlikely(skb->dev != orig_dev)) {
		deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
				       &skb->dev->ptype_specific);
	}

	if (pt_prev) {
		*ppt_prev = pt_prev;
	} else {
drop:
		if (!deliver_exact)
			dev_core_stats_rx_dropped_inc(skb->dev);
		else
			dev_core_stats_rx_nohandler_inc(skb->dev);

		kfree_skb_reason(skb, drop_reason);
		/* Jamal, now you will not able to escape explaining
		 * me how you were going to use this. :-)
		 */
		ret = NET_RX_DROP;
	}

out:
	/* The invariant here is that if *ppt_prev is not NULL
	 * then skb should also be non-NULL.
	 *
	 * Apparently *ppt_prev assignment above holds this invariant due to
	 * skb dereferencing near it.
	 */
	*pskb = skb;
	return ret;
}

수신 패킷을 여러 hook과 protocol handler로 전달하는 핵심 경로다. skb가 교체되거나 다른 경로로 넘어갈 수 있으므로 pskb와 pt_prev의 소유권을 함께 읽는다. 함수명만으로 XDP, VLAN, bridge, rx_handler 등의 모든 packet이 동일한 분기를 거친다고 가정하지 않는다.

napi_poll

원본 코드: net/core/dev.c:7689-7712 · v6.18.37 · 로컬 원문
static int napi_poll(struct napi_struct *n, struct list_head *repoll)
{
	bool do_repoll = false;
	void *have;
	int work;

	list_del_init(&n->poll_list);

	have = netpoll_poll_lock(n);

	work = __napi_poll(n, &do_repoll);

	if (do_repoll) {
#if defined(CONFIG_DEBUG_NET)
		if (unlikely(!napi_is_scheduled(n)))
			pr_crit("repoll requested for device %s %ps but napi is not scheduled.\n",
				n->dev->name, n->poll);
#endif
		list_add_tail(&n->poll_list, repoll);
	}
	netpoll_poll_unlock(have);

	return work;
}

확인 사항: 이 코드에서는 반환값보다 상태 변경을 먼저 확인한다. 어느 잠금을 획득한 뒤 어떤 필드를 바꾸는지, 실패 시 어느 레이블로 분기하는지, 변경된 상태를 다음 호출자가 어떤 전제로 사용하는지 추적한다.

함수별 분석

NIC ring에서 올라온 packet을 NAPI/GRO/protocol stack/socket receive queue로 전달하는 수신 datapath다.

원본 코드를 함수별로 나누어 살펴본다. 각 함수가 준비하는 값과 다음 함수가 그 값을 사용하는 방식을 확인한다.

그림 2. RX path 함수 체인과 관찰 지점
entrycaller가 넘기는 객체와 context를 확정
→
__netif_receive_skb_coreinterrupt mitigation 시작
→
napi_pollring에서 packet 수거
→
observable statetracepoint, counter, sysfs/proc에서 확인되는 결과

각 단계의 입력과 처리 결과를 연결해 본다. 다음 단계로 넘어가기 전에 바뀌는 필드를 코드에서 확인한다.

1. __netif_receive_skb_core

__netif_receive_skb_core 주변에서는 sk_buff를 중심으로 본다. 이 필드는 packet carrier 역할을 하므로, 함수가 끝날 때 IRQ schedules NAPI 상태가 실제로 성립했는지 확인해야 한다.

원본 코드에서 입력 범위 검사, 주요 필드 변경, 다른 계층에서 사용할 수 있게 하는 시점, 실패 시 복구 순서를 확인한다. 이 조건을 만족해야 다음 함수가 interrupt mitigation 시작을 전제로 삼을 수 있다.

자주 틀리는 해석: packet이 interrupt handler 안에서 전부 처리된다고 생각함

2. napi_poll

napi_poll 주변에서는 napi_struct를 중심으로 본다. 이 필드는 poll budget state 역할을 하므로, 함수가 끝날 때 poll fetches skb 상태가 실제로 성립했는지 확인해야 한다.

원본 코드에서 입력 범위 검사, 주요 필드 변경, 다른 계층에서 사용할 수 있게 하는 시점, 실패 시 복구 순서를 확인한다. 이 조건을 만족해야 다음 함수가 ring에서 packet 수거을 전제로 삼을 수 있다.

자주 틀리는 해석: GRO 때문에 packet 수가 줄어드는 현상을 drop으로 오해함

함수입력상태 변경확인할 사항
__netif_receive_skb_coresk_buff, 호출 시 실행 문맥, 하위 시스템의 준비 조건IRQ schedules NAPI: interrupt mitigation 시작packet이 interrupt handler 안에서 전부 처리된다고 생각함 문제를 코드상 어느 조건문 또는 error label에서 분리하는가
napi_pollnapi_struct, 호출 시 실행 문맥, 하위 시스템의 준비 조건poll fetches skb: ring에서 packet 수거GRO 때문에 packet 수가 줄어드는 현상을 drop으로 오해함 문제를 코드상 어느 조건문 또는 error label에서 분리하는가

구조체와 필드

구조체의 필드를 언제 바꿀 수 있고 다른 코드가 언제 읽을 수 있는지 확인한다. 필드의 의미와 함께 잠금 등 접근을 보호하는 규칙을 살펴본다.

그림 3. RX path 핵심 필드 연결
sk_buffpacket carrier
→
napi_structpoll budget state
→
gro_listaggregation 후보
→
ptype tablesprotocol dispatch table

각 단계에서 읽고 쓰는 필드를 구조체 정의와 대조한다.

어떤 코드가 필드를 변경하고 어떤 방식으로 접근을 보호하는지, 객체를 언제 해제하는지 원본 코드에서 확인한다.

필드읽는 법
sk_buffpacket carrier
napi_structpoll budget state
gro_listaggregation 후보
ptype tablesprotocol dispatch table

실행 단계와 상태 변화

실행 단계를 따로 정리하면 정상 경로와 실패 경로를 나란히 비교할 수 있다. 커널 문제는 최종 결과보다 준비가 덜 된 중간 상태를 다른 코드에 공개한 뒤, 실패 시 제대로 정리하지 못할 때 자주 발생한다.

그림 4. RX path 실행 단계
IRQ schedules NAPIinterrupt mitigation 시작
→
poll fetches skbring에서 packet 수거
→
GRO/protocolstack으로 전달
→
socket queueduserspace wakeup 후보

화살표는 정상 진행 방향을 나타낸다. 중간 단계에서 실패하면 각 단계의 오류 처리 또는 대체 경로로 이동한다.

상태의미진입 조건깨지는 지점
IRQ schedules NAPIinterrupt mitigation 시작앞 단계의 준비와 오류 처리가 끝난 뒤다음 단계가 준비되지 않은 상태를 사용하거나 필요한 정리를 늦출 때
poll fetches skbring에서 packet 수거앞 단계의 준비와 오류 처리가 끝난 뒤다음 단계가 준비되지 않은 상태를 사용하거나 필요한 정리를 늦출 때
GRO/protocolstack으로 전달앞 단계의 준비와 오류 처리가 끝난 뒤다음 단계가 준비되지 않은 상태를 사용하거나 필요한 정리를 늦출 때
socket queueduserspace wakeup 후보앞 단계의 준비와 오류 처리가 끝난 뒤다음 단계가 준비되지 않은 상태를 사용하거나 필요한 정리를 늦출 때
RX path 검토 기준 = 상태 변화 + 소유권 변화 + 외부 공개 시점

불변 조건과 실패 사례

lifetime

RX path의 핵심 객체가 외부에 공개된 뒤에는 마지막 참조가 사라질 때까지 해제 경로가 callback, timer, IRQ, worker와 경합하지 않아야 한다.

ordering

다른 CPU나 하위 계층이 변경된 필드를 읽는다면 잠금과 메모리 배리어가 접근 순서를 어떻게 보장하는지 확인한다. 참조 횟수와 RCU로 관리하는 객체 수명도 별도로 확인한다.

오류 복구

중간 단계에서 실패하면 이미 확보한 자원을 의존 관계에 맞춰 해제해야 한다. goto 레이블이 많다면 각 분기에 도달했을 때 확보한 자원을 표로 정리한다.

bring-up symptom

임베디드 보드를 처음 구동할 때는 패닉 대신 로그 중단, 시간 초과, 장치 초기화 지연, 과도한 인터럽트 같은 증상으로 문제가 드러날 수 있다.

주의

packet이 interrupt handler 안에서 전부 처리된다고 생각함

주의

GRO 때문에 packet 수가 줄어드는 현상을 drop으로 오해함

주의

NAPI budget exhaustion을 driver bug로 단정함

계측과 검증

로그를 무작정 추가하지 말고 확인할 가설을 먼저 세운다. 상태표에서 처리가 멈춘 단계를 찾은 뒤, 상태를 바꾸는 함수와 그 결과를 사용하는 함수를 함께 살펴본다.

로그가 출력되었다고 처리가 끝난 것으로 판단하지 않는다. 원본 코드에서 로그 앞뒤의 필드 변경을 확인한다.

도구보는 것
netif_receive_skbRX path 실행이 어느 단계에서 멈추는지 확인
net_dev_xmitRX path 실행이 어느 단계에서 멈추는지 확인
dropwatchRX path 실행이 어느 단계에서 멈추는지 확인
perf record napi_pollRX path 실행이 어느 단계에서 멈추는지 확인
기본 추적 경로:
# 예시: tracefs가 켜진 보드에서 토픽별 event를 좁혀 본다.
mount -t tracefs nodev /sys/kernel/tracing
echo function_graph > /sys/kernel/tracing/current_tracer
echo ':mod:*' > /sys/kernel/tracing/set_ftrace_filter
cat /sys/kernel/tracing/trace_pipe

추가 확인 사항

  • RX path 의 state machine을 네 단계로 줄였을 때, 실제 코드에서 빠지는 intermediate state는 무엇인가?
  • RX path 의 fast path가 생략한 검사는 어느 init path 또는 slow path에서 보증되는가?
  • 실험으로 확인한다면 'packet이 interrupt handler 안에서 전부 처리된다고 생각함' 문제를 어떤 tracepoint와 counter로 분리할 수 있는가?
  • 실험으로 확인한다면 'GRO 때문에 packet 수가 줄어드는 현상을 drop으로 오해함' 문제를 어떤 tracepoint와 counter로 분리할 수 있는가?