Created
December 14, 2016 16:20
-
-
Save pjhades/7b3491bfaa06ed73e7830626bcda8b96 to your computer and use it in GitHub Desktop.
eBPF program to distribute incoming traffic among multiple cores in a round-robin way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int load_bpf(int mod) | |
{ | |
int map_fd; | |
map_fd = bpf_create_map(BPF_MAP_TYPE_ARRAY, sizeof(int), | |
sizeof(uint64_t), 1); | |
if (map_fd < 0) { | |
log_error("creating BPF map failed"); | |
return map_fd; | |
} | |
struct bpf_insn prog[] = { | |
BPF_MOV64_REG(BPF_REG_6, BPF_REG_1), | |
/* store 0 at fp - 4 */ | |
/* r0 = 0 */ | |
BPF_MOV64_IMM(BPF_REG_0, 0), | |
/* *(u32 *)(fp - 4) = r0 */ | |
BPF_STX_MEM(BPF_W, BPF_REG_10, BPF_REG_0, -4), | |
/* argument 2: pointer to lookup key */ | |
/* r2 = fp */ | |
BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), | |
/* r2 -= 4 */ | |
BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), | |
/* argument 1: map fd */ | |
/* r1 = mapfd */ | |
BPF_LD_MAP_FD(BPF_REG_1, map_fd), | |
/* search the map */ | |
/* r0 = map_lookup_elem(map_fd, r2) */ | |
BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), | |
/* check result */ | |
/* if (r0 == 0) goto pc + 2 */ | |
BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 6), | |
/* if found */ | |
/* r1 = *(u64 *)(r0 + 0)*/ | |
BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_0, 0), | |
/* r1 %= mod */ | |
BPF_ALU64_IMM(BPF_MOD, BPF_REG_1, mod), | |
/* update the value in the map */ | |
/* r2 = 1 */ | |
BPF_MOV64_IMM(BPF_REG_2, 1), | |
/* *(u64 *)(r0 + 0) += r2 */ | |
BPF_RAW_INSN(BPF_STX | BPF_XADD | BPF_DW, BPF_REG_0, BPF_REG_2, 0, 0), | |
/* set return value */ | |
/* r0 = r1 */ | |
BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), | |
BPF_EXIT_INSN(), | |
/* if not found */ | |
/* r0 = 0 */ | |
BPF_MOV64_IMM(BPF_REG_0, 0), | |
BPF_EXIT_INSN(), | |
}; | |
return bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, prog, sizeof(prog), | |
"test_bpf_reuseport", 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment