Skip to content

Fix incorrect pinned maps handling and missing userspace setup code #12

@SiyuanSun0736

Description

@SiyuanSun0736

When using the pin keyword with map declarations (e.g., pin var cpu_counters : array<...>), the current implementation faces two primary issues that prevent the maps from being correctly pinned to the BPF filesystem.

The Problems

  1. Incorrect Treatment as Global Variables: The IR generator incorrectly creates both an IR map definition and an IR global variable for pinned maps. This causes the userspace codegen to treat the map as a "pinned global variable," looking for a non-existent __pinned_globals map and resulting in the error: Failed to find pinned globals map in eBPF object.
  2. Missing Setup Code: Setup and pinning logic for maps is only generated if the userspace code explicitly performs map operations. However, pinned maps require setup (pinning to /sys/fs/bpf/...) even if they are only accessed within the eBPF program itself.
  3. Variable Redefinition: If multiple pinned maps exist, the generated C code uses the same variable name (existing_fd) for all of them, leading to compilation errors.
  4. Missing Directory Creation: The generated code fails to pin maps if the parent directory (e.g., /sys/fs/bpf/<project>/maps/) does not already exist.

Proposed Changes

The provided patch addresses these issues with the following logic:

  • IR Generator: Modified ir_generator.ml to ensure that map-type global declarations only produce map definitions, not global variable entries.
  • Userspace Codegen:
  • Updated userspace_codegen.ml to trigger map setup and FD declarations if any pinned maps are detected (has_pinned_maps), regardless of whether they are used in userspace C code.
  • Implemented unique variable naming (e.g., %s_existing_fd) to prevent C redefinition errors.
  • Added a C helper function ensure_bpf_dir to recursively create the necessary BPF filesystem directories before pinning.
  • Included necessary headers (<sys/stat.h>, <sys/types.h>) when pinning is required.

fix_pin_var_map.patch

Verification

Testing with examples/maps_demo.ks confirms:

  • The "Failed to find pinned globals map" error is resolved.
  • Maps are correctly pinned to /sys/fs/bpf/maps_demo/maps/.
  • Userspace programs compile and run correctly with multiple pinned maps.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions