BPF_MAP_TYPE_SK_STORAGE
BPF_MAP_TYPE_SK_STORAGE is used to provide socket-local storage for BPF programs. A map of type BPF_MAP_TYPE_SK_STORAGE declares the type of storage to be provided and acts as the handle for accessing the socket-local storage. The values for maps of type BPF_MAP_TYPE_SK_STORAGE are stored locally with each socket instead of with the map. The kernel is responsible for allocating storage for a socket when requested and for freeing the storage when either the map or the socket is deleted.
Usage #
Kernel BPF #
bpf_sk_storage_get() #
void *Socket-local storage for map can be retrieved from socket sk using the bpf_sk_storage_get() helper. If the BPF_LOCAL_STORAGE_GET_F_CREATE flag is used then bpf_sk_storage_get() will create the storage for sk if it does not already exist. value can be used together with BPF_LOCAL_STORAGE_GET_F_CREATE to initialize the storage value, otherwise it will be zero initialized. Returns a pointer to the storage on success, or NULL in case of failure.
bpf_sk_storage_delete() #
long Socket-local storage for map can be deleted from socket sk using the bpf_sk_storage_delete() helper. Returns 0 on success, or negative error in case of failure.
User space #
bpf_map_update_elem() #
int Socket-local storage for map map_fd can be added or updated locally to a socket using the bpf_map_update_elem() libbpf function. The socket is identified by a socket fd stored in the pointer key. The pointer value has the data to be added or updated to the socket fd. The type and size of value should be the same as the value type of the map definition.
The flags parameter can be used to control the update behaviour:
-
BPF_ANYwill create storage forsocketfdor update existing storage. -
BPF_NOEXISTwill create storage forsocketfdonly if it did not already exist, otherwise the call will fail with-EEXIST. -
BPF_EXISTwill update existing storage forsocketfdif it already exists, otherwise the call will fail with-ENOENT.
Returns 0 on success, or negative error in case of failure.
bpf_map_lookup_elem() #
int Socket-local storage for map map_fd can be retrieved from a socket using the bpf_map_lookup_elem() libbpf function. The storage is retrieved from the socket identified by a socket fd stored in the pointer key. Returns 0 on success, or negative error in case of failure.
bpf_map_delete_elem() #
int Socket-local storage for map map_fd can be deleted from a socket using the bpf_map_delete_elem() libbpf function. The storage is deleted from the socket identified by a socket fd stored in the pointer key. Returns 0 on success, or negative error in case of failure.
Examples #
Kernel BPF #
This snippet shows how to declare socket-local storage in a BPF program:
socket_storage ;
This snippet shows how to retrieve socket-local storage in a BPF program:
int
Please see the tools/testing/selftests/bpf directory for functional examples.
References #
https://lwn.net/ml/netdev/20190426171103.61892-1-kafai@fb.com/