Repository: rex-rs/rex Branch: main Commit: fbb60edcdb10 Files: 226 Total size: 606.4 KB Directory structure: gitextract_lgp5l1or/ ├── .github/ │ ├── dependabot.yml │ └── workflows/ │ ├── dco-check.yml │ ├── memcached_benchmark.yml │ ├── meson.yml │ ├── rustfmt.yml │ └── update-nix.yml ├── .gitignore ├── .gitmodules ├── Cargo.toml ├── LICENSE ├── README.md ├── docs/ │ ├── entry-insertion.md │ ├── exception-handling.md │ ├── getting-started.md │ ├── kernel-symbols.md │ ├── librex.md │ └── rust_rex_subset.md ├── flake.nix ├── librex/ │ ├── .gitignore │ ├── include/ │ │ └── librex.h │ ├── lib/ │ │ ├── bindings.h │ │ └── librex.cpp │ └── meson.build ├── meson.build ├── rex/ │ ├── .cargo/ │ │ └── config.toml │ ├── .gitignore │ ├── Cargo.toml │ ├── build.py │ ├── build.rs │ ├── librexstub/ │ │ └── lib.c │ ├── meson.build │ └── src/ │ ├── base_helper.rs │ ├── bindings/ │ │ ├── linux/ │ │ │ ├── kernel.rs │ │ │ └── mod.rs │ │ ├── mod.rs │ │ └── uapi/ │ │ ├── linux/ │ │ │ ├── bpf.rs │ │ │ ├── errno.rs │ │ │ ├── in.rs │ │ │ ├── mod.rs │ │ │ ├── perf_event.rs │ │ │ ├── pkt_cls.rs │ │ │ ├── ptrace.rs │ │ │ ├── seccomp.rs │ │ │ └── unistd.rs │ │ └── mod.rs │ ├── debug.rs │ ├── ffi.rs │ ├── kprobe/ │ │ ├── kprobe_impl.rs │ │ └── mod.rs │ ├── lib.rs │ ├── log.rs │ ├── map.rs │ ├── panic.rs │ ├── per_cpu.rs │ ├── perf_event/ │ │ ├── mod.rs │ │ └── perf_event_impl.rs │ ├── pt_regs.rs │ ├── random32.rs │ ├── sched_cls/ │ │ ├── mod.rs │ │ └── sched_cls_impl.rs │ ├── spinlock.rs │ ├── task_struct.rs │ ├── tracepoint/ │ │ ├── binding.rs │ │ ├── mod.rs │ │ └── tp_impl.rs │ ├── utils.rs │ └── xdp/ │ ├── mod.rs │ └── xdp_impl.rs ├── rex-macros/ │ ├── .gitignore │ ├── Cargo.toml │ └── src/ │ ├── args.rs │ ├── kprobe.rs │ ├── lib.rs │ ├── perf_event.rs │ ├── tc.rs │ ├── tracepoint.rs │ └── xdp.rs ├── rex-native.ini ├── rustfmt.toml ├── samples/ │ ├── .clang-format │ ├── .gitignore │ ├── atomic/ │ │ ├── .cargo/ │ │ │ └── config.toml │ │ ├── Cargo.toml │ │ ├── clippy.toml │ │ ├── event-trigger.c │ │ ├── loader.c │ │ ├── meson.build │ │ ├── rustfmt.toml │ │ └── src/ │ │ └── main.rs │ ├── bmc/ │ │ ├── .cargo/ │ │ │ └── config.toml │ │ ├── Cargo.toml │ │ ├── clippy.toml │ │ ├── entry.c │ │ ├── meson.build │ │ ├── rustfmt.toml │ │ └── src/ │ │ └── main.rs │ ├── electrode/ │ │ ├── .cargo/ │ │ │ └── config.toml │ │ ├── Cargo.toml │ │ ├── clippy.toml │ │ ├── config.txt │ │ ├── entry.c │ │ ├── fast_common.h │ │ ├── meson.build │ │ ├── rustfmt.toml │ │ └── src/ │ │ ├── common.rs │ │ ├── main.rs │ │ └── maps.rs │ ├── error_injector/ │ │ ├── .cargo/ │ │ │ └── config.toml │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ ├── clippy.toml │ │ ├── loader.c │ │ ├── meson.build │ │ ├── src/ │ │ │ └── main.rs │ │ ├── tests/ │ │ │ └── runtest.py │ │ └── userapp.c │ ├── hello/ │ │ ├── .cargo/ │ │ │ └── config.toml │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ ├── clippy.toml │ │ ├── event-trigger.c │ │ ├── loader.c │ │ ├── meson.build │ │ ├── rustfmt.toml │ │ ├── src/ │ │ │ └── main.rs │ │ └── tests/ │ │ └── runtest.py │ ├── map_bench/ │ │ ├── .cargo/ │ │ │ └── config.toml │ │ ├── Cargo.toml │ │ ├── bench.sh │ │ ├── clippy.toml │ │ ├── event-trigger.c │ │ ├── loader.c │ │ ├── meson.build │ │ ├── rustfmt.toml │ │ └── src/ │ │ └── main.rs │ ├── map_test/ │ │ ├── .cargo/ │ │ │ └── config.toml │ │ ├── Cargo.toml │ │ ├── clippy.toml │ │ ├── event-trigger.c │ │ ├── loader.c │ │ ├── meson.build │ │ ├── rustfmt.toml │ │ ├── src/ │ │ │ └── main.rs │ │ └── tests/ │ │ └── runtest.py │ ├── map_test_2/ │ │ ├── .cargo/ │ │ │ └── config.toml │ │ ├── Cargo.toml │ │ ├── clippy.toml │ │ ├── event-trigger.c │ │ ├── loader.c │ │ ├── meson.build │ │ ├── rustfmt.toml │ │ ├── src/ │ │ │ └── main.rs │ │ └── tests/ │ │ └── runtest.py │ ├── meson.build │ ├── recursive/ │ │ ├── .cargo/ │ │ │ └── config.toml │ │ ├── Cargo.toml │ │ ├── bench.sh │ │ ├── clippy.toml │ │ ├── event-trigger.c │ │ ├── loader.c │ │ ├── meson.build │ │ ├── rustfmt.toml │ │ └── src/ │ │ └── main.rs │ ├── spinlock_cleanup_benchmark/ │ │ ├── .cargo/ │ │ │ └── config.toml │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ ├── clippy.toml │ │ ├── loader.c │ │ ├── meson.build │ │ ├── rustfmt.toml │ │ └── src/ │ │ └── main.rs │ ├── spinlock_test/ │ │ ├── .cargo/ │ │ │ └── config.toml │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ ├── clippy.toml │ │ ├── event-trigger.c │ │ ├── loader.c │ │ ├── meson.build │ │ ├── rustfmt.toml │ │ └── src/ │ │ └── main.rs │ ├── startup_overhead_benchmark/ │ │ ├── .cargo/ │ │ │ └── config.toml │ │ ├── .gitignore │ │ ├── Cargo.toml │ │ ├── clippy.toml │ │ ├── event-trigger.c │ │ ├── loader.c │ │ ├── meson.build │ │ ├── rustfmt.toml │ │ └── src/ │ │ └── main.rs │ ├── syscount/ │ │ ├── .cargo/ │ │ │ └── config.toml │ │ ├── Cargo.toml │ │ ├── clippy.toml │ │ ├── loader.c │ │ ├── meson.build │ │ ├── rustfmt.toml │ │ └── src/ │ │ └── main.rs │ └── xdp_test/ │ ├── .cargo/ │ │ └── config.toml │ ├── Cargo.toml │ ├── README.md │ ├── clippy.toml │ ├── entry.c │ ├── meson.build │ ├── rustfmt.toml │ ├── src/ │ │ └── main.rs │ └── tests/ │ └── runtest.py ├── scripts/ │ ├── cargo-wrapper.pl │ ├── q-script/ │ │ ├── .config │ │ ├── nix-q │ │ ├── sanity-test-q │ │ └── yifei-q │ └── sanity_tests/ │ └── run_tests.py └── tools/ └── memcached_benchmark/ ├── .cargo/ │ └── config.toml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── bench.py ├── flake.nix ├── rustfmt.toml ├── src/ │ ├── cli.rs │ ├── dict.rs │ ├── fs.rs │ ├── get_values.rs │ ├── main.rs │ └── set_values.rs └── tests/ └── benchmark_test.rs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: - package-ecosystem: cargo directories: - / - tools/memcached_benchmark schedule: interval: weekly cooldown: # applies only to non-security updates semver-patch-days: 3 # wait 3 days before applying patch updates semver-minor-days: 7 semver-major-days: 14 - package-ecosystem: github-actions directory: / schedule: interval: weekly # - package-ecosystem: gitsubmodule # directory: / # schedule: # interval: weekly ================================================ FILE: .github/workflows/dco-check.yml ================================================ name: DCO Check on: pull_request: jobs: check: runs-on: ubuntu-latest steps: - uses: KineticCafe/actions-dco@6e1652ef3027ce128e65e6edd215ae053350bd16 # v2.1.1 ================================================ FILE: .github/workflows/memcached_benchmark.yml ================================================ name: memcached_benchmark on: push: pull_request: env: CARGO_TERM_COLOR: always jobs: changes: if: github.repository == 'rex-rs/rex' runs-on: ubuntu-latest permissions: pull-requests: read outputs: bench: ${{ steps.filter.outputs.bench }} steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: filter with: filters: | bench: - 'tools/memcached_benchmark/**' build: needs: changes if: ${{ needs.changes.outputs.bench == 'true' }} runs-on: ubuntu-latest defaults: run: working-directory: ./tools/memcached_benchmark steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - id: filter uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 with: filters: | bench: - 'tools/memcached_benchmark/**' - uses: cachix/install-nix-action@616559265b40713947b9c190a8ff4b507b5df49b # v31.10.4 - name: Build run: nix develop --command bash -e -c 'cargo fmt --check --verbose && cargo build -r --verbose' - name: Run tests run: nix develop --command bash -e -c 'cargo test --verbose && cargo test -r --verbose' ================================================ FILE: .github/workflows/meson.yml ================================================ name: Meson Build and Test on: push: branches: [main, ci] pull_request: branches: [main] env: CARGO_TERM_COLOR: always jobs: changes: if: github.repository == 'rex-rs/rex' runs-on: ubuntu-latest permissions: pull-requests: read outputs: meson: ${{ steps.filter.outputs.meson }} nix: ${{ steps.filter.outputs.nix }} steps: # For pull requests it's not necessary to checkout the code - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: filter with: predicate-quantifier: 'every' filters: | nix: &nix - '**' - '!docs/**' - '!tools/**' - '!**/*.md' - '!.github/workflows/!(meson).yml' meson: - *nix - '!flake.nix' - '!flake.lock' build_and_test: needs: changes if: ${{ needs.changes.outputs.meson == 'true' }} runs-on: [self-hosted, gentoo] concurrency: group: build_and_test-${{ github.ref_name }} cancel-in-progress: true steps: - name: Checkout repository uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: submodules: recursive - name: Cache Rex build directory uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 with: path: build key: ${{ runner.os }}-${{ runner.name }}-meson-${{ hashFiles('rex-native.ini', 'meson.build') }} - name: Setup Rex build directory run: meson setup --native-file rex-native.ini --reconfigure ./build - name: Compile Rex deps run: meson compile -C build build_deps - name: Compile Rex samples run: meson compile -C build - name: Run Rex sanity tests run: meson test -C build # build_with_nix: # needs: changes # if: ${{ needs.changes.outputs.nix == 'true' }} # runs-on: [self-hosted, nix] # concurrency: # group: build_with_nix_fhs-${{ github.ref_name }} # cancel-in-progress: true # steps: # - name: Checkout repository # uses: actions/checkout@v4 # with: # submodules: recursive # # - name: Setup Rex build directory # run: meson setup --native-file rex-native.ini --reconfigure ./build # shell: nix develop -v -L .#rex --command bash -e {0} # # - name: Compile Rex deps # run: meson compile -C build build_deps # shell: nix develop -v -L .#rex --command bash -e {0} # # - name: Compile Rex samples # run: meson compile -C build # shell: nix develop -v -L .#rex --command bash -e {0} build_with_nix_fhs: needs: changes if: ${{ needs.changes.outputs.nix == 'true' }} runs-on: [self-hosted, nix] concurrency: group: build_with_nix_fhs-${{ github.ref_name }} cancel-in-progress: true steps: - name: Checkout repository uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: submodules: recursive - name: Setup Rex build directory run: nix run .#fhsExec -- -c "meson setup --native-file rex-native.ini --reconfigure ./build" - name: Compile Rex deps run: nix run .#fhsExec -- -c "meson compile -C build build_deps" - name: Compile Rex samples run: nix run .#fhsExec -- -c "meson compile -C build" ================================================ FILE: .github/workflows/rustfmt.yml ================================================ name: Formatting check on: push: pull_request: jobs: formatting: if: github.repository == 'rex-rs/rex' name: cargo fmt runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: submodules: true - name: Determine nightly date from rust submodule id: rust-version run: | # compiler_date in src/stage0 is the previous stable's release date, # which is the same day the beta branch is cut and nightly bumps forward. # The day before is the last nightly that matches this version's rustfmt. COMPILER_DATE=$(grep '^compiler_date=' rust/src/stage0 | cut -d= -f2) NIGHTLY_DATE=$(date -d "${COMPILER_DATE} - 1 day" +%Y-%m-%d) echo "nightly_date=${NIGHTLY_DATE}" >> "$GITHUB_OUTPUT" echo "Using nightly-${NIGHTLY_DATE}" - name: Install matching rust nightly env: NIGHTLY_DATE: ${{ steps.rust-version.outputs.nightly_date }} run: | rustup toolchain install "nightly-${NIGHTLY_DATE}" --component rustfmt rustup default "nightly-${NIGHTLY_DATE}" - name: formatting rex code run: cargo fmt --verbose --check - name: formatting samples code run: | for d in $(find ./samples -name Cargo.toml); do echo "→ Processing $d" cargo fmt --manifest-path $d --verbose --check done ================================================ FILE: .github/workflows/update-nix.yml ================================================ name: Update Nix Dependencies on: workflow_dispatch: # push: # branches: [ ci ] # for testing schedule: - cron: '0 0 * * 1' # Monday morning at 00:00 UTC permissions: contents: write pull-requests: write jobs: update-nix: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v6 with: token: ${{ secrets.GITHUB_TOKEN }} - name: Install Nix uses: DeterminateSystems/nix-installer-action@main - name: Update root flake.lock uses: DeterminateSystems/update-flake-lock@main with: commit-msg: "nix: update root flake.lock" pr-title: "nix-flake: update nix dependencies" pr-labels: | dependencies nix pr-body: | Automated update of nix flake dependencies. Updated lock files: - `flake.lock` - `tools/memcached_benchmark/flake.lock` - name: Update memcached_benchmark flake.lock uses: DeterminateSystems/update-flake-lock@main with: flake-lock-path: tools/memcached_benchmark/flake.lock commit-msg: "nix: update memcached_benchmark flake.lock" pr-title: "nix-flake: update nix dependencies" pr-labels: | dependencies nix pr-body: | Automated update of nix flake dependencies. Updated lock files: - `flake.lock` - `tools/memcached_benchmark/flake.lock` ================================================ FILE: .gitignore ================================================ .vscode* .cargo !samples/*/.cargo !tools/*/.cargo samples/*/event-trigger samples/*/loader samples/*/entry samples/*/.cache test_dict.yml.zst bench_entries.yml.zst compile_commands.json !rex/.cargo # Generated by Cargo # will have compiled files and executables target/ .direnv .envrc .cache ================================================ FILE: .gitmodules ================================================ [submodule "linux"] path = linux url = git@github.com:rex-rs/linux.git branch = rex-linux [submodule "rust"] path = rust url = git@github.com:rex-rs/rust.git branch = rex-rust ================================================ FILE: Cargo.toml ================================================ [workspace] members = [ # rex lib "rex", # macros "rex-macros", ] resolver = "2" exclude = ["samples", "rust", "tools", "scripts"] [workspace.package] authors = ["Rex Contributors"] repository = "https://github.com/rex-rs/rex" edition = "2021" [workspace.dependencies] proc-macro-error = { version = "1.0", default-features = false } proc-macro2 = { version = "1", default-features = false } paste = { version = "1" } syn = { version = "2", features = ["full"] } quote = { version = "1" } rex-macros = { path = "./rex-macros" } [profile.dev] debug = 0 panic = "abort" [profile.release] debug = 0 panic = "abort" lto = true ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ================================================ FILE: README.md ================================================ ``` ____ _______ __ _____ _ _ | _ \| ____\ \/ / | ____|_ _| |_ ___ _ __ ___(_) ___ _ __ ___ | |_) | _| \ / | _| \ \/ / __/ _ \ '_ \/ __| |/ _ \| '_ \/ __| | _ <| |___ / \ | |___ > <| || __/ | | \__ \ | (_) | | | \__ \ |_| \_\_____/_/\_\ |_____/_/\_\\__\___|_| |_|___/_|\___/|_| |_|___/ ``` # Rex Kernel Extensions [![CI](https://img.shields.io/github/actions/workflow/status/rex-rs/rex/.github%2Fworkflows%2Fmeson.yml?label=ci)](https://github.com/rex-rs/rex/actions) [![Gentoo](./docs/image/gentoo-badge3.svg)](https://www.gentoo.org) #### Table of Contents - [What is Rex](#what-is-rex) - [Example program](#example-program) - [Build and run](#build-and-run) - [Documentations](#documentations) - [Why Rex](#why-rex) - [License](#license) ## What is Rex Rex is a safe and usable kernel extension framework that allows loading and executing Rust kernel extension programs in the place of eBPF. Unlike eBPF-based frameworks such as [Aya](https://aya-rs.dev), Rex programs do not go through the in-kernel verifier, instead, the programs are implemented in the safe subset of Rust, on which the Rust compiler performs the needed safety checks and generates native code directly. This approach avoids the overly restricted verification requirements (e.g., program complexity constraints) and the resulting arcane verification errors, while at the same time potentially provides a better optimization opportunity in the native compiler backend (i.e., LLVM) than the eBPF backend + in-kernel JIT approach. Rex currently supports the following features: - 5 eBPF program types: `kprobe`, `perf_event`, `tracepoint`, `xdp`, and `tc`. - invocation of eBPF helper functions that are commonly used by these programs - interaction with eBPF maps - RAII-style management of kernel resources obtainable by programs - cleanup and in-kernel exception handling of Rust runtime panics with call stack traces - kernel stack (only when CFG cannot be computed statically) and termination safety from a thin in-kernel runtime - bindings and abstractions of kernel data types commonly needed by eBPF programs ## Example program The following example implements a kprobe program that attaches to a selected system call and injects an error (specified by `errno`) to the system call on a process (specified by its `pid`). The full example, including the loader program, can be found under [samples/error_injector](samples/error_injector). ```Rust #![no_std] #![no_main] use rex::kprobe::kprobe; use rex::map::RexHashMap; use rex::pt_regs::PtRegs; use rex::rex_kprobe; use rex::rex_map; use rex::Result; #[allow(non_upper_case_globals)] #[rex_map] static pid_to_errno: RexHashMap = RexHashMap::new(1, 0); #[rex_kprobe] pub fn err_injector(obj: &kprobe, ctx: &mut PtRegs) -> Result { obj.bpf_get_current_task() .map(|t| t.get_pid()) .and_then(|p| obj.bpf_map_lookup_elem(&pid_to_errno, &p).cloned()) .map(|e| obj.bpf_override_return(ctx, e)) .ok_or(0) } ``` More sample programs can be found under [samples](samples). ## Build and run You can find the detailed guide [here](docs/getting-started.md). ## Documentations Additional design documentations can be found under [docs](docs). ## Why Rex The existing eBPF extension relies on the in-kernel eBPF verifier to provide safety guarantees. This unfortunately leads to usability issues where safe programs are rejected by the verifier, including but not limited to: - programs may exceed the inherent complexity contraints of static verification - compilers may not generate verifier-friendly code - same logic may need to be implemented in a certain way to please the verifier Rex aims to address these issues by directly leveraging the safety guarantee from _safe Rust_. Developers can implement their programs in any way that can be written in safe Rust with [few restrictions](docs/rust_rex_subset.md), and no longer need to worry about program complexity, the code generator, or finding the (many time counter-intuitive) way of expressing the same logic to please the verifier. We demonstrate this with the implementation of the [BPF Memcached Cache (BMC)](https://github.com/Orange-OpenSource/bmc-cache), a state-of-the-art extension program for Memcached acceleration. As a complex eBPF program, BMC is forced to be splitted into several components connected by BPF tail-calls and use awkward loop/branch implementations to please the verifier, which are totally not needed in [its Rex implementation](samples/bmc). For example, we show the code in cache invalidation logic of the BPF-BMC that searches for a `SET` command in the packet payload: ```C // Searches for SET command in payload for (unsigned int off = 0; off < BMC_MAX_PACKET_LENGTH && payload + off + 1 <= data_end; off++) { if (set_found == 0 && payload[off] == 's' && payload + off + 3 <= data_end && payload[off + 1] == 'e' && payload[off + 2] == 't') { off += 3; set_found = 1; } ... } ``` The code not only introduces an extra constraint in the loop (`off < BMC_MAX_PACKET_LENGTH`) solely for passing the verifier, but also employs repeated boilerplate code to check packet ends (`data_end`) and cumbersome logic to match the `"set"` string in the packet. None of these burdens is needed with the power of safe Rust in Rex, which has no complexity limits and provides more freedom on the implementation: ```rust let set_iter = payload.windows(4).enumerate().filter_map(|(i, v)| { if v == b"set " { Some(i) } else { None } }); ``` The full implementation of BMC in Rex can be found at [samples/bmc](samples/bmc). ## License Rex is licensed under the GPLv2 license. The submodules (Linux, Rust, LLVM) in this repo are licensed under their own terms. Please see the corresponding license files for more details. Additionally, the memcached benchmark is licensed under the MIT license. ## Talks - Open Source Summit North America 2025: https://youtu.be/4r7ECxEaGqM - USENIX ATC 2025: https://youtu.be/phJ-fb5lEA8 - Linux Plumbers Conference 2025: https://youtu.be/ivcLS4LFfKE ================================================ FILE: docs/entry-insertion.md ================================================ # Entry point code Insertion ## Motivation To allow Rust extension code to be called from the kernel, an FFI entry-point function is needed to wrap around the user-defined extension function. This wrapper function needs to handle certain unsafe operations, for example, context conversion for XDP and perf event programs. Because of this, it should never be implemented by the user. For example, interpreting an XDP context as perf event context and perform the context conversion specific to perf-event clearly violates memory and type safety and could result in undefined behavior. Therefore, we choose to automatically generate the entry point code during compilation for the Rust extension programs. Since Rust by default uses LLVM as its code generation backend. We performs the generation of entry code in the middle-end on LLVM IR. ## Implementation The entry point insertion is implemented as an LLVM pass (`RexEntryInsertion`) that operates on the compilation unit that contains the Rust extension programs. This LLVM pass can be enabled via the `enable_rex` codegen option in rustc, which sets the corresponding pass for the LLVM backend. Take the [error_injector sample](../samples//error_injector/src/main.rs) as an example: ```Rust #![no_std] #![no_main] use rex::kprobe::kprobe; use rex::map::RexHashMap; use rex::pt_regs::PtRegs; use rex::rex_kprobe; use rex::rex_map; use rex::Result; #[allow(non_upper_case_globals)] #[rex_map] static pid_to_errno: RexHashMap = RexHashMap::new(1, 0); #[rex_kprobe] pub fn err_injector(obj: &kprobe, ctx: &mut PtRegs) -> Result { obj.bpf_get_current_task() .map(|t| t.get_pid()) .and_then(|p| obj.bpf_map_lookup_elem(&pid_to_errno, &p).cloned()) .map(|e| obj.bpf_override_return(ctx, e)) .ok_or(0) } ``` Here, the [`rex_kprobe`](https://github.com/rex-rs/rex/blob/93777ca3ad238ad3ace1d45614933f277ab587e8/rex-macros/src/lib.rs#L47) proc-macro defines a kprobe program object in section (`rex/kprobe/*`) using the [`const`](https://doc.rust-lang.org/std/keyword.const.html#compile-time-evaluable-functions) function `kprobe::new`, which takes the program function `rex_kprobe` is specified on and its literal name as arguments: ```Rust #![no_std] #![no_main] use rex::kprobe::kprobe; use rex::map::RexHashMap; use rex::pt_regs::PtRegs; use rex::rex_kprobe; use rex::rex_map; use rex::Result; #[allow(non_upper_case_globals)] #[rex_map] static pid_to_errno: RexHashMap = RexHashMap::new(1, 0); pub fn err_injector(obj: &kprobe, ctx: &mut PtRegs) -> Result { obj.bpf_get_current_task() .map(|t| t.get_pid()) .and_then(|p| obj.bpf_map_lookup_elem(&pid_to_errno, &p).cloned()) .map(|e| obj.bpf_override_return(ctx, e)) .ok_or(0) } #[used] #[link_section = "rex/kprobe"] static PROG_err_injector: kprobe = kprobe::new(err_injector, "err_injector"); ``` Under the hood, the `kprobe` object is defined as the following: ```Rust #[repr(C)] pub struct kprobe { rtti: u64, prog: fn(&Self, &mut PtRegs) -> Result, name: &'static str, } ``` The `rtti` field stores the corresponding [`bpf_prog_type`](https://elixir.bootlin.com/linux/v5.15.128/source/include/uapi/linux/bpf.h#L919) enum value (i.e. `BPF_PROG_TYPE_KPROBE` in this case). `prog` is a function pointer that points to the user-defined extension program function. `name` holds the user-intended name of the program, in a string literal form (as mentioned above, the proc-macros in `rex-macros` always set this to the literal name of the program function). At LLVM-IR level, the `RexEntryInsertion` will iterate over all global variables and look for variables with the special `rex/*` sections generated by proc-macros from `rex-macros`. For the found program objects, it will then generate the entry point based on the object contents. Because the `kprobe::new` function is a `const` function. The object is initialized with a constant expression that can be parsed by the `RexEntryInsertion` pass. This effectively allows the pass to obtain the program type (via `rtti`), the actual extension function (via `prog`), and the intended name (via `name`). The pass will construct a new `fn (*const()) -> u32` function with the specified name and eBPF link section, which will be used as the entry point function the kernel can invoke. This function takes in the context pointer (as `*mut ()`) and invokes the special program-type-specific entry function in the `rex` crate. The code of the aforementioned example would be modified as (the process happens at LLVM-IR stage, but here Rust is used for clarity): ```Rust #![no_std] #![no_main] use rex::kprobe::kprobe; use rex::map::RexHashMap; use rex::pt_regs::PtRegs; use rex::rex_kprobe; use rex::rex_map; use rex::Result; #[allow(non_upper_case_globals)] #[rex_map] static pid_to_errno: RexHashMap = RexHashMap::new(1, 0); #[inline(always)] pub fn err_injector(obj: &kprobe, ctx: &mut PtRegs) -> Result { obj.bpf_get_current_task() .map(|t| t.get_pid()) .and_then(|p| obj.bpf_map_lookup_elem(&pid_to_errno, &p).cloned()) .map(|e| obj.bpf_override_return(ctx, e)) .ok_or(0) } #[used] #[link_section = "rex/kprobe"] static PROG_err_injector: kprobe = kprobe::new(err_injector, "err_injector");); #[link_section = "kprobe"] #[no_mangle] pub fn err_injector(ctx: *mut ()) -> u32 { rex::__rex_entry_kprobe(&PROG_err_injector, ctx) } ``` `__rex_entry_kprobe` is the tracepoint specific entry function defined in the `rex` crate (not to be confused with the generated kernel entry point). The function essentially calls `kprobe::prog_run` that converts the context to the type specific to the program and invokes the `prog` function. In this way the program context conversion and other preparation for execution is safely abstracted away from the users. ### Add new program type support The only file needs to be updated is [llvm/include/llvm/Transforms/Rex/RexProgType.def](https://github.com/rex-rs/llvm-project/blob/rex-llvm-rebase/llvm/include/llvm/Transforms/Rex/RexProgType.def). The basic syntex is: ```C REX_PROG_TYPE_1(, , ) ``` If the program type has more than 1 section names, use `REX_PROG_TYPE_2` instead, which will support 2 names. Therefore, for `tracepoint` this is: ```C REX_PROG_TYPE_2(BPF_PROG_TYPE_TRACEPOINT, tracepoint, "tracepoint", "tp") ``` Relevant files: - LLVM pass: - [llvm/lib/Transforms/Rex/RexInsertEntry.cpp](https://github.com/rex-rs/llvm-project/blob/rex-llvm-rebase/llvm/lib/Transforms/Rex/RexInsertEntry.cpp) - [llvm/include/llvm/Transforms/Rex/RexInsertEntry.h](https://github.com/rex-rs/llvm-project/blob/rex-llvm-rebase/llvm/include/llvm/Transforms/Rex/RexInsertEntry.h) - [llvm/include/llvm/Transforms/Rex/RexProgType.def](https://github.com/rex-rs/llvm-project/blob/rex-llvm-rebase/llvm/include/llvm/Transforms/Rex/RexProgType.def) - Program-type-specific entry function (defined using the `define_prog_entry` macro): - [rex/src/lib.rs](https://github.com/rex-rs/rex/blob/main/rex/src/lib.rs) - Kprobe implementation (can be generalized to other programs): - [rex/src/kprobe/kprobe_impl.rs](https://github.com/rex-rs/rex/blob/main/rex/src/kprobe/kprobe_impl.rs) ================================================ FILE: docs/exception-handling.md ================================================ # Exception handling and runtime mechanism This document will cover the following: - [Handling of Rust panics (language exceptions)](#handling-of-rust-panics-in-kernel-space) - [Kernel dispatch and landingpad](#kernel-stack-unwinding) - [Rust panic handler and cleanup mechanism](#resource-cleanup-in-rust) ## Handling of Rust panics in kernel space In userspace, Rust panics are essentially the same as C++ exceptions and are handled based on [Itanium ABI](https://llvm.org/docs/ExceptionHandling.html#itanium-abi-zero-cost-exception-handling). That is, when a panic is triggered, the control flow will be redirect to the unwind library (e.g. `libgcc` or `llvm-libunwind`). The unwind library will then unwind the program stack. For each function call frame, it will invoke the `personality` routine to look for feasible landingpads which contains cleaup and (possibly) exception handling code. The unwind process ends when either the exception is handled (e.g. by a C++ `catch`) or no handler is found. P.S. The actual Itanium ABI is more complicated than described here, e.g. the unwind library runs two passes on the stack, once for searching landingpads, and another time for executing landingpads code. However, the Itanium EH ABI is not suitable in our case for the following reasons: - It adds too much complexity, as the userspace unwind libraries are not directly usable. - It usually requires dynamic allocation for certain exception contexts, which may not be available to kernel extensions (e.g. kprobe executes in interrupt contexts and is therefore not sleepable). - It allows failures during the unwinding which cannot be tolerated in kernel space. Incomplete cleanup means leaking kernel resources. - It generally executes destructors for all existing objects on the stack, but executing untrusted, user-defined destructors (via the `Drop` trait in Rust) may not be safe. Therefore, in our framework we implement our exception handling mechanism. It can be divided into two parts: stack unwinding in the kernel and resource cleanup in the runtime crate. ### Kernel stack unwinding We need to be able support graceful exception handling in kernel space, i.e. the extension program should be terminated without bringing down the kernel. The idea is to transfer the exceptional control flow back to the return address of the extension program and reset the stack and frame pointer to ensure the context remains valid. In this way, the program would act as if it just returned normally. The implementation consists the `rex_dispatcher_func` to dispatch Rex programs so that rust panics can be handled. The dispatcher have a prototype of: ```C extern asmlinkage unsigned int rex_dispatcher_func( const void *ctx, const struct bpf_prog *prog, unsigned int (*bpf_func)(const void *, const struct bpf_insn *)); ``` which shares a similar signature as `bpf_dispatcher_nop_func` but with the `struct bpf_insn` array argument replaced by a pointer to the program struct, as Rex does not work with eBPF bytecode. The function first saves the current stack pointer to the top of the per-CPU Rex-specific stack, and then switches the stack before calling into the program. If the execution is successful (i.e. no exceptions), the function will just return normally and the old stack pointer will be restored with a `pop`. ``` +-----------------------+ | rex_dispatcher_func: | | ... | | movq %gs:rex_sp, %rbp | | movq %rsp, (%rbp) | | movq %rbp, %rsp | +-----------+ | call *%rdx |--------------->| rex_prog: | | | | ... | | rex_exit: |<---------------| ret | | popq %rsp | +-----------+ | ... | | ret | +-----------------------+ ``` Under exceptional cases (where a rust panic is fired), `rust_begin_unwind` (i.e. panic handler) will transfer the control flow to the `rex_landingpad` C function in the kernel, which, after dumping some information to the kernel ring buffer, will call `rex_landingpad_asm`. `rex_landingpad_asm` sets a default reutrn value, restores the stack pointer to the top of the Rex stack, i.e. the same address when program returns without an exception, and issues an direct jump to the `rex_exit` label in the middle of `rex_dispatcher_func`. ``` +-----------------------+ | rex_dispatcher_func: | | ... | | movq %gs:rex_sp, %rbp | | movq %rsp, (%rbp) | | movq %rbp, %rsp | +-----------+ | call *%rdx |--------------->| rex_prog: | | | +------| ... | +---->| rex_exit: | | | ret | | | popq %rsp | | +-----------+ | | ... | | | | ret | | panic!() | | | | | | rex_landingpad_asm: |<-----+ | +-------------------------+ | | ... | | +----->| rex_landingpad: | | | movq %gs:rex_sp, %rsp | | | ... | +-----| jmp rex_exit | +---------| call rex_landingpad_asm | +-----------------------+ +-------------------------+ ``` The Rex stack uses the same layout as other kernel stacks -- the pointer to the previous stack is stored in the top-most entry of the Rex stack. This, combined with `bpf-ksyms`, allows smooth integration with the ORC unwinder and provides meaningful stack traces: ```console [ 12.568364][ T208] rex: Panic from Rex prog: called `Option::unwrap()` on a `None` value [ 12.568622][ T208] CPU: 3 UID: 0 PID: 208 Comm: userapp Not tainted 6.13.0-rex+ #226 [ 12.568854][ T208] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.16.3-20240910_120124-localhost 04/01/2014 [ 12.569236][ T208] Call Trace: [ 12.569345][ T208] [ 12.569428][ T208] dump_stack_lvl+0x6e/0xa8 [ 12.569559][ T208] rex_landingpad+0x64/0xb0 [ 12.569704][ T208] rex_prog_4168211f00000000::rust_begin_unwind+0x15a/0x1a0 [ 12.569944][ T208] rex_prog_4168211f00000000::core::panicking::panic_fmt+0x9/0x10 [ 12.570188][ T208] rex_prog_4168211f00000000::core::panicking::panic+0x53/0x60 [ 12.570423][ T208] rex_prog_4168211f00000000::core::option::unwrap_failed+0x9/0x10 [ 12.570668][ T208] rex_prog_4168211f00000000::err_injector+0x8f/0xa0 [ 12.570879][ T208] rex_dispatcher_func+0x32/0x32 [ 12.571045][ T208] [ 12.571137][ T208] [ 12.571229][ T208] trace_call_bpf+0x1a1/0x1f0 [ 12.571363][ T208] ? __x64_sys_dup+0x1/0xd0 [ 12.571468][ T208] kprobe_perf_func+0x4e/0x260 [ 12.571582][ T208] ? kmem_cache_free+0x29/0x290 [ 12.571718][ T208] ? __cfi___x64_sys_dup+0x10/0x10 [ 12.571879][ T208] kprobe_ftrace_handler+0x115/0x1a0 [ 12.572046][ T208] ? __x64_sys_dup+0x5/0xd0 [ 12.572189][ T208] 0xffffffffa02010c8 [ 12.572310][ T208] ? __x64_sys_dup+0x1/0xd0 [ 12.572452][ T208] __x64_sys_dup+0x5/0xd0 [ 12.572582][ T208] do_syscall_64+0x42/0xb0 [ 12.572722][ T208] entry_SYSCALL_64_after_hwframe+0x4b/0x53 [ 12.572910][ T208] RIP: 0033:0x7f6039f0ee9d [ 12.573050][ T208] Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 90 f3 0f 1e fa 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 8b 0d 33 bf 0b 00 f7 d8 64 89 01 48 [ 12.573579][ T208] RSP: 002b:00007ffd562cee08 EFLAGS: 00000246 ORIG_RAX: 0000000000000020 [ 12.573779][ T208] RAX: ffffffffffffffda RBX: 00007ffd562cef28 RCX: 00007f6039f0ee9d [ 12.573967][ T208] RDX: 000055cc27f9b988 RSI: 00007ffd562cef38 RDI: 0000000000000000 [ 12.574150][ T208] RBP: 0000000000000001 R08: 00007f6039ffada0 R09: 000055cc27f9a730 [ 12.574348][ T208] R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000 [ 12.574600][ T208] R13: 00007ffd562cef38 R14: 00007f603a02a000 R15: 000055cc27f9b988 [ 12.574810][ T208] ``` For further information please refer to the [actual code](https://github.com/rex-rs/linux/blob/rex-linux/arch/x86/net/rex_64.S). ### Resource cleanup in Rust Not using the existing ABI-based exception handling / stack unwinding scheme means we need to handle resource cleanup in our own way. We make the observation that the only resources that requires cleanup are the resources obtained from kernel helper functions. This is because of the restricted programing interface exposed to these extension programs, which disallow direct kernel resource alloation (e.g. allocate memory, directly access a lock, etc). This brings us chance to create a light-weight resource clean up scheme. We can record allocated kernel resources and their destructors on-the-fly during program execution. When termination is needed, the destructors of allocated resources are invoked to release the resources. Since only the trusted kernel crate that interfaces with the kernel resources is responsible for implementing the aforementioned destructors, all the cleanup code is trusted and guaranteed not to fail. The PoC implemention uses `CleanupEntry` to represent an allocated resource: ```Rust pub(crate) type CleanupFn = fn(*const ()) -> (); #[derive(Debug, Copy, Clone)] #[repr(C)] pub(crate) struct CleanupEntry { pub(crate) valid: u64, pub(crate) cleanup_fn: Option, pub(crate) cleanup_arg: *const (), } ``` An instance of the struct is supposed to be instantiated in the constructor of the kernel resource binding types in the runtime crate: - `valid` should be set to 1 - `cleanup_fn` should point to a function provided in `impl` of the binding type, which takes in a pointer to the object and runs `drop` on it. The `drop` handler is also responsible for setting `valid` to 0. - `cleanup_arg` should point to the newly created object. It is used as the argument to `cleanup_fn`. Note: 1. `valid` field is of type `u64`. This may not seem space effcient at a glance, but since both `cleanup_fn` and `cleanup_arg` are 64 bit large. The alignment of the struct is 64 bits anyway. 2. According to [Rustonomicon](https://doc.rust-lang.org/nomicon/repr-rust.html) and [Rust doc](https://doc.rust-lang.org/std/option/#representation), `Option` has the same size and bit-level representation as `CleanupFn` as long as it is a `Some`. This is important because on the kernel side it can be treated as a `void (*)(void *)`. The created struct is then stored in a per-CPU array `rex_cleanup_entries` in the kernel. This also implies that a C binding for `CleanupEntry` is needed in the kernel: ```C struct rex_cleanup_entry { u64 valid; void *cleanup_fn; void *cleanup_arg; }; ``` Note: 1. Using `void *` to store function pointer is not standard compliant, though at ABI level it is always a 64-bit value and should work correctly. We should change it to a real function pointer: `void (*)(void *)`. 2. Currently, the array is statically allocated with a capacity of 64. This **may not** be sustainable. During normal execution, the `drop` handlers are executed normally so the kernel resource will be released and the `CleanupEntry` will be invalidated. Upon a panic, the control flow will transfer to `rust_begin_unwind` (i.e. the Rust panic handler). `rust_begin_unwind` will traverse the array on current CPU and free any resources allocated by invoking `(cleanup_fn)(cleanup_arg)`. It then invalidate these entries. Code references: 1. [Rust side `CleanupEntry` and panic handler implementation](https://github.com/rex-rs/rex/blob/main/rex/src/panic.rs) 2. [Kernel side binding type and per-CPU array](https://github.com/rex-rs/linux/blob/cd07f685c08b6087da0b1468a97d75c3de51e296/kernel/bpf/core.c#L3146) ================================================ FILE: docs/getting-started.md ================================================ # Getting started (p20250206) Building Rex extensions requires modifications to the toolchain (Rust and LLVM) and running Rex extensions requires modifications to the Linux kernel. The steps below describe how to set up both the toolchain and kernel for running Rex extensions in a VM. Rex currently only supports the `x86-64` (`amd64`) architecture. Running Rex in VMs addtionally requires [`KVM`](https://linux-kvm.org/page/Main_Page) to be available on the host machine. ## Nix flake Using Nix, a package manager, allows you to bypass these dependency requirements below. Check out the https://nixos.org/download/ for installation instructions, the single-user installation should be sufficient. ## Dependencies: The following tools/libraries are required. Older versions are not guaranteed to (or guaranteed not to) work. This list does not include standard kernel build dependencies. - `clang+LLVM (>= 18.1.0)` - `cmake` - `elfutils` - `libstdc++ (>=13)` for missing `c++23` support in LLVM's `libcxx` - `meson` - `mold` - `ninja` - `python (>= 3.11)` - `QEMU` - `rust-bindgen` ## Repo setup and build Clone this repo and its submodules: ```bash git clone https://github.com/rex-rs/rex.git rex-kernel cd rex-kernel git submodule update --init --progress ``` If you are using Nix, the following additional step is required. ```bash nix develop --extra-experimental-features nix-command --extra-experimental-features flakes ``` It will launch a Nix shell with all necessary dependencies installed. All subsequent steps should be carried out within this shell. Rex uses `meson` as its build system, to get started, first set up `meson` in Rex: ```bash meson setup --native-file rex-native.ini ./build/ ``` Rex requries the modified kernel and its `libbpf` library, which resides in the `linux` directory after submodule initialization. Rex also uses custom LLVM passes in the Rust compiler to generate additional code and instruments the extension programs, therefore, [bootstraping](https://en.wikipedia.org/wiki/Bootstrapping_(compilers)) the Rust compiler is required. The Rust toolchain source can be found under the `rust` directory as another submodule. Building these dependencies is a one-time effort with the following command: ```bash meson compile -C build build_deps ``` This will build the kernel and its `libbpf`. It will also bootstrap the Rust compiler and build the relevant tools (e.g., `cargo`, `clippy`, etc). With the linux and Rust setup, all Rex sample programs can then be built with: ```bash meson compile -C build ``` ## Run `hello` example First boot the VM: ```bash cd build/linux ../../scripts/q-script/yifei-q # use ../scripts/q-script/nix-q instead if you are using Nix ``` Inside the VM: ```bash cd ../samples/hello ./loader & ./event-trigger ``` The following output should be printed out: ```console <...>-245 [002] d...1 18.417331: bpf_trace_printk: Rust triggered from PID 245. ``` ## Troubleshooting ### Building dependencies: This step includes compiling the Linux kernel which can get quite resource intensive. In our tests `6GB` is the minimum value for which compiling Linux is possible, this means you might not be able to use Rex on machines with 6GB or less RAM. A sign that you ran into Out-Of-Memory (OOM) error is if you encounter this warning: ```bash /root/rex/linux/scripts/link-vmlinux.sh: line 113: 55407 Killed LLVM_OBJCOPY="${OBJCOPY}" ${PAHOLE} -J ${PAHOLE_FLAGS} ${1} ``` And error: ```bash FAILED: load BTF from vmlinux: invalid argument ``` Or similar problems. For WSL users, it is recommended to allocate more RAM to WSL before starting this step since WSL by default only utilizes half the RAM available on the host machine: From a Powershell instance, create and open a `.wslconfig` file in your home directory: ```bash notepad $HOME/.wslconfig ``` Add the following lines to the file then save: ```bash [wsl2] memory=8GB swap=8GB ``` You should change the value to how much memory you want to allocate to WSL. Another issue that may happen is bootstrap failure due to the missing `libLLVM-19-rex.so`: ```console --- stderr llvm-config: error: libLLVM-19-rex.so is missing thread 'main' panicked at compiler/rustc_llvm/build.rs:264:16: command did not execute successfully: "/home/chin39/Documents/rex-kernel/build/rust-build/x86_64-unknown-linux-gnu/llvm/bin/llvm-config" "--link-shared" "--libs" "--system-libs" "asmparser" "bitreader" "bitwriter" "coverage" "instrumentation" "ipo" "linker" "lto" "x86" expected success, got: exit status: 1 stack backtrace: 0: rust_begin_unwind at /rustc/9fc6b43126469e3858e2fe86cafb4f0fd5068869/library/std/src/panicking.rs:665:5 1: core::panicking::panic_fmt at /rustc/9fc6b43126469e3858e2fe86cafb4f0fd5068869/library/core/src/panicking.rs:76:14 2: build_script_build::output 3: build_script_build::main 4: core::ops::function::FnOnce::call_once note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace. Build completed unsuccessfully in 0:00:12 FAILED: cargo rustc env 'RUSTFLAGS=-Z threads=8 -C target-cpu=native -C codegen-units=1 -C link-arg=-fuse-ld=mold -C link-arg=-Wl,-O1 -C link-arg=-Wl,--as-needed -C link-arg=-flto=thin' /usr/bin/python3 ../rust/x.py install --config=../rust/rex-config.toml --build-dir=./rust-build --set install.prefix=./rust-dist ninja: build stopped: subcommand failed. ``` Notably this may happen as a result of [`ba85ec815c2f ("rust: enable more optimizations and features in bootstrap config")`](https://github.com/rex-rs/rex/commit/ba85ec815c2fc9721e3b466d1c296bd7dd79b1b3), as it changes the linkage of `libLLVM` from static to dynamic, but rust bootstrap process does not rebuild `libLLVM.so` following the change. The issue can be fixed by removing the build directory created by meson and starting a clean build. ### Building the Rex samples: There are some caveats before you run this step. By default the `ninja` build tool uses a quite high level of parallelism, which might again cause OOM on personal machines. A sign of this happenning is if you try this step and run into similar errors to: ```bash error: could not compile `core` (lib) Caused by: process didn't exit successfully: ``` To resolve this problem, try running with fewer commands in parallel using the `-j` argument, for example to run with 4 commands in parallel: ```bash meson compile -C build -j 4 ``` Our tests indicate a peak memory usage of 12GB with `-j 8`, so if you have less RAM it's helpful to keep the `-j` argument below 8. ### Booting the QEMU VM: By default our QEMU VM runs on 8GB of memory. To reduce this, open the qemu scripts using an editor and locate line 300: ```bash MEMORY=8192 ``` And change this value to the number you want. Rex has been tested to work with 4GB or `MEMORY=4096`. ================================================ FILE: docs/kernel-symbols.md ================================================ # Handling of kernel symbols This document covers dynamic kernel symbol resolution. The `rex` crate serves as an interface for the extension programs to interact with the kernel. To accomplish this, the crate will need to access kernel symbols. For example, invoking kernel helper functions requires knowing the kernel address of the target helper function symbol. These kernel symbols includes not only BPF helper functions, but also certain per-cpu variables and other kernel functions (these comes partly from our previous effort on rewriting kernel helpers, but it is also used by the stack unwind/protection and panic cleanup mechanism). Before [`36b91e1aab92: ("libiu: support dynamic symbol relocation")`](https://github.com/rex-rs/rex/commit/36b91e1aab92a28cf341852c1ffd187597736d60), the `rex` crate directly compiles the address of the kernel symbols in. The build script uses `nm` to resolve addresses of the needed kernel symbols (specified in a special section of `Cargo.toml`) and generates the `stub.rs` file. The rest of the crate can use the generated `xxx_addr` function to get the address of kernel symbol `xxx` as an `u64`. The code can then transmute the value into the appropriate type (e.g. a function pointer for helper functions). This way of kernel symbol resolution causes several problems: 1. The compiled executable will contain kernel addresses, which should not be leaked to userspace. 2. It requires KASLR to be turned off (because addresses from `nm`/`System.map` are static), which is not portable on KASLR-enabled kernels. 3. When ever kernel image layout changes (e.g. changes in function offset), the extension program needs to be re-compiled. 4. The transmuted stub becomes a function pointer for helper functions, which, after inlining, hinders further optimization on stack instrumentation (the instrumentation can only be omitted if there are no indirect calls / recursions). Therefore, it is reasonable to defer the kernel symbol resolution to load time. At this point, the kernel always knows where the symbols are located (even with KASLR), which solves problems 2 and 3. At the same time, the final executable will not contain any actual kernel address, addressing problem 1. In order to avoid the need of an indirect call (problem 4), we choose to implement the kernel symbol resolution the same way dynamic linking works in userspace -- declare the needed kernel symbols as external symbols and let the compiler generate relocation entries for these symbols. The new implementation involves the following: 1. Declare the needed kernel symbols as `extern "C"` and with appropriate type. For example `bpf_probe_read_kernel` is declared as: ```Rust extern "C" { /// `long bpf_probe_read_kernel(void *dst, u32 size, const void *unsafe_ptr)` pub(crate) fn bpf_probe_read_kernel( dst: *mut (), size: u32, unsafe_ptr: *const (), ) -> i64; } ``` `extern "C"` specifies that the symbol uses the C ABI, which matches that of the actual in-kernel object/function (check the [Rustonomicon](https://doc.rust-lang.org/nomicon/other-reprs.html) for more information). The declarations can be found in [`src/stub.rs`](https://github.com/rex-rs/rex/blob/main/rex/src/stub.rs). 2. To make it easy to generate the relocations, we add a dummy library, [`librexstub`](https://github.com/rex-rs/rex/tree/main/rex/librexstub), that provides "fake" definitions of the symbols. The extension programs will link against this library dynamically so that a dynamic relocation entry is generated for each kernel symbol and the linker will not complain about undefined symbols. For example, dumping relocations for the [`error_injector`](https://github.com/rex-rs/rex/tree/main/samples/error_injector) sample gives the following: ```console $ objdump -R target/x86_64-unknown-none/release/error_injector target/x86_64-unknown-none/release/error_injector: file format elf64-x86-64 DYNAMIC RELOCATION RECORDS OFFSET TYPE VALUE 0000000000003e58 R_X86_64_RELATIVE *ABS*+0x0000000000002029 0000000000003e68 R_X86_64_RELATIVE *ABS*+0x0000000000002000 0000000000003fc0 R_X86_64_RELATIVE *ABS*+0x0000000000001210 0000000000003ff8 R_X86_64_RELATIVE *ABS*+0x0000000000001020 0000000000003fb8 R_X86_64_GLOB_DAT this_cpu_off 0000000000003fc8 R_X86_64_GLOB_DAT pcpu_hot 0000000000003fd0 R_X86_64_GLOB_DAT rex_cleanup_entries 0000000000003fd8 R_X86_64_GLOB_DAT rex_landingpad 0000000000003fe0 R_X86_64_GLOB_DAT just_return_func 0000000000003fe8 R_X86_64_GLOB_DAT rex_termination_state 0000000000003ff0 R_X86_64_GLOB_DAT bpf_map_lookup_elem ``` The relocations with type `R_X86_64_GLOB_DAT` are the kernel symbol relocations generated from dynamic linking, where the `OFFSET` denotes the address offset within the binary and the `VALUE` specifies the actual symbol name. Other relocations with type `R_X86_64_RELATIVE` are a result from position-independent executables (PIE). In PIE, function invocations involve a IP-relative call that indexes into the global offset table (GOT) that stores the absolute address of the function. The GOT entries are generated as relocations that are patched at the program load time. For example, `3fc0 R_X86_64_RELATIVE *ABS*+0x1270` specifies that the value at offset `3fc0` of the binary needs to be patched to the absolute start address of the binary (after it is mapped into memory) plus `0x1270`. The library exists solely for the generation of relocations, it is never mapped into the kernel with the program and the symbols defined in the library are therefore never accessed. At the same time, because the symbols are not accessed, their types are not relevant, only the name matters. The build script of the `rex` crate automatically builds the library and adds the needed linker flags so that users can just use `cargo` to build the programs. 3. At load time, librex parses the relocation entries to find out the offsets and symbol names (accessible by symbol table index), and send them to the kernel. The decision to let the loader library parse the relocation entries is to reduce the complexity of code in the kernel and take advantage of the existing userspace ELF libraries (we use `elfutils`, the same library used by `libbpf`). Each dynamic symbol relocation is the stored in an [`rex_dyn_sym`](https://github.com/rex-rs/linux/blob/cd07f685c08b6087da0b1468a97d75c3de51e296/include/uapi/linux/bpf.h#L1472-L1475) struct: ```C struct rex_dyn_sym { __u64 offset; // symbol offset __u64 symbol; // symbol name string (actually a char *) }; ``` When invoking the `bpf(2)` syscall to load the program, the library will pass an array of `struct rex_dyn_sym` to the kernel (by setting pointer to the start address and the size in the [`bpf_attr`](https://github.com/rex-rs/linux/blob/cd07f685c08b6087da0b1468a97d75c3de51e296/include/uapi/linux/bpf.h#L1591-L1592) union). The kernel copies the array into kernel space and queries each symbol name against `kallsyms` to lookup the in-kernel address of the symbol, it then patches the value at the specified offset to that address. The same symbol resolution mechanism is applied to maps as well. ================================================ FILE: docs/librex.md ================================================ # LIBREX `librex` serves as the loader library for Rex programs -- similar to what `libbpf` is to eBPF programs -- but in a simpler way. ### APIs `librex` only contains the code that loads Rex programs from ELF binaries, other operations (e.g., attachment, map manipulation, etc) are delegated to the existing code in `libbpf`. Therefore, the library only exposes the following simple APIs: ```c struct rex_obj *rex_obj_load(const char *file_path); struct bpf_object *rex_obj_get_bpf(struct rex_obj *obj); void rex_set_debug(int val); ``` The `rex_obj_load` function loads the Rex programs from the ELF binary identified by the `file_path` argument into the kernel. It returns a pointer to the corresponding `rex_obj` that encapsulates information about the loaded programs and created maps. If there is an error, a null pointer is returned. The `rex_obj_get_bpf` returns a pointer to the equivalent `bpf_object` of the `obj` argument, which can be subsequently passed to `libbpf` APIs. If there is an error, a null pointer is returned. **Note**: The returned pointer from both functions above are **non-owning** pointers, which means the caller of these function should not try to `free`/`realloc`/`delete` the pointer. The ownership of the pointers is managed by `librex` internally and will be automatically freed after the program terminates. The `rex_set_debug` function can be used to toggle the internal logging mechanism of `librex` (with `(bool)val` determining whether logging is enabled). This will most likely be helpful during debugging. ================================================ FILE: docs/rust_rex_subset.md ================================================ ### Rex subset of Rust - `std` - depends on libc, therefore not available in standalone mode - `alloc` - Rex currently does not hook onto kernel's allocator - unsafe - can break any safety guarrantee - `core::mem::forget` and `core::mem::ManuallyDrop` - take ownership and “forget” about the value **without running its destructor**. - lifetime related: disrupts resource cleanup - `core::intrinsics::abort`: - uses an illegal instruction and therefore can crash the kernel. - `core::simd` - no simd/fp allowed in the kernel in the first place ================================================ FILE: flake.nix ================================================ { description = "A flake for the REX project"; inputs = { nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; }; outputs = { self, nixpkgs, ... }: let system = "x86_64-linux"; basePkgs = import nixpkgs { inherit system; }; remoteNixpkgsPatches = [ { meta.description = "cc-wrapper: remove -nostdlibinc"; url = "https://github.com/chinrw/nixpkgs/commit/2a5bd9cecd9ae28d899eb9bf434255a9fa09cbb0.patch"; sha256 = "sha256-TBmNtH8C5Vp1UArLtXDk+dxEzUR3tohjPMpJc9pIEN8="; } ]; patchedNixpkgsSrc = basePkgs.applyPatches { name = "nixpkgs-patched"; src = basePkgs.path; patches = map basePkgs.fetchpatch remoteNixpkgsPatches; }; # patchedBindgen = # (self: super: { # rust-bindgen-unwrapped = super.rust-bindgen-unwrapped.overrideAttrs (finalAttrs: oldAttrs: { # src = super.fetchFromGitHub { # owner = "rust-lang"; # repo = "rust-bindgen"; # rev = "20aa65a0b9edfd5f8ab3e038197da5cb2c52ff18"; # sha256 = "sha256-OrwPpXXfbkeS7SAmZDZDUXZV4BfSF3e/58LJjedY1vA="; # }; # cargoDeps = pkgs.rustPlatform.fetchCargoVendor { # inherit (finalAttrs) pname src version; # hash = finalAttrs.cargoHash; # }; # cargoHash = "sha256-e94pwjeGOv/We6uryQedj7L41dhCUc2wzi/lmKYnEMA="; # }); # }); patchedPkgs = import patchedNixpkgsSrc { inherit system; # overlays = [ patchedBindgen ]; }; pkgs = import nixpkgs { inherit system; # overlays = [ overrideLLVM ]; }; wrapCC = cc: pkgs.wrapCCWith { inherit cc; extraBuildCommands = '' # Remove the line that contains "-nostdlibinc" sed -i 's|-nostdlibinc||g' "$out/nix-support/cc-cflags" echo " -resource-dir=${pkgs.llvmPackages.clang}/resource-root" >> "$out/nix-support/cc-cflags" echo > "$out/nix-support/add-local-cc-cflags-before.sh" ''; }; # wrappedClang = wrapCC pkgs.llvmPackages.clang.cc; # lib = nixpkgs.lib; # Use unwrapped clang & lld to avoid warnings about multi-target usage rexPackages = with pkgs; [ # Kernel builds autoconf bc binutils bison cmake diffutils elfutils elfutils.dev fakeroot findutils flex git gcc getopt gnumake ncurses openssl openssl.dev pkg-config xz xz.dev zlib zlib.dev bpftools cargo-pgo ninja patchedPkgs.rust-bindgen pahole strace zstd perf-tools # linuxKernel.packages.linux_latest.perf # Clang kernel builds patchedPkgs.llvmPackages.clang patchedPkgs.llvmPackages.llvm # wrappedClang # llvmPackages.libcxxStdenv lld mold qemu file util-linux hostname sysctl perf-tools # for llvm/Demangle/Demangle.h libllvm.lib libllvm.dev libgcc libclang.lib libclang.dev # meson deps meson curl perl bear # generate compile commands rsync # for make headers_install gdb # bmc deps iproute2 memcached python3 # Rex utils zoxide # in case host is using zoxide openssh # q-script ssh support bat fd eza zsh ]; llvmBuildFHSEnv = pkgs.buildFHSEnv.override { stdenv = pkgs.llvmPackages.stdenv; }; fhsBase = { name = "rex-env"; targetPkgs = pkgs: rexPackages ++ [ pkgs.systemd pkgs.file ]; profile = '' export NIX_ENFORCE_NO_NATIVE=0 export PATH=$(realpath "./build/rust-dist/bin"):$PATH export RUST_BACKTRACE=1 ''; }; fhsRex = llvmBuildFHSEnv (fhsBase // { runScript = "zsh"; }); # FHS environment for running arbitrary commands fhsExec = llvmBuildFHSEnv (fhsBase // { name = "rex-exec"; runScript = pkgs.writeScript "fhs-exec-wrapper" '' #!${pkgs.bash}/bin/bash exec bash "$@" ''; }); in { devShells."${system}" = { default = fhsRex.env; rex = pkgs.mkShell { packages = rexPackages; # Disable default hardening flags. These are very confusing when doing # development and they break builds of packages/systems that don't # expect these flags to be on. Automatically enables stuff like # FORTIFY_SOURCE, -Werror=format-security, -fPIE, etc. See: # - https://nixos.org/manual/nixpkgs/stable/#sec-hardening-in-nixpkgs # - https://nixos.wiki/wiki/C#Hardening_flags hardeningDisable = [ "all" ]; LD_LIBRARY_PATH = "${pkgs.stdenv.cc.cc.lib.outPath}/lib:${pkgs.lib.makeLibraryPath rexPackages}:$LD_LIBRARY_PATH"; shellHook = '' export NIX_CC_WRAPPER_SUPPRESS_TARGET_WARNING=1 export PATH=$(realpath "./build/rust-dist/bin"):$PATH # Add required llvm-config export PATH=${patchedPkgs.llvmPackages.libllvm.out}/bin:$PATH export PATH=${patchedPkgs.llvmPackages.libllvm.dev}/bin:$PATH export RUST_BACKTRACE=1 export NIX_ENFORCE_NO_NATIVE=0 export LLVM_SRC_INC="$PWD/rust/src/llvm-project/llvm/include" # export LLVM_BUILD_INCLUDE="$PWD/build/rust-build/x86_64-unknown-linux-gnu/llvm/build/include" export NIX_CFLAGS_COMPILE_BEFORE="-I$LLVM_SRC_INC" echo "loading rex env" ''; }; }; packages."${system}" = { fhsRex = fhsRex; fhsExec = fhsExec; }; }; } ================================================ FILE: librex/.gitignore ================================================ librex.a librex.o librex.so .cache ================================================ FILE: librex/include/librex.h ================================================ #ifndef LIBREX_H #define LIBREX_H struct bpf_object; struct rex_obj; #ifdef __cplusplus extern "C" { #endif [[gnu::visibility("default")]] void rex_set_debug(int val); [[nodiscard, gnu::visibility("default")]] struct rex_obj * rex_obj_load(const char *file_path); [[nodiscard, gnu::visibility("default")]] struct bpf_object * rex_obj_get_bpf(struct rex_obj *obj); #ifdef __cplusplus } #endif #endif // LIBREX_H ================================================ FILE: librex/lib/bindings.h ================================================ // This file contains the non-portable part, it has to mirror some libbpf types #ifndef _LIBREX_BINDINGS_H #define _LIBREX_BINDINGS_H #include #include /* From tools/lib/bpf/libbpf_internal.h */ #define SHA256_DIGEST_LENGTH 32 struct elf_state { int fd; const void *obj_buf; size_t obj_buf_sz; Elf *elf; Elf64_Ehdr *ehdr; Elf_Data *symbols; Elf_Data *arena_data; size_t shstrndx; /* section index for section name strings */ size_t strtabidx; struct elf_sec_desc *secs; size_t sec_cnt; int btf_maps_shndx; __u32 btf_maps_sec_btf_id; int text_shndx; int symbols_shndx; bool has_st_ops; int arena_data_shndx; int jumptables_data_shndx; }; struct bpf_sec_def { char *sec; enum bpf_prog_type prog_type; enum bpf_attach_type expected_attach_type; long cookie; int handler_id; libbpf_prog_setup_fn_t prog_setup_fn; libbpf_prog_prepare_load_fn_t prog_prepare_load_fn; libbpf_prog_attach_fn_t prog_attach_fn; }; enum bpf_object_state { OBJ_OPEN, OBJ_PREPARED, OBJ_LOADED, }; struct bpf_object { char name[BPF_OBJ_NAME_LEN]; char license[64]; __u32 kern_version; enum bpf_object_state state; struct bpf_program *programs; size_t nr_programs; struct bpf_map *maps; size_t nr_maps; size_t maps_cap; char *kconfig; struct extern_desc *externs; int nr_extern; int kconfig_map_idx; bool has_subcalls; bool has_rodata; struct bpf_gen *gen_loader; /* Information when doing ELF related work. Only valid if efile.elf is not * NULL */ struct elf_state efile; unsigned char byteorder; struct btf *btf; struct btf_ext *btf_ext; /* Parse and load BTF vmlinux if any of the programs in the object need * it at load time. */ struct btf *btf_vmlinux; /* Path to the custom BTF to be used for BPF CO-RE relocations as an * override for vmlinux BTF. */ char *btf_custom_path; /* vmlinux BTF override for CO-RE relocations */ struct btf *btf_vmlinux_override; /* Lazily initialized kernel module BTFs */ struct module_btf *btf_modules; bool btf_modules_loaded; size_t btf_module_cnt; size_t btf_module_cap; /* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */ char *log_buf; size_t log_size; __u32 log_level; int *fd_array; size_t fd_array_cap; size_t fd_array_cnt; struct usdt_manager *usdt_man; int arena_map_idx; void *arena_data; size_t arena_data_sz; void *jumptables_data; size_t jumptables_data_sz; struct { struct bpf_program *prog; int sym_off; int fd; } *jumptable_maps; size_t jumptable_map_cnt; struct kern_feature_cache *feat_cache; char *token_path; int token_fd; char path[]; }; struct bpf_light_subprog; /* * bpf_prog should be a better name but it has been used in * linux/filter.h. */ struct bpf_program { char *name; char *sec_name; size_t sec_idx; const struct bpf_sec_def *sec_def; /* this program's instruction offset (in number of instructions) * within its containing ELF section */ size_t sec_insn_off; /* number of original instructions in ELF section belonging to this * program, not taking into account subprogram instructions possible * appended later during relocation */ size_t sec_insn_cnt; /* Offset (in number of instructions) of the start of instruction * belonging to this BPF program within its containing main BPF * program. For the entry-point (main) BPF program, this is always * zero. For a sub-program, this gets reset before each of main BPF * programs are processed and relocated and is used to determined * whether sub-program was already appended to the main program, and * if yes, at which instruction offset. */ size_t sub_insn_off; /* instructions that belong to BPF program; insns[0] is located at * sec_insn_off instruction within its ELF section in ELF file, so * when mapping ELF file instruction index to the local instruction, * one needs to subtract sec_insn_off; and vice versa. */ struct bpf_insn *insns; /* actual number of instruction in this BPF program's image; for * entry-point BPF programs this includes the size of main program * itself plus all the used sub-programs, appended at the end */ size_t insns_cnt; struct reloc_desc *reloc_desc; int nr_reloc; /* BPF verifier log settings */ char *log_buf; size_t log_size; __u32 log_level; struct bpf_object *obj; int fd; bool autoload; bool autoattach; bool sym_global; bool mark_btf_static; enum bpf_prog_type type; enum bpf_attach_type expected_attach_type; int exception_cb_idx; int prog_ifindex; __u32 attach_btf_obj_fd; __u32 attach_btf_id; __u32 attach_prog_fd; void *func_info; __u32 func_info_rec_size; __u32 func_info_cnt; void *line_info; __u32 line_info_rec_size; __u32 line_info_cnt; __u32 prog_flags; __u8 hash[SHA256_DIGEST_LENGTH]; struct bpf_light_subprog *subprogs; __u32 subprog_cnt; }; enum libbpf_map_type { LIBBPF_MAP_UNSPEC, LIBBPF_MAP_DATA, LIBBPF_MAP_BSS, LIBBPF_MAP_RODATA, LIBBPF_MAP_KCONFIG, }; struct bpf_map_def { unsigned int type; unsigned int key_size; unsigned int value_size; unsigned int max_entries; unsigned int map_flags; }; struct bpf_map { struct bpf_object *obj; char *name; /* real_name is defined for special internal maps (.rodata*, * .data*, .bss, .kconfig) and preserves their original ELF section * name. This is important to be able to find corresponding BTF * DATASEC information. */ char *real_name; int fd; int sec_idx; size_t sec_offset; int map_ifindex; int inner_map_fd; struct bpf_map_def def; __u32 numa_node; __u32 btf_var_idx; int mod_btf_fd; __u32 btf_key_type_id; __u32 btf_value_type_id; __u32 btf_vmlinux_value_type_id; enum libbpf_map_type libbpf_type; void *mmaped; struct bpf_struct_ops *st_ops; struct bpf_map *inner_map; void **init_slots; int init_slots_sz; char *pin_path; bool pinned; bool reused; bool autocreate; bool autoattach; __u64 map_extra; struct bpf_program *excl_prog; }; #endif // _LIBREX_BINDINGS_H ================================================ FILE: librex/lib/librex.cpp ================================================ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "bindings.h" #include "librex.h" using namespace std::literals; namespace { int debug = 0; bool sec_def_matches(const struct bpf_sec_def *sec_def, std::string_view sec_name) { std::string_view sec_pfx(sec_def->sec); // "type/" always has to have proper SEC("type/extras") form if (sec_pfx.back() == '/') return sec_name.starts_with(sec_pfx); // "type+" means it can be either exact SEC("type") or // well-formed SEC("type/extras") with proper '/' separator if (sec_pfx.back() == '+') { size_t pfx_size; sec_pfx.remove_suffix(1); pfx_size = sec_pfx.size(); // not even a prefix if (!sec_name.starts_with(sec_pfx)) return false; // exact match or has '/' separator return sec_name.size() == pfx_size || sec_name[pfx_size] == '/'; } return sec_name == sec_pfx; } /// @brief Walk through the static const struct bpf_sec_def section_defs /// in libbpf.c and figure out the valid bpf section /// /// @param sec_name section for our own rex prog /// @return section_defs const bpf_sec_def *find_sec_def(std::string_view sec_name) { for (size_t i = 0; i < global_bpf_section_defs.size; i++) { if (!sec_def_matches(&global_bpf_section_defs.arr[i], sec_name)) continue; return &global_bpf_section_defs.arr[i]; } return nullptr; } inline long bpf(__u64 cmd, union bpf_attr *attr, unsigned int size) { return syscall(__NR_bpf, cmd, attr, size); } inline uint64_t align_up_16(uint64_t val) { return (val & 0xf) ? (val & ~0xf) + 0x10 : val; } } // end anonymous namespace // This struct is POD, meaning the C++ standard guarantees the same memory // layout as that of the equivalent C struct // https://stackoverflow.com/questions/422830/structure-of-a-c-object-in-memory-vs-a-struct struct map_def { uint32_t map_type; uint32_t key_size; uint32_t val_size; uint32_t max_size; uint32_t map_flag; void *kptr; }; struct rex_map { private: map_def def; std::optional map_fd; std::string name; public: rex_map() = delete; rex_map(const Elf_Data *data, Elf64_Addr base, Elf64_Off off, const char *c_name) : map_fd(), name(c_name) { auto def_addr = reinterpret_cast(data->d_buf) + off - base; this->def = *reinterpret_cast(def_addr); if (debug) { std::clog << "sym_name=" << c_name << std::endl; std::clog << "map_type=" << this->def.map_type << std::endl; std::clog << "key_size=" << this->def.key_size << std::endl; std::clog << "val_size=" << this->def.val_size << std::endl; std::clog << "max_size=" << this->def.max_size << std::endl; std::clog << "map_flag=" << this->def.map_flag << std::endl; } } rex_map(const rex_map &) = delete; rex_map(rex_map &&) = delete; ~rex_map() { map_fd.transform([](int fd) { return close(fd); }); } rex_map &operator=(const rex_map &) = delete; rex_map &operator=(rex_map &&) = delete; std::optional create() { int ret; union bpf_attr attr{ .map_type = def.map_type, .key_size = def.key_size, .value_size = def.val_size, .max_entries = def.max_size, .map_flags = def.map_flag, }; memcpy(attr.map_name, name.c_str(), std::min(name.size(), sizeof(attr.map_name) - 1)); ret = bpf(BPF_MAP_CREATE, &attr, sizeof(attr)); if (ret >= 0) this->map_fd = ret; return this->map_fd; } // rename bpf_map into bpfmap to avoid name collision std::optional bpfmap() { // Do not create a bpf_map if the map has not been loaded if (!map_fd) return std::nullopt; return bpf_map{ .name = name.data(), .fd = map_fd.value(), .inner_map_fd = -1, .def = { .type = def.map_type, .key_size = def.key_size, .value_size = def.val_size, .max_entries = def.max_size, .map_flags = def.map_flag, }, .libbpf_type = LIBBPF_MAP_UNSPEC, }; } friend struct ::rex_obj; }; struct rex_prog { private: std::string name; std::string scn_name; const struct bpf_sec_def *sec_def; Elf64_Off offset; std::optional prog_fd; public: rex_prog() = delete; rex_prog(const char *nm, const char *scn_nm, Elf64_Off off) : name(nm), scn_name(scn_nm), offset(off) { sec_def = find_sec_def(scn_name); } rex_prog(const rex_prog &) = delete; // std::optional only moves its underlying value and does not set the source // object to std::nullopt. This prevents us from using a compiler-generated // default implementation, because it would just copy the fd without // invalidating afterwards (as int is trivially movable). rex_prog(rex_prog &&other) noexcept : name(std::move(other.name)), scn_name(std::move(other.scn_name)), sec_def(std::move(other.sec_def)), offset(std::move(other.offset)), prog_fd(std::move(other.prog_fd)) { other.sec_def = nullptr; other.offset = -1; other.prog_fd = std::nullopt; } ~rex_prog() { prog_fd.transform([](int fd) { return close(fd); }); } rex_prog &operator=(const rex_prog &) = delete; rex_prog &operator=(rex_prog &&) = delete; std::optional bpf_prog() { // Do not create a bpf_program if the prog has not been loaded if (!prog_fd) return std::nullopt; // bpf_program::obj will be initliazed by the caller // bpf_program will never outlive "this" as both are managed by rex_obj, // so just redirect pointers return bpf_program{ .name = name.data(), .sec_name = scn_name.data(), .sec_idx = (size_t)-1, .sec_def = sec_def, .fd = prog_fd.value(), .type = sec_def->prog_type, }; } friend struct ::rex_obj; }; struct rex_obj { private: struct elf_del { [[gnu::always_inline]] void operator()(Elf *ep) const { elf_end(ep); } }; struct file_map_del { size_t size; file_map_del() = default; explicit file_map_del(size_t sz) : size(sz) {} [[gnu::always_inline]] void operator()(unsigned char *addr) const { munmap(addr, size); } }; struct bpf_obj_del { [[gnu::always_inline]] void operator()(bpf_object *bp) const { delete[] bp->programs; delete[] bp->maps; delete bp; } }; std::vector progs; std::unordered_map map_defs; std::unique_ptr elf; Elf_Scn *symtab_scn; Elf_Scn *dynsym_scn; Elf_Scn *maps_scn; // Global Offset Table for PIE Elf_Scn *got_scn; // Dynamic relocation for PIE Elf_Scn *rela_dyn_scn; std::vector dyn_relas; std::vector dyn_syms; std::vector rela_sym_name; std::optional timeout_handler_off; std::vector> text_syms; std::unique_ptr file_map; std::optional prog_fd; bool loaded; std::string basename; std::unique_ptr bpf_obj_ptr; int parse_scns(); int parse_maps(); int parse_progs(); int parse_got(); int parse_rela_dyn(); public: rex_obj() = delete; explicit rex_obj(const char *); rex_obj(const rex_obj &) = delete; rex_obj(rex_obj &&) = delete; ~rex_obj(); rex_obj &operator=(const rex_obj &) = delete; rex_obj &operator=(rex_obj &&) = delete; int parse_elf(); int fix_maps(); int load(); bpf_object *bpf_obj(); }; rex_obj::rex_obj(const char *c_path) : map_defs(), symtab_scn(nullptr), dynsym_scn(nullptr), maps_scn(nullptr), prog_fd(-1), loaded(false) { struct stat st; void *mmap_ret; int fd = open(c_path, 0, O_RDONLY); Elf *ep = elf_begin(fd, ELF_C_READ_MMAP, NULL); if (!ep) throw std::invalid_argument("elf: failed to open file "s + c_path); elf = std::unique_ptr(ep, elf_del()); if (fstat(fd, &st) < 0) throw std::system_error(errno, std::system_category(), "fstat"); // MAP_PRIVATE ensures the changes to the memory mapped by mmap(2) are not // carried through to the backing file mmap_ret = mmap(NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); if (mmap_ret == MAP_FAILED) throw std::system_error(errno, std::system_category(), "mmap"); file_map = std::unique_ptr( reinterpret_cast(mmap_ret), file_map_del(st.st_size)); std::string copy(c_path); copy += ".base"; basename = ::basename(copy.data()); close(fd); } rex_obj::~rex_obj() { prog_fd.transform([](int fd) { return close(fd); }); } int rex_obj::parse_scns() { size_t shstrndx; if (elf_getshdrstrndx(elf.get(), &shstrndx)) { std::cerr << "elf: failed to get section names section index for " << std::endl; return -1; } for (auto scn = elf_nextscn(elf.get(), NULL); scn; scn = elf_nextscn(elf.get(), scn)) { char *name; int idx = elf_ndxscn(scn); Elf64_Shdr *sh = elf64_getshdr(scn); if (!sh) { std::cerr << "elf: failed to get section header, idx=" << idx << std::endl; return -1; } name = elf_strptr(elf.get(), shstrndx, sh->sh_name); if (!name) { std::cerr << "elf: failed to get section name" << std::endl; return -1; } if (debug) std::clog << "section " << name << ", idx=" << idx << std::endl; if (sh->sh_type == SHT_SYMTAB && !strcmp(".symtab", name)) this->symtab_scn = scn; else if (sh->sh_type == SHT_DYNSYM && !strcmp(".dynsym", name)) this->dynsym_scn = scn; else if (!strcmp(".maps", name)) this->maps_scn = scn; else if (sh->sh_type == SHT_RELA && !strcmp(".rela.dyn", name)) this->rela_dyn_scn = scn; } if (!this->maps_scn && debug) std::clog << "section .maps not found" << std::endl; if (!this->rela_dyn_scn && debug) std::clog << "section .rela.dyn not found" << std::endl; return 0; } int rex_obj::parse_maps() { Elf_Data *maps, *syms; int nr_syms, nr_maps = 0, maps_shndx; size_t strtabidx; Elf64_Addr maps_shaddr; if (!this->maps_scn) return 0; maps = elf_getdata(maps_scn, 0); syms = elf_getdata(symtab_scn, 0); if (!syms) { std::cerr << "elf: failed to get symbol definitions" << std::endl; return -1; } if (!maps) { std::cerr << "elf: failed to get map definitions" << std::endl; return -1; } strtabidx = elf64_getshdr(symtab_scn)->sh_link; maps_shndx = elf_ndxscn(maps_scn); maps_shaddr = elf64_getshdr(maps_scn)->sh_addr; nr_syms = syms->d_size / sizeof(Elf64_Sym); for (int i = 0; i < nr_syms; i++) { Elf64_Sym *sym = reinterpret_cast(syms->d_buf) + i; char *name; if (sym->st_shndx != maps_shndx || ELF64_ST_TYPE(sym->st_info) != STT_OBJECT) continue; name = elf_strptr(elf.get(), strtabidx, sym->st_name); if (debug) { std::clog << "symbol: " << name << ", st_value=0x" << std::hex << sym->st_value << ", st_size=" << std::dec << sym->st_size << std::endl; } if (sym->st_size == sizeof(map_def)) { map_defs.try_emplace(sym->st_value, maps, maps_shaddr, sym->st_value, name); } nr_maps++; } if (debug) std::clog << "# of symbols in \".maps\": " << nr_maps << std::endl; return 0; } // get sec name // get function symbols int rex_obj::parse_progs() { size_t shstrndx, strtabidx; Elf_Data *syms; int nr_syms; strtabidx = elf64_getshdr(symtab_scn)->sh_link; if (elf_getshdrstrndx(elf.get(), &shstrndx)) { std::cerr << "elf: failed to get section names section index" << std::endl; return -1; } syms = elf_getdata(symtab_scn, 0); if (!syms) { std::cerr << "elf: failed to get symbol definitions" << std::endl; return -1; } nr_syms = syms->d_size / sizeof(Elf64_Sym); for (int i = 0; i < nr_syms; i++) { Elf64_Sym *sym = reinterpret_cast(syms->d_buf) + i; Elf_Scn *scn = elf_getscn(elf.get(), sym->st_shndx); char *scn_name, *sym_name; const bpf_sec_def *sec_def; if (!scn || ELF64_ST_TYPE(sym->st_info) != STT_FUNC) continue; scn_name = elf_strptr(elf.get(), shstrndx, elf64_getshdr(scn)->sh_name); sym_name = elf_strptr(elf.get(), strtabidx, sym->st_name); if (sym->st_value) { // Align symbol size up to 16-byte boundary, which is the default function // alignment in x86-64, to account for trailing nops text_syms.emplace_back(llvm::demangle(sym_name), sym->st_value, align_up_16(sym->st_size)); } if ("__rex_handle_timeout"sv == sym_name) timeout_handler_off = sym->st_value; if (debug) { std::clog << "symbol: \"" << sym_name << "\"" << ", section: \"" << scn_name << "\"" << ", st_value=0x" << std::hex << sym->st_value << ", st_size=" << sym->st_size << std::dec << std::endl; } sec_def = find_sec_def(scn_name); if (!sec_def) continue; if (debug) std::clog << "successfully matched" << std::endl; sym_name = elf_strptr(elf.get(), strtabidx, sym->st_name); progs.emplace_back(sym_name, scn_name, sym->st_value); } if (!timeout_handler_off) { std::cerr << "elf: __rex_handle_timeout not found" << std::endl; return -1; } if (debug) { std::clog << "Found __rex_handle_timeout at offset" << std::hex << timeout_handler_off.value() << std::dec << std::endl; } return 0; }; int rex_obj::parse_rela_dyn() { Elf64_Shdr *rela_dyn; rex_rela_dyn *rela_dyn_data; uint64_t rela_dyn_addr, rela_dyn_size, nr_dyn_relas; size_t idx; if (!this->rela_dyn_scn) return 0; rela_dyn = elf64_getshdr(rela_dyn_scn); if (!rela_dyn) { std::cerr << "elf: failed to get .rela.dyn section" << std::endl; return -1; } rela_dyn_data = reinterpret_cast(elf_getdata(rela_dyn_scn, 0)->d_buf); rela_dyn_addr = rela_dyn->sh_addr; rela_dyn_size = rela_dyn->sh_size; if (debug) { std::clog << ".rela.dyn offset=" << std::hex << rela_dyn_addr << ", .rela.dyn size=" << std::dec << rela_dyn_size << std::endl; } if (rela_dyn_size % sizeof(rex_rela_dyn)) { std::cerr << "elf: ill-formed .rela.dyn section" << std::endl; return -1; } nr_dyn_relas = rela_dyn_size / sizeof(rex_rela_dyn); for (idx = 0; idx < nr_dyn_relas; idx++) { if (ELF64_R_TYPE(rela_dyn_data[idx].info) == R_X86_64_RELATIVE) { dyn_relas.push_back(rela_dyn_data[idx]); } else if (ELF64_R_TYPE(rela_dyn_data[idx].info) == R_X86_64_GLOB_DAT) { uint32_t dynsym_idx = ELF64_R_SYM(rela_dyn_data[idx].info); Elf_Data *syms = elf_getdata(dynsym_scn, 0); size_t strtabidx = elf64_getshdr(dynsym_scn)->sh_link; Elf64_Sym *sym = reinterpret_cast(syms->d_buf) + dynsym_idx; rex_dyn_sym dyn_sym = {}; char *name = elf_strptr(elf.get(), strtabidx, sym->st_name); dyn_sym.offset = rela_dyn_data[idx].offset; dyn_sym.symbol = name; dyn_syms.push_back(dyn_sym); } else { std::cerr << "elf: relocation type not supported" << std::endl; return -1; } } if (debug) { std::clog << ".rela.dyn: " << std::hex << std::endl; for (auto &dyn_rela : dyn_relas) { std::clog << "0x" << dyn_rela.offset << ", 0x" << dyn_rela.info << ", 0x" << dyn_rela.addend << std::endl; } for (auto &dyn_sym : dyn_syms) { std::clog << "0x" << dyn_sym.offset << ", " << dyn_sym.symbol << std::endl; } std::clog << std::dec; } return 0; } int rex_obj::parse_elf() { int ret; if (!elf) { std::cerr << "elf: failed to open object" << std::endl; return -1; } ret = this->parse_scns(); ret = ret < 0 ? ret : this->parse_maps(); ret = ret < 0 ? ret : this->parse_progs(); ret = ret < 0 ? ret : this->parse_rela_dyn(); return ret; } int rex_obj::fix_maps() { Elf64_Addr maps_shaddr; Elf64_Off maps_shoff; if (!this->maps_scn) { return 0; } maps_shaddr = elf64_getshdr(maps_scn)->sh_addr; maps_shoff = elf64_getshdr(maps_scn)->sh_offset; if (debug) { std::clog << ".maps section file offset=0x" << std::hex << elf64_getshdr(maps_scn)->sh_offset << std::dec << std::endl; } for (auto &[m_off, m_def] : map_defs) { size_t kptr_file_off = m_off + offsetof(map_def, kptr) - maps_shaddr + maps_shoff; if (debug) { std::clog << "map_ptr=0x" << std::hex << m_off << std::dec << std::endl; std::clog << "map_name=\"" << m_def.name << '\"' << std::endl; } std::optional map_fd = m_def.create(); if (!map_fd) { perror("bpf_map_create"); return -1; } if (debug) std::clog << "map_fd=" << map_fd.value() << std::endl; *reinterpret_cast(&this->file_map[kptr_file_off]) = map_fd.value(); } return 0; } int rex_obj::load() { int fd; auto arr = std::make_unique(map_defs.size()); union bpf_attr attr = {}; int idx = 0, ret = 0; std::filesystem::path tmp_file = "/tmp/rex-" + std::to_string(gettid()); std::unique_ptr tsym_arr(new rex_text_sym[text_syms.size()]); // TODO: Will have race condition if multiple objs loaded at same time std::ofstream output(tmp_file, std::ios::out | std::ios::binary); output.write((char *)this->file_map.get(), this->file_map.get_deleter().size); output.close(); fd = open(tmp_file.c_str(), O_RDONLY); for (auto &def : map_defs) arr[idx++] = def.first + offsetof(map_def, kptr); attr.prog_type = BPF_PROG_TYPE_REX_BASE; // progname was zero-initialized so we don't copy the null terminator memcpy(attr.prog_name, basename.c_str(), std::min(basename.size(), sizeof(attr.prog_name) - 1)); attr.rustfd = fd; attr.license = reinterpret_cast<__u64>("GPL"); attr.map_offs = reinterpret_cast<__u64>(arr.get()); attr.map_cnt = map_defs.size(); attr.dyn_relas = reinterpret_cast<__u64>(dyn_relas.data()); attr.nr_dyn_relas = dyn_relas.size(); attr.dyn_syms = reinterpret_cast<__u64>(dyn_syms.data()); attr.nr_dyn_syms = dyn_syms.size(); // Copy data into the array that will be sent to the kernel for (const auto &[idx, sym] : std::views::enumerate(text_syms)) { tsym_arr[idx].symbol = std::get<0>(sym).c_str(); std::tie(std::ignore, tsym_arr[idx].offset, tsym_arr[idx].size) = sym; } attr.text_syms = reinterpret_cast<__u64>(tsym_arr.get()); attr.nr_text_syms = text_syms.size(); ret = bpf(BPF_PROG_LOAD_REX_BASE, &attr, sizeof(attr)); if (ret < 0) { perror("bpf_prog_load_rex_base"); return -1; } this->prog_fd = ret; if (debug) std::clog << "Base program loaded, fd = " << ret << std::endl; close(fd); if (!std::filesystem::remove(tmp_file)) { perror("remove"); goto close_fds; } for (auto &prog : progs) { int curr_fd; attr.prog_type = prog.sec_def->prog_type; strncpy(attr.prog_name, prog.name.c_str(), sizeof(attr.prog_name) - 1); attr.base_prog_fd = this->prog_fd.value(); attr.prog_offset = prog.offset; attr.license = (__u64) "GPL"; attr.unwinder_insn_off = timeout_handler_off.value(); curr_fd = bpf(BPF_PROG_LOAD_REX, &attr, sizeof(attr)); if (curr_fd < 0) { perror("bpf_prog_load_rex"); goto close_fds; } prog.prog_fd = curr_fd; if (debug) std::clog << "Program " << prog.name << " loaded, fd = " << prog.prog_fd.value_or(-1) << std::endl; } loaded = true; return ret; close_fds: for (auto &prog : progs) { prog.prog_fd = prog.prog_fd.and_then([](int fd) -> std::optional { close(fd); return std::nullopt; }); } prog_fd = prog_fd.and_then([](int fd) -> std::optional { close(fd); return std::nullopt; }); return -1; } bpf_object *rex_obj::bpf_obj() { size_t i; // Do not create a bpf_object if the obj has not been loaded if (!loaded) return nullptr; // Return the previously created ptr if (bpf_obj_ptr) return bpf_obj_ptr.get(); // Create a new ptr decltype(bpf_obj_ptr) ptr(new bpf_object, bpf_obj_del()); ptr->maps = new bpf_map[map_defs.size()]; ptr->programs = new bpf_program[progs.size()]; // Fill in maps i = 0; for (auto &[_, m_def] : map_defs) { if (std::optional map = m_def.bpfmap()) { ptr->maps[i] = std::move(map.value()); ptr->maps[i++].obj = ptr.get(); } else { return nullptr; } } ptr->nr_maps = i; // Fill in programs i = 0; for (auto &prog : progs) { if (std::optional bpf_prog = prog.bpf_prog()) { ptr->programs[i] = std::move(bpf_prog.value()); ptr->programs[i].obj = ptr.get(); i++; } else { return nullptr; } } ptr->nr_programs = i; ptr->state = OBJ_LOADED; // Now transfer the ownership bpf_obj_ptr = std::move(ptr); return bpf_obj_ptr.get(); } [[gnu::visibility("default")]] void rex_set_debug(int val) { debug = val; } static std::vector> objs; [[nodiscard, gnu::visibility("default")]] rex_obj * rex_obj_load(const char *file_path) { int ret; if (elf_version(EV_CURRENT) == EV_NONE) { std::cerr << "elf: failed to init libelf" << std::endl; return nullptr; } try { auto obj = std::make_unique(file_path); ret = obj->parse_elf(); ret = ret ? ret : obj->fix_maps(); ret = ret ? ret : obj->load(); if (ret >= 0) { objs.push_back(std::move(obj)); return objs.back().get(); } else { return nullptr; } } catch (std::exception &e) { std::cerr << e.what() << std::endl; return nullptr; } } [[nodiscard, gnu::visibility("default")]] bpf_object * rex_obj_get_bpf(rex_obj *obj) { try { return obj->bpf_obj(); } catch (std::exception &e) { std::cerr << e.what() << std::endl; return nullptr; } } ================================================ FILE: librex/meson.build ================================================ rex_rootdir = '..' llvm_dep = dependency('llvm', version : '>=18') elf_dep = dependency('libelf') librex_public_inc = include_directories('include') librex_sources = [ 'lib/librex.cpp' ] librex = library( 'rex', librex_sources, cpp_args: ['-Wno-missing-designated-field-initializers'], build_rpath: join_paths(meson.project_source_root(), 'linux/tools/lib/bpf'), build_by_default: false, dependencies: [elf_dep, llvm_dep, kernel_dep, libbpf_dep], gnu_symbol_visibility: 'hidden', include_directories: librex_public_inc, pic: true ) librex_dep = declare_dependency( link_with: librex, include_directories: librex_public_inc ) ================================================ FILE: meson.build ================================================ project('rex-compile', ['c', 'cpp'], version: '0.1.0', default_options : [ 'buildtype=debugoptimized', 'warning_level=2', 'werror=true', 'b_lto=true', 'b_lto_mode=thin', 'b_pie=true', 'c_std=gnu23', 'cpp_std=c++23' ] ) add_project_arguments( [ '-pipe', '-march=native', '-ffunction-sections', '-fdata-sections', '-fno-semantic-interposition' ], language: ['c', 'cpp'] ) add_project_link_arguments( [ '-Wl,-O1', '-Wl,--gc-sections', '-Wl,-z,now', '-Wl,-z,relro' ], language: ['c', 'cpp'] ) bindgen = find_program('bindgen') cmake = find_program('cmake') ninja = find_program('ninja') perl = find_program('perl') python3_bin = find_program('python3', version: '>=3.11') realpath = find_program('realpath') lld = find_program('ld.lld') bc = find_program('bc') flex = find_program('flex') bison = find_program('bison') subdir('linux') subdir('librex') rust_bootstrap_config = files('./rust/rex-config.toml') rust_bootstrap = custom_target( 'rust', output : ['cargo', 'rustc'], command: [ python3_bin, '@SOURCE_ROOT@/rust/x.py', 'install', '--config=@SOURCE_ROOT@/rust/rex-config.toml', '--build-dir=@OUTDIR@/rust-build', '--set', 'install.prefix=@OUTDIR@/rust-dist' ], console: true, build_by_default: false, env: ['RUSTFLAGS=-C link-arg=-fuse-ld=mold'] ) all_programs = custom_target('build_deps', output: ['kernel', 'kernel_libbpf', 'rust'], command: ['echo', 'Build all depends'], depends: [kernel_build, kernel_libbpf, rust_bootstrap], console: true ) rust_bin = join_paths(meson.current_build_dir(), 'rust-dist/bin') cargo_wrapper = join_paths(meson.project_source_root(), 'scripts/cargo-wrapper.pl') sanity_test_scripts = join_paths(meson.project_source_root(), 'scripts/sanity_tests/run_tests.py') runtest_deps = [] subdir('samples') subdir('rex') ================================================ FILE: rex/.cargo/config.toml ================================================ [build] target = "x86_64-unknown-none" [target.x86_64-unknown-none] linker = "ld.mold" rustflags = [ "-Zthreads=8", "-Cforce-frame-pointers=y", "-Csymbol-mangling-version=v0", "-Ccodegen-units=1", "-Crelocation-model=pie", "-Crelro-level=full", ] [unstable] build-std = ["core"] ================================================ FILE: rex/.gitignore ================================================ Cargo.lock target libiustub/libiustub.so ================================================ FILE: rex/Cargo.toml ================================================ [package] name = "rex" version = "0.2.0" build = "build.rs" autotests = false repository.workspace = true edition.workspace = true authors.workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [lib] test = false doctest = false [dependencies] paste = { workspace = true } rex-macros = { workspace = true } [features] default = ["debug_printk"] debug_printk = [] [rex] uheaders = [ "linux/bpf.h", "linux/errno.h", "linux/in.h", "linux/perf_event.h", "linux/pkt_cls.h", "linux/ptrace.h", "linux/seccomp.h", "linux/unistd.h", ] kheaders = [ "linux/filter.h", "linux/gfp_types.h", "linux/if_ether.h", "linux/ip.h", "linux/kcsan.h", "linux/perf_event.h", "linux/prandom.h", "linux/sched.h", "linux/seqlock.h", "linux/skbuff.h", "linux/tcp.h", "linux/timekeeper_internal.h", "linux/udp.h", "net/xdp.h", ] kconfigs = ["CONFIG_BPF_KPROBE_OVERRIDE", "CONFIG_KALLSYMS_ALL"] ================================================ FILE: rex/build.py ================================================ import os import re import subprocess import sys import tomllib # https://github.com/rust-lang/rust-bindgen bindgen_cmd = '''bindgen $LINUX_OBJ/usr/include/%s --use-core --with-derive-default --ctypes-prefix core::ffi --no-layout-tests --no-debug '.*' --no-doc-comments --rust-target=1.85.0 --rust-edition=2024 --translate-enum-integer-types --no-prepend-enum-name --blocklist-type pt_regs --wrap-unsafe-ops -o %s -- -I$LINUX_OBJ/usr/include''' k_structs = ['task_struct', 'tk_read_base', 'seqcount_raw_spinlock_t', 'clocksource', 'seqcount_t', 'seqcount_latch_t', 'timekeeper', 'kcsan_ctx', 'rnd_state', 'timespec64', 'bpf_spin_lock', 'bpf_sysctl_kern', 'xdp_buff', 'ethhdr', 'iphdr', 'tcphdr', 'udphdr', 'sk_buff', 'sock', 'pcpu_hot', 'bpf_perf_event_data_kern'] bindgen_kernel_cmd = '''bindgen %s --allowlist-type="%s" --allowlist-var="(___GFP.*|CONFIG_.*|MAX_BPRINTF_BUF)" --opaque-type xregs_state --opaque-type desc_struct --opaque-type arch_lbr_state --opaque-type local_apic --opaque-type alt_instr --opaque-type x86_msi_data --opaque-type x86_msi_addr_lo --opaque-type kunit_try_catch --opaque-type spinlock --no-doc-comments --blocklist-function __list_.*_report --use-core --with-derive-default --ctypes-prefix core::ffi --no-layout-tests --no-debug '.*' --rust-target=1.85.0 --rust-edition=2024 --wrap-unsafe-ops -o %s -- -nostdinc -I$LINUX_SRC/arch/x86/include -I$LINUX_OBJ/arch/x86/include/generated -I$LINUX_SRC/include -I$LINUX_SRC/arch/x86/include/uapi -I$LINUX_OBJ/arch/x86/include/generated/uapi -I$LINUX_SRC/include/uapi -I$LINUX_OBJ/include -I$LINUX_OBJ/include/generated/uapi -include $LINUX_SRC/include/linux/compiler-version.h -include $LINUX_SRC/include/linux/kconfig.h -include $LINUX_SRC/include/linux/compiler_types.h -D__KERNEL__ --target=x86_64-linux-gnu -fintegrated-as -Werror=unknown-warning-option -Werror=ignored-optimization-argument -Werror=option-ignored -Werror=unused-command-line-argument -fmacro-prefix-map=./= -std=gnu11 -fshort-wchar -funsigned-char -fno-common -fno-PIE -fno-strict-aliasing -mno-sse -mno-mmx -mno-sse2 -mno-3dnow -mno-avx -fcf-protection=branch -fno-jump-tables -m64 -falign-loops=1 -mno-80387 -mno-fp-ret-in-387 -mstack-alignment=8 -mskip-rax-setup -mtune=generic -mno-red-zone -mcmodel=kernel -Wno-sign-compare -fno-asynchronous-unwind-tables -fno-delete-null-pointer-checks -O2 -fstack-protector-strong -fno-stack-clash-protection -pg -mfentry -DCC_USING_NOP_MCOUNT -DCC_USING_FENTRY -fno-lto -falign-functions=16 -fstrict-flex-arrays=3 -fms-extensions -fno-strict-overflow -fno-stack-check -Wall -Wundef -Werror=implicit-function-declaration -Werror=implicit-int -Werror=return-type -Werror=strict-prototypes -Wno-format-security -Wno-trigraphs -Wno-frame-address -Wno-address-of-packed-member -Wmissing-declarations -Wmissing-prototypes -Wframe-larger-than=2048 -Wno-gnu -Wno-microsoft-anon-tag -Wvla -Wno-pointer-sign -Wcast-function-type -Wimplicit-fallthrough -Werror=date-time -Werror=incompatible-pointer-types -Wenum-conversion -Wextra -Wunused -Wno-unused-but-set-variable -Wno-unused-const-variable -Wno-format-overflow -Wno-format-overflow-non-kprintf -Wno-format-truncation-non-kprintf -Wno-override-init -Wno-pointer-to-enum-cast -Wno-tautological-constant-out-of-range-compare -Wno-unaligned-access -Wno-enum-compare-conditional -Wno-enum-enum-conversion -Wno-missing-field-initializers -Wno-type-limits -Wno-shift-negative-value -Wno-sign-compare -Wno-unused-parameter -g -DKBUILD_MODFILE='"rex/rex_generated"' -DKBUILD_BASENAME='"rex_generated"' -DKBUILD_MODNAME='"rex_generated"' -D__KBUILD_MODNAME=kmod_rex_generated -D__BINDGEN__ -DMODULE''' def prep_uapi_headers(linux_path, headers, out_dir): for header in headers: subdir, hfile = os.path.split(header) subdir = os.path.join(out_dir, subdir) if not os.path.exists(subdir): os.makedirs(subdir) out_f = os.path.join(subdir, '%s.rs' % os.path.splitext(hfile)[0]) cmd = bindgen_cmd.replace('\n', ' ').replace('$LINUX_OBJ', linux_path) subprocess.run(cmd % (header, out_f), check=True, shell=True) def parse_cargo_toml(cargo_toml_path): with open(cargo_toml_path, 'rb') as toml_f: cargo_toml = tomllib.load(toml_f) uheaders = cargo_toml['rex'].get('uheaders', []) kheaders = cargo_toml['rex'].get('kheaders', []) kconfigs = cargo_toml['rex'].get('kconfigs', []) return uheaders, kheaders, kconfigs def prep_kernel_headers(headers, linux_src, linux_obj, out_dir): bindings_h = os.path.join(out_dir, 'bindings.h') out_subdir = os.path.join(out_dir, 'linux') if not os.path.exists(out_subdir): os.makedirs(out_subdir) kernel_rs = os.path.join(out_subdir, 'kernel.rs') with open(bindings_h, 'w') as bindings: for h in headers: bindings.write('#include <%s>\n' % h) cmd = ( bindgen_kernel_cmd.replace("\n", " ") .replace("$LINUX_SRC", linux_src) .replace("$LINUX_OBJ", linux_obj) ) subprocess.run( cmd % (bindings_h, "|".join(k_structs), kernel_rs), check=True, shell=True ) def parse_kconfigs(dot_config_path, kconfigs): if len(kconfigs) == 0: return with open(dot_config_path) as dot_config: dot_config_content = dot_config.readlines() ptn = re.compile('(%s)' % '|'.join(kconfigs)) fmt = 'cargo:rustc-cfg=%s="%s"\n' + \ 'cargo::rustc-check-cfg=cfg(%s, values("%s"))' print('\n'.join(map(lambda l: fmt % (l * 2), map(lambda l: tuple(l.strip().split('=')), filter(lambda l: l[0] != '#' and ptn.match(l), dot_config_content))))) def main(argv): linux_obj = argv[1] linux_src = argv[2] out_dir = argv[3] target_path = os.getcwd() result = parse_cargo_toml(os.path.join(target_path, 'Cargo.toml')) uheaders, kheaders, kconfigs = result u_out_dir = os.path.join(out_dir, 'uapi') prep_uapi_headers(linux_obj, uheaders, u_out_dir) prep_kernel_headers(kheaders, linux_src, linux_obj, out_dir) parse_kconfigs(os.path.join(linux_obj, '.config'), kconfigs) return 0 if __name__ == '__main__': exit(main(sys.argv)) ================================================ FILE: rex/build.rs ================================================ #![feature(exit_status_error)] use std::io::Result; use std::path::Path; use std::process::Command; use std::string::String; use std::{env, fs}; fn main() -> Result<()> { let out_dir = env::var("OUT_DIR").unwrap(); let linux_obj = env::var("LINUX_OBJ").unwrap(); let linux_src = env::var("LINUX_SRC").unwrap(); let output = Command::new("python3") .arg("build.py") .arg(&linux_obj) .arg(&linux_src) .arg(&out_dir) .output()?; output .status .exit_ok() .map(|_| print!("{}", String::from_utf8_lossy(&output.stdout))) .map_err(|_| panic!("\n{}", String::from_utf8_lossy(&output.stderr))) .unwrap(); let mut rexstub_outdir = Path::new(&out_dir).join("librexstub"); if !rexstub_outdir.exists() { fs::create_dir(&rexstub_outdir)?; } let rexstub_so = rexstub_outdir.join("librexstub.so"); Command::new("clang") .arg("-fPIC") .arg("-nostartfiles") .arg("-nodefaultlibs") .arg("--shared") .arg("-o") .arg(rexstub_so.to_string_lossy().to_mut()) .arg("./librexstub/lib.c") .output()?; rexstub_outdir = rexstub_outdir.canonicalize()?; println!("cargo:rerun-if-changed=Cargo.toml"); println!("cargo:rerun-if-changed=./src/*"); println!("cargo:rerun-if-changed=./librexstub/*"); println!("cargo:rustc-link-lib=dylib=rexstub"); println!( "cargo:rustc-link-search=native={}", rexstub_outdir.to_string_lossy() ); Ok(()) } ================================================ FILE: rex/librexstub/lib.c ================================================ // Functions #define KSYM_FUNC(func) \ int func() { return 0; } KSYM_FUNC(bpf_get_current_pid_tgid) KSYM_FUNC(bpf_trace_printk) KSYM_FUNC(bpf_map_lookup_elem) KSYM_FUNC(bpf_map_update_elem) KSYM_FUNC(bpf_map_delete_elem) KSYM_FUNC(bpf_map_push_elem) KSYM_FUNC(bpf_map_pop_elem) KSYM_FUNC(bpf_map_peek_elem) KSYM_FUNC(bpf_probe_read_kernel) KSYM_FUNC(ktime_get_mono_fast_ns) KSYM_FUNC(ktime_get_boot_fast_ns) KSYM_FUNC(get_random_u32) KSYM_FUNC(bpf_snprintf) KSYM_FUNC(vprintk) KSYM_FUNC(rex_landingpad) KSYM_FUNC(bpf_spin_lock) KSYM_FUNC(bpf_spin_unlock) KSYM_FUNC(just_return_func) KSYM_FUNC(bpf_get_stackid_pe) KSYM_FUNC(bpf_perf_prog_read_value) KSYM_FUNC(bpf_perf_event_output_tp) KSYM_FUNC(bpf_perf_event_read_value) KSYM_FUNC(bpf_skb_event_output) KSYM_FUNC(bpf_xdp_event_output) KSYM_FUNC(bpf_xdp_adjust_head) KSYM_FUNC(bpf_xdp_adjust_tail) KSYM_FUNC(bpf_clone_redirect) KSYM_FUNC(bpf_ringbuf_output) KSYM_FUNC(bpf_ringbuf_reserve) KSYM_FUNC(bpf_ringbuf_submit) KSYM_FUNC(bpf_ringbuf_discard) KSYM_FUNC(bpf_ringbuf_query) KSYM_FUNC(bpf_ktime_get_ns) KSYM_FUNC(bpf_ktime_get_boot_ns) KSYM_FUNC(bpf_ktime_get_coarse_ns) KSYM_FUNC(rex_trace_printk) KSYM_FUNC(bpf_task_from_pid) KSYM_FUNC(bpf_task_release) // Global variables unsigned long jiffies; int numa_node; void *rex_cleanup_entries; unsigned long rex_stack_ptr; void *current_task; int cpu_number; unsigned char rex_termination_state; unsigned long this_cpu_off; char *rex_log_buf; ================================================ FILE: rex/meson.build ================================================ build_dir = run_command( realpath, '--relative-to', meson.current_source_dir(), meson.current_build_dir(), capture: true, check: true ).stdout().strip() env = environment() env.prepend('PATH', rust_bin) env.set('LINUX_OBJ', kbuild_dir) env.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux')) env.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target')) rex_build = custom_target( 'rex-build', output: ['target'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'rustc', '-qr', '--', '-Cenable_rex' ], env: env, console: false, build_always_stale: true, build_by_default: false ) ================================================ FILE: rex/src/base_helper.rs ================================================ // use crate::timekeeping::*; use core::intrinsics::unlikely; use core::mem::MaybeUninit; use crate::ffi; use crate::linux::bpf::bpf_map_type; use crate::linux::errno::EINVAL; use crate::map::*; use crate::per_cpu::this_cpu_read; use crate::random32::bpf_user_rnd_u32; use crate::utils::{to_result, NoRef, Result}; macro_rules! termination_check { ($func:expr) => {{ // Declare and initialize the termination flag pointer let termination_flag: *mut u8; unsafe { termination_flag = crate::per_cpu::this_cpu_ptr_mut( &raw mut crate::ffi::rex_termination_state, ); // Set the termination flag *termination_flag = 1; } // Call the provided function let res = $func; // Check the termination flag and handle timeout unsafe { if core::intrinsics::unlikely(*termination_flag == 2) { crate::panic::__rex_handle_timeout(); } else { // Reset the termination flag upon exiting *termination_flag = 0; } } // Return the result of the function call res }}; } pub(crate) fn bpf_get_smp_processor_id() -> i32 { unsafe { this_cpu_read(&raw const ffi::cpu_number) } } pub(crate) fn bpf_map_lookup_elem<'a, const MT: bpf_map_type, K, V>( map: &'static RexMapHandle, key: &'a K, ) -> Option<&'a mut V> where V: Copy + NoRef, { let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) }; if unlikely(map_kptr.is_null()) { return None; } let value = termination_check!(unsafe { ffi::bpf_map_lookup_elem(map_kptr, key as *const K as *const ()) as *mut V }); if value.is_null() { None } else { Some(unsafe { &mut *value }) } } pub(crate) fn bpf_map_update_elem( map: &'static RexMapHandle, key: &K, value: &V, flags: u64, ) -> Result where V: Copy + NoRef, { let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) }; if unlikely(map_kptr.is_null()) { return Err(EINVAL as i32); } termination_check!(unsafe { to_result!(ffi::bpf_map_update_elem( map_kptr, key as *const K as *const (), value as *const V as *const (), flags ) as i32) }) } pub(crate) fn bpf_map_delete_elem( map: &'static RexMapHandle, key: &K, ) -> Result where V: Copy + NoRef, { let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) }; if unlikely(map_kptr.is_null()) { return Err(EINVAL as i32); } termination_check!(unsafe { to_result!(ffi::bpf_map_delete_elem( map_kptr, key as *const K as *const () ) as i32) }) } pub(crate) fn bpf_map_push_elem( map: &'static RexMapHandle, value: &V, flags: u64, ) -> Result where V: Copy + NoRef, { let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) }; if unlikely(map_kptr.is_null()) { return Err(EINVAL as i32); } termination_check!(unsafe { to_result!(ffi::bpf_map_push_elem( map_kptr, value as *const V as *const (), flags ) as i32) }) } pub(crate) fn bpf_map_pop_elem( map: &'static RexMapHandle, ) -> Option where V: Copy + NoRef, { let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) }; if unlikely(map_kptr.is_null()) { return None; } let mut value: MaybeUninit = MaybeUninit::uninit(); let res = termination_check!(unsafe { to_result!(ffi::bpf_map_pop_elem( map_kptr, value.as_mut_ptr() as *mut () ) as i32) }); res.map(|_| unsafe { value.assume_init() }).ok() } pub(crate) fn bpf_map_peek_elem( map: &'static RexMapHandle, ) -> Option where V: Copy + NoRef, { let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) }; if unlikely(map_kptr.is_null()) { return None; } let mut value: MaybeUninit = MaybeUninit::uninit(); let res = termination_check!(unsafe { to_result!(ffi::bpf_map_peek_elem( map_kptr, value.as_mut_ptr() as *mut () ) as i32) }); res.map(|_| unsafe { value.assume_init() }).ok() } // pub(crate) fn bpf_for_each_map_elem( // map: &'static RexMapHandle, // callback_fn: extern "C" fn(*const (), *const K, *const V, *const C) -> // i64, callback_ctx: &C, // flags: u64, // ) -> Result { // let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) }; // if unlikely(map_kptr.is_null()) { // return Err(EINVAL as i32); // } // unsafe { // to_result!(ffi::bpf_for_each_map_elem(map_kptr, callback_fn as // *const (), callback_ctx as *const C as *const (), flags) as i32) } // } // Design decision: Make the destination a generic type so that probe read // kernel can directly fill in variables of certain type. This also achieves // size checking, since T is known at compile time for monomorphization pub(crate) fn bpf_probe_read_kernel( dst: &mut T, unsafe_ptr: *const (), ) -> Result where T: Copy + NoRef, { termination_check!(unsafe { to_result!(ffi::bpf_probe_read_kernel( dst as *mut T as *mut (), core::mem::size_of::() as u32, unsafe_ptr, )) }) } pub(crate) fn bpf_jiffies64() -> u64 { unsafe { core::ptr::read_volatile(&ffi::jiffies) } } /// Assumes `CONFIG_USE_PERCPU_NUMA_NODE_ID` pub(crate) fn bpf_get_numa_node_id() -> i32 { unsafe { this_cpu_read(&raw const ffi::numa_node) } } // This two functions call the original helper directly, so that confirm the // return value is correct /* pub(crate) fn bpf_ktime_get_ns_origin() -> u64 { unsafe { ffi::ktime_get_mono_fast_ns() } } pub(crate) fn bpf_ktime_get_boot_ns_origin() -> u64 { unsafe { ffi::ktime_get_boot_fast_ns() } } */ pub(crate) fn bpf_ktime_get_ns() -> u64 { termination_check!(unsafe { ffi::bpf_ktime_get_ns() }) } pub(crate) fn bpf_ktime_get_boot_ns() -> u64 { termination_check!(unsafe { ffi::bpf_ktime_get_boot_ns() }) } pub(crate) fn bpf_ktime_get_coarse_ns() -> u64 { termination_check!(unsafe { ffi::bpf_ktime_get_coarse_ns() }) } /* pub(crate) fn bpf_ktime_get_ns() -> u64 { ktime_get_mono_fast_ns() } pub(crate) fn bpf_ktime_get_boot_ns() -> u64 { ktime_get_boot_fast_ns() } pub(crate) fn bpf_ktime_get_coarse_ns() -> u64 { ktime_get_coarse() as u64 } */ pub(crate) fn bpf_get_prandom_u32() -> u32 { termination_check!(bpf_user_rnd_u32()) } // In document it says that data is a pointer to an array of 64-bit values. pub(crate) fn bpf_snprintf( str: &mut [u8; N], fmt: &str, data: &[u64; M], ) -> Result { termination_check!(unsafe { to_result!(ffi::bpf_snprintf( str.as_mut_ptr(), N as u32, fmt.as_ptr(), data.as_ptr(), M as u32, ) as i32) }) } macro_rules! base_helper_defs { () => { #[inline(always)] pub fn bpf_get_smp_processor_id(&self) -> i32 { crate::base_helper::bpf_get_smp_processor_id() } // Self should already have impl<'a> #[inline(always)] pub fn bpf_map_lookup_elem<'b, const MT: bpf_map_type, K, V>( &self, map: &'static crate::map::RexMapHandle, key: &'b K, ) -> Option<&'b mut V> where V: Copy + crate::utils::NoRef, { crate::base_helper::bpf_map_lookup_elem(map, key) } #[inline(always)] pub fn bpf_map_update_elem( &self, map: &'static crate::map::RexMapHandle, key: &K, value: &V, flags: u64, ) -> crate::Result where V: Copy + crate::utils::NoRef, { crate::base_helper::bpf_map_update_elem(map, key, value, flags) } #[inline(always)] pub fn bpf_map_delete_elem( &self, map: &'static crate::map::RexMapHandle, key: &K, ) -> crate::Result where V: Copy + crate::utils::NoRef, { crate::base_helper::bpf_map_delete_elem(map, key) } #[inline(always)] pub fn bpf_map_push_elem( &self, map: &'static crate::map::RexMapHandle, value: &V, flags: u64, ) -> crate::Result where V: Copy + crate::utils::NoRef, { crate::base_helper::bpf_map_push_elem(map, value, flags) } #[inline(always)] pub fn bpf_map_pop_elem( &self, map: &'static crate::map::RexMapHandle, ) -> Option where V: Copy + crate::utils::NoRef, { crate::base_helper::bpf_map_pop_elem(map) } #[inline(always)] pub fn bpf_map_peek_elem( &self, map: &'static crate::map::RexMapHandle, ) -> Option where V: Copy + crate::utils::NoRef, { crate::base_helper::bpf_map_peek_elem(map) } #[inline(always)] pub fn bpf_probe_read_kernel( &self, dst: &mut T, unsafe_ptr: *const (), ) -> crate::Result where T: Copy + crate::utils::NoRef, { crate::base_helper::bpf_probe_read_kernel(dst, unsafe_ptr) } #[inline(always)] pub fn bpf_jiffies64(&self) -> u64 { crate::base_helper::bpf_jiffies64() } #[inline(always)] pub fn bpf_get_numa_node_id(&self) -> i32 { crate::base_helper::bpf_get_numa_node_id() } /* #[inline(always)] pub fn bpf_ktime_get_ns_origin(&self) -> u64 { crate::base_helper::bpf_ktime_get_ns_origin() } #[inline(always)] pub fn bpf_ktime_get_boot_ns_origin(&self) -> u64 { crate::base_helper::bpf_ktime_get_boot_ns_origin() } */ #[inline(always)] pub fn bpf_ktime_get_ns(&self) -> u64 { crate::base_helper::bpf_ktime_get_ns() } #[inline(always)] pub fn bpf_ktime_get_boot_ns(&self) -> u64 { crate::base_helper::bpf_ktime_get_boot_ns() } #[inline(always)] pub fn bpf_ktime_get_coarse_ns(&self) -> u64 { crate::base_helper::bpf_ktime_get_coarse_ns() } #[inline(always)] pub fn bpf_get_prandom_u32(&self) -> u32 { crate::base_helper::bpf_get_prandom_u32() } #[inline(always)] pub fn bpf_snprintf( &self, buf: &mut [u8; N], fmt: &str, data: &[u64; M], ) -> crate::Result { crate::base_helper::bpf_snprintf(buf, fmt, data) } // #[inline(always)] // pub fn bpf_ringbuf_reserve( // &self, // map: &'static RexRingBuf, // size: u64, // flags: u64, // ) -> *mut T { // crate::base_helper::bpf_ringbuf_reserve(map, flags) // } // // #[inline(always)] // pub fn bpf_ringbuf_submit(&self, data: &mut T, flags: u64) { // crate::base_helper::bpf_ringbuf_submit(data, flags) // } }; } pub(crate) use base_helper_defs; pub(crate) use termination_check; ================================================ FILE: rex/src/bindings/linux/kernel.rs ================================================ include!(concat!(env!("OUT_DIR"), "/linux/kernel.rs")); ================================================ FILE: rex/src/bindings/linux/mod.rs ================================================ pub mod kernel; ================================================ FILE: rex/src/bindings/mod.rs ================================================ #![allow( non_camel_case_types, non_snake_case, non_upper_case_globals, unused, unnecessary_transmutes )] pub(crate) mod linux; pub mod uapi; ================================================ FILE: rex/src/bindings/uapi/linux/bpf.rs ================================================ include!(concat!(env!("OUT_DIR"), "/uapi/linux/bpf.rs")); ================================================ FILE: rex/src/bindings/uapi/linux/errno.rs ================================================ include!(concat!(env!("OUT_DIR"), "/uapi/linux/errno.rs")); ================================================ FILE: rex/src/bindings/uapi/linux/in.rs ================================================ include!(concat!(env!("OUT_DIR"), "/uapi/linux/in.rs")); ================================================ FILE: rex/src/bindings/uapi/linux/mod.rs ================================================ pub mod bpf; pub mod errno; pub mod r#in; pub mod perf_event; pub mod pkt_cls; pub mod ptrace; pub mod seccomp; pub mod unistd; ================================================ FILE: rex/src/bindings/uapi/linux/perf_event.rs ================================================ include!(concat!(env!("OUT_DIR"), "/uapi/linux/perf_event.rs")); ================================================ FILE: rex/src/bindings/uapi/linux/pkt_cls.rs ================================================ include!(concat!(env!("OUT_DIR"), "/uapi/linux/pkt_cls.rs")); ================================================ FILE: rex/src/bindings/uapi/linux/ptrace.rs ================================================ include!(concat!(env!("OUT_DIR"), "/uapi/linux/ptrace.rs")); ================================================ FILE: rex/src/bindings/uapi/linux/seccomp.rs ================================================ include!(concat!(env!("OUT_DIR"), "/uapi/linux/seccomp.rs")); ================================================ FILE: rex/src/bindings/uapi/linux/unistd.rs ================================================ include!(concat!(env!("OUT_DIR"), "/uapi/linux/unistd.rs")); ================================================ FILE: rex/src/bindings/uapi/mod.rs ================================================ pub mod linux; ================================================ FILE: rex/src/debug.rs ================================================ use core::ffi::{c_int, c_uchar}; use crate::ffi; // WARN must add "\0" at the end of &str, c_str is different from rust str #[unsafe(no_mangle)] pub(crate) unsafe extern "C" fn printk(fmt: &str, mut ap: ...) -> c_int { unsafe { ffi::vprintk(fmt.as_ptr() as *const c_uchar, ap) } } ================================================ FILE: rex/src/ffi.rs ================================================ // All kernel symbols we need should be declared here #![allow(dead_code)] use core::ffi::{c_uchar, VaList}; use crate::bindings::linux::kernel::{ bpf_perf_event_data_kern, sk_buff, task_struct, xdp_buff, MAX_BPRINTF_BUF, }; use crate::bindings::uapi::linux::bpf::{bpf_perf_event_value, bpf_spin_lock}; use crate::panic::{CleanupEntry, ENTRIES_SIZE}; // Functions unsafe extern "C" { /// `void *bpf_map_lookup_elem(struct bpf_map *map, const void *key)` /// /// `struct bpf_map` is opaque in our case so make it a `*mut ()` pub(crate) fn bpf_map_lookup_elem(map: *mut (), key: *const ()) -> *mut (); /// `long bpf_map_update_elem(struct bpf_map *map, const void *key, const /// void *value, u64 flags)` /// /// `struct bpf_map` is opaque in our case so make it a `*mut ()` pub(crate) fn bpf_map_update_elem( map: *mut (), key: *const (), value: *const (), flags: u64, ) -> i64; /// `long bpf_map_delete_elem(struct bpf_map *map, const void *key)` /// /// `struct bpf_map` is opaque in our case so make it a `*mut ()` pub(crate) fn bpf_map_delete_elem(map: *mut (), key: *const ()) -> i64; /// `long bpf_map_push_elem(struct bpf_map *map, const void *value, u64 /// flags)` /// /// `struct bpf_map` is opaque in our case so make it a `*mut ()` pub(crate) fn bpf_map_push_elem( map: *mut (), value: *const (), flags: u64, ) -> i64; /// `long bpf_map_pop_elem(struct bpf_map *map, void *value)` /// /// `struct bpf_map` is opaque in our case so make it a `*mut ()` pub(crate) fn bpf_map_pop_elem(map: *mut (), value: *const ()) -> i64; /// `long bpf_map_peek_elem(struct bpf_map *map, void *value)` /// /// `struct bpf_map` is opaque in our case so make it a `*mut ()` pub(crate) fn bpf_map_peek_elem(map: *mut (), value: *const ()) -> i64; /// `long bpf_probe_read_kernel(void *dst, u32 size, const void /// *unsafe_ptr)` pub(crate) fn bpf_probe_read_kernel( dst: *mut (), size: u32, unsafe_ptr: *const (), ) -> i64; /// `u64 notrace ktime_get_mono_fast_ns(void)` pub(crate) fn ktime_get_mono_fast_ns() -> u64; /// `u64 notrace ktime_get_boot_fast_ns(void)` pub(crate) fn ktime_get_boot_fast_ns() -> u64; /// `u64 bpf_ktime_get_ns(void)` pub(crate) fn bpf_ktime_get_ns() -> u64; /// `u64 bpf_ktime_get_boot_ns(void)` pub(crate) fn bpf_ktime_get_boot_ns() -> u64; /// `u64 bpf_ktime_get_coarse_ns(void)` pub(crate) fn bpf_ktime_get_coarse_ns() -> u64; /// `u32 get_random_u32(void)` pub(crate) fn get_random_u32() -> u32; /// `long bpf_snprintf_btf(char *str, u32 str_size, struct btf_ptr *ptr, u32 /// btf_ptr_size, u64 flags)` pub(crate) fn bpf_snprintf( str: *mut u8, str_size: u32, fmt: *const u8, data: *const u64, data_len: u32, ) -> i64; /// `asmlinkage int vprintk(const char *fmt, va_list args)` pub(crate) fn vprintk(fmt: *const c_uchar, args: VaList) -> i32; /// `__nocfi noinline void notrace __noreturn rex_landingpad(char *msg)` /// /// The in-kernel panic landingpad for panic recovery pub(crate) fn rex_landingpad() -> !; /// `long bpf_spin_lock(struct bpf_spin_lock *lock)` pub(crate) fn bpf_spin_lock(lock: *mut bpf_spin_lock) -> i64; /// `long bpf_spin_unlock(struct bpf_spin_lock *lock)` pub(crate) fn bpf_spin_unlock(lock: *mut bpf_spin_lock) -> i64; /// `asmlinkage void just_return_func(void)` pub(crate) fn just_return_func(); /// `long bpf_get_stackid_pe(struct bpf_perf_event_data_kern *ctx, struct /// bpf_map *map, u64 flags)` /// /// The specialized version of `bpf_get_stackid` for perf event programs /// /// Also allow improper_ctypes here since the empty lock_class_key is /// guaranteed not touched by us #[allow(improper_ctypes)] pub(crate) fn bpf_get_stackid_pe( ctx: *const bpf_perf_event_data_kern, map: *mut (), flags: u64, ) -> i64; /// `long bpf_perf_prog_read_value(struct bpf_perf_event_data *ctx, struct /// bpf_perf_event_value *buf, u32 buf_size)` /// /// Also allow improper_ctypes here since the empty lock_class_key is /// guaranteed not touched by us #[allow(improper_ctypes)] pub(crate) fn bpf_perf_prog_read_value( ctx: *const bpf_perf_event_data_kern, buf: &mut bpf_perf_event_value, size: u32, ) -> i64; /// `long bpf_perf_event_output_tp(void *tp_buff, struct bpf_map *map, u64 /// flags, void *data, u64 size)` pub(crate) fn bpf_perf_event_output_tp( tp_buff: *const (), map: *mut (), flags: u64, data: *const (), size: u64, ) -> i64; /// `long bpf_perf_event_read_value(struct bpf_map *map, u64 flags, /// struct bpf_perf_event_value *buf, u32 buf_size)` /// same reason for use of improper_ctypes as bpf_perf_prog_read_value #[allow(improper_ctypes)] pub(crate) fn bpf_perf_event_read_value( map: *mut (), flags: u64, buf: &mut bpf_perf_event_value, buf_size: u32, ) -> i64; /// `long bpf_skb_event_output(struct sk_buff *skb, struct bpf_map *map, u64 /// flags, void *meta, u64 meta_size)` /// The compiler complains about some non-FFI safe type, but since the /// kernel is using it fine it should be safe for an FFI call using C ABI #[allow(improper_ctypes)] pub(crate) fn bpf_skb_event_output( skb: *const sk_buff, map: *mut (), flags: u64, meta: *const (), meta_size: u64, ) -> i64; /// `long bpf_xdp_event_output(struct xdp_buff *xdp, struct bpf_map *map, /// u64 flags, void *meta, u64 meta_size)` /// The compiler complains about some non-FFI safe type, but since the /// kernel is using it fine it should be safe for an FFI call using C ABI #[allow(improper_ctypes)] pub(crate) fn bpf_xdp_event_output( xdp: *const xdp_buff, map: *mut (), flags: u64, meta: *const (), meta_size: u64, ) -> i64; /// `long bpf_xdp_adjust_head(struct xdp_buff *xdp, int offset)` /// /// The compiler complains about some non-FFI safe type, but since the /// kernel is using it fine it should be safe for an FFI call using C ABI #[allow(improper_ctypes)] pub(crate) fn bpf_xdp_adjust_head(xdp: *mut xdp_buff, offset: i32) -> i32; /// long bpf_xdp_adjust_tail(struct xdp_buff *xdp, int offset) /// /// The compiler complains about some non-FFI safe type, but since the /// kernel is using it fine it should be safe for an FFI call using C ABI #[allow(improper_ctypes)] pub(crate) fn bpf_xdp_adjust_tail(xdp: *mut xdp_buff, offset: i32) -> i32; /// long bpf_clone_redirect(struct sk_buff *skb, u32 ifindex, u64 flags) /// /// The compiler complains about some non-FFI safe type, but since the /// kernel is using it fine it should be safe for an FFI call using C ABI #[allow(improper_ctypes)] pub(crate) fn bpf_clone_redirect( skb: *mut sk_buff, ifindex: u32, flags: u64, ) -> i32; /// void *bpf_ringbuf_reserve(void *ringbuf, u64 size, u64 flags) pub(crate) fn bpf_ringbuf_reserve( ringbuf: *mut (), size: u64, flags: u64, ) -> *mut (); /// long bpf_ringbuf_output(void *ringbuf, void *data, u64 size, u64 flags) // data is marked `ARG_PTR_TO_MEM | MEM_RDONLY`, which implies the argument // is comptiable with readonly memory and does not modifiy the memory // pointed by the pointer, therefore, we use a *const () type. pub(crate) fn bpf_ringbuf_output( ringbuf: *mut (), data: *const (), size: u64, flags: u64, ) -> i64; /// void bpf_ringbuf_submit(void *data, u64 flags) pub(crate) fn bpf_ringbuf_submit(data: *mut (), flags: u64); /// void bpf_ringbuf_discard(void *data, u64 flags) pub(crate) fn bpf_ringbuf_discard(data: *mut (), flags: u64); /// u64 bpf_ringbuf_query(void *ringbuf, u64 flags) pub(crate) fn bpf_ringbuf_query(ringbuf: *mut (), flags: u64) -> u64; /// void rex_trace_printk(void) pub(crate) fn rex_trace_printk(); /// __bpf_kfunc struct task_struct *bpf_task_from_pid(s32 pid) pub(crate) fn bpf_task_from_pid(pid: i32) -> *mut task_struct; /// __bpf_kfunc void bpf_task_release(struct task_struct *p) pub(crate) fn bpf_task_release(task: *mut task_struct); } // Global variables unsafe extern "C" { /// `extern unsigned long volatile __cacheline_aligned_in_smp /// __jiffy_arch_data jiffies;` /// /// Real definition done via linker script (`arch/x86/kernel/vmlinux.lds.S`) /// and is made an alias to `jiffies_64` on x86 pub(crate) static jiffies: u64; /// `DEFINE_PER_CPU(int, numa_node);` pub(crate) static numa_node: i32; /// `DEFINE_PER_CPU(struct rex_cleanup_entry[64], rex_cleanup_entries) /// ____cacheline_aligned = { 0 };` /// /// Used for cleanup upon panic /// /// Pointee type omitted since this per-cpu variable will never be directly /// dereferenced, it is always used for per-cpu address calculation /// /// Allow the use of rust fn ptr as the function is only called in Rust #[allow(improper_ctypes)] pub(crate) static mut rex_cleanup_entries: [CleanupEntry; ENTRIES_SIZE]; /// `DEFINE_PER_CPU(void *, rex_stack_ptr);` /// /// Top of the per-cpu stack for rex programs pub(crate) static rex_stack_ptr: u64; /// `DECLARE_PER_CPU_CACHE_HOT(struct task_struct *, current_task);` /// /// Per-cpu pointer of the current task // rustc properly treats the empty `lock_class_key` as zero-sized #[allow(improper_ctypes)] pub(crate) static current_task: *mut task_struct; /// `DECLARE_PER_CPU_CACHE_HOT(int, cpu_number);` /// /// Current CPU number pub(crate) static cpu_number: i32; /// `DEFINE_PER_CPU(int, rex_termination_state);` /// /// Used to indidicate whether a BPF program in a CPU is executing /// inside a helper, or inside a panic handler, or just in BPF text. pub(crate) static mut rex_termination_state: u8; /// DEFINE_PER_CPU_READ_MOSTLY(unsigned long, this_cpu_off) = /// BOOT_PERCPU_OFFSET; /// /// Offset on the current pub(crate) static this_cpu_off: u64; /// DEFINE_PER_CPU(char[MAX_BPRINTF_BUF], rex_log_buf) = { 0 }; pub(crate) static mut rex_log_buf: [u8; MAX_BPRINTF_BUF as usize]; } ================================================ FILE: rex/src/kprobe/kprobe_impl.rs ================================================ use core::marker::PhantomData; use crate::bindings::uapi::linux::bpf::bpf_map_type; use crate::ffi; use crate::pt_regs::PtRegs; use crate::task_struct::TaskStruct; #[repr(C)] pub struct kprobe { _placeholder: PhantomData<()>, } impl kprobe { crate::base_helper::base_helper_defs!(); pub const unsafe fn new() -> kprobe { Self { _placeholder: PhantomData, } } // Now returns a mutable ref, but since every reg is private the user prog // cannot change reg contents. The user should not be able to directly // assign this reference a new value either, given that they will not able // to create another instance of pt_regs (private fields, no pub ctor) pub unsafe fn convert_ctx(&self, ctx: *mut ()) -> &'static mut PtRegs { // ctx has actual type *mut crate::bindings::linux::kernel::pt_regs // therefore it is safe to just interpret it as a *mut pt_regs // since the later is #[repr(transparent)] over the former unsafe { &mut *(ctx as *mut PtRegs) } } #[cfg(CONFIG_BPF_KPROBE_OVERRIDE = "y")] pub fn bpf_override_return(&self, regs: &mut PtRegs, rc: u64) -> i32 { regs.regs.ax = rc; regs.regs.ip = ffi::just_return_func as *const () as u64; 0 } pub fn bpf_get_current_task(&self) -> Option { TaskStruct::get_current_task() } } ================================================ FILE: rex/src/kprobe/mod.rs ================================================ mod kprobe_impl; pub use kprobe_impl::*; ================================================ FILE: rex/src/lib.rs ================================================ #![no_std] #![feature( array_ptr_get, auto_traits, c_variadic, core_intrinsics, negative_impls )] #![allow(non_camel_case_types, internal_features)] pub mod kprobe; pub mod map; pub mod perf_event; pub mod pt_regs; pub mod sched_cls; pub mod spinlock; pub mod task_struct; pub mod tracepoint; pub mod utils; pub mod xdp; mod base_helper; mod bindings; mod debug; mod ffi; mod log; mod panic; mod per_cpu; mod random32; extern crate paste; pub use rex_macros::*; #[cfg(not(CONFIG_KALLSYMS_ALL = "y"))] compile_error!("CONFIG_KALLSYMS_ALL is required for rex"); pub use bindings::uapi::*; pub use log::rex_trace_printk; pub use utils::Result; ================================================ FILE: rex/src/log.rs ================================================ use core::fmt::{self, Write}; use crate::base_helper::termination_check; use crate::bindings::uapi::linux::errno::E2BIG; use crate::ffi; use crate::per_cpu::this_cpu_ptr_mut; /// An abstraction over the in-kernel per-cpu log buffer /// This struct implements [`Write`], and therefore can be used for formatting pub(crate) struct LogBuf { buf: &'static mut [u8], off: usize, } impl LogBuf { /// Construct a new `LogBuf` from the kernel log buffer on the current CPU pub(crate) fn new() -> Self { let buf = unsafe { &mut *this_cpu_ptr_mut(&raw mut ffi::rex_log_buf).as_mut_slice() }; Self { buf, off: 0 } } /// Reset the offset of the buffer, i.e. discarding all contents not yet /// sent to the kernel #[inline(always)] pub(crate) fn reset(&mut self) { self.off = 0; } } impl Write for LogBuf { /// Writes a string slice into the kernel buffer on this CPU fn write_str(&mut self, s: &str) -> fmt::Result { let input_len = s.len(); let available = self.buf.len() - self.off - 1; // Make sure we have enough space if input_len > available { return Err(fmt::Error); } // Copy and null-terminated the buf let end = self.off + input_len; self.buf[self.off..end].copy_from_slice(s.as_bytes()); self.buf[end] = 0; // Update the write offset self.off = end; Ok(()) } } #[macro_export] macro_rules! function_name { () => {{ fn f() {} fn type_name_of(_: T) -> &'static str { core::any::type_name::() } let data = type_name_of(f); &data[..data.len() - 3] }}; } /// Prints a message defined by `args` to the TraceFS file /// `/sys/kernel/debug/tracing/trace`. pub fn rex_trace_printk(args: fmt::Arguments<'_>) -> crate::Result { // Format and write message to the per-cpu buf, then print it out write!(&mut LogBuf::new(), "{}", args).map_err(|_| -(E2BIG as i32))?; termination_check!(unsafe { ffi::rex_trace_printk() }); Ok(0) } /// `println`-style convenience macro for [`rex_trace_printk`]. /// Different from `println`, this macro produces the value of [`crate::Result`] /// from [`rex_trace_printk`] #[cfg(feature = "debug_printk")] #[macro_export] macro_rules! rex_printk { ($($arg:tt)*) => {{ $crate::rex_trace_printk( format_args!( "[{}] {}", $crate::function_name!(), format_args!($($arg)*) ), ) }}; } #[cfg(not(feature = "debug_printk"))] #[macro_export] macro_rules! rex_printk { ($($arg:tt)*) => { $crate::Result::Ok(0) }; } ================================================ FILE: rex/src/map.rs ================================================ use core::fmt::{self, Write}; use core::intrinsics::unlikely; use core::marker::PhantomData; use core::ops::{Deref, DerefMut}; use core::{mem, ptr, slice}; use crate::base_helper::{ bpf_map_delete_elem, bpf_map_lookup_elem, bpf_map_peek_elem, bpf_map_pop_elem, bpf_map_push_elem, bpf_map_update_elem, termination_check, }; use crate::ffi; use crate::linux::bpf::{ bpf_map_type, BPF_ANY, BPF_EXIST, BPF_MAP_TYPE_ARRAY, BPF_MAP_TYPE_HASH, BPF_MAP_TYPE_PERCPU_ARRAY, BPF_MAP_TYPE_PERF_EVENT_ARRAY, BPF_MAP_TYPE_QUEUE, BPF_MAP_TYPE_RINGBUF, BPF_MAP_TYPE_STACK, BPF_MAP_TYPE_STACK_TRACE, BPF_NOEXIST, BPF_RB_AVAIL_DATA, BPF_RB_CONS_POS, BPF_RB_PROD_POS, BPF_RB_RING_SIZE, }; use crate::linux::errno::EINVAL; use crate::utils::{ to_result, NoRef, PerfEventMaskedCPU, PerfEventStreamer, Result, }; /// Rex equivalent to be used for map APIs in place of the `struct bpf_map`. /// The key and the value type are encoded as generics types `K` and `V`. /// The map type is encoded as a const-generic using the `bpf_map_type` enum. #[repr(C)] pub struct RexMapHandle where V: Copy + NoRef, { // Map metadata map_type: u32, key_size: u32, val_size: u32, max_size: u32, map_flag: u32, // Actual kernel side map pointer pub(crate) kptr: *mut (), // Zero-sized marker key_type: PhantomData, val_type: PhantomData, } impl RexMapHandle where V: Copy + NoRef, { pub const fn new(ms: u32, mf: u32) -> RexMapHandle { Self { map_type: MT, key_size: mem::size_of::() as u32, val_size: mem::size_of::() as u32, max_size: ms, map_flag: mf, kptr: ptr::null_mut(), key_type: PhantomData, val_type: PhantomData, } } } unsafe impl Sync for RexMapHandle where V: Copy + NoRef { } pub type RexStackTrace = RexMapHandle; pub type RexPerCPUArrayMap = RexMapHandle; pub type RexPerfEventArray = RexMapHandle; pub type RexArrayMap = RexMapHandle; pub type RexHashMap = RexMapHandle; pub type RexStack = RexMapHandle; pub type RexQueue = RexMapHandle; pub type RexRingBuf = RexMapHandle; impl<'a, K, V> RexHashMap where V: Copy + NoRef, { pub fn insert(&'static self, key: &K, value: &V) -> Result { bpf_map_update_elem(self, key, value, BPF_ANY as u64) } pub fn insert_new(&'static self, key: &K, value: &V) -> Result { bpf_map_update_elem(self, key, value, BPF_NOEXIST as u64) } pub fn update(&'static self, key: &K, value: &V) -> Result { bpf_map_update_elem(self, key, value, BPF_EXIST as u64) } pub fn get_mut(&'static self, key: &'a K) -> Option<&'a mut V> { bpf_map_lookup_elem(self, key) } pub fn delete(&'static self, key: &K) -> Result { bpf_map_delete_elem(self, key) } } impl<'a, V> RexArrayMap where V: Copy + NoRef, { pub fn insert(&'static self, key: &u32, value: &V) -> Result { bpf_map_update_elem(self, key, value, BPF_ANY as u64) } pub fn get_mut(&'static self, key: &'a u32) -> Option<&'a mut V> { bpf_map_lookup_elem(self, key) } pub fn delete(&'static self, key: &u32) -> Result { bpf_map_delete_elem(self, key) } } impl RexPerfEventArray where V: Copy + NoRef, { pub fn output( &'static self, program: &P, ctx: &P::Context, data: &V, cpu: PerfEventMaskedCPU, ) -> Result { program.output_event(ctx, self, data, cpu) } } impl RexStack where V: Copy + NoRef, { pub fn push(&'static self, value: &V) -> Result { bpf_map_push_elem(self, value, BPF_ANY as u64) } pub fn force_push(&'static self, value: &V) -> Result { bpf_map_push_elem(self, value, BPF_EXIST as u64) } pub fn pop(&'static self) -> Option { bpf_map_pop_elem(self) } pub fn peek(&'static self) -> Option { bpf_map_peek_elem(self) } } impl RexQueue where V: Copy + NoRef, { pub fn push(&'static self, value: &V) -> Result { bpf_map_push_elem(self, value, BPF_ANY as u64) } pub fn force_push(&'static self, value: &V) -> Result { bpf_map_push_elem(self, value, BPF_EXIST as u64) } pub fn pop(&'static self) -> Option { bpf_map_pop_elem(self) } pub fn peek(&'static self) -> Option { bpf_map_peek_elem(self) } } impl RexRingBuf { /// Reserves `size` bytes of payload in the ring buffer. /// /// If the operation succeeds, A [`RexRingBufEntry`] representing the /// payload is returned, otherwise (e.g., there is not enough memory /// available), `None` is returned. pub fn reserve<'a>( &'static self, size: usize, ) -> Option> { let map_kptr = unsafe { core::ptr::read_volatile(&self.kptr) }; if unlikely(map_kptr.is_null()) { return None; } let data = termination_check!(unsafe { ffi::bpf_ringbuf_reserve(map_kptr, size as u64, 0) }); if data.is_null() { None } else { let data = unsafe { slice::from_raw_parts_mut(data as *mut u8, size) }; Some(RexRingBufEntry { data, off: 0 }) } } /// Copies bytes from the `data` slice into the ring buffer. /// /// If [`crate::linux::bpf::BPF_RB_NO_WAKEUP`] is specified in `flags`, /// no notification of new data availability is sent. /// If [`crate::linux::bpf::BPF_RB_FORCE_WAKEUP`] is specified in `flags`, /// notification of new data availability is sent unconditionally. /// If `0` is specified in `flags`, an adaptive notification of new data /// availability is sent. /// /// Returns a [`crate::Result`] on whether the operation is successful pub fn output(&'static self, data: &[u8], flags: u64) -> crate::Result { let map_kptr = unsafe { core::ptr::read_volatile(&self.kptr) }; if unlikely(map_kptr.is_null()) { return Err(EINVAL as i32); } termination_check!(unsafe { to_result!(ffi::bpf_ringbuf_output( map_kptr, data.as_ptr() as *const (), data.len() as u64, flags )) }) } /// Queries the amount of data not yet consumed. /// /// Returns `None` is `self` is not a valid ring buffer. pub fn available_bytes(&'static self) -> Option { let map_kptr = unsafe { core::ptr::read_volatile(&self.kptr) }; if unlikely(map_kptr.is_null()) { return None; } termination_check!(unsafe { Some(ffi::bpf_ringbuf_query(map_kptr, BPF_RB_AVAIL_DATA as u64)) }) } /// Queries the size of ring buffer. /// /// Returns `None` is `self` is not a valid ring buffer. pub fn size(&'static self) -> Option { let map_kptr = unsafe { core::ptr::read_volatile(&self.kptr) }; if unlikely(map_kptr.is_null()) { return None; } termination_check!(unsafe { Some(ffi::bpf_ringbuf_query(map_kptr, BPF_RB_RING_SIZE as u64)) }) } /// Queries the consumer position, which may wrap around. /// /// Returns `None` is `self` is not a valid ring buffer. pub fn consumer_position(&'static self) -> Option { let map_kptr = unsafe { core::ptr::read_volatile(&self.kptr) }; if unlikely(map_kptr.is_null()) { return None; } termination_check!(unsafe { Some(ffi::bpf_ringbuf_query(map_kptr, BPF_RB_CONS_POS as u64)) }) } /// Queries the Producer(s) position which may wrap around. /// /// Returns `None` is `self` is not a valid ring buffer. pub fn producer_position(&'static self) -> Option { let map_kptr = unsafe { core::ptr::read_volatile(&self.kptr) }; if unlikely(map_kptr.is_null()) { return None; } termination_check!(unsafe { Some(ffi::bpf_ringbuf_query(map_kptr, BPF_RB_PROD_POS as u64)) }) } } pub struct RexRingBufEntry<'a> { data: &'a mut [u8], off: usize, // offset when the entry is used as a &str } impl RexRingBufEntry<'_> { /// Consumes the reserved payload and submits it to the ring buffer. /// /// If [`crate::linux::bpf::BPF_RB_NO_WAKEUP`] is specified in `flags`, /// no notification of new data availability is sent. /// If [`crate::linux::bpf::BPF_RB_FORCE_WAKEUP`] is specified in `flags`, /// notification of new data availability is sent unconditionally. /// If `0` is specified in `flags`, an adaptive notification of new data /// availability is sent. /// /// This method always succeeds. pub fn submit(self, flags: u64) { termination_check!(unsafe { ffi::bpf_ringbuf_submit(self.data.as_mut_ptr() as *mut (), flags) }); // Avoid calling ringbuf_discard twice mem::forget(self); } /// Consumes the reserved payload and discards it. /// /// If [`crate::linux::bpf::BPF_RB_NO_WAKEUP`] is specified in `flags`, /// no notification of new data availability is sent. /// If [`crate::linux::bpf::BPF_RB_FORCE_WAKEUP`] is specified in `flags`, /// notification of new data availability is sent unconditionally. /// If `0` is specified in `flags`, an adaptive notification of new data /// availability is sent. /// /// This method always succeeds. pub fn discard(self, flags: u64) { termination_check!(unsafe { ffi::bpf_ringbuf_discard(self.data.as_mut_ptr() as *mut (), flags) }); // Avoid calling ringbuf_discard twice mem::forget(self); } } impl Write for RexRingBufEntry<'_> { fn write_str(&mut self, s: &str) -> fmt::Result { let input_len = s.len(); // Remaining capacity plus the space reserved for the null-terminated let available = self.data.len().saturating_sub(self.off + 1); // Make sure we have enough space if input_len > available { return Err(fmt::Error); } // Copy and null-terminated the buf let end = self.off + input_len; self.data[self.off..end].copy_from_slice(s.as_bytes()); self.data[end] = 0; // Update the write offset self.off = end; Ok(()) } } impl Deref for RexRingBufEntry<'_> { type Target = [u8]; fn deref(&self) -> &Self::Target { self.data } } impl DerefMut for RexRingBufEntry<'_> { fn deref_mut(&mut self) -> &mut Self::Target { self.data } } impl core::ops::Drop for RexRingBufEntry<'_> { /// Discard reserved payload when dropped fn drop(&mut self) { termination_check!(unsafe { ffi::bpf_ringbuf_discard(self.data.as_mut_ptr() as *mut (), 0) }); } } ================================================ FILE: rex/src/panic.rs ================================================ //! Implementation of various routines/frameworks related to EH/termination use core::fmt::Write; use core::panic::PanicInfo; use crate::ffi; use crate::log::LogBuf; use crate::per_cpu::this_cpu_ptr_mut; /// Needs to match the kernel side per-cpu definition pub(crate) const ENTRIES_SIZE: usize = 64; pub(crate) type CleanupFn = unsafe fn(*mut ()) -> (); /// Aggregate to hold cleanup information of a specific object. The information /// is used during panics to ensure proper cleanup of allocated kernel /// resources. The `valid` field is used to mark whether this given entry holds /// valid information. The cleanup will happen in the form of /// `cleanup_fn(cleanup_arg)` /// /// `#[repr(C)]` is needed because this struct is used from the kernel side. #[derive(Debug, Copy, Clone)] #[repr(C)] pub(crate) struct CleanupEntry { pub(crate) valid: u64, pub(crate) cleanup_fn: Option, pub(crate) cleanup_arg: *mut (), } impl CleanupEntry { /// Create a new entry with valid function and argument #[inline] pub(crate) fn new(cleanup_fn: CleanupFn, cleanup_arg: *mut ()) -> Self { Self { valid: 1, cleanup_fn: Some(cleanup_fn), cleanup_arg, } } /// Run cleanup function #[inline] pub(crate) unsafe fn cleanup(&self) { if self.valid != 0 { if let Some(cleanup_fn) = self.cleanup_fn { unsafe { (cleanup_fn)(self.cleanup_arg); } } } } } impl Default for CleanupEntry { /// Create a default entry without valid function and argument #[inline] fn default() -> Self { Self { valid: 0, cleanup_fn: None, cleanup_arg: core::ptr::null_mut(), } } } /// Represents an array of `CleanupEntry` on a given CPU. The backing storage /// is defined as a per-cpu array in the kernel. pub(crate) struct CleanupEntries<'a> { entries: &'a mut [CleanupEntry], } impl<'a> CleanupEntries<'a> { /// Retrieve the array of `CleanupEntry` on the current CPU. #[inline] fn this_cpu_cleanup_entries() -> CleanupEntries<'a> { let entries: &mut [CleanupEntry]; unsafe { entries = &mut *this_cpu_ptr_mut(&raw mut ffi::rex_cleanup_entries) .as_mut_slice(); } Self { entries } } /// Finds the next empty entry in the array /// /// Triggers a panic when the array is full. This is allowed because /// `CleanupEntries::register_cleanup` is its only caller and is only /// called by object constructors #[inline] fn find_next_emtpy_entry(&mut self) -> (usize, &mut CleanupEntry) { for (idx, entry) in self.entries.iter_mut().enumerate() { if entry.valid == 0 { return (idx, entry); } } panic!("Object count exceeded\n"); } /// This function is (and must only be) called by object constructors /// /// Panic is allowed here pub(crate) fn register_cleanup( cleanup_fn: CleanupFn, cleanup_arg: *mut (), ) -> usize { let mut entries = Self::this_cpu_cleanup_entries(); let (idx, entry) = entries.find_next_emtpy_entry(); *entry = CleanupEntry::new(cleanup_fn, cleanup_arg); idx } /// This function is called by the object drop handler. It invalidates the /// entry corresponding to the object. pub(crate) fn deregister_cleanup(idx: usize) { let entries = Self::this_cpu_cleanup_entries(); entries.entries[idx].valid = 0; } /// This function is called on panic to cleanup everything on the current /// CPU. It **must** not cause another panic pub(crate) unsafe fn cleanup_all() { let entries = Self::this_cpu_cleanup_entries(); for entry in entries.entries.iter_mut() { unsafe { entry.cleanup(); } entry.valid = 0; } } } // The best way to deal with this is probably insert it directly in LLVM IR as // an inline asm block // For now, use inline(always) to hint the compiler for inlining if LTO is on #[allow(unused_attributes)] #[unsafe(no_mangle)] // Note: Rust warns that inline(always) is ignored on no_mangle functions, // #[inline(always)] + #[no_mangle] under fat LTO generally means: inline // internally where possible, but still keep the exported symbol #[inline(always)] unsafe fn __rex_check_stack() { // The program can only use the top 4 pages of the stack, therefore subtract // 0x4000 unsafe { core::arch::asm!( "mov {1:r}, gs:[{0:r}]", "sub {1:r}, 0x4000", "cmp rsp, {1:r}", "ja 2f", "call __rex_handle_stack_overflow", "2:", in(reg) &ffi::rex_stack_ptr as *const u64 as u64, lateout(reg) _, ); } } #[unsafe(no_mangle)] pub(crate) unsafe fn __rex_handle_timeout() -> ! { panic!("Timeout in Rex program"); } #[unsafe(no_mangle)] unsafe fn __rex_handle_stack_overflow() -> ! { panic!("Stack overflow in Rex program"); } // This function is called on panic. #[panic_handler] fn panic(info: &PanicInfo) -> ! { // Set the termination flag unsafe { let termination_flag: *mut u8 = crate::per_cpu::this_cpu_ptr_mut( &raw mut crate::ffi::rex_termination_state, ); *termination_flag = 1; }; unsafe { CleanupEntries::cleanup_all() }; let mut buf = LogBuf::new(); if write!(&mut buf, "{}", info).is_err() { buf.reset(); // This string always fits in the buffer, so we ignore the Result write!(&mut buf, "unknown rust panic").ok(); } unsafe { ffi::rex_landingpad() } } ================================================ FILE: rex/src/per_cpu.rs ================================================ use crate::ffi; pub(crate) trait PerCPURead { unsafe fn this_cpu_read(addr: *const Self) -> Self; } // rustc does not auto-detect subregs for us macro_rules! reg_template { (u64) => { ":r" }; (i64) => { ":r" }; (u32) => { ":e" }; (i32) => { ":e" }; (u16) => { ":x" }; (i16) => { ":x" }; } macro_rules! impl_pcpu_read_integral { ($t:tt $($ts:tt)*) => { impl PerCPURead for $t { #[inline(always)] unsafe fn this_cpu_read(addr: *const Self) -> Self { let mut var: Self; unsafe { core::arch::asm!( concat!("mov {0", reg_template!($t), "}, gs:[{1:r}]"), lateout(reg) var, in(reg) addr, options(readonly, nostack), ); } var } } impl_pcpu_read_integral!($($ts)*); }; () => {}; } macro_rules! impl_pcpu_read_byte { ($t:tt $($ts:tt)*) => { impl PerCPURead for $t { #[inline(always)] unsafe fn this_cpu_read(addr: *const Self) -> Self { let mut var: Self; unsafe { core::arch::asm!( concat!("mov {0}, gs:[{1:r}]"), lateout(reg_byte) var, in(reg) addr, options(readonly, nostack), ); } var } } impl_pcpu_read_byte!($($ts)*); }; () => {}; } macro_rules! impl_pcpu_read_ptr { ($t:tt $($ts:tt)*) => { impl PerCPURead for *$t T { #[inline(always)] unsafe fn this_cpu_read(addr: *const Self) -> Self { let mut var: Self; unsafe { core::arch::asm!( concat!("mov {0:r}, gs:[{1:r}]"), lateout(reg) var, in(reg) addr, options(readonly, nostack), ); } var } } impl_pcpu_read_ptr!($($ts)*); }; () => {}; } impl_pcpu_read_integral!(u64 i64 u32 i32 u16 i16); impl_pcpu_read_byte!(u8 i8); // Mut: we have the CPU and assume no nesting impl_pcpu_read_ptr!(const mut); /// For values of per-cpu variables #[inline(always)] pub(crate) unsafe fn this_cpu_read(pcp_addr: *const T) -> T { unsafe { T::this_cpu_read(pcp_addr) } } /// For addresses of per-cpu variables /// This is more expensive (in terms of # of insns) #[allow(dead_code)] #[inline(always)] pub unsafe fn this_cpu_ptr(pcp_addr: *const T) -> *const T { unsafe { pcp_addr.byte_add(this_cpu_read(&raw const ffi::this_cpu_off) as usize) } } #[inline(always)] pub unsafe fn this_cpu_ptr_mut(pcp_addr: *mut T) -> *mut T { unsafe { pcp_addr.byte_add(this_cpu_read(&raw const ffi::this_cpu_off) as usize) } } ================================================ FILE: rex/src/perf_event/mod.rs ================================================ mod perf_event_impl; pub use perf_event_impl::*; ================================================ FILE: rex/src/perf_event/perf_event_impl.rs ================================================ use core::intrinsics::unlikely; use core::marker::PhantomData; use crate::base_helper::termination_check; use crate::bindings::linux::kernel::bpf_perf_event_data_kern; use crate::bindings::uapi::linux::bpf::{bpf_map_type, bpf_perf_event_value}; use crate::ffi; use crate::linux::errno::EINVAL; use crate::map::*; use crate::pt_regs::PtRegs; use crate::task_struct::TaskStruct; use crate::utils::{to_result, NoRef, Result}; #[repr(transparent)] pub struct bpf_perf_event_data { kdata: bpf_perf_event_data_kern, } impl bpf_perf_event_data { #[inline(always)] pub fn regs(&self) -> &PtRegs { unsafe { &*(self.kdata.regs as *const PtRegs) } } #[inline(always)] pub fn sample_period(&self) -> u64 { unsafe { (*self.kdata.data).period } } #[inline(always)] pub fn addr(&self) -> u64 { unsafe { (*self.kdata.data).addr } } } #[repr(C)] pub struct perf_event { _placeholder: PhantomData<()>, } impl perf_event { crate::base_helper::base_helper_defs!(); pub const unsafe fn new() -> perf_event { Self { _placeholder: PhantomData, } } pub unsafe fn convert_ctx( &self, ctx: *mut (), ) -> &'static bpf_perf_event_data { unsafe { &*(ctx as *mut bpf_perf_event_data) } } pub fn bpf_perf_prog_read_value( &self, ctx: &bpf_perf_event_data, buf: &mut bpf_perf_event_value, ) -> Result { let size = core::mem::size_of::() as u32; let ctx_kptr = ctx as *const bpf_perf_event_data as *const bpf_perf_event_data_kern; termination_check!(unsafe { to_result!(ffi::bpf_perf_prog_read_value(ctx_kptr, buf, size)) }) } pub fn bpf_get_stackid_pe( &self, ctx: &bpf_perf_event_data, map: &'static RexStackTrace, flags: u64, ) -> Result where V: Copy + NoRef, { let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) }; if unlikely(map_kptr.is_null()) { return Err(EINVAL as i32); } let ctx_kptr = ctx as *const bpf_perf_event_data as *const bpf_perf_event_data_kern; termination_check!(unsafe { to_result!(ffi::bpf_get_stackid_pe(ctx_kptr, map_kptr, flags)) }) } pub fn bpf_get_current_task(&self) -> Option { TaskStruct::get_current_task() } } ================================================ FILE: rex/src/pt_regs.rs ================================================ use paste::paste; use crate::bindings::linux::kernel::pt_regs; /// Transparently wraps around the kernel-internal `struct pt_regs` and make the /// fields read-only to prevent user-defined code from modifying the registers #[repr(transparent)] pub struct PtRegs { pub(crate) regs: pt_regs, } macro_rules! decl_reg_accessors_1 { ($t:ident $($ts:ident)*) => { #[inline(always)] pub fn $t(&self) -> u64 { self.regs.$t } decl_reg_accessors_1!($($ts)*); }; () => {}; } macro_rules! decl_reg_accessors_2 { ($t:ident $($ts:ident)*) => { paste! { #[inline(always)] pub fn [](&self) -> u64 { self.regs.$t } } decl_reg_accessors_2!($($ts)*); }; () => {}; } macro_rules! decl_reg_accessors { ($t1:ident $($ts1:ident)*, $t2:ident $($ts2:ident)*) => { // regs that does not require special handling decl_reg_accessors_1!($t1 $($ts1)*); // regs that does not have the 'r' prefix in kernel pt_regs decl_reg_accessors_2!($t2 $($ts2)*); } } impl PtRegs { decl_reg_accessors!(r15 r14 r13 r12 r11 r10 r9 r8, bp bx ax cx dx si di ip sp); // orig_rax cs eflags ss cannot be batch-processed by macros #[inline(always)] pub fn orig_rax(&self) -> u64 { self.regs.orig_ax } #[inline(always)] pub fn cs(&self) -> u64 { unsafe { self.regs.__bindgen_anon_1.cs as u64 } } #[inline(always)] pub fn eflags(&self) -> u64 { self.regs.flags } #[inline(always)] pub fn ss(&self) -> u64 { unsafe { self.regs.__bindgen_anon_2.ss as u64 } } } ================================================ FILE: rex/src/random32.rs ================================================ use crate::ffi; // fn get_cpu_var() #[inline(always)] pub(crate) fn bpf_user_rnd_u32() -> u32 { // directly use get_random_u32 unsafe { ffi::get_random_u32() } } ================================================ FILE: rex/src/sched_cls/mod.rs ================================================ // mod binding; mod sched_cls_impl; pub use sched_cls_impl::*; ================================================ FILE: rex/src/sched_cls/sched_cls_impl.rs ================================================ use core::ffi::{c_char, c_uchar}; use core::marker::PhantomData; use core::{mem, slice}; use crate::base_helper::termination_check; use crate::bindings::linux::kernel::{ ethhdr, iphdr, sk_buff, sock, tcphdr, udphdr, }; use crate::bindings::uapi::linux::bpf::bpf_map_type; pub use crate::bindings::uapi::linux::pkt_cls::{ TC_ACT_OK, TC_ACT_REDIRECT, TC_ACT_SHOT, }; use crate::ffi; use crate::utils::*; pub struct __sk_buff<'a> { pub data_slice: &'a mut [c_uchar], kptr: &'static mut sk_buff, } // Define accessors of program-accessible fields // TODO: may need to append more based on __sk_buff impl<'a> __sk_buff<'a> { #[inline(always)] pub fn len(&self) -> u32 { self.kptr.len } #[inline(always)] pub fn data_len(&self) -> u32 { self.kptr.data_len } #[inline(always)] pub fn protocol(&self) -> u16be { u16be(unsafe { (self.kptr.__bindgen_anon_4.__bindgen_anon_1) .as_ref() .protocol }) } #[inline(always)] pub fn priority(&self) -> u32 { unsafe { (self.kptr.__bindgen_anon_4.__bindgen_anon_1) .as_ref() .priority } } #[inline(always)] // TODO: may need to update based on __sk_buff pub fn ingress_ifindex(&self) -> u32 { 0 } #[inline(always)] pub fn ifindex(&self) -> u32 { unsafe { (*self .kptr .__bindgen_anon_1 .__bindgen_anon_1 .__bindgen_anon_1 .dev) .ifindex as u32 } } #[inline(always)] pub fn hash(&self) -> u32 { unsafe { (self.kptr.__bindgen_anon_4.__bindgen_anon_1).as_ref().hash } } #[inline(always)] // TODO: may need to update based on __sk_buff pub fn mark(&self) -> u32 { 0 } #[inline(always)] // TODO: may need to update based on __sk_buff pub fn pkt_type(&self) -> u32 { 0 } #[inline(always)] // TODO: may need to update based on __sk_buff pub fn queue_mapping(&self) -> u16 { self.kptr.queue_mapping } #[inline(always)] // TODO: may need to update based on __sk_buff pub fn vlan_present(&self) -> u32 { 0 } #[inline(always)] // TODO: may need to update based on __sk_buff pub fn vlan_tci(&self) -> u16 { unsafe { self.kptr .__bindgen_anon_4 .__bindgen_anon_1 .as_ref() .__bindgen_anon_2 .__bindgen_anon_1 .vlan_tci } } #[inline(always)] pub fn vlan_proto(&self) -> u16be { u16be(unsafe { self.kptr .__bindgen_anon_4 .__bindgen_anon_1 .as_ref() .__bindgen_anon_2 .__bindgen_anon_1 .vlan_proto }) } #[inline(always)] pub fn cb(&self) -> [c_char; 20] { let mut cb = [0; 20]; cb[0..20].clone_from_slice(&self.kptr.cb[0..20]); cb } #[inline(always)] // TODO: may need to update based on __sk_buff pub fn tc_classid(&self) -> u32 { 0 } #[inline(always)] pub fn tc_index(&self) -> u16 { unsafe { (self.kptr.__bindgen_anon_4.__bindgen_anon_1) .as_ref() .tc_index } } #[inline(always)] // TODO: may need to update based on __sk_buff pub fn napi_id(&self) -> u32 { 0 } #[inline(always)] // TODO: may need to update based on __sk_buff pub fn data_meta(&self) -> u32 { 0 } #[inline(always)] pub fn sk(&self) -> &'a sock { unsafe { &*self.kptr.sk } } } #[repr(C)] pub struct sched_cls { _placeholder: PhantomData<()>, } impl sched_cls { crate::base_helper::base_helper_defs!(); pub const unsafe fn new() -> sched_cls { Self { _placeholder: PhantomData, } } // NOTE: copied from xdp impl, may change in the future #[inline(always)] pub fn eth_header<'b>( &self, skb: &'b mut __sk_buff, ) -> AlignedMut<'b, ethhdr> { convert_slice_to_struct_mut::( &mut skb.data_slice[0..mem::size_of::()], ) } #[inline(always)] pub fn udp_header<'b>( &self, skb: &'b mut __sk_buff, ) -> AlignedMut<'b, udphdr> { // NOTE: this assumes packet has ethhdr and iphdr let begin = mem::size_of::() + mem::size_of::(); let end = mem::size_of::() + begin; convert_slice_to_struct_mut::(&mut skb.data_slice[begin..end]) } #[inline(always)] pub fn tcp_header<'b>( &self, skb: &'b mut __sk_buff, ) -> AlignedMut<'b, tcphdr> { // NOTE: this assumes packet has ethhdr and iphdr let begin = mem::size_of::() + mem::size_of::(); let end = mem::size_of::() + begin; convert_slice_to_struct_mut::(&mut skb.data_slice[begin..end]) } #[inline(always)] pub fn ip_header<'b>( &self, skb: &'b mut __sk_buff, ) -> AlignedMut<'b, iphdr> { // NOTE: this assumes packet has ethhdr let begin = mem::size_of::(); let end = mem::size_of::() + begin; convert_slice_to_struct_mut::(&mut skb.data_slice[begin..end]) } #[inline(always)] pub fn bpf_clone_redirect( &self, skb: &mut __sk_buff, ifindex: u32, flags: u64, ) -> Result { let ret = termination_check!(unsafe { ffi::bpf_clone_redirect(skb.kptr, ifindex, flags) }); if ret != 0 { return Err(ret); } // WARN: bpf_clone_redirect does not update skb.kptr? skb.data_slice = unsafe { slice::from_raw_parts_mut( skb.kptr.data as *mut c_uchar, skb.len() as usize, ) }; Ok(0) } // Now returns a mutable ref, but since every reg is private the user prog // cannot change reg contents. The user should not be able to directly // assign this reference a new value either, given that they will not able // to create another instance of pt_regs (private fields, no pub ctor) #[inline(always)] pub unsafe fn convert_ctx(&self, ctx: *mut ()) -> __sk_buff<'_> { let kptr = unsafe { &mut *(ctx as *mut sk_buff) }; // NOTE: not support jumobo frame yet with non-linear sk_buff let data_length = (kptr.len - kptr.data_len) as usize; let data_slice = unsafe { slice::from_raw_parts_mut(kptr.data as *mut c_uchar, data_length) }; __sk_buff { data_slice, kptr } } } ================================================ FILE: rex/src/spinlock.rs ================================================ use crate::base_helper::termination_check; pub use crate::bindings::uapi::linux::bpf::bpf_spin_lock; use crate::ffi; use crate::panic::CleanupEntries; /// An RAII implementation of a "scoped lock" of a bpf spinlock. When this /// structure is dropped (falls out of scope), the lock will be unlocked. /// /// Ref: #[must_use = "if unused the spinlock will immediately unlock"] #[clippy::has_significant_drop] pub struct rex_spinlock_guard<'a> { lock: &'a mut bpf_spin_lock, cleanup_idx: usize, } impl<'a> rex_spinlock_guard<'a> { /// Constructor function that locks the spinlock pub fn new(lock: &'a mut bpf_spin_lock) -> Self { termination_check!({ // Put it before lock so if it panics we will not be holding the // lock without a valid cleanup entry for it let cleanup_idx = CleanupEntries::register_cleanup( Self::panic_cleanup, lock as *mut bpf_spin_lock as *mut (), ); // Lock unsafe { ffi::bpf_spin_lock(lock) }; Self { lock, cleanup_idx } }) } /// Function that unlocks the spinlock, used by cleanup list and drop pub(crate) unsafe fn panic_cleanup(lock: *mut ()) { unsafe { ffi::bpf_spin_unlock(lock as *mut bpf_spin_lock); } } } impl Drop for rex_spinlock_guard<'_> { /// Unlock the spinlock when the guard is out-of-scope fn drop(&mut self) { termination_check!({ // Put it before unlock so if it panics we will not unlock twice // (once here in the drop handler, the other in the // panic handler triggered by this function) CleanupEntries::deregister_cleanup(self.cleanup_idx); // Unlock unsafe { ffi::bpf_spin_unlock(self.lock) }; }) } } /// Unimplement Send and Sync /// Ref: impl !Send for rex_spinlock_guard<'_> {} impl !Sync for rex_spinlock_guard<'_> {} ================================================ FILE: rex/src/task_struct.rs ================================================ use core::ffi::{self as core_ffi, CStr}; use core::ops::Deref; use crate::base_helper::termination_check; use crate::bindings::linux::kernel::task_struct; use crate::ffi; use crate::panic::CleanupEntries; use crate::per_cpu::this_cpu_read; use crate::pt_regs::PtRegs; // Bindgen has problem generating these constants const TOP_OF_KERNEL_STACK_PADDING: u64 = 0; const PAGE_SHIFT: u64 = 12; const PAGE_SIZE: u64 = 1u64 << PAGE_SHIFT; const THREAD_SIZE_ORDER: u64 = 2; // assume no kasan const THREAD_SIZE: u64 = PAGE_SIZE << THREAD_SIZE_ORDER; pub struct TaskStruct { // struct task_struct * should always live longer than program execution // given the RCU read lock task: &'static task_struct, kptr: *mut task_struct, } impl TaskStruct { pub(crate) fn get_current_task() -> Option { let current: *mut task_struct = unsafe { this_cpu_read(&raw const ffi::current_task) }; if current.is_null() { None } else { Some(TaskStruct { task: unsafe { &*current }, kptr: current, }) } } #[inline(always)] pub fn get_pid(&self) -> i32 { self.task.pid } #[inline(always)] pub fn get_tgid(&self) -> i32 { self.task.tgid } #[inline(always)] pub fn get_utime(&self) -> u64 { self.task.utime } // Design decision: the equivalent BPF helper writes the program name to // a user-provided buffer, here we can take advantage of Rust's ownership by // just providing a &CStr instead pub fn get_comm(&self) -> Result<&CStr, core_ffi::FromBytesUntilNulError> { // casting from c_char to u8 is sound, see: // https://doc.rust-lang.org/src/core/ffi/c_str.rs.html#264 let comm_bytes = unsafe { &*(&self.task.comm[..] as *const _ as *const [u8]) }; CStr::from_bytes_until_nul(comm_bytes) } pub fn get_pt_regs(&self) -> &'static PtRegs { // X86 specific // stack_top is actually bottom of the kernel stack, it refers to the // highest address of the stack pages let stack_top = self.task.stack as u64 + THREAD_SIZE - TOP_OF_KERNEL_STACK_PADDING; let reg_addr = stack_top - core::mem::size_of::() as u64; // The pt_regs should always be on the top of the stack unsafe { &*(reg_addr as *const PtRegs) } } } pub struct OwnedTaskStruct { inner: TaskStruct, cleanup_idx: usize, } impl OwnedTaskStruct { pub fn from_pid(pid: i32) -> Option { termination_check!({ let task = unsafe { ffi::bpf_task_from_pid(pid) }; if task.is_null() { None } else { let cleanup_idx = CleanupEntries::register_cleanup( Self::panic_cleanup, task as *mut (), ); Some(Self { inner: TaskStruct { task: unsafe { &*task }, kptr: task, }, cleanup_idx, }) } }) } pub(crate) unsafe fn panic_cleanup(task: *mut ()) { unsafe { ffi::bpf_task_release(task as *mut task_struct); } } } impl Deref for OwnedTaskStruct { type Target = TaskStruct; fn deref(&self) -> &Self::Target { &self.inner } } impl Drop for OwnedTaskStruct { fn drop(&mut self) { termination_check!({ unsafe { CleanupEntries::deregister_cleanup(self.cleanup_idx); ffi::bpf_task_release(self.inner.kptr); } }) } } ================================================ FILE: rex/src/tracepoint/binding.rs ================================================ #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct SyscallsEnterOpenCtx { unused: u64, pub syscall_nr: i64, pub filename_ptr: i64, pub flags: i64, pub mode: i64, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct SyscallsEnterOpenatCtx { unused: u64, pub syscall_nr: i64, pub dfd: i64, pub filename_ptr: i64, pub flags: i64, pub mode: i64, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct SyscallsExitOpenCtx { unused: u64, pub syscall_nr: i64, pub ret: i64, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct SyscallsExitOpenatCtx { unused: u64, pub syscall_nr: i64, pub ret: i64, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct SyscallsEnterDupCtx { unused: u64, pub syscall_nr: i64, pub fildes: u64, } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct RawSyscallsEnterCtx { unused: u64, pub id: i64, pub args: [u64; 6], } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct RawSyscallsExitCtx { unused: u64, pub id: i64, pub ret: i64, } ================================================ FILE: rex/src/tracepoint/mod.rs ================================================ mod binding; mod tp_impl; pub use binding::*; pub use tp_impl::*; ================================================ FILE: rex/src/tracepoint/tp_impl.rs ================================================ use core::marker::PhantomData; use super::{ RawSyscallsEnterCtx, RawSyscallsExitCtx, SyscallsEnterDupCtx, SyscallsEnterOpenCtx, SyscallsEnterOpenatCtx, SyscallsExitOpenCtx, SyscallsExitOpenatCtx, }; use crate::base_helper::termination_check; use crate::bindings::uapi::linux::bpf::bpf_map_type; use crate::map::RexPerfEventArray; use crate::task_struct::TaskStruct; use crate::utils::sealed::PerfEventStreamerBase; use crate::utils::{to_result, NoRef, PerfEventMaskedCPU, PerfEventStreamer}; use crate::{ffi, Result}; pub trait TracepointContext {} impl TracepointContext for SyscallsEnterOpenCtx {} impl TracepointContext for SyscallsEnterOpenatCtx {} impl TracepointContext for SyscallsExitOpenCtx {} impl TracepointContext for SyscallsExitOpenatCtx {} impl TracepointContext for SyscallsEnterDupCtx {} impl TracepointContext for RawSyscallsEnterCtx {} impl TracepointContext for RawSyscallsExitCtx {} #[repr(C)] pub struct tracepoint { _placeholder: PhantomData, } impl tracepoint { crate::base_helper::base_helper_defs!(); pub const unsafe fn new() -> tracepoint { Self { _placeholder: PhantomData, } } pub unsafe fn convert_ctx(&self, ctx: *mut ()) -> &'static C { unsafe { &*(ctx as *mut C) } } pub fn bpf_get_current_task(&self) -> Option { TaskStruct::get_current_task() } } impl PerfEventStreamerBase for tracepoint {} impl PerfEventStreamer for tracepoint { type Context = C; fn output_event( &self, ctx: &Self::Context, map: &'static RexPerfEventArray, data: &T, cpu: PerfEventMaskedCPU, ) -> Result { let map_kptr = unsafe { core::ptr::read_volatile(&map.kptr) }; let ctx_ptr = ctx as *const C as *const (); termination_check!(unsafe { to_result!(ffi::bpf_perf_event_output_tp( ctx_ptr, map_kptr, cpu.masked_cpu, data as *const T as *const (), core::mem::size_of::() as u64 )) }) } } ================================================ FILE: rex/src/utils.rs ================================================ use core::ffi::{c_int, c_uchar}; use core::mem; use core::ops::{Deref, DerefMut, Drop}; use crate::bindings::uapi::linux::bpf::{BPF_F_CURRENT_CPU, BPF_F_INDEX_MASK}; use crate::map::RexPerfEventArray; #[repr(transparent)] #[derive(Copy, Clone)] pub struct u16be(pub(crate) u16); impl From for u16 { // Required method fn from(value: u16be) -> Self { u16::from_be(value.0) } } /// A specialized Result for typical int return value in the kernel /// /// To be used as the return type for functions that may fail. /// /// Ref: linux/rust/kernel/error.rs pub type Result = core::result::Result; /// Converts an integer as returned by a C kernel function to an error if it's /// negative, and `Ok(val)` otherwise. /// /// Ref: linux/rust/kernel/error.rs // genetic specialization to Macro #[macro_export] macro_rules! to_result { ($retval:expr) => {{ let val = $retval; if val < 0 { Err(val as i32) } else { Ok(val as i32) } }}; } pub(crate) use to_result; /// A marker trait that prevents derivation on types that contain references or /// raw pointers. This avoids accidental dereference of invalid pointers in /// foreign objects obtained from the kernel (e.g. via `bpf_map_lookup_elem` or /// `bpf_probe_read_kernel`). /// /// Though dererferencing raw pointers are not possible in Rex programs as it /// requires `unsafe`, we still need to consider the case where a core library /// type wraps the unsafe deref operation under a safe interface (an example is /// `core::slice::Iter`). pub unsafe auto trait NoRef {} impl !NoRef for &T {} impl !NoRef for &mut T {} impl !NoRef for *const T {} impl !NoRef for *mut T {} /// An enum used internally by `Aligned` and `AlignedMut`, the encapsulated /// value is either a reference to the data if the aligned requirement is /// satisfied, or a copied value of the data if it is not aligned and a /// reference cannot be taken directly. enum AlignedInner { Ref(RefT), Val(ValT), } /// An abstraction over a `&T` for both aligned and unaligned accesses. This /// struct can be constructed with [`convert_slice_to_struct`] from an /// underlying data slice. The underlying data is either a direct `&'a T` by /// reborrowing the slice or a copied value of `T` from the slice, depending on /// whether the slice pointer is properly aligned for `T`. /// /// The abstraction provided by this struct is a shared reference, for an /// abstraction over mutable references, use [`AlignedMut`]. pub struct Aligned<'a, T> { inner: AlignedInner<&'a T, T>, } impl<'a, T> Aligned<'a, T> { /// Constructs an `Aligned<'a, T>` from an aligned reference. #[inline(always)] pub(crate) const fn from_ref(aligned_ref: &'a T) -> Self { Self { inner: AlignedInner::Ref(aligned_ref), } } /// Constructs an `Aligned<'a, T>` from a copied value of `T` to handle /// unaligned cases. #[inline(always)] pub(crate) const fn from_val(copied_val: T) -> Self { Self { inner: AlignedInner::Val(copied_val), } } } /// Allows users of `Aligned<'_, T>` to transparently access the value behind /// the reference abstraction. impl Deref for Aligned<'_, T> { type Target = T; /// If the underlying data is a `&T`, it is directly returned; /// otherwise a shared reference to the copied value of `T` is taken and /// returned. #[inline(always)] fn deref(&self) -> &Self::Target { match &self.inner { AlignedInner::Ref(aligned_ref) => aligned_ref, AlignedInner::Val(ref unaligned_val) => unaligned_val, } } } /// An abstraction over a `&mut T` for both aligned and unaligned accesses. This /// struct can be constructed with [`convert_slice_to_struct_mut`] from an /// underlying data slice. The underlying data is either a direct `&'a mut T` by /// reborrowing the slice or a copied value of `T` from the slice, depending on /// whether the slice pointer is properly aligned for `T`. In the unaligned /// case, the mutable reference to slice is also stored in this struct. /// /// The abstraction provided by this struct is a mutable reference, for an /// abstraction over shared references, use [`Aligned`]. pub struct AlignedMut<'a, T: Copy> { inner: AlignedInner<&'a mut T, (T, &'a mut [c_uchar])>, } impl<'a, T: Copy> AlignedMut<'a, T> { /// Constructs an `AlignedMut<'a, T>` from an aligned reference. #[inline(always)] pub(crate) const fn from_ref(aligned_ref: &'a mut T) -> Self { Self { inner: AlignedInner::Ref(aligned_ref), } } /// Constructs an `AlignedMut<'a, T>` from a copied value of `T` and the /// original mutable reference to slice to handle unaligned cases. #[inline(always)] pub(crate) const fn from_val( copied_val: T, slice: &'a mut [c_uchar], ) -> Self { Self { inner: AlignedInner::Val((copied_val, slice)), } } } /// Allows users of `AlignedMut<'_, T>` to transparently access the value behind /// the reference abstraction. impl Deref for AlignedMut<'_, T> { type Target = T; /// If the underlying data is a `&mut T`, the coerced `&T` is returned; /// otherwise a shared reference to the copied value of `T` is taken and /// returned. #[inline(always)] fn deref(&self) -> &Self::Target { match &self.inner { AlignedInner::Ref(aligned_ref) => aligned_ref, AlignedInner::Val(ref unaligned_val) => &unaligned_val.0, } } } /// Allows users of `AlignedMut<'_, T>` to transparently access and mutate the /// value behind the reference abstraction. impl DerefMut for AlignedMut<'_, T> { /// If the underlying data is a `&mut T`, it is directly returned; /// otherwise a mutable reference to the copied value of `T` is taken and /// returned. #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { match &mut self.inner { AlignedInner::Ref(aligned_ref) => aligned_ref, AlignedInner::Val(ref mut unaligned_val) => &mut unaligned_val.0, } } } /// Drop handler to support automatic writeback to the original data slice impl Drop for AlignedMut<'_, T> { #[inline(always)] fn drop(&mut self) { if let AlignedInner::Val(ref mut unaligned_val) = self.inner { unsafe { (unaligned_val.1.as_mut_ptr() as *mut T) .write_unaligned(unaligned_val.0); } } } } /// Converts the bytes in `slice` into a `&T` abstracted by [`Aligned<'_, T>`]. /// This is only performed on the first `core::mem::size_of::()` bytes. /// If the slice is not long enough, this function panics. /// /// If `slice.as_ptr()` is properly aligned for `T`, the pointer is reborrowed /// into a `&T` and stored in the returned `Aligned<'_, T>`. /// If the pointer does not satisfy the alignment requirement of `T`, this /// function copies the value via `core::ptr::read_unaligned` and stores it in /// the returned `Aligned<'_, T>`. /// /// The [operation][read_unaligned_doc] performed in the unaligned case implies /// that `T` has to be [`Copy`]. /// /// [read_unaligned_doc]: https://doc.rust-lang.org/core/ptr/fn.read_unaligned.html #[inline] pub fn convert_slice_to_struct(slice: &[c_uchar]) -> Aligned<'_, T> where T: Copy + NoRef, { assert!( slice.len() >= mem::size_of::(), "size mismatch in convert_slice_to_struct" ); let ptr = slice.as_ptr() as *const T; if ptr.is_aligned() { unsafe { Aligned::from_ref(&*ptr) } } else { unsafe { Aligned::from_val(ptr.read_unaligned()) } } } /// Converts the bytes in `slice` into a `&mut T` abstracted by /// [`AlignedMut<'_, T>`]. /// This is only performed on the first `core::mem::size_of::()` bytes. /// If the slice is not long enough, this function panics. /// /// If `slice.as_mut_ptr()` is properly aligned for `T`, the pointer is /// reborrowed into a `&mut T` and stored in the returned `AlignedMut<'_, T>`. /// If the pointer does not satisfy the alignment requirement of `T`, this /// function copies the value via `core::ptr::read_unaligned` and stores it in /// the returned `AlignedMut<'_, T>`. /// /// The [operation][read_unaligned_doc] performed in the unaligned case implies /// that `T` has to be [`Copy`]. /// /// [read_unaligned_doc]: https://doc.rust-lang.org/core/ptr/fn.read_unaligned.html #[inline] pub fn convert_slice_to_struct_mut( slice: &mut [c_uchar], ) -> AlignedMut<'_, T> where T: Copy + NoRef, { assert!( slice.len() >= mem::size_of::(), "size mismatch in convert_slice_to_struct_mut" ); let ptr = slice.as_mut_ptr() as *mut T; if ptr.is_aligned() { unsafe { AlignedMut::from_ref(&mut *ptr) } } else { unsafe { AlignedMut::from_val(ptr.read_unaligned(), slice) } } } /// Read a numeric field that is stored **big-endian** inside a header already /// sitting in `payload_slice` at offset `hdr_base`. /// /// Example: /// ``` /// let iphdr_base = size_of::(); /// let proto_be = read_field!(skb.data_slice, iphdr_base, iphdr, protocol, u8); /// match u8::from_be(proto_be) as u32 { /// IPPROTO_TCP => handle_tcp(), /// IPPROTO_UDP => handle_udp(), /// _ => {} /// } /// ``` #[macro_export] macro_rules! read_field { ($slice:expr, // payload slice $hdr_base:expr, // where this header starts inside the buffer $hdr:path, // concrete header type, for `offset_of!` $field:ident, // field we want $ty:ty // Rust type of that field (u8, u16, …) ) => {{ let start = $hdr_base + core::mem::offset_of!($hdr, $field); *$crate::utils::convert_slice_to_struct::<$ty>( &$slice[start..start + size_of::<$ty>()], ) }}; } pub(crate) mod sealed { pub trait PerfEventStreamerBase {} } // For implementers, see tp_impl.rs for how to implement // this trait /// Programs that can stream data through a /// RexPerfEventArray will implement this trait pub trait PerfEventStreamer: sealed::PerfEventStreamerBase { type Context; fn output_event( &self, ctx: &Self::Context, map: &'static RexPerfEventArray, data: &T, cpu: PerfEventMaskedCPU, ) -> Result; } /// Newtype for a cpu for perf event output to ensure /// type safety since the cpu must be masked with /// BPF_F_INDEX_MASK #[derive(Debug, Copy, Clone)] pub struct PerfEventMaskedCPU { pub(crate) masked_cpu: u64, } impl PerfEventMaskedCPU { pub fn current_cpu() -> Self { PerfEventMaskedCPU { masked_cpu: BPF_F_CURRENT_CPU, } } pub fn any_cpu(cpu: u64) -> Self { PerfEventMaskedCPU { masked_cpu: cpu & BPF_F_INDEX_MASK, } } } ================================================ FILE: rex/src/xdp/mod.rs ================================================ // mod binding; mod xdp_impl; pub use xdp_impl::*; ================================================ FILE: rex/src/xdp/xdp_impl.rs ================================================ use core::ffi::c_uchar; use core::marker::PhantomData; use core::mem::size_of; use core::{mem, slice}; use crate::base_helper::termination_check; pub use crate::bindings::linux::kernel::{ ethhdr, iphdr, tcphdr, udphdr, xdp_buff, }; use crate::bindings::uapi::linux::bpf::bpf_map_type; // expose the following constants to the user pub use crate::bindings::uapi::linux::bpf::{ XDP_ABORTED, XDP_DROP, XDP_PASS, XDP_REDIRECT, XDP_TX, }; pub use crate::bindings::uapi::linux::r#in::{IPPROTO_TCP, IPPROTO_UDP}; use crate::ffi; use crate::utils::*; impl iphdr { #[inline(always)] pub fn saddr(&mut self) -> &mut u32 { unsafe { &mut self.__bindgen_anon_1.__bindgen_anon_1.saddr } } pub fn daddr(&mut self) -> &mut u32 { unsafe { &mut self.__bindgen_anon_1.__bindgen_anon_1.daddr } } } #[inline(always)] pub fn compute_ip_checksum(ip_header: &mut iphdr) -> u16 { let mut sum: u32 = 0; ip_header.check = 0; let count = size_of::() >> 1; let u16_slice = unsafe { core::slice::from_raw_parts(ip_header as *const _ as *const u16, count) }; for &word in u16_slice { sum += word as u32; } sum = (sum & 0xffff) + (sum >> 16); !sum as u16 } pub struct xdp_md<'a> { pub data_slice: &'a mut [c_uchar], kptr: &'static mut xdp_buff, } // Define accessors of program-accessible fields impl xdp_md<'_> { #[inline(always)] pub fn data_length(&self) -> usize { self.data_slice.len() } #[inline(always)] pub fn data_meta(&self) -> usize { self.kptr.data_meta as usize } #[inline(always)] pub fn ingress_ifindex(&self) -> u32 { unsafe { (*(*self.kptr.rxq).dev).ifindex as u32 } } #[inline(always)] pub fn rx_qeueu_index(&self) -> u32 { unsafe { (*self.kptr.rxq).queue_index } } #[inline(always)] pub fn egress_ifindex(&self) -> u32 { // TODO: https://elixir.bootlin.com/linux/v5.15.123/source/net/core/filter.c#L8271 // egress_ifindex is valid only for BPF_XDP_DEVMAP option 0 } } #[repr(C)] pub struct xdp { _placeholder: PhantomData<()>, } impl xdp { crate::base_helper::base_helper_defs!(); pub const unsafe fn new() -> xdp { Self { _placeholder: PhantomData, } } // Now returns a mutable ref, but since every reg is private the user prog // cannot change reg contents. The user should not be able to directly // assign this reference a new value either, given that they will not able // to create another instance of pt_regs (private fields, no pub ctor) #[inline(always)] pub unsafe fn convert_ctx(&self, ctx: *mut ()) -> xdp_md<'_> { let kptr = unsafe { &mut *(ctx as *mut xdp_buff) }; // NOTE: not support jumobo frame yet with non-linear xdp_buff let data_length = kptr.data_end as usize - kptr.data as usize; let data_slice = unsafe { slice::from_raw_parts_mut(kptr.data as *mut c_uchar, data_length) }; xdp_md { data_slice, kptr } } #[inline(always)] pub fn tcp_header<'b>( &self, ctx: &'b mut xdp_md, ) -> AlignedMut<'b, tcphdr> { // NOTE: this assumes packet has ethhdr and iphdr let begin = mem::size_of::() + mem::size_of::(); let end = mem::size_of::() + begin; convert_slice_to_struct_mut::(&mut ctx.data_slice[begin..end]) } #[inline(always)] pub fn udp_header<'b>( &self, ctx: &'b mut xdp_md, ) -> AlignedMut<'b, udphdr> { // NOTE: this assumes packet has ethhdr and iphdr let begin = mem::size_of::() + mem::size_of::(); let end = mem::size_of::() + begin; convert_slice_to_struct_mut::(&mut ctx.data_slice[begin..end]) } #[inline(always)] pub fn ip_header<'b>(&self, ctx: &'b mut xdp_md) -> AlignedMut<'b, iphdr> { // NOTE: this assumes packet has ethhdr let begin = mem::size_of::(); let end = mem::size_of::() + begin; convert_slice_to_struct_mut::(&mut ctx.data_slice[begin..end]) } #[inline(always)] pub fn eth_header<'b>( &self, ctx: &'b mut xdp_md, ) -> AlignedMut<'b, ethhdr> { convert_slice_to_struct_mut::( &mut ctx.data_slice[0..mem::size_of::()], ) } // FIX: update based on xdp_md to convert to xdp_buff // pub fn bpf_xdp_adjust_head(&self, xdp: &mut xdp_buff, offset: i32) -> i32 // { unsafe { ffi::bpf_xdp_adjust_head(xdp, offset) } // } // WARN: this function is unsafe #[inline(always)] pub fn bpf_xdp_adjust_tail(&self, ctx: &mut xdp_md, offset: i32) -> Result { let ret = termination_check!(unsafe { ffi::bpf_xdp_adjust_tail(ctx.kptr, offset) }); if ret != 0 { return Err(ret); } // Update xdp_md fields let data_length = ctx.kptr.data_end as usize - ctx.kptr.data as usize; ctx.data_slice = unsafe { slice::from_raw_parts_mut( ctx.kptr.data as *mut c_uchar, data_length, ) }; Ok(0) } } ================================================ FILE: rex-macros/.gitignore ================================================ # Generated by Cargo # will have compiled files and executables debug/ target/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html Cargo.lock # These are backup files generated by rustfmt **/*.rs.bk # MSVC Windows builds of rustc generate these, which store debugging information *.pdb ================================================ FILE: rex-macros/Cargo.toml ================================================ [package] name = "rex-macros" version = "0.2.0" repository.workspace = true edition.workspace = true authors.workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [lib] proc-macro = true [dependencies] syn = { workspace = true } quote = { workspace = true } proc-macro-error = { workspace = true } proc-macro2 = { workspace = true } ================================================ FILE: rex-macros/src/args.rs ================================================ use std::collections::HashMap; use proc_macro2::TokenStream; use proc_macro_error::abort; use syn::spanned::Spanned; use syn::{parse_str, Expr, ExprAssign, Lit, LitStr, Result}; macro_rules! pop_string_args { ($self:expr, $key:expr) => { $self.get($key).map(|v| v.value()) }; } pub(crate) fn parse_string_args( input: TokenStream, ) -> Result> { let parsed: syn::ExprArray = parse_str(&format!("[{input}]"))?; let mut map = HashMap::new(); // Iterate over the expressions and extract key-value pairs let parse_and_insert = |expr| { let Expr::Assign(ExprAssign { left, right, .. }) = expr else { return; }; let Expr::Path(path) = *left else { return }; let Some(ident) = path.path.get_ident() else { return; }; let key = ident.to_string(); let value = match *right { Expr::Lit(syn::ExprLit { lit: Lit::Str(lit_str), .. }) => lit_str, _ => { abort!(input.span(), "Macro processing failed, please follow the syntax `key` = `value`"); } }; map.insert(key, value); }; parsed.elems.into_iter().for_each(parse_and_insert); // println!("{:?}", map); Ok(map) } ================================================ FILE: rex-macros/src/kprobe.rs ================================================ use std::fmt; use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{parse2, ItemFn, Result}; use crate::args::parse_string_args; #[allow(dead_code)] pub enum KprobeFlavor { Kprobe, Kretprobe, Uprobe, Uretprobe, } impl fmt::Display for KprobeFlavor { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { KprobeFlavor::Kprobe => write!(f, "kprobe"), KprobeFlavor::Kretprobe => write!(f, "kretprobe"), KprobeFlavor::Uprobe => write!(f, "uprobe"), KprobeFlavor::Uretprobe => write!(f, "uretprobe"), } } } pub(crate) struct KProbe { function: Option, item: ItemFn, } impl KProbe { // parse the argument of function pub(crate) fn parse( attrs: TokenStream, item: TokenStream, ) -> Result { let item: ItemFn = parse2(item)?; let args = parse_string_args(attrs)?; let function = pop_string_args!(args, "function"); Ok(KProbe { function, item }) } pub(crate) fn expand(&self, flavor: KprobeFlavor) -> Result { let fn_name = self.item.sig.ident.clone(); let item = &self.item; let function_name = format!("{fn_name}"); let prog_ident = format_ident!("PROG_{}", fn_name.to_string().to_uppercase()); let attached_function = if self.function.is_some() { format!("rex/{}/{}", flavor, self.function.as_ref().unwrap()) } else { format!("rex/{flavor}") }; let entry_name = format_ident!("__rex_entry_{}", fn_name); let function_body_tokens = quote! { #[inline(always)] #item #[used] static #prog_ident: kprobe = unsafe { kprobe::new() }; #[unsafe(export_name = #function_name)] #[unsafe(link_section = #attached_function)] extern "C" fn #entry_name(ctx: *mut ()) -> u32 { let newctx = unsafe { #prog_ident.convert_ctx(ctx) }; #fn_name(&#prog_ident, newctx).unwrap_or_else(|e| e) as u32 } }; Ok(function_body_tokens) } } ================================================ FILE: rex-macros/src/lib.rs ================================================ #[macro_use] pub(crate) mod args; mod kprobe; mod perf_event; mod tc; mod tracepoint; mod xdp; use std::borrow::Cow; use kprobe::{KProbe, KprobeFlavor}; use perf_event::PerfEvent; use proc_macro::TokenStream; use proc_macro_error::{abort, proc_macro_error}; use quote::quote; use syn::ItemStatic; use tc::SchedCls; use tracepoint::TracePoint; use xdp::Xdp; #[proc_macro_error] #[proc_macro_attribute] pub fn rex_xdp(attrs: TokenStream, item: TokenStream) -> TokenStream { match Xdp::parse(attrs.into(), item.into()) { Ok(prog) => prog .expand() .unwrap_or_else(|err| abort!(err.span(), "{}", err)) .into(), Err(err) => abort!(err.span(), "{}", err), } } #[proc_macro_error] #[proc_macro_attribute] pub fn rex_tc(attrs: TokenStream, item: TokenStream) -> TokenStream { match SchedCls::parse(attrs.into(), item.into()) { Ok(prog) => prog .expand() .unwrap_or_else(|err| abort!(err.span(), "{}", err)) .into(), Err(err) => abort!(err.span(), "{}", err), } } #[proc_macro_error] #[proc_macro_attribute] pub fn rex_kprobe(attrs: TokenStream, item: TokenStream) -> TokenStream { match KProbe::parse(attrs.into(), item.into()) { Ok(prog) => prog .expand(KprobeFlavor::Kprobe) .unwrap_or_else(|err| abort!(err.span(), "{}", err)) .into(), Err(err) => abort!(err.span(), "{}", err), } } #[proc_macro_error] #[proc_macro_attribute] pub fn rex_uprobe(attrs: TokenStream, item: TokenStream) -> TokenStream { match KProbe::parse(attrs.into(), item.into()) { Ok(prog) => prog .expand(KprobeFlavor::Uprobe) .unwrap_or_else(|err| abort!(err.span(), "{}", err)) .into(), Err(err) => abort!(err.span(), "{}", err), } } #[proc_macro_error] #[proc_macro_attribute] pub fn rex_tracepoint(attrs: TokenStream, item: TokenStream) -> TokenStream { match TracePoint::parse(attrs.into(), item.into()) { Ok(prog) => prog .expand() .unwrap_or_else(|err| abort!(err.span(), "{}", err)) .into(), Err(err) => abort!(err.span(), "{}", err), } } #[proc_macro_error] #[proc_macro_attribute] pub fn rex_perf_event(attrs: TokenStream, item: TokenStream) -> TokenStream { match PerfEvent::parse(attrs.into(), item.into()) { Ok(prog) => prog .expand() .unwrap_or_else(|err| abort!(err.span(), "{}", err)) .into(), Err(err) => abort!(err.span(), "{}", err), } } /// Ref: #[proc_macro_attribute] pub fn rex_map(_: TokenStream, item: TokenStream) -> TokenStream { let item: ItemStatic = syn::parse(item).unwrap(); let name = item.ident.to_string(); let section_name: Cow<'_, _> = ".maps".to_string().into(); (quote! { #[unsafe(link_section = #section_name)] #[unsafe(export_name = #name)] #[allow(non_upper_case_globals)] #item }) .into() } ================================================ FILE: rex-macros/src/perf_event.rs ================================================ use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{ItemFn, Result}; pub(crate) struct PerfEvent { item: ItemFn, } impl PerfEvent { // parse the argument of function pub(crate) fn parse( _: TokenStream, item: TokenStream, ) -> Result { let item = syn::parse2(item)?; Ok(PerfEvent { item }) } pub(crate) fn expand(&self) -> Result { // TODO: section may update in the future let fn_name = self.item.sig.ident.clone(); let item = &self.item; let function_name = format!("{fn_name}"); let prog_ident = format_ident!("PROG_{}", fn_name.to_string().to_uppercase()); let entry_name = format_ident!("__rex_entry_{}", fn_name); let function_body_tokens = quote! { #[inline(always)] #item #[used] static #prog_ident: perf_event = unsafe { perf_event::new() }; #[unsafe(export_name = #function_name)] #[unsafe(link_section = "rex/perf_event")] extern "C" fn #entry_name(ctx: *mut ()) -> u32 { let newctx = unsafe { #prog_ident.convert_ctx(ctx) }; #fn_name(&#prog_ident, newctx).unwrap_or_else(|e| e) as u32 } }; Ok(function_body_tokens) } } ================================================ FILE: rex-macros/src/tc.rs ================================================ use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{ItemFn, Result}; pub(crate) struct SchedCls { item: ItemFn, } impl SchedCls { // parse the argument of function pub(crate) fn parse(_: TokenStream, item: TokenStream) -> Result { let item = syn::parse2(item)?; Ok(SchedCls { item }) } // expand the function into two function with original function // #[entry_link(inner_unikernel/tc)] // static PROG2: sched_cls = sched_cls::new( // xdp_tx_filter, // "xdp_tx_filter", // BPF_PROG_TYPE_SCHED_CLS as u64, // ); pub(crate) fn expand(&self) -> Result { // TODO: section may update in the future let fn_name = self.item.sig.ident.clone(); let item = &self.item; let function_name = format!("{fn_name}"); let prog_ident = format_ident!("PROG_{}", fn_name.to_string().to_uppercase()); let entry_name = format_ident!("__rex_entry_{}", fn_name); let function_body_tokens = quote! { #[inline(always)] #item #[used] static #prog_ident: sched_cls = unsafe { sched_cls::new() }; #[unsafe(export_name = #function_name)] #[unsafe(link_section = "rex/tc")] extern "C" fn #entry_name(ctx: *mut ()) -> u32 { let mut newctx = unsafe { #prog_ident.convert_ctx(ctx) }; // return TC_ACT_OK if error #fn_name(&#prog_ident, &mut newctx).unwrap_or_else(|e| e) as u32 } }; Ok(function_body_tokens) } } ================================================ FILE: rex-macros/src/tracepoint.rs ================================================ use proc_macro2::TokenStream; use proc_macro_error::abort_call_site; use quote::{format_ident, quote, ToTokens}; use syn::{parse2, FnArg, Ident, ItemFn, Result, Type}; pub(crate) struct TracePoint { item: ItemFn, } impl TracePoint { // parse the argument of function pub(crate) fn parse( _attrs: TokenStream, item: TokenStream, ) -> Result { let item: ItemFn = parse2(item)?; Ok(TracePoint { item }) } pub(crate) fn expand(&self) -> Result { let fn_name = self.item.sig.ident.clone(); // get context type let FnArg::Typed(context_arg) = self.item.sig.inputs.last().unwrap().clone() else { abort_call_site!("Program needs non-self arguments"); }; let Type::Reference(context_type_ref) = *context_arg.ty else { abort_call_site!("Context type needs to be behind a reference"); }; let context_type = match *context_type_ref.elem.clone() { Type::Verbatim(t) => parse2(t).unwrap(), Type::Path(p) => p.path.segments.last().unwrap().clone().ident, _ => { abort_call_site!("Tracepoint context needs to be a literal type or a path to such") } }; let full_context_type: Ident = match *context_type_ref.elem { Type::Verbatim(t) => parse2(t).unwrap(), Type::Path(p) => parse2(p.to_token_stream()).unwrap(), _ => unreachable!(), }; // other tracepoint pieces let item = &self.item; let function_name = format!("{fn_name}"); let prog_ident = format_ident!("PROG_{}", fn_name.to_string().to_uppercase()); let hook_point_name = match context_type.to_string().as_str() { "SyscallsEnterOpenCtx" => "syscalls/sys_enter_open", "SyscallsEnterOpenatCtx" => "syscalls/sys_enter_openat", "SyscallsExitOpenCtx" => "syscalls/sys_exit_open", "SyscallsExitOpenatCtx" => "syscalls/sys_exit_openat", "SyscallsEnterDupCtx" => "syscalls/sys_enter_dup", "RawSyscallsEnterCtx" => "raw_syscalls/sys_enter", "RawSyscallsExitCtx" => "raw_syscalls/sys_exit", _ => abort_call_site!("Please provide a valid context type. If your needed context isn't supported consider opening a PR!"), }; let attached_name = format!("rex/tracepoint/{hook_point_name}"); let entry_name = format_ident!("__rex_entry_{}", fn_name); let function_body_tokens = quote! { #[inline(always)] #item #[used] static #prog_ident: tracepoint<#full_context_type> = unsafe { tracepoint::new() }; #[unsafe(export_name = #function_name)] #[unsafe(link_section = #attached_name)] extern "C" fn #entry_name(ctx: *mut ()) -> u32 { let newctx = unsafe { #prog_ident.convert_ctx(ctx) }; #fn_name(&#prog_ident, newctx).unwrap_or_else(|e| e) as u32 } }; Ok(function_body_tokens) } } ================================================ FILE: rex-macros/src/xdp.rs ================================================ use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{ItemFn, Result}; pub(crate) struct Xdp { item: ItemFn, } impl Xdp { // parse the argument of function pub(crate) fn parse(_: TokenStream, item: TokenStream) -> Result { let item = syn::parse2(item)?; Ok(Xdp { item }) } // expand the function into two function with original function // #[entry_link(inner_unikernel/xdp)] // static PROG1: xdp = // xdp::new(xdp_rx_filter_fn, "xdp_rx_filter", BPF_PROG_TYPE_XDP as u64); pub(crate) fn expand(&self) -> Result { // TODO: section may update in the future let fn_name = self.item.sig.ident.clone(); let item = &self.item; let function_name = format!("{fn_name}"); let prog_ident = format_ident!("PROG_{}", fn_name.to_string().to_uppercase()); let entry_name = format_ident!("__rex_entry_{}", fn_name); let function_body_tokens = quote! { #[inline(always)] #item #[used] static #prog_ident: xdp = unsafe { xdp::new() }; #[unsafe(export_name = #function_name)] #[unsafe(link_section = "rex/xdp")] extern "C" fn #entry_name(ctx: *mut ()) -> u32 { let mut newctx = unsafe { #prog_ident.convert_ctx(ctx) }; // Return XDP_PASS if Err, i.e. discard event #fn_name(&#prog_ident, &mut newctx).unwrap_or_else(|e| e) as u32 } }; Ok(function_body_tokens) } } ================================================ FILE: rex-native.ini ================================================ [binaries] c = 'clang' c_ld = 'mold' cpp = 'clang++' cpp_ld = 'mold' ar = 'llvm-ar' ================================================ FILE: rustfmt.toml ================================================ max_width = 80 binop_separator = "Back" reorder_impl_items = true wrap_comments = true imports_granularity = "Module" group_imports = "StdExternalCrate" ================================================ FILE: samples/.clang-format ================================================ # SPDX-License-Identifier: GPL-2.0 # # clang-format configuration file. Intended for clang-format >= 11. # # For more information, see: # # Documentation/dev-tools/clang-format.rst # https://clang.llvm.org/docs/ClangFormat.html # https://clang.llvm.org/docs/ClangFormatStyleOptions.html # --- AccessModifierOffset: -4 AlignAfterOpenBracket: Align AlignConsecutiveAssignments: false AlignConsecutiveDeclarations: false AlignEscapedNewlines: Left AlignOperands: true AlignTrailingComments: false AllowAllParametersOfDeclarationOnNextLine: false AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: None AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: false BinPackArguments: true BinPackParameters: true BraceWrapping: AfterClass: false AfterControlStatement: false AfterEnum: false AfterFunction: true AfterNamespace: true AfterObjCDeclaration: false AfterStruct: false AfterUnion: false AfterExternBlock: false BeforeCatch: false BeforeElse: false IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace: true BreakBeforeBinaryOperators: None BreakBeforeBraces: Custom BreakBeforeInheritanceComma: false BreakBeforeTernaryOperators: false BreakConstructorInitializersBeforeComma: false BreakConstructorInitializers: BeforeComma BreakAfterJavaFieldAnnotations: false BreakStringLiterals: false ColumnLimit: 80 CommentPragmas: '^ IWYU pragma:' CompactNamespaces: false ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 8 ContinuationIndentWidth: 8 Cpp11BracedListStyle: false DerivePointerAlignment: false DisableFormat: false ExperimentalAutoDetectBinPacking: false FixNamespaceComments: false # Taken from: # git grep -h '^#define [^[:space:]]*for_each[^[:space:]]*(' include/ tools/ \ # | sed "s,^#define \([^[:space:]]*for_each[^[:space:]]*\)(.*$, - '\1'," \ # | LC_ALL=C sort -u ForEachMacros: - '__ata_qc_for_each' - '__bio_for_each_bvec' - '__bio_for_each_segment' - '__evlist__for_each_entry' - '__evlist__for_each_entry_continue' - '__evlist__for_each_entry_from' - '__evlist__for_each_entry_reverse' - '__evlist__for_each_entry_safe' - '__for_each_mem_range' - '__for_each_mem_range_rev' - '__for_each_thread' - '__hlist_for_each_rcu' - '__map__for_each_symbol_by_name' - '__pci_bus_for_each_res0' - '__pci_bus_for_each_res1' - '__pci_dev_for_each_res0' - '__pci_dev_for_each_res1' - '__perf_evlist__for_each_entry' - '__perf_evlist__for_each_entry_reverse' - '__perf_evlist__for_each_entry_safe' - '__rq_for_each_bio' - '__shost_for_each_device' - '__sym_for_each' - 'apei_estatus_for_each_section' - 'ata_for_each_dev' - 'ata_for_each_link' - 'ata_qc_for_each' - 'ata_qc_for_each_raw' - 'ata_qc_for_each_with_internal' - 'ax25_for_each' - 'ax25_uid_for_each' - 'bio_for_each_bvec' - 'bio_for_each_bvec_all' - 'bio_for_each_folio_all' - 'bio_for_each_integrity_vec' - 'bio_for_each_segment' - 'bio_for_each_segment_all' - 'bio_list_for_each' - 'bip_for_each_vec' - 'bond_for_each_slave' - 'bond_for_each_slave_rcu' - 'bpf_for_each' - 'bpf_for_each_reg_in_vstate' - 'bpf_for_each_reg_in_vstate_mask' - 'bpf_for_each_spilled_reg' - 'bpf_object__for_each_map' - 'bpf_object__for_each_program' - 'btree_for_each_safe128' - 'btree_for_each_safe32' - 'btree_for_each_safe64' - 'btree_for_each_safel' - 'card_for_each_dev' - 'cgroup_taskset_for_each' - 'cgroup_taskset_for_each_leader' - 'cpu_aggr_map__for_each_idx' - 'cpufreq_for_each_efficient_entry_idx' - 'cpufreq_for_each_entry' - 'cpufreq_for_each_entry_idx' - 'cpufreq_for_each_valid_entry' - 'cpufreq_for_each_valid_entry_idx' - 'css_for_each_child' - 'css_for_each_descendant_post' - 'css_for_each_descendant_pre' - 'damon_for_each_region' - 'damon_for_each_region_from' - 'damon_for_each_region_safe' - 'damon_for_each_scheme' - 'damon_for_each_scheme_safe' - 'damon_for_each_target' - 'damon_for_each_target_safe' - 'damos_for_each_filter' - 'damos_for_each_filter_safe' - 'data__for_each_file' - 'data__for_each_file_new' - 'data__for_each_file_start' - 'device_for_each_child_node' - 'displayid_iter_for_each' - 'dma_fence_array_for_each' - 'dma_fence_chain_for_each' - 'dma_fence_unwrap_for_each' - 'dma_resv_for_each_fence' - 'dma_resv_for_each_fence_unlocked' - 'do_for_each_ftrace_op' - 'drm_atomic_crtc_for_each_plane' - 'drm_atomic_crtc_state_for_each_plane' - 'drm_atomic_crtc_state_for_each_plane_state' - 'drm_atomic_for_each_plane_damage' - 'drm_client_for_each_connector_iter' - 'drm_client_for_each_modeset' - 'drm_connector_for_each_possible_encoder' - 'drm_exec_for_each_locked_object' - 'drm_exec_for_each_locked_object_reverse' - 'drm_for_each_bridge_in_chain' - 'drm_for_each_connector_iter' - 'drm_for_each_crtc' - 'drm_for_each_crtc_reverse' - 'drm_for_each_encoder' - 'drm_for_each_encoder_mask' - 'drm_for_each_fb' - 'drm_for_each_legacy_plane' - 'drm_for_each_plane' - 'drm_for_each_plane_mask' - 'drm_for_each_privobj' - 'drm_gem_for_each_gpuva' - 'drm_gem_for_each_gpuva_safe' - 'drm_gpuva_for_each_op' - 'drm_gpuva_for_each_op_from_reverse' - 'drm_gpuva_for_each_op_safe' - 'drm_gpuvm_for_each_va' - 'drm_gpuvm_for_each_va_range' - 'drm_gpuvm_for_each_va_range_safe' - 'drm_gpuvm_for_each_va_safe' - 'drm_mm_for_each_hole' - 'drm_mm_for_each_node' - 'drm_mm_for_each_node_in_range' - 'drm_mm_for_each_node_safe' - 'dsa_switch_for_each_available_port' - 'dsa_switch_for_each_cpu_port' - 'dsa_switch_for_each_cpu_port_continue_reverse' - 'dsa_switch_for_each_port' - 'dsa_switch_for_each_port_continue_reverse' - 'dsa_switch_for_each_port_safe' - 'dsa_switch_for_each_user_port' - 'dsa_tree_for_each_cpu_port' - 'dsa_tree_for_each_user_port' - 'dsa_tree_for_each_user_port_continue_reverse' - 'dso__for_each_symbol' - 'dsos__for_each_with_build_id' - 'elf_hash_for_each_possible' - 'elf_symtab__for_each_symbol' - 'evlist__for_each_cpu' - 'evlist__for_each_entry' - 'evlist__for_each_entry_continue' - 'evlist__for_each_entry_from' - 'evlist__for_each_entry_reverse' - 'evlist__for_each_entry_safe' - 'flow_action_for_each' - 'for_each_acpi_consumer_dev' - 'for_each_acpi_dev_match' - 'for_each_active_dev_scope' - 'for_each_active_drhd_unit' - 'for_each_active_iommu' - 'for_each_active_route' - 'for_each_aggr_pgid' - 'for_each_and_bit' - 'for_each_andnot_bit' - 'for_each_available_child_of_node' - 'for_each_bench' - 'for_each_bio' - 'for_each_board_func_rsrc' - 'for_each_btf_ext_rec' - 'for_each_btf_ext_sec' - 'for_each_bvec' - 'for_each_card_auxs' - 'for_each_card_auxs_safe' - 'for_each_card_components' - 'for_each_card_dapms' - 'for_each_card_pre_auxs' - 'for_each_card_prelinks' - 'for_each_card_rtds' - 'for_each_card_rtds_safe' - 'for_each_card_widgets' - 'for_each_card_widgets_safe' - 'for_each_cgroup_storage_type' - 'for_each_child_of_node' - 'for_each_clear_bit' - 'for_each_clear_bit_from' - 'for_each_clear_bitrange' - 'for_each_clear_bitrange_from' - 'for_each_cmd' - 'for_each_cmsghdr' - 'for_each_collection' - 'for_each_comp_order' - 'for_each_compatible_node' - 'for_each_component_dais' - 'for_each_component_dais_safe' - 'for_each_conduit' - 'for_each_console' - 'for_each_console_srcu' - 'for_each_cpu' - 'for_each_cpu_and' - 'for_each_cpu_andnot' - 'for_each_cpu_or' - 'for_each_cpu_wrap' - 'for_each_dapm_widgets' - 'for_each_dedup_cand' - 'for_each_dev_addr' - 'for_each_dev_scope' - 'for_each_dma_cap_mask' - 'for_each_dpcm_be' - 'for_each_dpcm_be_rollback' - 'for_each_dpcm_be_safe' - 'for_each_dpcm_fe' - 'for_each_drhd_unit' - 'for_each_dss_dev' - 'for_each_efi_memory_desc' - 'for_each_efi_memory_desc_in_map' - 'for_each_element' - 'for_each_element_extid' - 'for_each_element_id' - 'for_each_endpoint_of_node' - 'for_each_event' - 'for_each_event_tps' - 'for_each_evictable_lru' - 'for_each_fib6_node_rt_rcu' - 'for_each_fib6_walker_rt' - 'for_each_free_mem_pfn_range_in_zone' - 'for_each_free_mem_pfn_range_in_zone_from' - 'for_each_free_mem_range' - 'for_each_free_mem_range_reverse' - 'for_each_func_rsrc' - 'for_each_gpiochip_node' - 'for_each_group_evsel' - 'for_each_group_evsel_head' - 'for_each_group_member' - 'for_each_group_member_head' - 'for_each_hstate' - 'for_each_if' - 'for_each_inject_fn' - 'for_each_insn' - 'for_each_insn_prefix' - 'for_each_intid' - 'for_each_iommu' - 'for_each_ip_tunnel_rcu' - 'for_each_irq_nr' - 'for_each_lang' - 'for_each_link_codecs' - 'for_each_link_cpus' - 'for_each_link_platforms' - 'for_each_lru' - 'for_each_matching_node' - 'for_each_matching_node_and_match' - 'for_each_media_entity_data_link' - 'for_each_mem_pfn_range' - 'for_each_mem_range' - 'for_each_mem_range_rev' - 'for_each_mem_region' - 'for_each_member' - 'for_each_memory' - 'for_each_migratetype_order' - 'for_each_missing_reg' - 'for_each_mle_subelement' - 'for_each_mod_mem_type' - 'for_each_net' - 'for_each_net_continue_reverse' - 'for_each_net_rcu' - 'for_each_netdev' - 'for_each_netdev_continue' - 'for_each_netdev_continue_rcu' - 'for_each_netdev_continue_reverse' - 'for_each_netdev_dump' - 'for_each_netdev_feature' - 'for_each_netdev_in_bond_rcu' - 'for_each_netdev_rcu' - 'for_each_netdev_reverse' - 'for_each_netdev_safe' - 'for_each_new_connector_in_state' - 'for_each_new_crtc_in_state' - 'for_each_new_mst_mgr_in_state' - 'for_each_new_plane_in_state' - 'for_each_new_plane_in_state_reverse' - 'for_each_new_private_obj_in_state' - 'for_each_new_reg' - 'for_each_node' - 'for_each_node_by_name' - 'for_each_node_by_type' - 'for_each_node_mask' - 'for_each_node_state' - 'for_each_node_with_cpus' - 'for_each_node_with_property' - 'for_each_nonreserved_multicast_dest_pgid' - 'for_each_numa_hop_mask' - 'for_each_of_allnodes' - 'for_each_of_allnodes_from' - 'for_each_of_cpu_node' - 'for_each_of_pci_range' - 'for_each_old_connector_in_state' - 'for_each_old_crtc_in_state' - 'for_each_old_mst_mgr_in_state' - 'for_each_old_plane_in_state' - 'for_each_old_private_obj_in_state' - 'for_each_oldnew_connector_in_state' - 'for_each_oldnew_crtc_in_state' - 'for_each_oldnew_mst_mgr_in_state' - 'for_each_oldnew_plane_in_state' - 'for_each_oldnew_plane_in_state_reverse' - 'for_each_oldnew_private_obj_in_state' - 'for_each_online_cpu' - 'for_each_online_node' - 'for_each_online_pgdat' - 'for_each_or_bit' - 'for_each_path' - 'for_each_pci_bridge' - 'for_each_pci_dev' - 'for_each_pcm_streams' - 'for_each_physmem_range' - 'for_each_populated_zone' - 'for_each_possible_cpu' - 'for_each_present_blessed_reg' - 'for_each_present_cpu' - 'for_each_prime_number' - 'for_each_prime_number_from' - 'for_each_probe_cache_entry' - 'for_each_process' - 'for_each_process_thread' - 'for_each_prop_codec_conf' - 'for_each_prop_dai_codec' - 'for_each_prop_dai_cpu' - 'for_each_prop_dlc_codecs' - 'for_each_prop_dlc_cpus' - 'for_each_prop_dlc_platforms' - 'for_each_property_of_node' - 'for_each_reg' - 'for_each_reg_filtered' - 'for_each_reloc' - 'for_each_reloc_from' - 'for_each_requested_gpio' - 'for_each_requested_gpio_in_range' - 'for_each_reserved_mem_range' - 'for_each_reserved_mem_region' - 'for_each_rtd_codec_dais' - 'for_each_rtd_components' - 'for_each_rtd_cpu_dais' - 'for_each_rtd_dais' - 'for_each_sband_iftype_data' - 'for_each_script' - 'for_each_sec' - 'for_each_set_bit' - 'for_each_set_bit_from' - 'for_each_set_bit_wrap' - 'for_each_set_bitrange' - 'for_each_set_bitrange_from' - 'for_each_set_clump8' - 'for_each_sg' - 'for_each_sg_dma_page' - 'for_each_sg_page' - 'for_each_sgtable_dma_page' - 'for_each_sgtable_dma_sg' - 'for_each_sgtable_page' - 'for_each_sgtable_sg' - 'for_each_sibling_event' - 'for_each_sta_active_link' - 'for_each_subelement' - 'for_each_subelement_extid' - 'for_each_subelement_id' - 'for_each_sublist' - 'for_each_subsystem' - 'for_each_supported_activate_fn' - 'for_each_supported_inject_fn' - 'for_each_sym' - 'for_each_test' - 'for_each_thread' - 'for_each_token' - 'for_each_unicast_dest_pgid' - 'for_each_valid_link' - 'for_each_vif_active_link' - 'for_each_vma' - 'for_each_vma_range' - 'for_each_vsi' - 'for_each_wakeup_source' - 'for_each_zone' - 'for_each_zone_zonelist' - 'for_each_zone_zonelist_nodemask' - 'func_for_each_insn' - 'fwnode_for_each_available_child_node' - 'fwnode_for_each_child_node' - 'fwnode_for_each_parent_node' - 'fwnode_graph_for_each_endpoint' - 'gadget_for_each_ep' - 'genradix_for_each' - 'genradix_for_each_from' - 'genradix_for_each_reverse' - 'hash_for_each' - 'hash_for_each_possible' - 'hash_for_each_possible_rcu' - 'hash_for_each_possible_rcu_notrace' - 'hash_for_each_possible_safe' - 'hash_for_each_rcu' - 'hash_for_each_safe' - 'hashmap__for_each_entry' - 'hashmap__for_each_entry_safe' - 'hashmap__for_each_key_entry' - 'hashmap__for_each_key_entry_safe' - 'hctx_for_each_ctx' - 'hists__for_each_format' - 'hists__for_each_sort_list' - 'hlist_bl_for_each_entry' - 'hlist_bl_for_each_entry_rcu' - 'hlist_bl_for_each_entry_safe' - 'hlist_for_each' - 'hlist_for_each_entry' - 'hlist_for_each_entry_continue' - 'hlist_for_each_entry_continue_rcu' - 'hlist_for_each_entry_continue_rcu_bh' - 'hlist_for_each_entry_from' - 'hlist_for_each_entry_from_rcu' - 'hlist_for_each_entry_rcu' - 'hlist_for_each_entry_rcu_bh' - 'hlist_for_each_entry_rcu_notrace' - 'hlist_for_each_entry_safe' - 'hlist_for_each_entry_srcu' - 'hlist_for_each_safe' - 'hlist_nulls_for_each_entry' - 'hlist_nulls_for_each_entry_from' - 'hlist_nulls_for_each_entry_rcu' - 'hlist_nulls_for_each_entry_safe' - 'i3c_bus_for_each_i2cdev' - 'i3c_bus_for_each_i3cdev' - 'idr_for_each_entry' - 'idr_for_each_entry_continue' - 'idr_for_each_entry_continue_ul' - 'idr_for_each_entry_ul' - 'in_dev_for_each_ifa_rcu' - 'in_dev_for_each_ifa_rtnl' - 'inet_bind_bucket_for_each' - 'interval_tree_for_each_span' - 'intlist__for_each_entry' - 'intlist__for_each_entry_safe' - 'kcore_copy__for_each_phdr' - 'key_for_each' - 'key_for_each_safe' - 'klp_for_each_func' - 'klp_for_each_func_safe' - 'klp_for_each_func_static' - 'klp_for_each_object' - 'klp_for_each_object_safe' - 'klp_for_each_object_static' - 'kunit_suite_for_each_test_case' - 'kvm_for_each_memslot' - 'kvm_for_each_memslot_in_gfn_range' - 'kvm_for_each_vcpu' - 'libbpf_nla_for_each_attr' - 'list_for_each' - 'list_for_each_codec' - 'list_for_each_codec_safe' - 'list_for_each_continue' - 'list_for_each_entry' - 'list_for_each_entry_continue' - 'list_for_each_entry_continue_rcu' - 'list_for_each_entry_continue_reverse' - 'list_for_each_entry_from' - 'list_for_each_entry_from_rcu' - 'list_for_each_entry_from_reverse' - 'list_for_each_entry_lockless' - 'list_for_each_entry_rcu' - 'list_for_each_entry_reverse' - 'list_for_each_entry_safe' - 'list_for_each_entry_safe_continue' - 'list_for_each_entry_safe_from' - 'list_for_each_entry_safe_reverse' - 'list_for_each_entry_srcu' - 'list_for_each_from' - 'list_for_each_prev' - 'list_for_each_prev_safe' - 'list_for_each_rcu' - 'list_for_each_reverse' - 'list_for_each_safe' - 'llist_for_each' - 'llist_for_each_entry' - 'llist_for_each_entry_safe' - 'llist_for_each_safe' - 'lwq_for_each_safe' - 'map__for_each_symbol' - 'map__for_each_symbol_by_name' - 'maps__for_each_entry' - 'maps__for_each_entry_safe' - 'mas_for_each' - 'mci_for_each_dimm' - 'media_device_for_each_entity' - 'media_device_for_each_intf' - 'media_device_for_each_link' - 'media_device_for_each_pad' - 'media_entity_for_each_pad' - 'media_pipeline_for_each_entity' - 'media_pipeline_for_each_pad' - 'mlx5_lag_for_each_peer_mdev' - 'msi_domain_for_each_desc' - 'msi_for_each_desc' - 'mt_for_each' - 'nanddev_io_for_each_page' - 'netdev_for_each_lower_dev' - 'netdev_for_each_lower_private' - 'netdev_for_each_lower_private_rcu' - 'netdev_for_each_mc_addr' - 'netdev_for_each_synced_mc_addr' - 'netdev_for_each_synced_uc_addr' - 'netdev_for_each_uc_addr' - 'netdev_for_each_upper_dev_rcu' - 'netdev_hw_addr_list_for_each' - 'nft_rule_for_each_expr' - 'nla_for_each_attr' - 'nla_for_each_nested' - 'nlmsg_for_each_attr' - 'nlmsg_for_each_msg' - 'nr_neigh_for_each' - 'nr_neigh_for_each_safe' - 'nr_node_for_each' - 'nr_node_for_each_safe' - 'of_for_each_phandle' - 'of_property_for_each_string' - 'of_property_for_each_u32' - 'pci_bus_for_each_resource' - 'pci_dev_for_each_resource' - 'pcl_for_each_chunk' - 'pcl_for_each_segment' - 'pcm_for_each_format' - 'perf_config_items__for_each_entry' - 'perf_config_sections__for_each_entry' - 'perf_config_set__for_each_entry' - 'perf_cpu_map__for_each_cpu' - 'perf_cpu_map__for_each_idx' - 'perf_evlist__for_each_entry' - 'perf_evlist__for_each_entry_reverse' - 'perf_evlist__for_each_entry_safe' - 'perf_evlist__for_each_evsel' - 'perf_evlist__for_each_mmap' - 'perf_hpp_list__for_each_format' - 'perf_hpp_list__for_each_format_safe' - 'perf_hpp_list__for_each_sort_list' - 'perf_hpp_list__for_each_sort_list_safe' - 'perf_tool_event__for_each_event' - 'plist_for_each' - 'plist_for_each_continue' - 'plist_for_each_entry' - 'plist_for_each_entry_continue' - 'plist_for_each_entry_safe' - 'plist_for_each_safe' - 'pnp_for_each_card' - 'pnp_for_each_dev' - 'protocol_for_each_card' - 'protocol_for_each_dev' - 'queue_for_each_hw_ctx' - 'radix_tree_for_each_slot' - 'radix_tree_for_each_tagged' - 'rb_for_each' - 'rbtree_postorder_for_each_entry_safe' - 'rdma_for_each_block' - 'rdma_for_each_port' - 'rdma_umem_for_each_dma_block' - 'resort_rb__for_each_entry' - 'resource_list_for_each_entry' - 'resource_list_for_each_entry_safe' - 'rhl_for_each_entry_rcu' - 'rhl_for_each_rcu' - 'rht_for_each' - 'rht_for_each_entry' - 'rht_for_each_entry_from' - 'rht_for_each_entry_rcu' - 'rht_for_each_entry_rcu_from' - 'rht_for_each_entry_safe' - 'rht_for_each_from' - 'rht_for_each_rcu' - 'rht_for_each_rcu_from' - 'rq_for_each_bvec' - 'rq_for_each_segment' - 'rq_list_for_each' - 'rq_list_for_each_safe' - 'sample_read_group__for_each' - 'scsi_for_each_prot_sg' - 'scsi_for_each_sg' - 'sctp_for_each_hentry' - 'sctp_skb_for_each' - 'sec_for_each_insn' - 'sec_for_each_insn_continue' - 'sec_for_each_insn_from' - 'sec_for_each_sym' - 'shdma_for_each_chan' - 'shost_for_each_device' - 'sk_for_each' - 'sk_for_each_bound' - 'sk_for_each_bound_bhash2' - 'sk_for_each_entry_offset_rcu' - 'sk_for_each_from' - 'sk_for_each_rcu' - 'sk_for_each_safe' - 'sk_nulls_for_each' - 'sk_nulls_for_each_from' - 'sk_nulls_for_each_rcu' - 'snd_array_for_each' - 'snd_pcm_group_for_each_entry' - 'snd_soc_dapm_widget_for_each_path' - 'snd_soc_dapm_widget_for_each_path_safe' - 'snd_soc_dapm_widget_for_each_sink_path' - 'snd_soc_dapm_widget_for_each_source_path' - 'strlist__for_each_entry' - 'strlist__for_each_entry_safe' - 'sym_for_each_insn' - 'sym_for_each_insn_continue_reverse' - 'symbols__for_each_entry' - 'tb_property_for_each' - 'tcf_act_for_each_action' - 'tcf_exts_for_each_action' - 'ttm_resource_manager_for_each_res' - 'twsk_for_each_bound_bhash2' - 'udp_portaddr_for_each_entry' - 'udp_portaddr_for_each_entry_rcu' - 'usb_hub_for_each_child' - 'v4l2_device_for_each_subdev' - 'v4l2_m2m_for_each_dst_buf' - 'v4l2_m2m_for_each_dst_buf_safe' - 'v4l2_m2m_for_each_src_buf' - 'v4l2_m2m_for_each_src_buf_safe' - 'virtio_device_for_each_vq' - 'while_for_each_ftrace_op' - 'xa_for_each' - 'xa_for_each_marked' - 'xa_for_each_range' - 'xa_for_each_start' - 'xas_for_each' - 'xas_for_each_conflict' - 'xas_for_each_marked' - 'xbc_array_for_each_value' - 'xbc_for_each_key_value' - 'xbc_node_for_each_array_value' - 'xbc_node_for_each_child' - 'xbc_node_for_each_key_value' - 'xbc_node_for_each_subkey' - 'zorro_for_each_dev' IncludeBlocks: Preserve IncludeCategories: - Regex: '.*' Priority: 1 IncludeIsMainRegex: '(Test)?$' IndentCaseLabels: false IndentGotoLabels: false IndentPPDirectives: None IndentWidth: 8 IndentWrappedFunctionNames: false JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: false MacroBlockBegin: '' MacroBlockEnd: '' MaxEmptyLinesToKeep: 1 NamespaceIndentation: None ObjCBinPackProtocolList: Auto ObjCBlockIndentWidth: 8 ObjCSpaceAfterProperty: true ObjCSpaceBeforeProtocolList: true # Taken from git's rules PenaltyBreakAssignment: 10 PenaltyBreakBeforeFirstCallParameter: 30 PenaltyBreakComment: 10 PenaltyBreakFirstLessLess: 0 PenaltyBreakString: 10 PenaltyExcessCharacter: 100 PenaltyReturnTypeOnItsOwnLine: 60 PointerAlignment: Right ReflowComments: false SortIncludes: false SortUsingDeclarations: false SpaceAfterCStyleCast: false SpaceAfterTemplateKeyword: true SpaceBeforeAssignmentOperators: true SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true SpaceBeforeParens: ControlStatementsExceptForEachMacros SpaceBeforeRangeBasedForLoopColon: true SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 1 SpacesInAngles: false SpacesInContainerLiterals: false SpacesInCStyleCastParentheses: false SpacesInParentheses: false SpacesInSquareBrackets: false Standard: Cpp03 TabWidth: 8 UseTab: Always ... ================================================ FILE: samples/.gitignore ================================================ */loader */event-trigger */src/linux */src/stub.rs */target */.gdbinit */.gdb_history */syscall_tp ================================================ FILE: samples/atomic/.cargo/config.toml ================================================ [build] target = "x86_64-unknown-none" [target.x86_64-unknown-none] linker = "ld.mold" rustflags = [ "-Zthreads=8", "-Cforce-frame-pointers=y", "-Csymbol-mangling-version=v0", "-Ccodegen-units=1", "-Crelocation-model=pie", "-Crelro-level=full", ] [unstable] build-std = ["core"] ================================================ FILE: samples/atomic/Cargo.toml ================================================ [package] name = "atomic" version = "0.1.0" edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] [dependencies.rex] path = "../../rex" [lints.clippy] disallowed_methods = "forbid" disallowed_types = "forbid" [lints.rust] incomplete_features = "forbid" internal_features = "forbid" unsafe_code = "forbid" unstable_features = "forbid" [profile.dev] panic = "abort" debug = false [profile.release] panic = "abort" debug = false lto = true ================================================ FILE: samples/atomic/clippy.toml ================================================ disallowed-methods = [ "core::mem::forget", ] disallowed-types = [ "core::mem::ManuallyDrop", ] ================================================ FILE: samples/atomic/event-trigger.c ================================================ #include #include #include #include #include int main(int argc, char *argv[]) { int nr_rounds, arg, fd; if (argc != 3) asm volatile("ud2"); nr_rounds = atoi(argv[1]); arg = atoi(argv[2]); fd = open("/proc/kprobe_target", O_RDONLY); if (fd < 0) { perror("open"); return 1; } for (int i = 0; i < nr_rounds; i++) ioctl(fd, 1313, arg); close(fd); } ================================================ FILE: samples/atomic/loader.c ================================================ #include #include #include #include #include #include #include #include #include #include #define EXE "./target/x86_64-unknown-none/release/atomic" int main(void) { struct bpf_object *obj; struct bpf_program *prog; struct bpf_link *link = NULL; obj = rex_obj_get_bpf(rex_obj_load(EXE)); if (!obj) { fprintf(stderr, "Object could not be opened\n"); return 1; } prog = bpf_object__find_program_by_name(obj, "rex_prog1"); if (!prog) { fprintf(stderr, "Program not found\n"); return 1; } link = bpf_program__attach(prog); if (libbpf_get_error(link)) { fprintf(stderr, "ERROR: bpf_program__attach failed\n"); link = NULL; return 1; } bpf_link__pin(link, "/sys/fs/bpf/link"); bpf_link__destroy(link); return 0; } ================================================ FILE: samples/atomic/meson.build ================================================ build_dir = run_command( realpath, '--relative-to', meson.current_source_dir(), meson.current_build_dir(), capture: true, check: true ).stdout().strip() env = environment() env.prepend('PATH', rust_bin) env.set('LINUX_OBJ', kbuild_dir) env.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux')) env.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target')) sample_clippy = custom_target( 'atomic-clippy', output: ['target'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'clippy', '-qr' ], env: env, console: false, build_by_default: true ) sample_build = custom_target( 'atomic-build', output: ['atomic'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'rustc', '-qr', '--', '-Cenable_rex' ], depends: sample_clippy, env: env, console: false, build_by_default: true ) executable( 'loader', 'loader.c', build_by_default: true, dependencies: [librex_dep, libbpf_dep, kernel_dep], pie: true ) executable( 'event-trigger', 'event-trigger.c', build_by_default: true, dependencies: [kernel_dep], pie: true ) ================================================ FILE: samples/atomic/rustfmt.toml ================================================ max_width = 80 binop_separator = "Back" reorder_impl_items = true wrap_comments = true imports_granularity = "Module" group_imports = "StdExternalCrate" ================================================ FILE: samples/atomic/src/main.rs ================================================ #![no_std] #![no_main] extern crate rex; use core::sync::atomic::{AtomicU64, Ordering}; use rex::kprobe::*; use rex::pt_regs::PtRegs; use rex::{Result, rex_kprobe, rex_printk}; static ATOM: AtomicU64 = AtomicU64::new(42); #[rex_kprobe(function = "kprobe_target_func")] fn rex_prog1(obj: &kprobe, _ctx: &mut PtRegs) -> Result { let random = obj.bpf_get_prandom_u32() as u64; ATOM.store(random, Ordering::Relaxed); let start = obj.bpf_ktime_get_ns(); let val = ATOM.load(Ordering::Relaxed); let end = obj.bpf_ktime_get_ns(); rex_printk!("Time elapsed: {} {}", end - start, val)?; Ok(0) } ================================================ FILE: samples/bmc/.cargo/config.toml ================================================ [build] target = "x86_64-unknown-none" [target.x86_64-unknown-none] linker = "ld.mold" rustflags = [ "-Zthreads=8", "-Cforce-frame-pointers=y", "-Csymbol-mangling-version=v0", "-Ccodegen-units=1", "-Crelocation-model=pie", "-Crelro-level=full", ] [unstable] build-std = ["core"] ================================================ FILE: samples/bmc/Cargo.toml ================================================ [package] name = "bmc" version = "0.1.0" edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] [dependencies.rex] path = "../../rex" [lints.clippy] disallowed_methods = "forbid" disallowed_types = "forbid" [lints.rust] incomplete_features = "forbid" internal_features = "forbid" unsafe_code = "forbid" unstable_features = "forbid" [profile.dev] panic = "abort" debug = false [profile.release] panic = "abort" debug = false lto = true ================================================ FILE: samples/bmc/clippy.toml ================================================ disallowed-methods = [ "core::mem::forget", ] disallowed-types = [ "core::mem::ManuallyDrop", ] ================================================ FILE: samples/bmc/entry.c ================================================ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define BPF_SYSFS_ROOT "/sys/fs/bpf" #define STATS_PATH "/tmp/rust_bmc_stats.txt" #define STATS_INTERVAL_PATH "/tmp/bmc_stats_interval.txt" #define EXE "./target/x86_64-unknown-none/release/bmc" static int nr_cpus = 0; struct bpf_progs_desc { char name[256]; enum bpf_prog_type type; unsigned char pin; int map_prog_idx; struct bpf_program *prog; }; struct bmc_stats { unsigned int get_recv_count; // Number of GET command received unsigned int set_recv_count; // Number of SET command received unsigned int get_resp_count; // Number of GET command reply analyzed unsigned int hit_misprediction; // Number of keys that were expected to hit but did not (either because of a hash colision or a race with an invalidation/update) unsigned int hit_count; // Number of HIT in kernel cache unsigned int miss_count; // Number of MISS in kernel cache unsigned int update_count; // Number of kernel cache updates unsigned int invalidation_count; // Number of kernel cache entry invalidated unsigned int debug_count; }; static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args) { if (level == LIBBPF_DEBUG || level == LIBBPF_INFO) { return vfprintf(stderr, format, args); } return 0; } int write_stats_to_file(char *filename, int map_fd) { struct bmc_stats stats[nr_cpus]; struct bmc_stats aggregate_stats; __u32 key = 0; FILE *fp; memset(&aggregate_stats, 0, sizeof(struct bmc_stats)); assert(bpf_map_lookup_elem(map_fd, &key, stats) == 0); for (int i = 0; i < nr_cpus; i++) { aggregate_stats.get_recv_count += stats[i].get_recv_count; aggregate_stats.set_recv_count += stats[i].set_recv_count; aggregate_stats.get_resp_count += stats[i].get_resp_count; aggregate_stats.hit_misprediction += stats[i].hit_misprediction; aggregate_stats.hit_count += stats[i].hit_count; aggregate_stats.miss_count += stats[i].miss_count; aggregate_stats.update_count += stats[i].update_count; aggregate_stats.invalidation_count += stats[i].invalidation_count; aggregate_stats.debug_count += stats[i].debug_count; } fp = fopen(STATS_PATH, "w+"); if (fp == NULL) { fprintf(stderr, "Error: failed to write stats to file '%s'\n", filename); return -1; } fprintf(fp, "STAT get_recv_count %u\n", aggregate_stats.get_recv_count); fprintf(fp, "STAT set_recv_count %u\n", aggregate_stats.set_recv_count); fprintf(fp, "STAT get_resp_count %u\n", aggregate_stats.get_resp_count); fprintf(fp, "STAT hit_misprediction %u\n", aggregate_stats.hit_misprediction); fprintf(fp, "STAT hit_count %u\n", aggregate_stats.hit_count); fprintf(fp, "STAT miss_count %u\n", aggregate_stats.miss_count); fprintf(fp, "STAT update_count %u\n", aggregate_stats.update_count); fprintf(fp, "STAT invalidation_count %u\n", aggregate_stats.invalidation_count); fprintf(fp, "STAT debug_count %u\n", aggregate_stats.debug_count); fclose(fp); return 0; } int main(int argc, char *argv[]) { struct rlimit r = { RLIM_INFINITY, RLIM_INFINITY }; int xdp_main_prog_fd; struct bpf_program *rx_prog, *tx_prog; struct bpf_object *obj; char filename[PATH_MAX]; int err; __u32 xdp_flags = 0; int *interfaces_idx; int ret = 0; int interface_count = 0; int sig, quit = 0; libbpf_set_print(libbpf_print_fn); interface_count = argc - optind; if (interface_count <= 0) { fprintf(stderr, "Missing at least one required interface index\n"); exit(EXIT_FAILURE); } interfaces_idx = calloc(sizeof(int), interface_count); if (interfaces_idx == NULL) { fprintf(stderr, "Error: failed to allocate memory\n"); return 1; } for (int i = 0; i < interface_count && optind < argc; optind++, i++) { interfaces_idx[i] = atoi(argv[optind]); } nr_cpus = libbpf_num_possible_cpus(); sigset_t signal_mask; sigemptyset(&signal_mask); sigaddset(&signal_mask, SIGINT); sigaddset(&signal_mask, SIGTERM); sigaddset(&signal_mask, SIGUSR1); if (setrlimit(RLIMIT_MEMLOCK, &r)) { perror("setrlimit failed"); return 1; } obj = rex_obj_get_bpf(rex_obj_load(EXE)); if (!obj) { fprintf(stderr, "Object could not be opened\n"); return 1; } rx_prog = bpf_object__find_program_by_name(obj, "xdp_rx_filter"); if (!rx_prog) { fprintf(stderr, "start not found\n"); return 1; } xdp_main_prog_fd = bpf_program__fd(rx_prog); if (xdp_main_prog_fd < 0) { fprintf(stderr, "Error: bpf_program__fd failed\n"); return 1; } xdp_flags |= XDP_FLAGS_DRV_MODE; /* xdp_flags |= XDP_FLAGS_SKB_MODE; */ for (int i = 0; i < interface_count; i++) { if (bpf_xdp_attach(interfaces_idx[i], xdp_main_prog_fd, xdp_flags, NULL) < 0) { fprintf(stderr, "Error: bpf_set_link_xdp_fd failed for interface %d\n", interfaces_idx[i]); return 1; } else { printf("Main BPF program attached to XDP on interface %d\n", interfaces_idx[i]); } } char prog_name[256] = "xdp_tx_filter"; tx_prog = bpf_object__find_program_by_name(obj, prog_name); if (!tx_prog) { fprintf(stderr, "tx_prog not found\n"); exit(1); } printf("tx_prog: %s\n", bpf_program__name(tx_prog)); int len = snprintf(filename, PATH_MAX, "%s/%s", BPF_SYSFS_ROOT, prog_name); if (len < 0) { fprintf(stderr, "Error: Program name '%s' is invalid\n", "xdp_tx_filter"); return -1; } else if (len >= PATH_MAX) { fprintf(stderr, "Error: Program name '%s' is too long\n", prog_name); return -1; } ret = bpf_program__pin(tx_prog, filename); if (ret != 0) { fprintf(stderr, "Error: Failed to pin program '%s' to path %s with error code %d\n", prog_name, filename, ret); return ret; } err = sigprocmask(SIG_BLOCK, &signal_mask, NULL); if (err != 0) { fprintf(stderr, "Error: Failed to set signal mask\n"); exit(EXIT_FAILURE); } while (!quit) { err = sigwait(&signal_mask, &sig); if (err != 0) { fprintf(stderr, "Error: Failed to wait for signal\n"); exit(EXIT_FAILURE); } switch (sig) { case SIGINT: case SIGTERM: case SIGUSR1: quit = 1; break; default: fprintf(stderr, "Unknown signal\n"); break; } } int map_stats_fd = bpf_object__find_map_fd_by_name(obj, "map_stats"); if (map_stats_fd < 0) { fprintf(stderr, "Error: bpf_object__find_map_fd_by_name failed\n"); return 1; } printf("Writing stats to file\n"); write_stats_to_file(STATS_PATH, map_stats_fd); for (int i = 0; i < interface_count; i++) { bpf_xdp_attach(interfaces_idx[i], -1, xdp_flags, NULL); } return ret; } ================================================ FILE: samples/bmc/meson.build ================================================ build_dir = run_command( realpath, '--relative-to', meson.current_source_dir(), meson.current_build_dir(), capture: true, check: true ).stdout().strip() env = environment() env.prepend('PATH', rust_bin) env.set('LINUX_OBJ', kbuild_dir) env.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux')) env.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target')) sample_clippy = custom_target( 'bmc-clippy', output: ['target'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'clippy', '-qr' ], env: env, console: false, build_by_default: true ) sample_build = custom_target( 'bmc-build', output: ['bmc'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'rustc', '-qr', '--', '-Cenable_rex' ], depends: sample_clippy, env: env, console: false, build_by_default: true ) executable( 'entry', 'entry.c', build_by_default: true, dependencies: [librex_dep, libbpf_dep, kernel_dep], pie: true ) ================================================ FILE: samples/bmc/rustfmt.toml ================================================ max_width = 80 binop_separator = "Back" reorder_impl_items = true wrap_comments = true imports_granularity = "Module" group_imports = "StdExternalCrate" ================================================ FILE: samples/bmc/src/main.rs ================================================ #![no_std] #![no_main] #![allow(non_camel_case_types)] use core::mem::{size_of, swap}; use rex::map::*; use rex::sched_cls::*; use rex::spinlock::*; use rex::utils::*; use rex::xdp::*; use rex::{rex_map, rex_printk, rex_tc, rex_xdp}; const BMC_MAX_PACKET_LENGTH: usize = 1500; const BMC_CACHE_ENTRY_COUNT: u32 = 3250000; const BMC_MAX_KEY_LENGTH: usize = 230; const BMC_MAX_VAL_LENGTH: usize = 1000; const BMC_MAX_ADDITIONAL_PAYLOAD_BYTES: usize = 53; const BMC_MAX_CACHE_DATA_SIZE: usize = BMC_MAX_KEY_LENGTH + BMC_MAX_VAL_LENGTH + BMC_MAX_ADDITIONAL_PAYLOAD_BYTES; const BMC_MAX_KEY_IN_PACKET: u32 = 30; const FNV_OFFSET_BASIS_32: u32 = 2166136261; const FNV_PRIME_32: u32 = 16777619; const ETH_ALEN: usize = 6; const MEMCACHED_PORT: u16 = 11211; #[repr(C)] pub struct memcached_udp_header { request_id: u16, seq_num: u16, num_dgram: u16, unused: u16, } #[repr(C)] #[derive(Clone, Copy)] pub struct bmc_cache_entry { lock: bpf_spin_lock, pub len: u32, pub valid: u8, pub hash: u32, pub data: [u8; BMC_MAX_PACKET_LENGTH], } #[repr(C)] #[derive(Clone, Copy)] struct memcached_key { hash: u32, data: [u8; BMC_MAX_KEY_LENGTH], len: usize, } #[repr(C)] #[derive(Clone, Copy)] pub struct bmc_stats { get_recv_count: u32, set_recv_count: u32, get_resp_count: u32, hit_misprediction: u32, hit_count: u32, miss_count: u32, update_count: u32, invalidation_count: u32, debug_count: u32, } struct parsing_context { key_count: u32, current_key: u32, read_pkt_offset: u8, } #[rex_map] static map_kcache: RexArrayMap = RexArrayMap::new(BMC_CACHE_ENTRY_COUNT, 0); #[rex_map] static map_keys: RexPerCPUArrayMap = RexPerCPUArrayMap::new(BMC_MAX_KEY_IN_PACKET, 0); #[rex_map] static map_stats: RexPerCPUArrayMap = RexPerCPUArrayMap::new(1, 0); // TODO: use simple hash function, may need update in the future macro_rules! hash_func { ($hash:expr, $value:expr) => { $hash = ($hash ^ $value as u32).wrapping_mul(FNV_PRIME_32); }; } macro_rules! swap_field { ($field1:expr, $field2:expr, $size:ident) => { for i in 0..$size { swap(&mut $field1[i], &mut $field2[i]) } }; } // payload after header and 'get ' #[inline(always)] fn hash_key( obj: &xdp, ctx: &mut xdp_md, pctx: &mut parsing_context, payload_index: usize, stats: &mut bmc_stats, ) -> Result { let payload = &ctx.data_slice[payload_index..]; let mut done_parsing = false; while !done_parsing { let key = obj .bpf_map_lookup_elem(&map_keys, &pctx.key_count) .ok_or(0i32)?; key.hash = FNV_OFFSET_BASIS_32; let payload = &payload[..(BMC_MAX_KEY_LENGTH + 1) .min(ctx.data_length() - pctx.read_pkt_offset as usize)]; let key_len = payload .iter() .take_while(|&&byte| byte != b'\r' && byte != b' ') .inspect(|&&byte| { hash_func!(key.hash, byte); }) .count(); // Returns the number of elements processed, effectively the key length done_parsing = payload[key_len] == b'\r'; // no key found if key_len == 0 || key_len > BMC_MAX_KEY_LENGTH { return Ok(XDP_PASS as i32); } // get the cache entry let cache_idx: u32 = key.hash % BMC_CACHE_ENTRY_COUNT; let entry = obj .bpf_map_lookup_elem(&map_kcache, &cache_idx) .ok_or(0i32)?; let entry_valid; { let _guard = rex_spinlock_guard::new(&mut entry.lock); entry_valid = entry.valid == 1 && entry.hash == key.hash } // potential cache hit if entry_valid { key.data[0..key_len].clone_from_slice(&payload[0..key_len]); key.len = key_len; pctx.key_count += 1; } else { // cache miss stats.miss_count += 1; } if done_parsing && pctx.key_count > 0 { { let eth_header: &mut ethhdr = &mut obj.eth_header(ctx); // exchange src and dst ip and mac swap_field!(eth_header.h_dest, eth_header.h_source, ETH_ALEN); } { let mut ip_header_mut = obj.ip_header(ctx); let temp: u32 = *ip_header_mut.saddr(); *ip_header_mut.saddr() = *ip_header_mut.daddr(); *ip_header_mut.daddr() = temp; } { let udp_header: &mut udphdr = &mut obj.udp_header(ctx); swap(&mut udp_header.source, &mut udp_header.dest); } return write_pkt_reply(obj, ctx, payload_index, pctx, stats); } // process more keys pctx.read_pkt_offset += key_len as u8 + 1; } Ok(XDP_PASS as i32) } // payload after headers and 'get ' #[inline(always)] fn write_pkt_reply( obj: &xdp, ctx: &mut xdp_md, payload_index: usize, pctx: &mut parsing_context, stats: &mut bmc_stats, ) -> Result { let key = obj .bpf_map_lookup_elem(&map_keys, &pctx.current_key) .ok_or(XDP_PASS as i32)?; let (mut cache_hit, _written) = (false, 0u32); let cache_idx = key.hash % BMC_CACHE_ENTRY_COUNT; let entry = obj .bpf_map_lookup_elem(&map_kcache, &cache_idx) .ok_or(XDP_DROP as i32)?; let _guard = rex_spinlock_guard::new(&mut entry.lock); if entry.valid == 1 && entry.hash == key.hash { if key.len >= BMC_MAX_KEY_LENGTH { cache_hit = false; } else { let entry_data_key = &entry.data[6..6 + key.len]; cache_hit = key .data .iter() .zip(entry_data_key.iter()) .all(|(a, b)| a == b); if !cache_hit { stats.hit_misprediction += 1; } } } // copy cache data if cache_hit { let _off = 0usize; let stats = obj.bpf_map_lookup_elem(&map_stats, &0).ok_or(0i32)?; stats.hit_count += 1; // NOTE: data end is determined by slice length limit, may changed in // future while off + U64_SIZE < BMC_MAX_CACHE_DATA_SIZE && off // + U64_SIZE <= entry.len as usize {} let padding = (entry.len as i32 - (ctx.data_length() - payload_index) as i32) + 1; match obj.bpf_xdp_adjust_tail(ctx, padding) { Ok(_) => {} Err(_) => { rex_printk!("adjust tail failed\n")?; return Ok(XDP_DROP as i32); } } // INFO: currently only support single key { // udp check not required let mut ip_header_mut = obj.ip_header(ctx); ip_header_mut.tot_len = (u16::from_be(ip_header_mut.tot_len) + padding as u16).to_be(); ip_header_mut.check = compute_ip_checksum(&mut ip_header_mut); } { let mut udp_header = obj.udp_header(ctx); udp_header.len = (u16::from_be(udp_header.len) + padding as u16).to_be(); udp_header.check = 0; } let payload = &mut ctx.data_slice[payload_index - 4..]; payload[0..entry.len as usize] .clone_from_slice(&entry.data[0..entry.len as usize]); let end = b"END\r\n"; for i in entry.len as usize..(entry.len + 5) as usize { payload[i] = end[i - entry.len as usize]; } } else { stats.miss_count += 1; } Ok(XDP_TX as i32) } #[inline(always)] fn bmc_invalidate_cache(obj: &xdp, ctx: &mut xdp_md) -> Result { let header_len = size_of::() + size_of::() + size_of::(); let tcp_header = obj.tcp_header(ctx); let port = u16::from_be(tcp_header.dest); drop(tcp_header); // start after the tcp header let payload = &ctx.data_slice[header_len..]; // check if using the memcached port // check if the payload has enough space for a memcached request if port != MEMCACHED_PORT || payload.len() < 4 { return Ok(XDP_PASS as i32); } // get the index for the set command in the payload let set_iter = payload .windows(4) .enumerate() .filter_map(|(i, v)| if v == b"set " { Some(i) } else { None }); // iterate through the possible set commands for index in set_iter { let stats = obj.bpf_map_lookup_elem(&map_stats, &0).ok_or(0i32)?; stats.set_recv_count += 1; let mut hash = FNV_OFFSET_BASIS_32; let payload = &payload[index + 4..]; // limit the size of key // hash the key until the first space payload.iter().take_while(|&&c| c != b' ').for_each(|&c| { hash_func!(hash, c); }); // get the cache entry let cache_idx: u32 = hash % BMC_CACHE_ENTRY_COUNT; let entry = obj .bpf_map_lookup_elem(&map_kcache, &cache_idx) .ok_or(0i32)?; if entry.valid == 1 { stats.invalidation_count += 1; let _guard = rex_spinlock_guard::new(&mut entry.lock); entry.valid = 0; } } Ok(XDP_PASS as i32) } #[rex_xdp] fn xdp_rx_filter(obj: &xdp, ctx: &mut xdp_md) -> Result { let iphdr = obj.ip_header(ctx); let protocol = iphdr.protocol; drop(iphdr); match u8::from_be(protocol) as u32 { IPPROTO_TCP => { return bmc_invalidate_cache(obj, ctx); } IPPROTO_UDP => { let header_len = size_of::() + size_of::() + size_of::() + size_of::(); let udp_header = obj.udp_header(ctx); let port = u16::from_be(udp_header.dest); drop(udp_header); let payload = &ctx.data_slice[header_len..]; // check if using the memcached port // check if the payload has enough space for a memcached request if port != MEMCACHED_PORT || payload.len() < 4 { return Ok(XDP_PASS as i32); } // check if a get command if !payload.starts_with(b"get ") { return Ok(XDP_PASS as i32); } let stats = obj .bpf_map_lookup_elem(&map_stats, &0) .ok_or(XDP_PASS as i32)?; stats.get_recv_count += 1; let mut off = 4; // move offset to the start of the first key while off < BMC_MAX_PACKET_LENGTH && off + 1 < payload.len() && payload[off] == b' ' { off += 1; } off += header_len; let mut pctx = parsing_context { key_count: 0, current_key: 0, read_pkt_offset: off as u8, }; // TODO: not sure if there is a better way return hash_key(obj, ctx, &mut pctx, off, stats); } _ => {} }; Ok(XDP_PASS as i32) } // payload after all headers #[inline(always)] fn bmc_update_cache( obj: &sched_cls, skb: &__sk_buff, payload: &[u8], header_len: usize, stats: &mut bmc_stats, ) -> Result { let mut hash = FNV_OFFSET_BASIS_32; let mut off = 6usize; while off < BMC_MAX_KEY_LENGTH && header_len + off < skb.len() as usize && payload[off] != b' ' { hash_func!(hash, payload[off]); off += 1; } let cache_idx: u32 = hash % BMC_CACHE_ENTRY_COUNT; let entry = obj // return TC_ACT_OK if the cache is not found or map error .bpf_map_lookup_elem(&map_kcache, &cache_idx) .ok_or(TC_ACT_OK as i32)?; let _guard = rex_spinlock_guard::new(&mut entry.lock); // check if the cache is up-to-date if entry.valid == 1 && entry.hash == hash { let mut diff = 0; off = 6; while off < BMC_MAX_KEY_LENGTH && header_len + off < payload.len() && (payload[off] != b' ' || entry.data[off] != b' ') { if entry.data[off] != payload[off] { diff = 1; break; } off += 1; } // cache is up-to-date, no need to update if diff == 0 { return Ok(TC_ACT_OK as i32); } } // cache is not up-to-date, update it entry.len = 0; let mut count = 0; for (i, &payload_data) in payload.iter().enumerate().take(BMC_MAX_CACHE_DATA_SIZE) { if header_len + i >= skb.len() as usize || count >= 2 { break; } entry.data[i] = payload_data; entry.len += 1; if payload_data == b'\n' { count += 1; } } // finished copying if count == 2 { entry.valid = 1; entry.hash = hash; stats.update_count += 1; } Ok(TC_ACT_OK as i32) } #[rex_tc] fn xdp_tx_filter(obj: &sched_cls, skb: &mut __sk_buff) -> Result { let header_len = size_of::() + size_of::() + size_of::() + size_of::(); if skb.len() as usize <= header_len || u8::from_be(obj.ip_header(skb).protocol) as u32 != IPPROTO_UDP || u16::from_be(obj.udp_header(skb).source) != MEMCACHED_PORT || skb.data_slice.len() < header_len + 6 || !skb.data_slice[header_len..].starts_with(b"VALUE ") { return Ok(TC_ACT_OK as i32); } let stats = obj.bpf_map_lookup_elem(&map_stats, &0).ok_or(0i32)?; stats.get_resp_count += 1; // update cache map based on the packet let payload = &skb.data_slice[header_len..]; bmc_update_cache(obj, skb, payload, header_len, stats)?; Ok(TC_ACT_OK as i32) } ================================================ FILE: samples/electrode/.cargo/config.toml ================================================ [build] target = "x86_64-unknown-none" [target.x86_64-unknown-none] linker = "ld.mold" rustflags = [ "-Zthreads=8", "-Cforce-frame-pointers=y", "-Csymbol-mangling-version=v0", "-Ccodegen-units=1", "-Crelocation-model=pie", "-Crelro-level=full", ] [unstable] build-std = ["core"] ================================================ FILE: samples/electrode/Cargo.toml ================================================ [package] name = "electrode" version = "0.1.0" edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [features] fast_reply = [] fast_quorum_prune = [] default = [] [dependencies] [dependencies.rex] path = "../../rex" [lints.clippy] disallowed_methods = "forbid" disallowed_types = "forbid" [lints.rust] incomplete_features = "forbid" internal_features = "forbid" unsafe_code = "forbid" unstable_features = "forbid" [profile.dev] panic = "abort" debug = false [profile.release] panic = "abort" debug = false lto = true ================================================ FILE: samples/electrode/clippy.toml ================================================ disallowed-methods = [ "core::mem::forget", ] disallowed-types = [ "core::mem::ManuallyDrop", ] ================================================ FILE: samples/electrode/config.txt ================================================ f 1 replica 10.10.1.1:12345 replica 10.10.1.2:12345 replica 10.10.1.3:12345 ================================================ FILE: samples/electrode/entry.c ================================================ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "fast_common.h" #include #define BPF_SYSFS_ROOT "/sys/fs/bpf" #define EXE "./target/x86_64-unknown-none/release/electrode" struct bpf_progs_desc { char name[256]; enum bpf_prog_type type; unsigned char pin; int map_prog_idx; struct bpf_program *prog; }; struct bpf_object *obj; struct bpf_object_load_attr *load_attr; struct bpf_program *rx_prog, *tx_prog; static int err; static int xdp_main_prog_fd; static char filename[PATH_MAX]; static char prog_name[PATH_MAX]; static char commandname[PATH_MAX]; static __u32 xdp_flags = 0; static int *interfaces_idx; struct rlimit r = { RLIM_INFINITY, RLIM_INFINITY }; static int map_paxos_ctr_state_fd; static int map_prepare_buffer_fd, map_configure_fd, map_request_buffer_fd; static int interface_count = 0; static int nr_cpus = 0; // define our eBPF program. static struct bpf_progs_desc progs[] = { { "fast_paxos_main", BPF_PROG_TYPE_XDP, 0, -1, NULL }, { "fast_broad_cast_main", BPF_PROG_TYPE_SCHED_CLS, 1, -1, NULL }, }; static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args) { if (level == LIBBPF_DEBUG || level == LIBBPF_INFO) return vfprintf(stderr, format, args); return 0; } static void read_config(void) { map_configure_fd = bpf_object__find_map_fd_by_name(obj, "map_configure"); if (map_configure_fd < 0) { fprintf(stderr, "Error: bpf_object__find_map_fd_by_name map_configure failed\n"); exit(1); // return 1; } FILE *fp; char buff[255]; int f = 0; struct sockaddr_in sa; char str[INET_ADDRSTRLEN]; struct paxos_configure conf; const char *eths[FAST_REPLICA_MAX] = { "9c:dc:71:56:8f:45", "9c:dc:71:56:bf:45", "9c:dc:71:5e:2f:51", "", "" }; fp = fopen("./config.txt", "r"); if (fp == NULL) { fprintf(stderr, "Error: failed to open config.txt\n"); exit(1); } (void)fscanf(fp, "%s", buff); // must be 'f' (void)fscanf(fp, "%d", &f); for (int i = 0; i < 2 * f + 1; ++i) { (void)fscanf(fp, "%s", buff); // must be 'replica' (void)fscanf(fp, "%s", buff); char *ipv4 = strtok(buff, ":"); assert(ipv4 != NULL); char *port = strtok(NULL, ":"); // store this IP address in sa: inet_pton(AF_INET, ipv4, &(sa.sin_addr)); // now get it back and print it inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN); conf.port = htons(atoi(port)); conf.addr = sa.sin_addr.s_addr; sscanf(eths[i], "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &conf.eth[0], &conf.eth[1], &conf.eth[2], &conf.eth[3], &conf.eth[4], &conf.eth[5]); err = bpf_map_update_elem(map_configure_fd, &i, &conf, 0); } fclose(fp); return; } static void create_object(void) { map_prepare_buffer_fd = bpf_object__find_map_fd_by_name(obj, "map_prepare_buffer"); if (map_prepare_buffer_fd < 0) { fprintf(stderr, "Error: bpf_object__find_map_fd_by_name map_prepare_buffer failed\n"); exit(1); // return 1; } map_request_buffer_fd = bpf_object__find_map_fd_by_name(obj, "map_request_buffer"); if (map_request_buffer_fd < 0) { fprintf(stderr, "Error: bpf_object__find_map_fd_by_name map_request_buffer failed\n"); exit(1); // return 1; } map_paxos_ctr_state_fd = bpf_object__find_map_fd_by_name(obj, "map_ctr_state"); if (map_paxos_ctr_state_fd < 0) { fprintf(stderr, "Error: bpf_object__find_map_fd_by_name map_ctr_state failed\n"); exit(1); // return 1; } } static void add_interrupt(void) { /* asd123www: !!!!!! the user-space program shouldn't quit here. Otherwise the program will be lost, due to fd lost??? */ sigset_t signal_mask; sigemptyset(&signal_mask); sigaddset(&signal_mask, SIGINT); sigaddset(&signal_mask, SIGTERM); sigaddset(&signal_mask, SIGUSR1); int sig, quit = 0; // FILE *fp = NULL; err = sigprocmask(SIG_BLOCK, &signal_mask, NULL); if (err != 0) { fprintf(stderr, "Error: Failed to set signal mask\n"); exit(EXIT_FAILURE); } while (!quit) { err = sigwait(&signal_mask, &sig); if (err != 0) { fprintf(stderr, "Error: Failed to wait for signal\n"); exit(EXIT_FAILURE); } switch (sig) { case SIGINT: case SIGTERM: quit = 1; break; default: fprintf(stderr, "Unknown signal\n"); break; } } return; } int main(int argc, char *argv[]) { int ret = 0; libbpf_set_print(libbpf_print_fn); rex_set_debug(1); // enable debug info obj = rex_obj_get_bpf(rex_obj_load(EXE)); if (!obj) { fprintf(stderr, "Object could not be opened\n"); return 1; } interface_count = argc - optind; if (interface_count <= 0) { fprintf(stderr, "Missing at least one required interface index\n"); return 1; } interfaces_idx = calloc(sizeof(int), interface_count); if (interfaces_idx == NULL) { fprintf(stderr, "Error: failed to allocate memory\n"); return 1; } for (int i = 0; i < interface_count && optind < argc; optind++, i++) interfaces_idx[i] = atoi(argv[optind]); nr_cpus = libbpf_num_possible_cpus(); if (setrlimit(RLIMIT_MEMLOCK, &r)) { perror("setrlimit failed"); return 1; } create_object(); read_config(); assert(bpf_obj_pin(map_prepare_buffer_fd, "/sys/fs/bpf/paxos_prepare_buffer") == 0); assert(bpf_obj_pin(map_request_buffer_fd, "/sys/fs/bpf/paxos_request_buffer") == 0); assert(bpf_obj_pin(map_paxos_ctr_state_fd, "/sys/fs/bpf/paxos_ctr_state") == 0); rx_prog = bpf_object__find_program_by_name(obj, progs[0].name); if (!rx_prog) { fprintf(stderr, "start not found\n"); exit(1); } xdp_main_prog_fd = bpf_program__fd(rx_prog); if (xdp_main_prog_fd < 0) { fprintf(stderr, "Error: bpf_program__fd failed\n"); return 1; } xdp_flags |= XDP_FLAGS_DRV_MODE; /* xdp_flags |= XDP_FLAGS_SKB_MODE; */ for (int i = 0; i < interface_count; i++) { if (bpf_xdp_attach(interfaces_idx[i], xdp_main_prog_fd, xdp_flags, NULL) < 0) { fprintf(stderr, "Error: bpf_set_link_xdp_fd failed for interface %d\n", interfaces_idx[i]); return 1; } else { printf("Main BPF program attached to XDP on interface %d\n", interfaces_idx[i]); } } tx_prog = bpf_object__find_program_by_name(obj, progs[1].name); if (!tx_prog) { fprintf(stderr, "tx_prog not found\n"); exit(1); } printf("tx_prog: %s\n", bpf_program__name(tx_prog)); int len = snprintf(filename, PATH_MAX, "%s/%s", BPF_SYSFS_ROOT, progs[1].name); if (len < 0) { fprintf(stderr, "Error: Program name '%s' is invalid\n", "xdp_tx_filter"); return -1; } else if (len >= PATH_MAX) { fprintf(stderr, "Error: Program name '%s' is too long\n", progs[1].name); return -1; } // pin sched_cls ret = bpf_program__pin(tx_prog, filename); if (ret != 0) { fprintf(stderr, "Error: Failed to pin program '%s' to path %s with error code %d\n", prog_name, filename, ret); return ret; } for (int i = 0; i < interface_count && optind < argc; i++) { snprintf(commandname, PATH_MAX, "tc qdisc add dev %s clsact", argv[optind + i]); assert(system(commandname) == 0); snprintf(commandname, PATH_MAX, "tc filter add dev %s egress bpf object-pinned " "/sys/fs/bpf/FastBroadCast", argv[optind + i]); assert(system(commandname) == 0); printf("Main BPF program attached to TC on interface %d\n", interfaces_idx[i]); } add_interrupt(); assert(remove("/sys/fs/bpf/paxos_prepare_buffer") == 0); assert(remove("/sys/fs/bpf/paxos_request_buffer") == 0); assert(remove("/sys/fs/bpf/paxos_ctr_state") == 0); for (int i = 0; i < interface_count; i++) bpf_xdp_attach(interfaces_idx[i], -1, xdp_flags, NULL); for (int i = 0; i < interface_count && optind < argc; i++) { snprintf(commandname, PATH_MAX, "tc filter del dev %s egress", argv[optind + i]); assert(system(commandname) == 0); snprintf(commandname, PATH_MAX, "tc qdisc del dev %s clsact", argv[optind + i]); assert(system(commandname) == 0); } assert(remove("/sys/fs/bpf/fast_broad_cast_main") == 0); printf("\nasd123www: quit safely!\n"); return 0; } ================================================ FILE: samples/electrode/fast_common.h ================================================ /* * Software Name : fast-paxos * SPDX-FileCopyrightText: Copyright (c) 2022 Orange * SPDX-License-Identifier: LGPL-2.1-only * * This software is distributed under the * GNU Lesser General Public License v2.1 only. * * Author: asd123www et al. */ #ifndef _FAST_COMMON_H #define _FAST_COMMON_H #define ETH_ALEN 6 /* Octets in one ethernet addr */ #define CLUSTER_SIZE 3 // need #define FAST_REPLICA_MAX 100 // max # of replicas. #define NONFRAG_MAGIC 0x20050318 #define FRAG_MAGIC 0x20101010 #define MAGIC_LEN 4 #define REQUEST_TYPE_LEN 33 #define PREPARE_TYPE_LEN 33 #define PREPAREOK_TYPE_LEN 35 #define MYPREPAREOK_TYPE_LEN 24 #define FAST_PAXOS_DATA_LEN 12 #define BROADCAST_SIGN_BIT (1 << 31) #define QUORUM_SIZE ((CLUSTER_SIZE + 1) >> 1) #define QUORUM_BITSET_ENTRY 1024 // must be 2^t enum ReplicaStatus { STATUS_NORMAL, STATUS_VIEW_CHANGE, STATUS_RECOVERING }; enum { FAST_PROG_XDP_HANDLE_PREPARE = 0, FAST_PROG_XDP_HANDLE_REQUEST, FAST_PROG_XDP_HANDLE_PREPAREOK, FAST_PROG_XDP_WRITE_BUFFER, FAST_PROG_XDP_PREPARE_REPLY, FAST_PROG_XDP_MAX }; enum { FAST_PROG_TC_BROADCAST = 0, FAST_PROG_TC_MAX }; struct paxos_configure { __u32 addr; // ipv4. __u16 port; char eth[ETH_ALEN]; }; #endif ================================================ FILE: samples/electrode/meson.build ================================================ build_dir = run_command( realpath, '--relative-to', meson.current_source_dir(), meson.current_build_dir(), capture: true, check: true ).stdout().strip() env = environment() env.prepend('PATH', rust_bin) env.set('LINUX_OBJ', kbuild_dir) env.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux')) env.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target')) sample_clippy = custom_target( 'electrode-clippy', output: ['target'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'clippy', '-qr' ], env: env, console: false, build_by_default: true ) electrode_config = custom_target( 'config.txt', input: 'config.txt', output: ['config.txt'], command: ['cp', '@INPUT@', '@OUTPUT@'], env: env, console: false, build_by_default: true ) sample_build = custom_target( 'electrode-build', output: ['electrode'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'rustc', '-qr', '--', '-Cenable_rex' ], depends: [sample_clippy, electrode_config], env: env, console: false, build_by_default: true ) executable( 'entry', 'entry.c', build_by_default: true, dependencies: [librex_dep, libbpf_dep, kernel_dep], pie: true ) ================================================ FILE: samples/electrode/rustfmt.toml ================================================ max_width = 80 binop_separator = "Back" reorder_impl_items = true wrap_comments = true imports_granularity = "Module" group_imports = "StdExternalCrate" ================================================ FILE: samples/electrode/src/common.rs ================================================ #![allow(unused)] // // Software Name : fast-paxos // SPDX-FileCopyrightText: Copyright (c) 2022 Orange // SPDX-License-Identifier: LGPL-2.1-only // // This software is distributed under the // GNU Lesser General Public License v2.1 only. // // Author: asd123www et al. // Author: Ruowen Qin et al. // pub(crate) const ETH_ALEN: usize = 6; // Octets in one ethernet addr pub(crate) const MTU: u64 = 1500; pub(crate) const MAX_DATA_LEN: usize = 64; pub(crate) const CLUSTER_SIZE: u8 = 3; pub(crate) const FAST_REPLICA_MAX: u32 = 100; // max # of replicas. pub(crate) const NONFRAG_MAGIC: u32 = 0x20050318; pub(crate) const FRAG_MAGIC: u32 = 0x20101010; pub(crate) const MAGIC_LEN: usize = 4; pub(crate) const REQUEST_TYPE_LEN: usize = 33; pub(crate) const PREPARE_TYPE_LEN: usize = 33; pub(crate) const PREPAREOK_TYPE_LEN: usize = 35; pub(crate) const MYPREPAREOK_TYPE_LEN: usize = 24; pub(crate) const FAST_PAXOS_DATA_LEN: usize = 12; pub(crate) const BROADCAST_SIGN_BIT: u32 = 1 << 31; pub(crate) const QUORUM_SIZE: u32 = (CLUSTER_SIZE as u32 + 1) >> 1; pub(crate) const QUORUM_BITSET_ENTRY: u32 = 1024; // must be 2^t pub(crate) const PAXOS_PORT: u16 = 12345; pub(crate) const MAGIC_BITS: [u8; MAGIC_LEN] = [0x18, 0x03, 0x05, 0x20]; #[derive(Debug, PartialEq, Eq, Clone, Copy)] #[repr(C)] pub(crate) enum ReplicaStatus { STATUS_NORMAL = 0, STATUS_VIEW_CHANGE, STATUS_RECOVERING, } #[derive(Debug, PartialEq, Eq)] #[repr(C)] pub(crate) enum FastProgXdp { FAILED = -1, FAST_PROG_XDP_HANDLE_PREPARE = 0, FAST_PROG_XDP_HANDLE_REQUEST, FAST_PROG_XDP_HANDLE_PREPAREOK, FAST_PROG_XDP_WRITE_BUFFER, FAST_PROG_XDP_PREPARE_REPLY, FAST_PROG_XDP_MAX, } #[derive(Debug, PartialEq, Eq)] #[repr(C)] pub(crate) enum FastProgTc { FAST_PROG_TC_BROADCAST = 0, FAST_PROG_TC_MAX, } #[repr(C)] #[derive(Clone, Copy)] pub(crate) struct PaxosConfigure { pub(crate) addr: u32, // ipv4. pub(crate) port: u16, pub(crate) eth: [u8; ETH_ALEN], } ================================================ FILE: samples/electrode/src/main.rs ================================================ #![no_std] #![no_main] #![allow(non_camel_case_types)] #![allow(non_snake_case)] extern crate rex; use core::mem::{size_of, swap}; use rex::sched_cls::*; use rex::utils::*; use rex::xdp::*; use rex::{read_field, rex_printk, rex_tc, rex_xdp}; pub mod common; pub mod maps; use common::*; use maps::*; macro_rules! swap_field { ($field1:expr, $field2:expr, $size:ident) => { for i in 0..$size { swap(&mut $field1[i], &mut $field2[i]) } }; } // NOTE: function calls are not allowed while holding a lock.... // Cause Paxos is in fact a serialized protocol, we limit our to one-core, then // no lock is needed. #[rex_xdp] fn fast_paxos_main(obj: &xdp, ctx: &mut xdp_md) -> Result { let header_len = size_of::() + size_of::() + size_of::(); let iphdr_base = size_of::(); let iphdr_end = iphdr_base + size_of::(); match u8::from_be(read_field!( ctx.data_slice, iphdr_base, iphdr, protocol, u8 )) as u32 { IPPROTO_TCP => { // NOTE: currently we only take care of UDP memcached } IPPROTO_UDP => { let port = u16::from_be(read_field!( ctx.data_slice, iphdr_end, udphdr, dest, u16 )); let payload = &mut ctx.data_slice[header_len..]; // port check, our process bound to 12345. // don't have magic bits... if port != PAXOS_PORT || payload.len() < MAGIC_LEN + size_of::() || !payload.starts_with(&MAGIC_BITS) { return Ok(XDP_PASS as i32); } // check the message type return handle_udp_fast_paxos(obj, ctx); } _ => {} }; Ok(XDP_PASS as i32) } #[rex_tc] fn fast_broad_cast_main(obj: &sched_cls, skb: &mut __sk_buff) -> Result { let header_len = size_of::() + size_of::() + size_of::(); let iphdr_base = size_of::(); let iphdr_end = iphdr_base + size_of::(); // check if the packet is long enough if skb.data_slice.len() <= header_len { return Ok(TC_ACT_OK as i32); } if u8::from_be(read_field!(skb.data_slice, iphdr_base, iphdr, protocol, u8)) as u32 == IPPROTO_UDP { let port = u16::from_be(read_field!( skb.data_slice, iphdr_end, udphdr, dest, u16 )); let payload = &skb.data_slice[header_len..]; // check for the magic bits and Paxos port // only port 12345 is allowed if port != PAXOS_PORT || payload.len() < MAGIC_LEN + size_of::() || !payload.starts_with(&MAGIC_BITS) { return Ok(TC_ACT_OK as i32); } return handle_udp_fast_broad_cast(obj, skb); } Ok(TC_ACT_OK as i32) } #[inline(always)] fn handle_udp_fast_broad_cast(obj: &sched_cls, skb: &mut __sk_buff) -> Result { let header_len = size_of::() + size_of::() + size_of::() + MAGIC_LEN; let payload = &skb.data_slice[header_len..]; let (type_len_bytes, payload) = payload.split_at(size_of::()); let type_str_len = header_len + size_of::(); let type_len = u64::from_ne_bytes(type_len_bytes.try_into().unwrap()); let len = payload.len(); if type_len >= MTU || len < type_len as usize || len < 5 { rex_printk!("too small type_len: {}\n", type_len).ok(); return Ok(TC_ACT_SHOT as i32); } rex_printk!("handle_udp_fast_broad_cast\n").ok(); // update payload index let payload = &payload[type_len as usize..]; if payload.len() < FAST_PAXOS_DATA_LEN { return Ok(TC_ACT_SHOT as i32); } let msg_view = u32::from_ne_bytes(payload[0..4].try_into().unwrap()); let is_broadcast = msg_view & BROADCAST_SIGN_BIT; let msg_view = msg_view ^ BROADCAST_SIGN_BIT; let msg_last_op = u32::from_ne_bytes(payload[4..8].try_into().unwrap()); let message_type = compute_message_type(payload); if message_type == FastProgXdp::FAST_PROG_XDP_HANDLE_PREPARE { let idx = msg_last_op & (QUORUM_BITSET_ENTRY - 1); let entry = obj.bpf_map_lookup_elem(&map_quorum, &idx).ok_or(0i32)?; if entry.view != msg_view || entry.opnum != msg_last_op { entry.view = msg_view; entry.opnum = msg_last_op; entry.bitset = 0; } } if is_broadcast == 0 { return Ok(TC_ACT_OK as i32); }; let zero = 0u32; let ctr_state = obj.bpf_map_lookup_elem(&map_ctr_state, &zero).ok_or(0i32)?; let mut id = 0u8; let mut nxt; { let type_str = &mut skb.data_slice[type_str_len..]; if type_str.starts_with(b"sp") { if ctr_state.leader_idx == 0 { id = 1; } nxt = id + 1; if ctr_state.leader_idx == nxt as u32 { nxt += 1; } type_str[0] = nxt; type_str[1] = b'M'; if nxt < CLUSTER_SIZE { obj.bpf_clone_redirect(skb, skb.ifindex(), 0).unwrap(); } } else { id = type_str[0]; nxt = id + 1; if ctr_state.leader_idx == nxt as u32 { nxt += 1; } type_str[0] = nxt; if nxt < CLUSTER_SIZE { obj.bpf_clone_redirect(skb, skb.ifindex(), 0).unwrap(); } } } // our version bpf_clone_redirect will update the data reference. let type_str = &mut skb.data_slice[type_str_len..]; type_str[0] = b's'; type_str[1] = b'p'; let key = id as u32; let replica_info = obj .bpf_map_lookup_elem(&map_configure, &key) .ok_or(TC_ACT_SHOT as i32)?; { let udp_header = &mut obj.udp_header(skb); udp_header.dest = replica_info.port; udp_header.check = 0; } { let ip_header = &mut obj.ip_header(skb); *ip_header.daddr() = replica_info.addr; ip_header.check = compute_ip_checksum(ip_header); } let mut eth_header = obj.eth_header(skb); for i in 0..ETH_ALEN { eth_header.h_dest[i] = replica_info.eth[i]; } Ok(TC_ACT_OK as i32) } #[inline(always)] fn handle_udp_fast_paxos(obj: &xdp, ctx: &mut xdp_md) -> Result { let header_len = size_of::() + size_of::() + size_of::(); let payload = &mut ctx.data_slice[header_len + MAGIC_LEN..]; let type_len_bytes = &payload[..size_of::()]; let type_len = u64::from_ne_bytes(type_len_bytes.try_into().unwrap()); rex_printk!("type_len: {}\n", type_len).ok(); // Check the conditions let len = payload.len(); if type_len >= MTU || len < type_len as usize { rex_printk!("too big type_len: {}\n", type_len).ok(); return Ok(XDP_PASS as i32); } let payload_index = header_len + MAGIC_LEN + size_of::(); let payload = &mut ctx.data_slice[payload_index..]; #[cfg(feature = "fast_reply")] { // PrepareMessage in `vr`. if len > PREPARE_TYPE_LEN && payload[10..12].starts_with(b"vr") && payload[19..27].starts_with(b"PrepareM") { let payload_index = payload_index + PREPARE_TYPE_LEN; return handle_prepare(obj, ctx, payload_index); } } #[cfg(feature = "fast_quorum_prune")] { // PrepareOK message in `vr`. if len > PREPAREOK_TYPE_LEN && payload[10..12].starts_with(b"vr") && payload[19..27].starts_with(b"PrepareO") { return handle_prepare_ok(obj, ctx, payload_index); } if len > MYPREPAREOK_TYPE_LEN && payload[10..12].starts_with(b"vr") && payload[13..17].starts_with(b"MyPr") { return handle_prepare_ok(obj, ctx, payload_index); } } Ok(XDP_PASS as i32) } #[inline(always)] fn compute_message_type(payload: &[u8]) -> FastProgXdp { let len = payload.len(); // if not a valid message, return FAILED if len < 13 || !payload[10..12].starts_with(b"vr") { return FastProgXdp::FAILED; } // check the message type if len > PREPARE_TYPE_LEN && payload[19..27].starts_with(b"PrepareM") { return FastProgXdp::FAST_PROG_XDP_HANDLE_PREPARE; } else if len > REQUEST_TYPE_LEN && payload[19..27].starts_with(b"RequestM") { return FastProgXdp::FAST_PROG_XDP_HANDLE_REQUEST; } else if len > PREPAREOK_TYPE_LEN && payload[19..27].starts_with(b"PrepareO") { return FastProgXdp::FAST_PROG_XDP_HANDLE_PREPAREOK; } else if len > MYPREPAREOK_TYPE_LEN && payload[13..17].starts_with(b"MyPr") { return FastProgXdp::FAST_PROG_XDP_HANDLE_PREPAREOK; } FastProgXdp::FAILED } // This function is ignored in the original implementation. // #[inline(always)] // fn handle_request(_obj: &xdp, _ctx: &mut xdp_md) -> Result { // Ok(XDP_PASS as i32) // } #[inline(always)] fn handle_prepare(obj: &xdp, ctx: &mut xdp_md, payload_index: usize) -> Result { // payload_index = header_len + MAGIC_LEN + size_of::() + // PREPARE_TYPE_LEN point to extra data let payload = &mut ctx.data_slice[payload_index..]; // check the message len if payload.len() < FAST_PAXOS_DATA_LEN { return Ok(XDP_PASS as i32); } // NOTE: may update to struct later let msg_view = u32::from_ne_bytes(payload[0..4].try_into().unwrap()) as u64; let msg_last_op = u32::from_ne_bytes(payload[4..8].try_into().unwrap()) as u64; let msg_batch_start = u32::from_ne_bytes(payload[8..12].try_into().unwrap()) as u64; let zero = 0u32; let ctr_state = obj.bpf_map_lookup_elem(&map_ctr_state, &zero).ok_or(0i32)?; rex_printk!("handle_prepare\n").ok(); // rare case, not handled properly now. if ctr_state.state != ReplicaStatus::STATUS_NORMAL { return Ok(XDP_DROP as i32); } if msg_view < ctr_state.view { return Ok(XDP_DROP as i32); } if msg_view > ctr_state.view { return Ok(XDP_PASS as i32); } // Resend the prepareOK message if msg_last_op <= ctr_state.last_op { return prepare_fast_reply(obj, ctx, payload_index); } // rare case, to user-space. if msg_batch_start > ctr_state.last_op + 1 { return Ok(XDP_PASS as i32); } ctr_state.last_op = msg_last_op; write_buffer(obj, ctx, payload_index) } #[inline(always)] fn write_buffer(obj: &xdp, ctx: &mut xdp_md, payload_index: usize) -> Result { // payload_index = header_len + MAGIC_LEN + size_of::() + // PREPARE_TYPE_LEN check the end of the payload if ctx.data_slice.len() < payload_index + FAST_PAXOS_DATA_LEN { return Ok(XDP_PASS as i32); } rex_printk!("write buffer\n").ok(); let payload = &mut ctx.data_slice[payload_index + FAST_PAXOS_DATA_LEN..]; if payload.len() < MAX_DATA_LEN { return Ok(XDP_PASS as i32); } // buffer not enough, offload to user-space. // It's easy to avoid cause VR sends `CommitMessage` make followers keep up // with the leader. let mut pt = map_prepare_buffer.reserve(MAX_DATA_LEN).ok_or(0i32)?; pt.copy_from_slice(&payload[0..MAX_DATA_LEN]); pt.submit(0); // guaranteed to succeed. prepare_fast_reply(obj, ctx, payload_index) } #[inline(always)] fn prepare_fast_reply( obj: &xdp, ctx: &mut xdp_md, payload_index: usize, ) -> Result { let mut payload = &mut ctx.data_slice[payload_index..]; if payload.len() <= FAST_PAXOS_DATA_LEN + size_of::() { return Ok(XDP_PASS as i32); } rex_printk!("prepare_fast_reply\n").ok(); // read our state // may update to function parameter later let zero = 0u32; let ctr_state = obj.bpf_map_lookup_elem(&map_ctr_state, &zero).ok_or(0i32)?; // struct paxos_configure *leaderInfo = // bpf_map_lookup_elem(&map_configure, &ctr_state->leaderIdx); let leader_info = obj .bpf_map_lookup_elem(&map_configure, &ctr_state.leader_idx) .ok_or(0i32)?; // Write NONFRAG_MAGIC to the start of the payload // FIX: need to check to_ne_bytes or to_be_bytes payload[0..4].copy_from_slice(&NONFRAG_MAGIC.to_ne_bytes()); payload = &mut payload[4..]; // Write MYPREPAREOK_TYPE_LEN to the new start of the payload payload[0..8].copy_from_slice(&MYPREPAREOK_TYPE_LEN.to_ne_bytes()); payload = &mut payload[8..]; // change "specpaxos.vr.proto.PrepareMessage" to "specpaxos.vr.MyPrepareOK" let replacement: &[u8] = b"MyPrepareOK"; for (i, &byte) in replacement.iter().enumerate() { payload[13 + i] = byte; } // Move the slice start by MYPREPAREOK_TYPE_LEN payload = &mut payload[MYPREPAREOK_TYPE_LEN..]; // Write the view number, last_op and my_idx to the payload payload[0..4].copy_from_slice(&(ctr_state.view as u32).to_ne_bytes()); payload[4..8].copy_from_slice(&(payload_index as u32).to_ne_bytes()); payload[8..12].copy_from_slice(&ctr_state.my_idx.to_ne_bytes()); // Move the slice start by FAST_PAXOS_DATA_LEN payload = &mut payload[FAST_PAXOS_DATA_LEN..]; if payload.len() < (size_of::() * 3 + size_of::()) { return Ok(XDP_PASS as i32); } let size = (size_of::() * 2 + size_of::()) as u64; // write the len in the protocal, last_op and my_idx to the payload payload[0..8].copy_from_slice(&size.to_ne_bytes()); payload[8..16].copy_from_slice(&ctr_state.view.to_ne_bytes()); payload[16..24].copy_from_slice(&(payload_index as u64).to_ne_bytes()); // Write ctr_state.my_idx payload[24..28].copy_from_slice(&ctr_state.my_idx.to_ne_bytes()); // move the slice start by size_of::() * 3 + size_of::() let size = (size_of::() * 3 + size_of::()) as u64; payload = &mut payload[size as usize..]; let useless_len = payload.len() as u16; let new_len = ctx.data_length() as u16 - useless_len; { let eth_header: &mut ethhdr = &mut obj.eth_header(ctx); swap_field!(eth_header.h_dest, eth_header.h_source, ETH_ALEN); } { // update the port let udp_header = &mut obj.udp_header(ctx); udp_header.source = udp_header.dest; udp_header.dest = leader_info.port; udp_header.check = 0; udp_header.len = new_len.to_be(); } { let ip_header = &mut obj.ip_header(ctx); ip_header.tot_len = (new_len + size_of::() as u16).to_be(); *ip_header.saddr() = *ip_header.daddr(); *ip_header.daddr() = leader_info.addr; ip_header.check = compute_ip_checksum(ip_header); } // FIX: need to consider the positive offset // but the original code check the length before adjust the tail if obj .bpf_xdp_adjust_tail(ctx, new_len as i32 - ctx.data_length() as i32) .is_err() { rex_printk!("adjust tail failed\n").ok(); return Ok(XDP_DROP as i32); } Ok(XDP_TX as i32) } #[inline(always)] fn handle_prepare_ok( obj: &xdp, ctx: &mut xdp_md, payload_index: usize, ) -> Result { // payload_index = header_len + MAGIC_LEN + size_of::() let payload = &mut ctx.data_slice[payload_index..]; let len = payload.len(); if len <= FAST_PAXOS_DATA_LEN { return Ok(XDP_DROP as i32); } rex_printk!("handle prepareOK\n").ok(); let msg_view = u32::from_ne_bytes(payload[0..4].try_into().unwrap()); let msg_opnum = u32::from_ne_bytes(payload[4..8].try_into().unwrap()); let msg_replica_idx = u32::from_ne_bytes(payload[8..12].try_into().unwrap()); let idx = msg_opnum & (QUORUM_BITSET_ENTRY - 1); let entry = obj.bpf_map_lookup_elem(&map_quorum, &idx).ok_or(0i32)?; if entry.view != msg_view || entry.opnum != msg_opnum { return Ok(XDP_PASS as i32); } entry.bitset |= 1 << msg_replica_idx; if entry.bitset.count_ones() != QUORUM_SIZE - 1 { return Ok(XDP_DROP as i32); } // *context = (void *)payload + typeLen - data; if obj .bpf_xdp_adjust_tail(ctx, -(payload_index as i32)) .is_err() { rex_printk!("adjust tail failed\n").ok(); return Ok(XDP_DROP as i32); } Ok(XDP_PASS as i32) } ================================================ FILE: samples/electrode/src/maps.rs ================================================ use rex::linux::bpf::bpf_spin_lock; use rex::map::*; use rex::rex_map; use crate::common::*; #[repr(C)] #[derive(Clone, Copy)] pub(crate) struct paxos_quorum { pub(crate) view: u32, pub(crate) opnum: u32, pub(crate) bitset: u32, } #[repr(C)] #[derive(Clone, Copy)] pub(crate) struct paxos_ctr_state { pub(crate) state: ReplicaStatus, pub(crate) my_idx: u32, pub(crate) leader_idx: u32, pub(crate) batch_size: u32, pub(crate) view: u64, pub(crate) last_op: u64, } #[repr(C)] #[derive(Clone, Copy)] pub(crate) struct paxos_batch { counter: u32, lock: bpf_spin_lock, } #[rex_map] pub(crate) static map_configure: RexArrayMap = RexArrayMap::new(FAST_REPLICA_MAX, 0); #[rex_map] pub(crate) static map_ctr_state: RexArrayMap = RexArrayMap::new(1, 0); #[rex_map] pub(crate) static map_msg_last_op: RexArrayMap = RexArrayMap::new(1, 0); #[rex_map] pub(crate) static map_quorum: RexArrayMap = RexArrayMap::new(QUORUM_BITSET_ENTRY, 0); #[rex_map] pub(crate) static batch_context: RexArrayMap = RexArrayMap::new(1, 0); #[rex_map] pub(crate) static map_prepare_buffer: RexRingBuf = RexRingBuf::new(1 << 20, 0); #[rex_map] pub(crate) static map_request_buffer: RexRingBuf = RexRingBuf::new(1 << 20, 0); ================================================ FILE: samples/error_injector/.cargo/config.toml ================================================ [build] target = "x86_64-unknown-none" [target.x86_64-unknown-none] linker = "ld.mold" rustflags = [ "-Zthreads=8", "-Cforce-frame-pointers=y", "-Csymbol-mangling-version=v0", "-Ccodegen-units=1", "-Crelocation-model=pie", "-Crelro-level=full", ] [unstable] build-std = ["core"] ================================================ FILE: samples/error_injector/.gitignore ================================================ target userapp ================================================ FILE: samples/error_injector/Cargo.toml ================================================ [package] name = "error_injector" version = "0.1.0" edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] [dependencies.rex] path = "../../rex" [lints.clippy] disallowed_methods = "forbid" disallowed_types = "forbid" [lints.rust] incomplete_features = "forbid" internal_features = "forbid" unsafe_code = "forbid" unstable_features = "forbid" [profile.dev] panic = "abort" debug = false [profile.release] panic = "abort" debug = false lto = true ================================================ FILE: samples/error_injector/clippy.toml ================================================ disallowed-methods = [ "core::mem::forget", ] disallowed-types = [ "core::mem::ManuallyDrop", ] ================================================ FILE: samples/error_injector/loader.c ================================================ #include #include #include #include #include #include #include #define EXE "./target/x86_64-unknown-none/release/error_injector" #define USAGE "./loader \n" int main(int argc, char *argv[]) { struct bpf_object *obj; struct bpf_program *prog; struct bpf_link *link = NULL; struct bpf_map *pid_to_errno; struct rex_obj *rex_obj; unsigned long errno_to_inject; int pid; LIBBPF_OPTS(bpf_ksyscall_opts, opts); if (argc < 3) { fprintf(stderr, USAGE); return 1; } errno_to_inject = -strtoul(argv[2], NULL, 10); rex_obj = rex_obj_load(EXE); if (!rex_obj) { fprintf(stderr, "rex_obj_load failed\n"); return 1; } obj = rex_obj_get_bpf(rex_obj); if (!obj) { fprintf(stderr, "rex_obj_get_bpf failed\n"); return 1; } prog = bpf_object__find_program_by_name(obj, "err_injector"); if (!prog) { fprintf(stderr, "bpf_object__find_program_by_name failed\n"); return 1; } opts.retprobe = 0; link = bpf_program__attach_ksyscall(prog, argv[1], &opts); if (libbpf_get_error(link)) { fprintf(stderr, "ERROR: bpf_program__attach failed\n"); link = NULL; return 1; } pid_to_errno = bpf_object__find_map_by_name(obj, "pid_to_errno"); if (libbpf_get_error(pid_to_errno)) { fprintf(stderr, "ERROR: Could not find map: pid_map\n"); goto cleanup; } pid = fork(); if (pid < 0) { perror("fork"); } else if (!pid) { pid = getpid(); if (bpf_map__update_elem( pid_to_errno, &pid, sizeof(pid), &errno_to_inject, sizeof(errno_to_inject), BPF_ANY) < 0) { fprintf(stderr, "ERROR: updating pid_map failed\n"); } bpf_link__destroy(link); execl("./userapp", "./userapp", NULL); perror("executing userapp failed"); return 1; } wait(NULL); cleanup: bpf_link__destroy(link); return 0; } ================================================ FILE: samples/error_injector/meson.build ================================================ build_dir = run_command( realpath, '--relative-to', meson.current_source_dir(), meson.current_build_dir(), capture: true, check: true ).stdout().strip() env = environment() env.prepend('PATH', rust_bin) env.set('LINUX_OBJ', kbuild_dir) env.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux')) env.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target')) error_injector_clippy = custom_target( 'error_injector-clippy', output: ['target'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'clippy', '-qr' ], env: env, console: false, build_by_default: true ) error_injector_build = custom_target( 'error_injector-build', output: ['error_injector'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'rustc', '-qr', '--', '-Cenable_rex' ], depends: error_injector_clippy, env: env, console: false, build_by_default: true ) error_injector_loader = executable( 'loader', 'loader.c', build_by_default: true, dependencies: [librex_dep, libbpf_dep, kernel_dep], pie: true ) error_injector_userapp = executable( 'userapp', 'userapp.c', build_by_default: true, dependencies: [kernel_dep], pie: true ) sanity_test = custom_target( 'sanity_test', output: ['runtest.py'], input: join_paths(meson.current_source_dir(), 'tests/runtest.py'), command: [ 'cp', '@INPUT@', '@OUTPUT@', ] ) runtest_deps += [error_injector_build, error_injector_loader, error_injector_userapp, sanity_test] sanity_test_env = environment() sanity_test_env.set('SAMPLE_PATH', meson.current_build_dir()) sanity_test_env.set('Q_SCRIPT', join_paths(meson.project_source_root(), 'scripts/q-script/sanity-test-q') ) sanity_test_env.set('KERNEL_PATH', kbuild_dir) test('error_injector', python3_bin, args: [sanity_test_scripts], env: sanity_test_env, depends: runtest_deps, is_parallel: false, workdir: meson.current_build_dir() ) ================================================ FILE: samples/error_injector/src/main.rs ================================================ #![no_std] #![no_main] use rex::kprobe::kprobe; use rex::map::RexHashMap; use rex::pt_regs::PtRegs; use rex::{Result, rex_kprobe, rex_map}; #[allow(non_upper_case_globals)] #[rex_map] static pid_to_errno: RexHashMap = RexHashMap::new(1, 0); #[rex_kprobe] pub fn err_injector(obj: &kprobe, ctx: &mut PtRegs) -> Result { obj.bpf_get_current_task() .map(|t| t.get_pid()) .and_then(|p| obj.bpf_map_lookup_elem(&pid_to_errno, &p).cloned()) .map(|e| obj.bpf_override_return(ctx, e)) .ok_or(0) } ================================================ FILE: samples/error_injector/tests/runtest.py ================================================ #!/usr/bin/env python import re import subprocess from time import sleep process = 0 def count_bpf_programs(): try: # Run bpftool to list all loaded BPF programs result = subprocess.run( "bpftool prog show", capture_output=True, shell=True, text=True, ) # Process the output to count programs if result.stdout: # Each program details start on a new line output = result.stdout.strip().split("\n") programs = [line for line in output if "name" in line] return len(programs) else: return 0 except FileNotFoundError: print("bpftool is not installed or not found in the PATH.") return 0 except Exception as e: print(f"An error occurred: {e}") return 0 def run_loader(): global process process = subprocess.Popen( ["./loader", "dup", "22"], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) def capture_output() -> bool: try: global process sleep(2) process.kill() std_out, std_err = process.communicate(timeout=7) prog_match = re.findall(r"dup: Invalid argument", std_err, re.M) if len(prog_match) == 1: print("Success") return True else: print("Failed") return False except subprocess.CalledProcessError: return False except subprocess.TimeoutExpired: process.kill() return False def main(): old_prog_num = count_bpf_programs() run_loader() count = 0 while old_prog_num == count_bpf_programs(): sleep(1) count += 1 if count == 5: break grade_file = open("auto_grade.txt", "w") if capture_output(): grade_file.write("success") else: grade_file.write("fail") if __name__ == "__main__": main() ================================================ FILE: samples/error_injector/userapp.c ================================================ #define _DEFAULT_SOURCE #include #include #include int main(void) { if (syscall(__NR_dup, 0) < 0) { perror("dup"); } } ================================================ FILE: samples/hello/.cargo/config.toml ================================================ [build] target = "x86_64-unknown-none" [target.x86_64-unknown-none] linker = "ld.mold" rustflags = [ "-Zthreads=8", "-Cforce-frame-pointers=y", "-Csymbol-mangling-version=v0", "-Ccodegen-units=1", "-Crelocation-model=pie", "-Crelro-level=full", ] [unstable] build-std = ["core"] ================================================ FILE: samples/hello/.gitignore ================================================ target ================================================ FILE: samples/hello/Cargo.toml ================================================ [package] name = "hello" version = "0.1.0" edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] [dependencies.rex] path = "../../rex" [lints.clippy] disallowed_methods = "forbid" disallowed_types = "forbid" [lints.rust] incomplete_features = "forbid" internal_features = "forbid" unsafe_code = "forbid" unstable_features = "forbid" [profile.dev] panic = "abort" debug = false [profile.release] panic = "abort" debug = false lto = true ================================================ FILE: samples/hello/clippy.toml ================================================ disallowed-methods = [ "core::mem::forget", ] disallowed-types = [ "core::mem::ManuallyDrop", ] ================================================ FILE: samples/hello/event-trigger.c ================================================ #include #include int main(void) { return syscall(__NR_dup, 1); } ================================================ FILE: samples/hello/loader.c ================================================ #include #include #include #include #include #include #include #include #include #include #define EXE "./target/x86_64-unknown-none/release/hello" int main(void) { int trace_pipe_fd; struct bpf_object *obj; struct bpf_program *prog; struct bpf_link *link = NULL; obj = rex_obj_get_bpf(rex_obj_load(EXE)); if (!obj) { fprintf(stderr, "Object could not be opened\n"); return 1; } prog = bpf_object__find_program_by_name(obj, "rex_prog1"); if (!prog) { fprintf(stderr, "_start not found\n"); return 1; } link = bpf_program__attach(prog); if (libbpf_get_error(link)) { fprintf(stderr, "ERROR: bpf_program__attach failed\n"); link = NULL; return 1; } trace_pipe_fd = openat(AT_FDCWD, "/sys/kernel/debug/tracing/trace_pipe", O_RDONLY); for (;;) { char c; fflush(stdout); if (read(trace_pipe_fd, &c, 1) == 1) putchar(c); } bpf_link__destroy(link); return 0; } ================================================ FILE: samples/hello/meson.build ================================================ build_dir = run_command( realpath, '--relative-to', meson.current_source_dir(), meson.current_build_dir(), capture: true, check: true ).stdout().strip() env = environment() env.prepend('PATH', rust_bin) env.set('LINUX_OBJ', kbuild_dir) env.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux')) env.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target')) hello_clippy = custom_target( 'hello-clippy', output: ['target'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'clippy', '-qr' ], env: env, console: false, build_by_default: true ) hello_build = custom_target( 'hello-build', output: ['hello'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'rustc', '-qr', '--', '-Cenable_rex' ], depends: sample_clippy, env: env, console: false, build_by_default: true ) hello_loader = executable( 'loader', 'loader.c', build_by_default: true, dependencies: [librex_dep, libbpf_dep, kernel_dep], pie: true ) hello_trigger = executable( 'event-trigger', 'event-trigger.c', build_by_default: true, dependencies: [kernel_dep], pie: true ) sanity_test = custom_target( 'sanity_test', output: ['runtest.py'], input: join_paths(meson.current_source_dir(), 'tests/runtest.py'), command: [ 'cp', '@INPUT@', '@OUTPUT@', ] ) runtest_deps += [hello_build, hello_loader, hello_trigger, sanity_test] sanity_test_env = environment() sanity_test_env.set('SAMPLE_PATH', meson.current_build_dir()) sanity_test_env.set('Q_SCRIPT', join_paths(meson.project_source_root(), 'scripts/q-script/sanity-test-q') ) sanity_test_env.set('KERNEL_PATH', kbuild_dir) test('hello_test', python3_bin, args: [sanity_test_scripts], env: sanity_test_env, depends: runtest_deps, is_parallel: false, workdir: meson.current_build_dir() ) ================================================ FILE: samples/hello/rustfmt.toml ================================================ max_width = 80 binop_separator = "Back" reorder_impl_items = true wrap_comments = true imports_granularity = "Module" group_imports = "StdExternalCrate" ================================================ FILE: samples/hello/src/main.rs ================================================ #![no_std] #![no_main] extern crate rex; use rex::tracepoint::*; use rex::{Result, rex_printk, rex_tracepoint}; #[rex_tracepoint] fn rex_prog1( obj: &tracepoint, _: &'static SyscallsEnterDupCtx, ) -> Result { let option_task = obj.bpf_get_current_task(); if let Some(task) = option_task { let cpu = obj.bpf_get_smp_processor_id(); let pid = task.get_pid(); rex_printk!("Rust triggered from PID {} on CPU {}.\n", pid, cpu)?; } Ok(0) } ================================================ FILE: samples/hello/tests/runtest.py ================================================ #!/bin/python import re import subprocess from time import sleep process = 0 def count_bpf_programs(): try: # Run bpftool to list all loaded BPF programs result = subprocess.run( "bpftool prog show", capture_output=True, shell=True, text=True, ) # Process the output to count programs if result.stdout: # Each program details start on a new line output = result.stdout.strip().split("\n") programs = [line for line in output if "name" in line] return len(programs) else: return 0 except FileNotFoundError: print("bpftool is not installed or not found in the PATH.") return 0 except Exception as e: print(f"An error occurred: {e}") return 0 def run_loader(): global process process = subprocess.Popen( ["./loader"], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) def trigger_prog(): try: subprocess.run("./event-trigger", shell=True) except subprocess.CalledProcessError: print("CalledProcessError") def capture_output() -> bool: try: global process trigger_prog() trigger_prog() sleep(2) process.kill() std_out, std_err = process.communicate(timeout=7) re_match = re.findall( r"Rust triggered from PID \d+ on CPU .+", std_out, re.M ) if len(re_match) == 2: print("Success") return True else: print("Failed") return False except subprocess.CalledProcessError: return False except subprocess.TimeoutExpired: process.kill() return False def main(): old_prog_num = count_bpf_programs() run_loader() count = 0 while old_prog_num == count_bpf_programs(): sleep(1) count += 1 if count == 5: break grade_file = open("auto_grade.txt", "w") if capture_output(): grade_file.write("success") else: grade_file.write("fail") if __name__ == "__main__": main() ================================================ FILE: samples/map_bench/.cargo/config.toml ================================================ [build] target = "x86_64-unknown-none" [target.x86_64-unknown-none] linker = "ld.mold" rustflags = [ "-Zthreads=8", "-Cforce-frame-pointers=y", "-Csymbol-mangling-version=v0", "-Ccodegen-units=1", "-Crelocation-model=pie", "-Crelro-level=full", ] [unstable] build-std = ["core"] ================================================ FILE: samples/map_bench/Cargo.toml ================================================ [package] name = "map_bench" version = "0.1.0" edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] [dependencies.rex] path = "../../rex" [lints.clippy] disallowed_methods = "forbid" disallowed_types = "forbid" [lints.rust] incomplete_features = "forbid" internal_features = "forbid" unsafe_code = "forbid" unstable_features = "forbid" [profile.dev] panic = "abort" debug = false [profile.release] panic = "abort" debug = false lto = true ================================================ FILE: samples/map_bench/bench.sh ================================================ #!/usr/bin/env bash if [ "$#" -ne 2 ]; then echo "Usage: $0 " exit 1 fi mkdir output echo 8192 > /sys/kernel/debug/tracing/buffer_size_kb if [[ "$1" == "rex" ]]; then ./event-trigger 6000 1 cat /sys/kernel/debug/tracing/trace | tail -5000 >"./output/rex_${2}.txt" elif [[ "$1" == "bpf" ]]; then ./event-trigger 6000 1 cat /sys/kernel/debug/tracing/trace | tail -5000 >"./output/bpf_${2}.txt" fi # clean buffer echo >/sys/kernel/debug/tracing/trace # unlink rm -rf /sys/fs/bpf/* ================================================ FILE: samples/map_bench/clippy.toml ================================================ disallowed-methods = [ "core::mem::forget", ] disallowed-types = [ "core::mem::ManuallyDrop", ] ================================================ FILE: samples/map_bench/event-trigger.c ================================================ #include #include #include #include #include int main(int argc, char *argv[]) { int nr_rounds, arg, fd; if (argc != 3) asm volatile("ud2"); nr_rounds = atoi(argv[1]); arg = atoi(argv[2]); fd = open("/proc/kprobe_target", O_RDONLY); if (fd < 0) { perror("open"); return 1; } for (int i = 0; i < nr_rounds; i++) ioctl(fd, 1313, arg); close(fd); } ================================================ FILE: samples/map_bench/loader.c ================================================ #include #include #include #include #include #include #include #include #include #include #define EXE "./target/x86_64-unknown-none/release/map_bench" int main(void) { struct bpf_object *obj; struct bpf_program *prog; struct bpf_link *link = NULL; obj = rex_obj_get_bpf(rex_obj_load(EXE)); if (!obj) { fprintf(stderr, "Object could not be opened\n"); return 1; } prog = bpf_object__find_program_by_name(obj, "rex_prog1"); if (!prog) { fprintf(stderr, "Program not found\n"); return 1; } link = bpf_program__attach(prog); if (libbpf_get_error(link)) { fprintf(stderr, "ERROR: bpf_program__attach failed\n"); link = NULL; return 1; } bpf_link__pin(link, "/sys/fs/bpf/link"); bpf_link__destroy(link); return 0; } ================================================ FILE: samples/map_bench/meson.build ================================================ build_dir = run_command( realpath, '--relative-to', meson.current_source_dir(), meson.current_build_dir(), capture: true, check: true ).stdout().strip() env = environment() env.prepend('PATH', rust_bin) env.set('LINUX_OBJ', kbuild_dir) env.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux')) env.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target')) sample_clippy = custom_target( 'map_bench-clippy', output: ['target'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'clippy', '-qr' ], env: env, console: false, build_by_default: true ) sample_build = custom_target( 'map_bench-build', output: ['map_bench'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'rustc', '-qr', '--', '-Cenable_rex' ], depends: sample_clippy, env: env, console: false, build_by_default: true ) executable( 'loader', 'loader.c', build_by_default: true, dependencies: [librex_dep, libbpf_dep, kernel_dep], pie: true ) executable( 'event-trigger', 'event-trigger.c', build_by_default: true, dependencies: [kernel_dep], pie: true ) ================================================ FILE: samples/map_bench/rustfmt.toml ================================================ max_width = 80 binop_separator = "Back" reorder_impl_items = true wrap_comments = true imports_granularity = "Module" group_imports = "StdExternalCrate" ================================================ FILE: samples/map_bench/src/main.rs ================================================ #![no_std] #![no_main] extern crate rex; use rex::kprobe::*; use rex::linux::bpf::*; use rex::map::*; use rex::pt_regs::PtRegs; use rex::{Result, rex_kprobe, rex_map, rex_printk}; #[rex_map] static MAP_HASH: RexHashMap = RexHashMap::new(5000, 0); #[rex_map] static MAP_ARRAY: RexArrayMap = RexArrayMap::new(5000, 0); #[rex_kprobe(function = "kprobe_target_func")] fn rex_prog1(obj: &kprobe, _ctx: &mut PtRegs) -> Result { let zero = 2500u32; let random = obj.bpf_get_prandom_u32() as u64; obj.bpf_map_update_elem(&MAP_HASH, &zero, &random, BPF_ANY as u64)?; let start = obj.bpf_ktime_get_ns(); obj.bpf_map_lookup_elem(&MAP_HASH, &zero); let end = obj.bpf_ktime_get_ns(); rex_printk!("Time elapsed: {}", end - start)?; // let random = obj.bpf_get_prandom_u32() as u64; // obj.bpf_map_update_elem(&MAP_ARRAY, &zero, &random, BPF_ANY as u64)?; // // let start = obj.bpf_ktime_get_ns(); // obj.bpf_map_lookup_elem(&MAP_ARRAY, &zero); // let end = obj.bpf_ktime_get_ns(); // // rex_printk!("Time elapsed: {}", end - start)?; Ok(0) } ================================================ FILE: samples/map_test/.cargo/config.toml ================================================ [build] target = "x86_64-unknown-none" [target.x86_64-unknown-none] linker = "ld.mold" rustflags = [ "-Zthreads=8", "-Cforce-frame-pointers=y", "-Csymbol-mangling-version=v0", "-Ccodegen-units=1", "-Crelocation-model=pie", "-Crelro-level=full", ] [unstable] build-std = ["core"] ================================================ FILE: samples/map_test/Cargo.toml ================================================ [package] name = "map_test" version = "0.1.0" edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] [dependencies.rex] path = "../../rex" [lints.clippy] disallowed_methods = "forbid" disallowed_types = "forbid" [lints.rust] incomplete_features = "forbid" internal_features = "forbid" unsafe_code = "forbid" unstable_features = "forbid" [profile.dev] panic = "abort" debug = false [profile.release] panic = "abort" debug = false lto = true ================================================ FILE: samples/map_test/clippy.toml ================================================ disallowed-methods = [ "core::mem::forget", ] disallowed-types = [ "core::mem::ManuallyDrop", ] ================================================ FILE: samples/map_test/event-trigger.c ================================================ #include #include int main(void) { return syscall(__NR_dup, 1); } ================================================ FILE: samples/map_test/loader.c ================================================ #include #include #include #include #include #include #include #include #include #include #define EXE "./target/x86_64-unknown-none/release/map_test" int main(void) { int trace_pipe_fd; struct bpf_object *obj; struct bpf_program *prog; struct bpf_link *link = NULL; obj = rex_obj_get_bpf(rex_obj_load(EXE)); if (!obj) { fprintf(stderr, "Object could not be opened\n"); return 1; } prog = bpf_object__find_program_by_name(obj, "rex_prog1"); if (!prog) { fprintf(stderr, "Program not found\n"); return 1; } link = bpf_program__attach(prog); if (libbpf_get_error(link)) { fprintf(stderr, "ERROR: bpf_program__attach failed\n"); link = NULL; return 1; } trace_pipe_fd = openat(AT_FDCWD, "/sys/kernel/debug/tracing/trace_pipe", O_RDONLY); for (;;) { char c; fflush(stdout); if (read(trace_pipe_fd, &c, 1) == 1) putchar(c); } bpf_link__destroy(link); return 0; } ================================================ FILE: samples/map_test/meson.build ================================================ build_dir = run_command( realpath, '--relative-to', meson.current_source_dir(), meson.current_build_dir(), capture: true, check: true ).stdout().strip() env = environment() env.prepend('PATH', rust_bin) env.set('LINUX_OBJ', kbuild_dir) env.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux')) env.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target')) map_test_clippy = custom_target( 'map_test-clippy', output: ['target'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'clippy', '-qr' ], env: env, console: false, build_by_default: true ) map_test_build = custom_target( 'map_test-build', output: ['map_test'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'rustc', '-qr', '--', '-Cenable_rex' ], depends: sample_clippy, env: env, console: false, build_by_default: true ) map_test_loader = executable( 'loader', 'loader.c', build_by_default: true, dependencies: [librex_dep, libbpf_dep, kernel_dep], pie: true ) map_test_trigger = executable( 'event-trigger', 'event-trigger.c', build_by_default: true, dependencies: [kernel_dep], pie: true ) sanity_test = custom_target( 'sanity_test', output: ['runtest.py'], input: join_paths(meson.current_source_dir(), 'tests/runtest.py'), command: [ 'cp', '@INPUT@', '@OUTPUT@', ] ) runtest_deps = [ map_test_build, map_test_loader, map_test_trigger, sanity_test ] sanity_test_env = environment() sanity_test_env.set('SAMPLE_PATH', meson.current_build_dir()) sanity_test_env.set('Q_SCRIPT', join_paths(meson.project_source_root(), 'scripts/q-script/sanity-test-q') ) sanity_test_env.set('KERNEL_PATH', kbuild_dir) test('map_test', python3_bin, args: [sanity_test_scripts], env: sanity_test_env, depends: runtest_deps, is_parallel: false, workdir: meson.current_build_dir() ) ================================================ FILE: samples/map_test/rustfmt.toml ================================================ max_width = 80 binop_separator = "Back" reorder_impl_items = true wrap_comments = true imports_granularity = "Module" group_imports = "StdExternalCrate" ================================================ FILE: samples/map_test/src/main.rs ================================================ #![no_std] #![no_main] extern crate rex; use rex::linux::bpf::BPF_ANY; use rex::map::*; use rex::tracepoint::*; use rex::{Result, rex_map, rex_printk, rex_tracepoint}; #[rex_map] static MAP_HASH: RexHashMap = RexHashMap::new(1024, 0); #[rex_map] static MAP_ARRAY: RexArrayMap = RexArrayMap::new(256, 0); fn map_test1(obj: &tracepoint) -> Result { let key: u32 = 0; rex_printk!("Map Testing 1 Start with key {}\n", key)?; match obj.bpf_map_lookup_elem(&MAP_HASH, &key) { None => { rex_printk!("Not found.\n")?; } Some(val) => { rex_printk!("Found Val={}.\n", *val)?; } } let pid = if let Some(task) = obj.bpf_get_current_task() { task.get_pid() } else { -1 }; rex_printk!("Rust program triggered from PID {}\n", pid)?; obj.bpf_map_update_elem(&MAP_HASH, &key, &(pid as i64), BPF_ANY as u64)?; rex_printk!("Map Updated\n")?; match obj.bpf_map_lookup_elem(&MAP_HASH, &key) { None => { rex_printk!("Not found.\n")?; } Some(val) => { rex_printk!("Found Val={}.\n", *val)?; } } obj.bpf_map_delete_elem(&MAP_HASH, &key)?; rex_printk!("Map delete key\n")?; match obj.bpf_map_lookup_elem(&MAP_HASH, &key) { None => { rex_printk!("Not found.\n")?; } Some(val) => { rex_printk!("Found Val={}.\n", *val)?; } } Ok(0) } fn map_test2(obj: &tracepoint) -> Result { rex_printk!("Array Map Testing Start\n")?; let key = 0; let pid = if let Some(task) = obj.bpf_get_current_task() { task.get_pid() } else { -1 }; rex_printk!("Rust program triggered from PID {}\n", pid)?; // Add a new element obj.bpf_map_update_elem(&MAP_ARRAY, &key, &(pid as u64), BPF_ANY as u64)?; rex_printk!("Map Updated\n")?; match obj.bpf_map_lookup_elem(&MAP_ARRAY, &key) { None => { rex_printk!("Not found.\n")?; } Some(val) => { rex_printk!("Found Val={}.\n", *val)?; } } // let ret = obj.bpf_map_push_elem(MAP_ARRAY, pid as u64, BPF_EXIST.into()); // rex_printk!(obj, "Map push ret={}\n", ret)?; Ok(0) } #[rex_tracepoint] fn rex_prog1( obj: &tracepoint, _: &'static SyscallsEnterDupCtx, ) -> Result { map_test1(obj) .or_else(|e| rex_printk!("map_test1 failed with {}.\n", e))?; map_test2(obj).or_else(|e| rex_printk!("map_test2 failed with {}.\n", e)) } ================================================ FILE: samples/map_test/tests/runtest.py ================================================ #!/bin/python import re import subprocess from time import sleep process = 0 def count_bpf_programs(): try: # Run bpftool to list all loaded BPF programs result = subprocess.run( "bpftool prog show", capture_output=True, shell=True, text=True, ) # Process the output to count programs if result.stdout: # Each program details start on a new line output = result.stdout.strip().split("\n") programs = [line for line in output if "name" in line] return len(programs) else: return 0 except FileNotFoundError: print("bpftool is not installed or not found in the PATH.") return 0 except Exception as e: print(f"An error occurred: {e}") return 0 def run_loader(): global process process = subprocess.Popen( ["./loader"], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) def trigger_prog(): try: subprocess.run("./event-trigger", shell=True) except subprocess.CalledProcessError: print("CalledProcessError") def capture_output() -> bool: try: global process trigger_prog() sleep(2) process.kill() std_out, std_err = process.communicate(timeout=7) test_title = re.findall(r"Map Testing 1 Start with key 0", std_out, re.M) re_match = re.findall(r"Rust program triggered from PID (\d+)", std_out, re.M) print(std_out) if len(re_match) == 2 and len(test_title) == 1: pid = re_match[0] print(pid) map_match = re.findall(r"Found Val={}.".format(pid), std_out, re.M) print(map_match) if len(map_match) == 2: print("Success") return True return False except subprocess.CalledProcessError: return False except subprocess.TimeoutExpired: process.kill() return False def main(): old_prog_num = count_bpf_programs() run_loader() count = 0 while old_prog_num == count_bpf_programs(): sleep(1) count += 1 if count == 5: break grade_file = open("auto_grade.txt", "w") if capture_output(): grade_file.write("success") else: grade_file.write("fail") if __name__ == "__main__": main() ================================================ FILE: samples/map_test_2/.cargo/config.toml ================================================ [build] target = "x86_64-unknown-none" [target.x86_64-unknown-none] linker = "ld.mold" rustflags = [ "-Zthreads=8", "-Cforce-frame-pointers=y", "-Csymbol-mangling-version=v0", "-Ccodegen-units=1", "-Crelocation-model=pie", "-Crelro-level=full", ] [unstable] build-std = ["core"] ================================================ FILE: samples/map_test_2/Cargo.toml ================================================ [package] name = "map_test_2" version = "0.1.0" edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] [dependencies.rex] path = "../../rex" [lints.clippy] disallowed_methods = "forbid" disallowed_types = "forbid" [lints.rust] incomplete_features = "forbid" internal_features = "forbid" unsafe_code = "forbid" unstable_features = "forbid" [profile.dev] panic = "abort" debug = false [profile.release] panic = "abort" debug = false lto = true ================================================ FILE: samples/map_test_2/clippy.toml ================================================ disallowed-methods = [ "core::mem::forget", ] disallowed-types = [ "core::mem::ManuallyDrop", ] ================================================ FILE: samples/map_test_2/event-trigger.c ================================================ #include #include int main(void) { return syscall(__NR_dup, 1); } ================================================ FILE: samples/map_test_2/loader.c ================================================ #include #include #include #include #include #include #include #include #include #include #define EXE "./target/x86_64-unknown-none/release/map_test_2" int main(void) { int trace_pipe_fd; struct bpf_object *obj; struct bpf_program *prog; struct bpf_link *link = NULL; obj = rex_obj_get_bpf(rex_obj_load(EXE)); if (!obj) { fprintf(stderr, "Object could not be opened\n"); return 1; } prog = bpf_object__find_program_by_name(obj, "rex_prog1"); if (!prog) { fprintf(stderr, "Program not found\n"); return 1; } link = bpf_program__attach(prog); if (libbpf_get_error(link)) { fprintf(stderr, "ERROR: bpf_program__attach failed\n"); link = NULL; return 1; } trace_pipe_fd = openat(AT_FDCWD, "/sys/kernel/debug/tracing/trace_pipe", O_RDONLY); for (;;) { char c; fflush(stdout); if (read(trace_pipe_fd, &c, 1) == 1) putchar(c); } bpf_link__destroy(link); return 0; } ================================================ FILE: samples/map_test_2/meson.build ================================================ build_dir = run_command( realpath, '--relative-to', meson.current_source_dir(), meson.current_build_dir(), capture: true, check: true ).stdout().strip() env = environment() env.prepend('PATH', rust_bin) env.set('LINUX_OBJ', kbuild_dir) env.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux')) env.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target')) map_test_2_clippy = custom_target( 'map_test_2-clippy', output: ['target'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'clippy', '-qr' ], env: env, console: false, build_by_default: true ) map_test_2_build = custom_target( 'map_test_2-build', output: ['map_test_2'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'rustc', '-qr', '--', '-Cenable_rex' ], depends: sample_clippy, env: env, console: false, build_by_default: true ) map_test_2_loader = executable( 'loader', 'loader.c', build_by_default: true, dependencies: [librex_dep, libbpf_dep, kernel_dep], pie: true ) map_test_2_trigger = executable( 'event-trigger', 'event-trigger.c', build_by_default: true, dependencies: [kernel_dep], pie: true ) sanity_test = custom_target( 'sanity_test', output: ['runtest.py'], input: join_paths(meson.current_source_dir(), 'tests/runtest.py'), command: [ 'cp', '@INPUT@', '@OUTPUT@', ] ) runtest_deps += [ map_test_2_build, map_test_2_loader, map_test_2_trigger, sanity_test ] sanity_test_env = environment() sanity_test_env.set('SAMPLE_PATH', meson.current_build_dir()) sanity_test_env.set('Q_SCRIPT', join_paths(meson.project_source_root(), 'scripts/q-script/sanity-test-q') ) sanity_test_env.set('KERNEL_PATH', kbuild_dir) test('map_test_2', python3_bin, args: [sanity_test_scripts], env: sanity_test_env, depends: runtest_deps, is_parallel: false, workdir: meson.current_build_dir() ) ================================================ FILE: samples/map_test_2/rustfmt.toml ================================================ max_width = 80 binop_separator = "Back" reorder_impl_items = true wrap_comments = true imports_granularity = "Module" group_imports = "StdExternalCrate" ================================================ FILE: samples/map_test_2/src/main.rs ================================================ #![no_std] #![no_main] extern crate rex; use core::mem; use rex::map::*; use rex::tracepoint::*; use rex::utils::convert_slice_to_struct_mut; use rex::{Result, rex_map, rex_printk, rex_tracepoint}; #[rex_map] static MAP_HASH: RexHashMap = RexHashMap::new(1024, 0); #[rex_map] static ARRAY: RexArrayMap = RexArrayMap::new(256, 0); #[rex_map] static STACK: RexStack = RexStack::new(256, 0); #[rex_map] static QUEUE: RexQueue = RexQueue::new(256, 0); #[rex_map] static RINGBUF: RexRingBuf = RexRingBuf::new(4096, 0); fn map_test_hash(obj: &tracepoint) -> Result { let key: u32 = 0; rex_printk!("Map Testing Hash Start with key {}\n", key)?; match MAP_HASH.get_mut(&key) { None => { rex_printk!("Not found.\n")?; } Some(val) => { rex_printk!("Found Val={}.\n", *val)?; } } let pid = if let Some(task) = obj.bpf_get_current_task() { task.get_pid() } else { -1 }; rex_printk!("Rust program triggered from PID {}\n", pid)?; MAP_HASH.insert(&key, &(pid as i64))?; rex_printk!("Map Updated\n")?; match MAP_HASH.get_mut(&key) { None => { rex_printk!("Not found.\n")?; } Some(val) => { rex_printk!("Found Val={}.\n", *val)?; } } MAP_HASH.delete(&key)?; rex_printk!("Map delete key\n")?; match MAP_HASH.get_mut(&key) { None => { rex_printk!("Not found.\n")?; } Some(val) => { rex_printk!("Found Val={}.\n", *val)?; } } Ok(0) } fn map_test_array(obj: &tracepoint) -> Result { let key: u32 = 0; rex_printk!("Map Testing Array Start with key {}\n", key)?; let pid = if let Some(task) = obj.bpf_get_current_task() { task.get_pid() } else { -1 }; rex_printk!("Rust program triggered from PID {}\n", pid)?; ARRAY.insert(&key, &(pid as i64))?; rex_printk!("Map Updated\n")?; match ARRAY.get_mut(&key) { None => { rex_printk!("Not found.\n")?; } Some(val) => { rex_printk!("Found Val={}.\n", *val)?; } } Ok(0) } fn map_test_stack(obj: &tracepoint) -> Result { rex_printk!("Map Testing Stack Start\n")?; let pid = if let Some(task) = obj.bpf_get_current_task() { task.get_pid() } else { -1 }; rex_printk!("Rust program triggered from PID {}\n", pid)?; STACK.push(&(pid as i64))?; rex_printk!("Pushed {} onto stack\n", pid)?; STACK.push(&((pid + 1) as i64))?; rex_printk!("Pushed {} onto stack\n", pid + 1)?; match STACK.peek() { None => rex_printk!("Not found.\n")?, Some(top) => rex_printk!("Top of stack: {}.\n", top)?, }; STACK.pop(); rex_printk!("Popped top of stack\n")?; match STACK.peek() { None => rex_printk!("Not found.\n")?, Some(next_top) => rex_printk!("Next top of stack: {}.\n", next_top)?, }; Ok(0) } fn map_test_queue(obj: &tracepoint) -> Result { rex_printk!("Map Testing Queue Start\n")?; let pid = if let Some(task) = obj.bpf_get_current_task() { task.get_pid() } else { -1 }; rex_printk!("Rust program triggered from PID {}\n", pid)?; QUEUE.push(&(pid as i64))?; rex_printk!("Pushed {} into queue\n", pid)?; QUEUE.push(&((pid + 1) as i64))?; rex_printk!("Pushed {} into queue\n", pid + 1)?; match QUEUE.peek() { None => rex_printk!("Not found.\n")?, Some(front) => rex_printk!("Front of queue: {}.\n", front)?, }; QUEUE.pop(); rex_printk!("Popped front of queue\n")?; match QUEUE.peek() { None => rex_printk!("Not found.\n")?, Some(next_front) => { rex_printk!("Next front of queue: {}.\n", next_front)? } }; Ok(0) } fn map_test_ringbuf(obj: &tracepoint) -> Result { rex_printk!("Map Testing Ring Buffer Start\n")?; let pid = if let Some(task) = obj.bpf_get_current_task() { task.get_pid() } else { -1 }; rex_printk!("Rust program triggered from PID {}\n", pid)?; rex_printk!( "Available bytes in ringbuf: {}\n", RINGBUF.available_bytes().unwrap() )?; let mut entry = match RINGBUF.reserve(mem::size_of::()) { None => { rex_printk!("Unable to reserve ringbuf.\n")?; return Err(0); } Some(entry) => entry, }; *convert_slice_to_struct_mut::(&mut entry) = pid as i64; entry.submit(0); rex_printk!( "Available bytes in ringbuf: {}\n", RINGBUF.available_bytes().unwrap() )?; Ok(0) } #[rex_tracepoint] fn rex_prog1( obj: &tracepoint, _: &'static SyscallsEnterDupCtx, ) -> Result { map_test_hash(obj) .or_else(|e| rex_printk!("map_test failed with {}.\n", e))?; map_test_array(obj) .or_else(|e| rex_printk!("map_test failed with {}.\n", e))?; map_test_stack(obj) .or_else(|e| rex_printk!("map_test failed with {}.\n", e))?; map_test_ringbuf(obj) .or_else(|e| rex_printk!("map_test2 failed with {}.\n", e))?; map_test_queue(obj) .or_else(|e| rex_printk!("map_test failed with {}.\n", e)) } ================================================ FILE: samples/map_test_2/tests/runtest.py ================================================ #!/bin/python import re import subprocess from time import sleep process = 0 def count_bpf_programs(): try: # Run bpftool to list all loaded BPF programs result = subprocess.run( "bpftool prog show", capture_output=True, shell=True, text=True, ) # Process the output to count programs if result.stdout: # Each program details start on a new line output = result.stdout.strip().split("\n") programs = [line for line in output if "name" in line] return len(programs) else: return 0 except FileNotFoundError: print("bpftool is not installed or not found in the PATH.") return 0 except Exception as e: print(f"An error occurred: {e}") return 0 def run_loader(): global process process = subprocess.Popen( ["./loader"], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) def trigger_prog(): try: subprocess.run("./event-trigger", shell=True) except subprocess.CalledProcessError: print("CalledProcessError") def capture_output() -> bool: try: global process trigger_prog() sleep(2) process.kill() std_out, std_err = process.communicate(timeout=7) test_title = re.findall(r"Map Testing Hash Start with key 0", std_out, re.M) re_match = re.findall(r"Rust program triggered from PID (\d+)", std_out, re.M) print(std_out) if len(re_match) == 5 and len(test_title) == 1: pid = re_match[0] print(pid) map_match = re.findall(r"Found Val={}.".format(pid), std_out, re.M) stack_match_1 = re.findall(r"Top of stack: {}.".format(int(pid) + 1), std_out, re.M) stack_match_2 = re.findall(r"Next top of stack: {}.".format(pid), std_out, re.M) queue_match_1 = re.findall(r"Front of queue: {}.".format(pid), std_out, re.M) queue_match_2 = re.findall(r"Next front of queue: {}.".format(int(pid) + 1), std_out, re.M) ringbuf_match = re.findall(r"Available bytes in ringbuf", std_out, re.M) print(map_match) print(stack_match_1) print(stack_match_2) print(queue_match_1) print(queue_match_2) if len(map_match) == 2 and stack_match_1 and stack_match_2 and queue_match_1 and queue_match_2 and len(ringbuf_match) == 2: print("Success") return True return False except subprocess.CalledProcessError: return False except subprocess.TimeoutExpired: process.kill() return False def main(): old_prog_num = count_bpf_programs() run_loader() count = 0 while old_prog_num == count_bpf_programs(): sleep(1) count += 1 if count == 5: break grade_file = open("auto_grade.txt", "w") if capture_output(): grade_file.write("success") else: grade_file.write("fail") if __name__ == "__main__": main() ================================================ FILE: samples/meson.build ================================================ subdir('atomic') subdir('bmc') subdir('electrode') subdir('error_injector') subdir('hello') subdir('map_bench') subdir('map_test') subdir('map_test_2') subdir('recursive') subdir('spinlock_cleanup_benchmark') subdir('spinlock_test') subdir('startup_overhead_benchmark') subdir('syscall_tp') subdir('trace_event') subdir('tracex5') subdir('xdp_test') subdir('syscount') ================================================ FILE: samples/recursive/.cargo/config.toml ================================================ [build] target = "x86_64-unknown-none" [target.x86_64-unknown-none] linker = "ld.mold" rustflags = [ "-Zthreads=8", "-Cforce-frame-pointers=y", "-Csymbol-mangling-version=v0", "-Ccodegen-units=1", "-Crelocation-model=pie", "-Crelro-level=full", ] [unstable] build-std = ["core"] ================================================ FILE: samples/recursive/Cargo.toml ================================================ [package] name = "recursive" version = "0.1.0" edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] [dependencies.rex] path = "../../rex" [lints.clippy] disallowed_methods = "forbid" disallowed_types = "forbid" [lints.rust] incomplete_features = "forbid" internal_features = "forbid" unsafe_code = "forbid" unstable_features = "forbid" [profile.dev] panic = "abort" debug = false [profile.release] panic = "abort" debug = false lto = true ================================================ FILE: samples/recursive/bench.sh ================================================ #!/usr/bin/env bash if [ "$#" -ne 1 ]; then echo "Usage: $0 " exit 1 fi echo 8192 > /sys/kernel/debug/tracing/buffer_size_kb mkdir output if [[ "$1" == "rex" ]]; then for i in {0..32}; do ./event-trigger 5000 $i cat /sys/kernel/debug/tracing/trace | tail -5000 >"./output/rust_${i}" echo >/sys/kernel/debug/tracing/trace echo $i sleep 0.5 done elif [[ "$1" == "bpf" ]]; then for i in {0..32}; do ./event-trigger 6000 $i cat /sys/kernel/debug/tracing/trace | tail -5000 >"./output/bpf_${i}" echo >/sys/kernel/debug/tracing/trace echo $i sleep 0.5 done fi # unlink rm -rf /sys/fs/bpf/* ================================================ FILE: samples/recursive/clippy.toml ================================================ disallowed-methods = [ "core::mem::forget", ] disallowed-types = [ "core::mem::ManuallyDrop", ] ================================================ FILE: samples/recursive/event-trigger.c ================================================ #include #include #include #include #include int main(int argc, char *argv[]) { int nr_rounds, arg, fd; if (argc != 3) asm volatile("ud2"); nr_rounds = atoi(argv[1]); arg = atoi(argv[2]); fd = open("/proc/kprobe_target", O_RDONLY); if (fd < 0) { perror("open"); return 1; } for (int i = 0; i < nr_rounds; i++) ioctl(fd, 1313, arg); close(fd); } ================================================ FILE: samples/recursive/loader.c ================================================ #include #include #include #include #include #include #include #include #include #include #include #define EXE "./target/x86_64-unknown-none/release/recursive" int main(void) { struct bpf_object *obj; struct bpf_program *prog; struct bpf_link *link = NULL; obj = rex_obj_get_bpf(rex_obj_load(EXE)); if (!obj) { fprintf(stderr, "Object could not be opened\n"); return 1; } prog = bpf_object__find_program_by_name(obj, "rex_recursive"); if (!prog) { fprintf(stderr, "_start not found\n"); return 1; } link = bpf_program__attach(prog); if (libbpf_get_error(link)) { fprintf(stderr, "ERROR: bpf_program__attach failed\n"); link = NULL; return 1; } bpf_link__pin(link, "/sys/fs/bpf/recursive_link"); bpf_link__destroy(link); return 0; } ================================================ FILE: samples/recursive/meson.build ================================================ build_dir = run_command( realpath, '--relative-to', meson.current_source_dir(), meson.current_build_dir(), capture: true, check: true ).stdout().strip() env = environment() env.prepend('PATH', rust_bin) env.set('LINUX_OBJ', kbuild_dir) env.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux')) env.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target')) sample_clippy = custom_target( 'recursive-clippy', output: ['target'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'clippy', '-qr' ], env: env, console: false, build_by_default: true ) sample_build = custom_target( 'recursive-build', output: ['recursive'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'rustc', '-qr', '--', '-Cenable_rex' ], depends: sample_clippy, env: env, console: false, build_by_default: true ) executable( 'loader', 'loader.c', build_by_default: true, dependencies: [librex_dep, libbpf_dep, kernel_dep], pie: true ) executable( 'event-trigger', 'event-trigger.c', build_by_default: true, dependencies: [kernel_dep], pie: true ) ================================================ FILE: samples/recursive/rustfmt.toml ================================================ max_width = 80 binop_separator = "Back" reorder_impl_items = true wrap_comments = true imports_granularity = "Module" group_imports = "StdExternalCrate" ================================================ FILE: samples/recursive/src/main.rs ================================================ #![no_std] #![no_main] extern crate rex; // use rex::tracepoint::*; use core::hint::black_box; use rex::kprobe::*; use rex::map::RexArrayMap; use rex::pt_regs::PtRegs; use rex::{Result, rex_kprobe, rex_map, rex_printk}; #[rex_map] static data_map: RexArrayMap = RexArrayMap::new(2, 0); #[rex_kprobe(function = "kprobe_target_func")] fn rex_recursive(obj: &kprobe, ctx: &mut PtRegs) -> Result { // let curr_pid: i32 = if let Some(task_struct) = obj.bpf_get_current_task() // { task_struct.get_pid() // } else { // return Err(0); // }; // let stored_pid: u32 = if let Some(val) = // obj.bpf_map_lookup_elem(&data_map, &0) { *val // } else { // return Err(0); // }; let n = ctx.rdi() as u32; // let n: u32 = if let Some(val) = obj.bpf_map_lookup_elem(&data_map, &1) { // *val // } else { // return Err(0); // }; // rex_printk!("Received n: {}", n)?; let start_time: u64 = obj.bpf_ktime_get_ns(); calculate_tail_fib(n); let end_time: u64 = obj.bpf_ktime_get_ns(); // rex_printk!("Result: {}", result)?; rex_printk!("Time: {}", end_time - start_time)?; Ok(0) } #[inline(never)] fn calculate_tail_fib(n: u32) { if n == 0 { return; } black_box(calculate_tail_fib(n - 1)) } ================================================ FILE: samples/spinlock_cleanup_benchmark/.cargo/config.toml ================================================ [build] target = "x86_64-unknown-none" [target.x86_64-unknown-none] linker = "ld.mold" rustflags = [ "-Zthreads=8", "-Cforce-frame-pointers=y", "-Csymbol-mangling-version=v0", "-Ccodegen-units=1", "-Crelocation-model=pie", "-Crelro-level=full", ] [unstable] build-std = ["core"] ================================================ FILE: samples/spinlock_cleanup_benchmark/.gitignore ================================================ target ================================================ FILE: samples/spinlock_cleanup_benchmark/Cargo.toml ================================================ [package] name = "spinlock_cleanup_benchmark" version = "0.1.0" edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] [dependencies.rex] path = "../../rex" [lints.clippy] disallowed_methods = "forbid" disallowed_types = "forbid" [lints.rust] incomplete_features = "forbid" internal_features = "forbid" unsafe_code = "forbid" unstable_features = "forbid" [profile.dev] panic = "abort" debug = false [profile.release] panic = "abort" debug = false lto = true ================================================ FILE: samples/spinlock_cleanup_benchmark/clippy.toml ================================================ disallowed-methods = [ "core::mem::forget", ] disallowed-types = [ "core::mem::ManuallyDrop", ] ================================================ FILE: samples/spinlock_cleanup_benchmark/loader.c ================================================ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define EXE "./target/x86_64-unknown-none/release/spinlock_cleanup_benchmark" #define __unused __attribute__((__unused__)) int main(int __unused argc, char **argv) { struct bpf_program *prog; struct bpf_object *obj; int interface_idx = atoi(argv[1]); unsigned int xdp_flags = 0; xdp_flags |= XDP_FLAGS_DRV_MODE; /* xdp_flags |= XDP_FLAGS_SKB_MODE; */ obj = rex_obj_get_bpf(rex_obj_load(EXE)); if (!obj) { fprintf(stderr, "Object could not be opened\n"); return 1; } prog = bpf_object__find_program_by_name(obj, "rex_prog1"); if (!prog) { printf("finding a prog in obj file failed\n"); return 1; } int xdp_main_prog_fd = bpf_program__fd(prog); if (bpf_xdp_attach(interface_idx, xdp_main_prog_fd, xdp_flags, NULL) < 0) { fprintf(stderr, "ERROR: xdp failed"); return 1; } return 0; } ================================================ FILE: samples/spinlock_cleanup_benchmark/meson.build ================================================ build_dir = run_command( realpath, '--relative-to', meson.current_source_dir(), meson.current_build_dir(), capture: true, check: true ).stdout().strip() env = environment() env.prepend('PATH', rust_bin) env.set('LINUX_OBJ', kbuild_dir) env.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux')) env.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target')) sample_clippy = custom_target( 'spinlock_cleanup_benchmark-clippy', output: ['target'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'clippy', '-qr' ], env: env, console: false, build_by_default: true ) sample_build = custom_target( 'spinlock_cleanup_benchmark-build', output: ['spinlock_cleanup_benchmark'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'rustc', '-qr', '--', '-Cenable_rex' ], depends: sample_clippy, env: env, console: false, build_by_default: true ) executable( 'loader', 'loader.c', build_by_default: true, dependencies: [librex_dep, libbpf_dep, kernel_dep], pie: true ) ================================================ FILE: samples/spinlock_cleanup_benchmark/rustfmt.toml ================================================ max_width = 80 binop_separator = "Back" reorder_impl_items = true wrap_comments = true imports_granularity = "Module" group_imports = "StdExternalCrate" ================================================ FILE: samples/spinlock_cleanup_benchmark/src/main.rs ================================================ #![no_std] #![no_main] extern crate rex; use rex::linux::bpf::bpf_spin_lock; use rex::map::RexArrayMap; use rex::spinlock::rex_spinlock_guard; use rex::xdp::*; use rex::{Result, rex_map, rex_printk, rex_xdp}; #[repr(C)] #[derive(Clone, Copy)] struct MapEntry { data: u64, lock: bpf_spin_lock, } #[rex_map] static MAP_ARRAY: RexArrayMap = RexArrayMap::new(256, 0); #[rex_xdp] fn rex_prog1(obj: &xdp, _: &mut xdp_md) -> Result { if let Some(entry) = obj.bpf_map_lookup_elem(&MAP_ARRAY, &0) { let start = obj.bpf_ktime_get_ns(); { let _guard = rex_spinlock_guard::new(&mut entry.lock); } let end = obj.bpf_ktime_get_ns(); rex_printk!("Spinlock allocation and cleanup: {} ns", end - start)?; Ok(XDP_PASS as i32) } else { rex_printk!("Unable to look up map")?; Err(XDP_PASS as i32) } } ================================================ FILE: samples/spinlock_test/.cargo/config.toml ================================================ [build] target = "x86_64-unknown-none" [target.x86_64-unknown-none] linker = "ld.mold" rustflags = [ "-Zthreads=8", "-Cforce-frame-pointers=y", "-Csymbol-mangling-version=v0", "-Ccodegen-units=1", "-Crelocation-model=pie", "-Crelro-level=full", ] [unstable] build-std = ["core"] ================================================ FILE: samples/spinlock_test/.gitignore ================================================ target ================================================ FILE: samples/spinlock_test/Cargo.toml ================================================ [package] name = "spinlock_test" version = "0.1.0" edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] [dependencies.rex] path = "../../rex" [lints.clippy] disallowed_methods = "forbid" disallowed_types = "forbid" [lints.rust] incomplete_features = "forbid" internal_features = "forbid" unsafe_code = "forbid" unstable_features = "forbid" [profile.dev] panic = "abort" debug = false [profile.release] panic = "abort" debug = false lto = true ================================================ FILE: samples/spinlock_test/clippy.toml ================================================ disallowed-methods = [ "core::mem::forget", ] disallowed-types = [ "core::mem::ManuallyDrop", ] ================================================ FILE: samples/spinlock_test/event-trigger.c ================================================ #include #include int main(void) { return syscall(__NR_dup, 1); } ================================================ FILE: samples/spinlock_test/loader.c ================================================ #include #include #include #include #include #include #include #include #include #define EXE "./target/x86_64-unknown-none/release/spinlock_test" int main(void) { int trace_pipe_fd; struct bpf_object *obj; struct bpf_program *prog; struct bpf_link *link = NULL; obj = rex_obj_get_bpf(rex_obj_load(EXE)); if (!obj) { fprintf(stderr, "Object could not be opened\n"); return 1; } prog = bpf_object__find_program_by_name(obj, "rex_prog1"); if (!prog) { fprintf(stderr, "_start not found\n"); return 1; } link = bpf_program__attach(prog); if (libbpf_get_error(link)) { fprintf(stderr, "ERROR: bpf_program__attach failed\n"); link = NULL; return 1; } trace_pipe_fd = openat(AT_FDCWD, "/sys/kernel/debug/tracing/trace_pipe", O_RDONLY); for (;;) { char c; if (read(trace_pipe_fd, &c, 1) == 1) putchar(c); } bpf_link__destroy(link); return 0; } ================================================ FILE: samples/spinlock_test/meson.build ================================================ build_dir = run_command( realpath, '--relative-to', meson.current_source_dir(), meson.current_build_dir(), capture: true, check: true ).stdout().strip() env = environment() env.prepend('PATH', rust_bin) env.set('LINUX_OBJ', kbuild_dir) env.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux')) env.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target')) sample_clippy = custom_target( 'spinlock_test-clippy', output: ['target'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'clippy', '-qr' ], env: env, console: false, build_by_default: true ) sample_build = custom_target( 'spinlock_test-build', output: ['spinlock_test'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'rustc', '-qr', '--', '-Cenable_rex' ], depends: sample_clippy, env: env, console: false, build_by_default: true ) executable( 'loader', 'loader.c', build_by_default: true, dependencies: [librex_dep, libbpf_dep, kernel_dep], pie: true ) executable( 'event-trigger', 'event-trigger.c', build_by_default: true, dependencies: [kernel_dep], pie: true ) ================================================ FILE: samples/spinlock_test/rustfmt.toml ================================================ max_width = 80 binop_separator = "Back" reorder_impl_items = true wrap_comments = true imports_granularity = "Module" group_imports = "StdExternalCrate" ================================================ FILE: samples/spinlock_test/src/main.rs ================================================ #![no_std] #![no_main] extern crate rex; use rex::linux::bpf::bpf_spin_lock; use rex::map::RexArrayMap; use rex::spinlock::rex_spinlock_guard; use rex::tracepoint::*; use rex::{Result, rex_map, rex_tracepoint}; #[repr(C)] #[derive(Clone, Copy)] struct MapEntry { data: u64, lock: bpf_spin_lock, } #[rex_map] static MAP_ARRAY: RexArrayMap = RexArrayMap::new(256, 0); fn test1(obj: &tracepoint) { if let Some(entry) = obj.bpf_map_lookup_elem(&MAP_ARRAY, &0) { // entry.lock locked in rex_spinlock_guard::new let _guard = rex_spinlock_guard::new(&mut entry.lock); entry.data = 1; // entry.lock is automatically released when _guard goes out of scope } } fn test2(obj: &tracepoint) { if let Some(entry) = obj.bpf_map_lookup_elem(&MAP_ARRAY, &0) { // entry.lock locked in rex_spinlock_guard::new let _guard = rex_spinlock_guard::new(&mut entry.lock); entry.data = 1; panic!("test\n"); // entry.lock is automatically released by cleanup mechanism } } #[rex_tracepoint] fn rex_prog1( obj: &tracepoint, _: &'static SyscallsEnterDupCtx, ) -> Result { test1(obj); test2(obj); Ok(0) } ================================================ FILE: samples/startup_overhead_benchmark/.cargo/config.toml ================================================ [build] target = "x86_64-unknown-none" [target.x86_64-unknown-none] linker = "ld.mold" rustflags = [ "-Zthreads=8", "-Cforce-frame-pointers=y", "-Csymbol-mangling-version=v0", "-Ccodegen-units=1", "-Crelocation-model=pie", "-Crelro-level=full", ] [unstable] build-std = ["core"] ================================================ FILE: samples/startup_overhead_benchmark/.gitignore ================================================ target ================================================ FILE: samples/startup_overhead_benchmark/Cargo.toml ================================================ [package] name = "startup_overhead_benchmark" version = "0.1.0" edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] [dependencies.rex] path = "../../rex" [lints.clippy] disallowed_methods = "forbid" disallowed_types = "forbid" [lints.rust] incomplete_features = "forbid" internal_features = "forbid" unsafe_code = "forbid" unstable_features = "forbid" [profile.dev] panic = "abort" debug = false [profile.release] panic = "abort" debug = false lto = true ================================================ FILE: samples/startup_overhead_benchmark/clippy.toml ================================================ disallowed-methods = [ "core::mem::forget", ] disallowed-types = [ "core::mem::ManuallyDrop", ] ================================================ FILE: samples/startup_overhead_benchmark/event-trigger.c ================================================ #include #include #include #include #include int main(int argc, char *argv[]) { int nr_rounds, arg, fd; if (argc != 3) asm volatile("ud2"); nr_rounds = atoi(argv[1]); arg = atoi(argv[2]); fd = open("/proc/kprobe_target", O_RDONLY); if (fd < 0) { perror("open"); return 1; } for (int i = 0; i < nr_rounds; i++) ioctl(fd, 1313, arg); close(fd); } ================================================ FILE: samples/startup_overhead_benchmark/loader.c ================================================ #include #include #include #include #include #include #include #include #include #include #define EXE "./target/x86_64-unknown-none/release/startup_overhead_benchmark" int main(void) { struct bpf_object *obj; struct bpf_program *prog; struct bpf_link *link = NULL; obj = rex_obj_get_bpf(rex_obj_load(EXE)); if (!obj) { fprintf(stderr, "Object could not be opened\n"); return 1; } prog = bpf_object__find_program_by_name(obj, "rex_prog1"); if (!prog) { fprintf(stderr, "_start not found\n"); return 1; } link = bpf_program__attach(prog); if (libbpf_get_error(link)) { fprintf(stderr, "ERROR: bpf_program__attach failed\n"); link = NULL; return 1; } bpf_link__pin(link, "/sys/fs/bpf/kprobe_link"); bpf_link__destroy(link); return 0; } ================================================ FILE: samples/startup_overhead_benchmark/meson.build ================================================ build_dir = run_command( realpath, '--relative-to', meson.current_source_dir(), meson.current_build_dir(), capture: true, check: true ).stdout().strip() env = environment() env.prepend('PATH', rust_bin) env.set('LINUX_OBJ', kbuild_dir) env.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux')) env.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target')) sample_clippy = custom_target( 'startup_overhead_benchmark-clippy', output: ['target'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'clippy', '-qr' ], env: env, console: false, build_by_default: true ) sample_build = custom_target( 'startup_overhead_benchmark-build', output: ['startup_overhead_benchmark'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'rustc', '-qr', '--', '-Cenable_rex' ], depends: sample_clippy, env: env, console: false, build_by_default: true ) executable( 'loader', 'loader.c', build_by_default: true, dependencies: [librex_dep, libbpf_dep, kernel_dep], pie: true ) executable( 'event-trigger', 'event-trigger.c', build_by_default: true, dependencies: [kernel_dep], pie: true ) ================================================ FILE: samples/startup_overhead_benchmark/rustfmt.toml ================================================ max_width = 80 binop_separator = "Back" reorder_impl_items = true wrap_comments = true imports_granularity = "Module" group_imports = "StdExternalCrate" ================================================ FILE: samples/startup_overhead_benchmark/src/main.rs ================================================ #![no_std] #![no_main] extern crate rex; use rex::kprobe::*; use rex::pt_regs::PtRegs; use rex::{Result, rex_kprobe}; #[rex_kprobe(function = "kprobe_target_func")] fn rex_prog1(_obj: &kprobe, _ctx: &mut PtRegs) -> Result { Ok(0) } ================================================ FILE: samples/syscount/.cargo/config.toml ================================================ [build] target = "x86_64-unknown-none" [target.x86_64-unknown-none] linker = "ld.mold" rustflags = [ "-Zthreads=8", "-Cforce-frame-pointers=y", "-Csymbol-mangling-version=v0", "-Ccodegen-units=1", "-Crelocation-model=pie", "-Crelro-level=full", ] [unstable] build-std = ["core"] ================================================ FILE: samples/syscount/Cargo.toml ================================================ [package] name = "syscount" version = "0.1.0" edition = "2024" [dependencies] [dependencies.rex] path = "../../rex" [lints.clippy] disallowed_methods = "forbid" disallowed_types = "forbid" [lints.rust] incomplete_features = "forbid" internal_features = "forbid" unsafe_code = "forbid" unstable_features = "forbid" [profile.dev] panic = "abort" debug = false [profile.release] panic = "abort" debug = false lto = true ================================================ FILE: samples/syscount/clippy.toml ================================================ disallowed-methods = [ "core::mem::forget", ] disallowed-types = [ "core::mem::ManuallyDrop", ] ================================================ FILE: samples/syscount/loader.c ================================================ #include #include #include #include #include #include #include #include #include #include #define EXE "./target/x86_64-unknown-none/release/syscount" #define __unused __attribute__((__unused__)) static const char *syscall_names[] = { "read", "write", "open", "close", "stat", "fstat", "lstat", "poll", "lseek", "mmap", "mprotect", "munmap", "brk", "rt_sigaction", "rt_sigprocmask", "rt_sigreturn", "ioctl", "pread64", "pwrite64", "readv", "writev", "access", "pipe", "select", "sched_yield", "mremap", "msync", "mincore", "madvise", "shmget", "shmat", "shmctl", "dup", "dup2", "pause", "nanosleep", "getitimer", "alarm", "setitimer", "getpid", "sendfile", "socket", "connect", "accept", "sendto", "recvfrom", "sendmsg", "recvmsg", "shutdown", "bind", "listen", "getsockname", "getpeername", "socketpair", "setsockopt", "getsockopt", "clone", "fork", "vfork", "execve", "exit", "wait4", "kill", "uname", "semget", "semop", "semctl", "shmdt", "msgget", "msgsnd", "msgrcv", "msgctl", "fcntl", "flock", "fsync", "fdatasync", "truncate", "ftruncate", "getdents", "getcwd", "chdir", "fchdir", "rename", "mkdir", "rmdir", "creat", "link", "unlink", "symlink", "readlink", "chmod", "fchmod", "chown", "fchown", "lchown", "umask", "gettimeofday", "getrlimit", "getrusage", "sysinfo" }; #define MAX_SYSCALL_ID (sizeof(syscall_names) / sizeof(syscall_names[0])) static volatile bool exiting = false; static void sig_handler(int __unused sig) { exiting = true; } enum stats_type_t { COUNT_ONLY, SHOW_ERRORS, SHOW_LATENCY, SHOW_BOTH }; static void print_header(bool timestamp, enum stats_type_t type) { if (timestamp) { printf("%-8s ", "TIME(s)"); } switch (type) { case COUNT_ONLY: printf("%-20s %-10s\n", "SYSCALL", "COUNT"); break; case SHOW_ERRORS: printf("%-20s %-10s %-10s\n", "SYSCALL", "COUNT", "ERRORS"); break; case SHOW_LATENCY: printf("%-20s %-10s %-15s\n", "SYSCALL", "COUNT", "TIME(us)"); break; case SHOW_BOTH: printf("%-20s %-10s %-10s %-15s\n", "SYSCALL", "COUNT", "ERRORS", "TIME(us)"); break; } if (timestamp) { printf("%-8s ", "--------"); } switch (type) { case COUNT_ONLY: printf("%-20s %-10s\n", "--------------------", "----------"); break; case SHOW_ERRORS: printf("%-20s %-10s %-10s\n", "--------------------", "----------", "----------"); break; case SHOW_LATENCY: printf("%-20s %-10s %-15s\n", "--------------------", "----------", "---------------"); break; case SHOW_BOTH: printf("%-20s %-10s %-10s %-15s\n", "--------------------", "----------", "----------", "---------------"); break; } } struct options { int interval; bool timestamp; bool clear_screen; bool sort_by_count; int top_n; enum stats_type_t type; int pid; char *filter_syscalls; }; static void print_usage(const char *prog_name) { printf("Usage: %s [options]\n\n", prog_name); printf("Options:\n"); printf(" -i Set the output interval (default: 1 second)\n"); printf(" -t Include timestamp in output\n"); printf(" -c Clear the screen between outputs\n"); printf(" -s Sort by syscall name instead of count\n"); printf(" -n Display only the top N syscalls\n"); printf(" -e Show errors count\n"); printf(" -l Show latency (average time per syscall in microseconds)\n"); printf(" -p Filter by process ID\n"); printf(" -x Trace only comma-separated syscalls\n"); printf(" -h Display this help message\n"); } static struct options parse_options(int argc, char *argv[]) { static struct options opts = { .interval = 1, .timestamp = false, .clear_screen = false, .sort_by_count = true, .top_n = -1, .type = COUNT_ONLY, .pid = -1, .filter_syscalls = NULL }; int c; while ((c = getopt(argc, argv, "i:tcn:selp:x:h")) != -1) { switch (c) { case 'i': opts.interval = atoi(optarg); if (opts.interval <= 0) opts.interval = 1; break; case 't': opts.timestamp = true; break; case 'c': opts.clear_screen = true; break; case 'n': opts.top_n = atoi(optarg); break; case 's': opts.sort_by_count = false; break; case 'e': if (opts.type == SHOW_LATENCY) opts.type = SHOW_BOTH; else opts.type = SHOW_ERRORS; break; case 'l': if (opts.type == SHOW_ERRORS) opts.type = SHOW_BOTH; else opts.type = SHOW_LATENCY; break; case 'p': opts.pid = atoi(optarg); break; case 'x': opts.filter_syscalls = optarg; break; case 'h': print_usage(argv[0]); exit(0); default: print_usage(argv[0]); exit(EXIT_FAILURE); } } return opts; } int main(int argc, char *argv[]) { struct bpf_object *obj; struct bpf_link **links = NULL; int link_count = 0; int syscall_counts_map_fd = -1; int syscall_errors_map_fd = -1; int syscall_latency_map_fd = -1; time_t start_time; int err = 0; struct options opts = parse_options(argc, argv); signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); obj = rex_obj_get_bpf(rex_obj_load(EXE)); if (!obj) { fprintf(stderr, "Failed to load BPF program\n"); return 1; } int prog_count = 0; struct bpf_program *prog; bpf_object__for_each_program(prog, obj) { prog_count++; } links = calloc(prog_count, sizeof(struct bpf_link *)); if (!links) { fprintf(stderr, "Failed to allocate memory for links\n"); return 1; } bpf_object__for_each_program(prog, obj) { links[link_count] = bpf_program__attach(prog); if (libbpf_get_error(links[link_count])) { fprintf(stderr, "Failed to attach program: %s\n", bpf_program__name(prog)); err = -1; } else { printf("Attached program: %s\n", bpf_program__name(prog)); link_count++; } } if (err != 0) { fprintf(stderr, "Failed to attach some programs\n"); goto cleanup; } syscall_counts_map_fd = bpf_object__find_map_fd_by_name(obj, "SYSCALL_COUNTS"); if (syscall_counts_map_fd < 0) { fprintf(stderr, "Failed to find syscall counts map\n"); err = -1; goto cleanup; } if (opts.type == SHOW_ERRORS || opts.type == SHOW_BOTH) { syscall_errors_map_fd = bpf_object__find_map_fd_by_name(obj, "SYSCALL_ERRORS"); if (syscall_errors_map_fd < 0) { fprintf(stderr, "Failed to find syscall errors map\n"); opts.type = opts.type == SHOW_BOTH ? SHOW_LATENCY : COUNT_ONLY; } } if (opts.type == SHOW_LATENCY || opts.type == SHOW_BOTH) { syscall_latency_map_fd = bpf_object__find_map_fd_by_name(obj, "SYSCALL_LATENCY"); if (syscall_latency_map_fd < 0) { fprintf(stderr, "Failed to find syscall latency map\n"); opts.type = opts.type == SHOW_BOTH ? SHOW_ERRORS : COUNT_ONLY; } } printf("Tracing syscalls... Hit Ctrl-C to end.\n"); start_time = time(NULL); while (!exiting) { sleep(opts.interval); if (opts.clear_screen) { printf("\033[2J\033[1;1H"); } print_header(opts.timestamp, opts.type); __u32 key = 0, next_key; __u64 count_value, error_value = 0, latency_value = 0; struct { __u32 id; __u64 count; __u64 errors; __u64 latency; } stats[512]; int stat_count = 0; while (bpf_map_get_next_key(syscall_counts_map_fd, &key, &next_key) == 0) { if (bpf_map_lookup_elem(syscall_counts_map_fd, &next_key, &count_value) == 0) { stats[stat_count].id = next_key; stats[stat_count].count = count_value; if (syscall_errors_map_fd >= 0 && bpf_map_lookup_elem(syscall_errors_map_fd, &next_key, &error_value) == 0) { stats[stat_count].errors = error_value; } else { stats[stat_count].errors = 0; } if (syscall_latency_map_fd >= 0 && bpf_map_lookup_elem(syscall_latency_map_fd, &next_key, &latency_value) == 0) { stats[stat_count].latency = latency_value; } else { stats[stat_count].latency = 0; } stat_count++; } key = next_key; } if (opts.sort_by_count) { for (int i = 0; i < stat_count - 1; i++) { for (int j = 0; j < stat_count - i - 1; j++) { if (stats[j].count < stats[j + 1].count) { __u32 temp_id = stats[j].id; __u64 temp_count = stats[j].count; __u64 temp_errors = stats[j].errors; __u64 temp_latency = stats[j].latency; stats[j].id = stats[j + 1].id; stats[j].count = stats[j + 1].count; stats[j].errors = stats[j + 1].errors; stats[j].latency = stats[j + 1].latency; stats[j + 1].id = temp_id; stats[j + 1].count = temp_count; stats[j + 1].errors = temp_errors; stats[j + 1].latency = temp_latency; } } } } else { for (int i = 0; i < stat_count - 1; i++) { for (int j = 0; j < stat_count - i - 1; j++) { if (stats[j].id > stats[j + 1].id) { __u32 temp_id = stats[j].id; __u64 temp_count = stats[j].count; __u64 temp_errors = stats[j].errors; __u64 temp_latency = stats[j].latency; stats[j].id = stats[j + 1].id; stats[j].count = stats[j + 1].count; stats[j].errors = stats[j + 1].errors; stats[j].latency = stats[j + 1].latency; stats[j + 1].id = temp_id; stats[j + 1].count = temp_count; stats[j + 1].errors = temp_errors; stats[j + 1].latency = temp_latency; } } } } int display_count = stat_count; if (opts.top_n > 0 && opts.top_n < stat_count) { display_count = opts.top_n; } for (int i = 0; i < display_count; i++) { const char *name; if (stats[i].id < MAX_SYSCALL_ID) { name = syscall_names[stats[i].id]; } else { name = "unknown"; } if (opts.timestamp) { printf("%-8ld ", time(NULL) - start_time); } switch (opts.type) { case COUNT_ONLY: printf("%-20s %-10llu\n", name, stats[i].count); break; case SHOW_ERRORS: printf("%-20s %-10llu %-10llu\n", name, stats[i].count, stats[i].errors); break; case SHOW_LATENCY: { double avg_us = 0; if (stats[i].count > 0) { avg_us = (double)stats[i].latency / stats[i].count / 1000.0; // ns to us } printf("%-20s %-10llu %-15.2f\n", name, stats[i].count, avg_us); break; } case SHOW_BOTH: { double avg_us = 0; if (stats[i].count > 0) { avg_us = (double)stats[i].latency / stats[i].count / 1000.0; // ns to us } printf("%-20s %-10llu %-10llu %-15.2f\n", name, stats[i].count, stats[i].errors, avg_us); break; } } } __u64 total_count = 0, total_errors = 0, total_latency = 0; for (int i = 0; i < stat_count; i++) { total_count += stats[i].count; total_errors += stats[i].errors; total_latency += stats[i].latency; } if (opts.timestamp) { printf("%-8ld ", time(NULL) - start_time); } switch (opts.type) { case COUNT_ONLY: printf("%-20s %-10llu\n", "TOTAL", total_count); break; case SHOW_ERRORS: printf("%-20s %-10llu %-10llu\n", "TOTAL", total_count, total_errors); break; case SHOW_LATENCY: { double avg_us = 0; if (total_count > 0) { avg_us = (double)total_latency / total_count / 1000.0; // ns to us } printf("%-20s %-10llu %-15.2f\n", "TOTAL", total_count, avg_us); break; } case SHOW_BOTH: { double avg_us = 0; if (total_count > 0) { avg_us = (double)total_latency / total_count / 1000.0; // ns to us } printf("%-20s %-10llu %-10llu %-15.2f\n", "TOTAL", total_count, total_errors, avg_us); break; } } printf("\n"); } cleanup: printf("\nDetaching programs\n"); for (int i = 0; i < link_count; i++) { bpf_link__destroy(links[i]); } free(links); return err; } ================================================ FILE: samples/syscount/meson.build ================================================ build_dir = run_command( realpath, '--relative-to', meson.current_source_dir(), meson.current_build_dir(), capture: true, check: true ).stdout().strip() env = environment() env.prepend('PATH', rust_bin) env.set('LINUX_OBJ', kbuild_dir) env.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux')) env.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target')) syscount_clippy = custom_target( 'syscount-clippy', output: ['target'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'clippy', '-qr' ], env: env, console: false, build_by_default: true ) syscount_build = custom_target( 'syscount-build', output: ['syscount'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'rustc', '-qr', '--', '-Cenable_rex' ], depends: syscount_clippy, env: env, console: false, build_by_default: true ) syscount_loader = executable( 'loader', 'loader.c', build_by_default: true, dependencies: [librex_dep, libbpf_dep, kernel_dep], pie: true ) ================================================ FILE: samples/syscount/rustfmt.toml ================================================ max_width = 80 binop_separator = "Back" reorder_impl_items = true wrap_comments = true imports_granularity = "Module" group_imports = "StdExternalCrate" ================================================ FILE: samples/syscount/src/main.rs ================================================ #![no_std] #![no_main] extern crate rex; use rex::linux::bpf::BPF_ANY; use rex::map::RexHashMap; use rex::tracepoint::*; use rex::{Result, rex_map, rex_tracepoint}; #[rex_map] static SYSCALL_COUNTS: RexHashMap = RexHashMap::new(512, 0); #[rex_map] static SYSCALL_ERRORS: RexHashMap = RexHashMap::new(512, 0); #[rex_map] static SYSCALL_START: RexHashMap = RexHashMap::new(1024, 0); #[rex_map] static SYSCALL_LATENCY: RexHashMap = RexHashMap::new(512, 0); // Tracepoint handler for raw_syscalls:sys_enter #[rex_tracepoint] fn trace_syscall_enter( obj: &tracepoint, ctx: &'static RawSyscallsEnterCtx, ) -> Result { let syscall_id = ctx.id as u32; match obj.bpf_map_lookup_elem(&SYSCALL_COUNTS, &syscall_id) { Some(count) => { *count += 1; } None => { obj.bpf_map_update_elem( &SYSCALL_COUNTS, &syscall_id, &1, BPF_ANY as u64, )?; } } if let Some(task) = obj.bpf_get_current_task() { let pid_tgid = ((task.get_tgid() as u64) << 32) | (task.get_pid() as u64); let key = (syscall_id as u64) | (pid_tgid << 32); let start_time = obj.bpf_ktime_get_ns(); obj.bpf_map_update_elem( &SYSCALL_START, &key, &start_time, BPF_ANY as u64, )?; } Ok(0) } // Tracepoint handler for raw_syscalls:sys_exit #[rex_tracepoint] fn trace_syscall_exit( obj: &tracepoint, ctx: &'static RawSyscallsExitCtx, ) -> Result { let syscall_id = ctx.id as u32; let ret = ctx.ret; if ret < 0 { match obj.bpf_map_lookup_elem(&SYSCALL_ERRORS, &syscall_id) { Some(count) => { *count += 1; } None => { obj.bpf_map_update_elem( &SYSCALL_ERRORS, &syscall_id, &1, BPF_ANY as u64, )?; } } } if let Some(task) = obj.bpf_get_current_task() { let pid_tgid = ((task.get_tgid() as u64) << 32) | (task.get_pid() as u64); let key = (syscall_id as u64) | (pid_tgid << 32); if let Some(start_time) = obj.bpf_map_lookup_elem(&SYSCALL_START, &key) { let now = obj.bpf_ktime_get_ns(); let delta = now - *start_time; match obj.bpf_map_lookup_elem(&SYSCALL_LATENCY, &syscall_id) { Some(total) => { *total += delta; } None => { obj.bpf_map_update_elem( &SYSCALL_LATENCY, &syscall_id, &delta, BPF_ANY as u64, )?; } } obj.bpf_map_delete_elem(&SYSCALL_START, &key)?; } } Ok(0) } ================================================ FILE: samples/xdp_test/.cargo/config.toml ================================================ [build] target = "x86_64-unknown-none" [target.x86_64-unknown-none] linker = "ld.mold" rustflags = [ "-Zthreads=8", "-Cforce-frame-pointers=y", "-Csymbol-mangling-version=v0", "-Ccodegen-units=1", "-Crelocation-model=pie", "-Crelro-level=full", ] [unstable] build-std = ["core"] ================================================ FILE: samples/xdp_test/Cargo.toml ================================================ [package] name = "xdp_test" version = "0.1.0" edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] [dependencies.rex] path = "../../rex" [lints.clippy] disallowed_methods = "forbid" disallowed_types = "forbid" [lints.rust] incomplete_features = "forbid" internal_features = "forbid" unsafe_code = "forbid" unstable_features = "forbid" [profile.dev] panic = "abort" debug = false [profile.release] panic = "abort" debug = false lto = true ================================================ FILE: samples/xdp_test/README.md ================================================
# Onboarding Task: Rust-based extensions **Note: You need to be on the x86-64 architecture in order to work on this MP. We assume the x86-64 architecture and ABI in this writeup.** **Note2: If you are using aarch64 architecture, you will need to find another x86-64 computer or run this project in emulation** **Please make sure you read through this document at least once before starting.** # Table of Contents - [Introduction](#introduction) - [Problem Description](#problem-description) - [eBPF XDP Program](#ebpf-xdp-program) - [Implementation Overview](#implementation-overview) - [Understand the rex repo structure](#understand-the-rex-repo-structure) - [Try out the rex xdp sample.](#try-out-the-rex-xdp-sample) - [Make the rex version program](#make-the-rex-version-program) - [Other Requirements](#other-requirements) - [Resources](#resources) # Introduction The emergence of verified eBPF bytecode is ushering in a new era of safe kernel extensions. In this paper, we argue that eBPF’s verifier—the source of its safety guarantees—has become a liability. In addition to the well-known bugs and vulnerabilities stemming from the complexity and ad hoc nature of the in-kernel verifier, we highlight a concerning trend in which escape hatches to unsafe kernel functions (in the form of helper functions) are being introduced to bypass verifier-imposed limitations on expressiveness, unfortunately also bypassing its safety guarantees. We propose safe kernel extension frameworks using a balance of not just static but also lightweight runtime techniques. We describe a design centered around kernel extensions in safe Rust that will eliminate the need of the in-kernel verifier, improve expressiveness, allow for reduced escape hatches, and ultimately improve the safety of kernel extensions. The basic ideas are documented in [a workshop paper](../../docs/rust-kernel-ext.pdf) (no need to read through). # Problem Description Your task is to implement an rex program in Rust, equivalent to an eBPF version. This is conceptually straightforward. However, the real challenge lies in mastering rex operations and integrating them with your knowledge of Linux kernel programming, Rust programming, and other essential aspects like ELF (Executable and Linkable Format). This task will test your technical skills and ability to quickly adapt to new programming environments. To implement a packet filtering mechanism using both eBPF and an rex program, your objective is to drop incoming network traffic based on predefined rules for port numbers and protocol types (TCP or UDP). The steps you need to follow are: 1. Write an eBPF program that employs the XDP hook to inspect and potentially drop packets at an early stage in the networking stack. 2. Create a user-space application that interacts with the eBPF program, particularly focusing on updating the rules for packet filtering (such as which ports to block). 3. Develop an rex program that similarly inspects traffic and creates a user-space application for updating the rules for packet filtering. ![xdp_image](../../docs/image/xdp-attach-point.png) ## eBPF XDP Program The eBPF program will be attached to the XDP hook in the Linux kernel. XDP provides high-performance packet processing at the earliest point where a packet is received by the network driver. The eBPF XDP program will: 1. Inspect each incoming packet's header to determine the port number and protocol (TCP/UDP). 2. Check against a set of rules defined in a BPF map (a key-value store used by eBPF programs for storing runtime data). 3. Decide whether to drop the packet or allow it to pass based on these rules. # Implementation Overview ## Understand the rex repo structure The repository contains the following directories: - `librex`: This is the equivalent of `libbpf` for rex programs. You should not modify any files in this directory. - `rex`: This is the runtime crate for rex programs and contains the program type and helper function definitions. - You will need to add helper functions to `src/xdp/xdp_impl.rs` but should avoid changing any other files. - `xdp_test`: This is the directory of the program you need to implement. - Specifically, you should place the rex program code in `src/main.rs` and the loader code in `entry.c`. ## Utilize Nix For this task, we encourage to utilize the support of Nix. Using Nix, a package manager, could allow you to bypass the dependency requirements. You can find the installation steps [here](../../README.org#nix-flake) All subsequent steps should be carried out within this shell. ## Make the rex version program ```bash # assume you are in the rex-kernel cd xdp_test # compile the xdp program make # bind xdp program to interface lo ./entry 1 ``` 1. We have provided you with the `samples/xdp_test` directory for the rex version of the XDP program. The function `ip_header` in the `rex/src/xdp/xdp_impl.rs` file is used to parse the IP header from a packet. It is used: `let ip_header = obj.ip_header(ctx);` in `samples/xdp_test/src/main.rs`. 2. For loader implementation: - One hint is that `rex_obj_load` and `rex_obj_get_bpf` should be used for loading and manipulating rex programs. ```c // load rex obj obj = rex_obj_get_bpf(rex_obj_load(EXE)); ``` - You need to add additional parameter processing for adding rules, besides the existing binding interface part. Implement the new action `./entry add_rule ` to add rules to the eBPF map. Adding rules for removal is optional. 3. You can refer to the `samples/map_test` folder to see how to use the map in Rust. ## Test your implementation 1. To test your implementation, you can use netcat(nc), a utility tool that uses TCP/UDP connections to read/write into the network. 2. On server: nc -l -p port_number (Start a listener at port_number) 3. On client: nc 127.0.0.1 port_number (Starts a client) 4. Note: The above netcat commands are for a TCP connection, for UDP connection, "-u" command needs to be added on both server and client. 5. The logs of bpf_printk, can be found at "/sys/kernel/debug/tracing/trace_pipe" 6. You can update the map using bpftool: bpftool map update id 1 key hex 35 00 00 00 value hex 01 00 (Update map with id 1 with hex a value b) # Other Requirements - Do not change any other files except the files mentioned above. - Your Rust code should not have any `unsafe` block in the rex program, but can have `unsafe` blocks in the `rex` crate. - You should not use any other extern crates (i.e. Rust packages) other than the provided `rex`. - You cannot use the Rust `std` library because it is not available in standalong mode, but the `core` library remains largely available. - This research is currently not available to the public. So please do not put the rex code on GPT. # Resources We recommend you to get your hands dirty directly and check these resources on demand. In fact, we didn’t know Rust well when we started this project – you can always learn a language by writing the code. - eBPF: [ebpf.io](https://ebpf.io/) and [The Illustrated Children’s Guide to eBPF](https://ebpf.io/books/buzzing-across-space-illustrated-childrens-guide-to-ebpf.pdf) and [xdp-tutorial](https://github.com/xdp-project/xdp-tutorial) both are good places to start. You can also find the official kernel documentation [here](https://elixir.bootlin.com/linux/v5.15.127/source/Documentation/bpf) along with the source code. In particular, try answering: - What is eBPF? - What is XDP? - What are some example use cases of eBPF? - How are eBPF programs loaded to the kernel and bind XDP program to interfaces? - How are the execution of eBPF programs triggered? - What are eBPF helpers? - Rust: If you are not familiar with the Rust program language, we have some resources for you: - [The Rust book](https://doc.rust-lang.org/book/) (Probably the most comprehensive guide on Rust programming) - [Library API reference](https://doc.rust-lang.org/std/index.html) (for searching API specifications) - [The Rust playground](https://play.rust-lang.org) (for trying out programs)
================================================ FILE: samples/xdp_test/clippy.toml ================================================ disallowed-methods = [ "core::mem::forget", ] disallowed-types = [ "core::mem::ManuallyDrop", ] ================================================ FILE: samples/xdp_test/entry.c ================================================ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define BPF_SYSFS_ROOT "/sys/fs/bpf" #define EXE "./target/x86_64-unknown-none/release/xdp_test" static int nr_cpus = 0; struct bpf_progs_desc { char name[256]; enum bpf_prog_type type; unsigned char pin; int map_prog_idx; struct bpf_program *prog; }; ; int main(int argc, char *argv[]) { struct rlimit r = { RLIM_INFINITY, RLIM_INFINITY }; int xdp_main_prog_fd; struct bpf_program *rx_prog, *tx_prog; struct bpf_object *obj; char filename[PATH_MAX]; int err; __u32 xdp_flags = 0; int *interfaces_idx; int ret = 0; int interface_count = 0; int sig, quit = 0; interface_count = argc - optind; if (interface_count <= 0) { fprintf(stderr, "Missing at least one required interface index\n"); exit(EXIT_FAILURE); } interfaces_idx = calloc(sizeof(int), interface_count); if (interfaces_idx == NULL) { fprintf(stderr, "Error: failed to allocate memory\n"); return 1; } for (int i = 0; i < interface_count && optind < argc; optind++, i++) { interfaces_idx[i] = atoi(argv[optind]); } nr_cpus = libbpf_num_possible_cpus(); sigset_t signal_mask; sigemptyset(&signal_mask); sigaddset(&signal_mask, SIGINT); sigaddset(&signal_mask, SIGTERM); sigaddset(&signal_mask, SIGUSR1); if (setrlimit(RLIMIT_MEMLOCK, &r)) { perror("setrlimit failed"); return 1; } // load rex obj obj = rex_obj_get_bpf(rex_obj_load(EXE)); if (!obj) { fprintf(stderr, "Object could not be opened\n"); return 1; } rx_prog = bpf_object__find_program_by_name(obj, "xdp_rx_filter"); if (!rx_prog) { fprintf(stderr, "start not found\n"); return 1; } xdp_main_prog_fd = bpf_program__fd(rx_prog); if (xdp_main_prog_fd < 0) { fprintf(stderr, "Error: bpf_program__fd failed\n"); return 1; } // Some nics do not support XDP DRV mode // xdp_flags |= XDP_FLAGS_DRV_MODE; xdp_flags |= XDP_FLAGS_SKB_MODE; for (int i = 0; i < interface_count; i++) { if (bpf_xdp_attach(interfaces_idx[i], xdp_main_prog_fd, xdp_flags, NULL) < 0) { fprintf(stderr, "Error: bpf_set_link_xdp_fd failed for interface %d\n", interfaces_idx[i]); return 1; } else { printf("Main BPF program attached to XDP on interface %d\n", interfaces_idx[i]); } } // binding sched_cls program char prog_name[256] = "xdp_tx_filter"; tx_prog = bpf_object__find_program_by_name(obj, prog_name); if (!tx_prog) { fprintf(stderr, "tx_prog not found\n"); exit(1); } printf("tx_prog: %s\n", bpf_program__name(tx_prog)); int len = snprintf(filename, PATH_MAX, "%s/%s", BPF_SYSFS_ROOT, prog_name); if (len < 0) { fprintf(stderr, "Error: Program name '%s' is invalid\n", "xdp_tx_filter"); return -1; } else if (len >= PATH_MAX) { fprintf(stderr, "Error: Program name '%s' is too long\n", prog_name); return -1; } ret = bpf_program__pin(tx_prog, filename); if (ret != 0) { fprintf(stderr, "Error: Failed to pin program '%s' to path %s with error code %d\n", prog_name, filename, ret); return ret; } err = sigprocmask(SIG_BLOCK, &signal_mask, NULL); if (err != 0) { fprintf(stderr, "Error: Failed to set signal mask\n"); exit(EXIT_FAILURE); } while (!quit) { err = sigwait(&signal_mask, &sig); if (err != 0) { fprintf(stderr, "Error: Failed to wait for signal\n"); exit(EXIT_FAILURE); } switch (sig) { case SIGINT: case SIGTERM: case SIGUSR1: quit = 1; break; default: fprintf(stderr, "Unknown signal\n"); break; } } // unattach program for (int i = 0; i < interface_count; i++) bpf_xdp_detach(interfaces_idx[i], xdp_flags, NULL); return ret; } ================================================ FILE: samples/xdp_test/meson.build ================================================ build_dir = run_command( realpath, '--relative-to', meson.current_source_dir(), meson.current_build_dir(), capture: true, check: true ).stdout().strip() env = environment() env.prepend('PATH', rust_bin) env.set('LINUX_OBJ', kbuild_dir) env.set('LINUX_SRC', join_paths(meson.project_source_root(), './linux')) env.set('CARGO_TARGET_DIR', join_paths(build_dir, 'target')) sample_clippy = custom_target( 'xdp_test-clippy', output: ['target'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'clippy', '-qr' ], env: env, console: false, build_by_default: true ) sample_build = custom_target( 'xdp_test-build', output: ['xdp_test'], command: [ cargo_wrapper, rust_bin, '-Z', 'unstable-options', '-C', meson.current_source_dir(), 'rustc', '-qr', '--', '-Cenable_rex' ], depends: sample_clippy, env: env, console: false, build_by_default: true ) xdp_test_entry = executable( 'entry', 'entry.c', build_by_default: true, dependencies: [librex_dep, libbpf_dep, kernel_dep], pie: true ) sanity_test = custom_target( 'sanity_test', output: ['runtest.py'], input: join_paths(meson.current_source_dir(), 'tests/runtest.py'), command: [ 'cp', '@INPUT@', '@OUTPUT@', ] ) runtest_deps += [sample_build, xdp_test_entry, sanity_test] sanity_test_env = environment() sanity_test_env.set('SAMPLE_PATH', meson.current_build_dir()) sanity_test_env.set('Q_SCRIPT', join_paths(meson.project_source_root(), 'scripts/q-script/sanity-test-q') ) sanity_test_env.set('KERNEL_PATH', kbuild_dir) test('xdp_test_test', python3_bin, args: [sanity_test_scripts], env: sanity_test_env, depends: runtest_deps, is_parallel: false, workdir: meson.current_build_dir() ) ================================================ FILE: samples/xdp_test/rustfmt.toml ================================================ max_width = 80 binop_separator = "Back" reorder_impl_items = true wrap_comments = true imports_granularity = "Module" group_imports = "StdExternalCrate" ================================================ FILE: samples/xdp_test/src/main.rs ================================================ #![no_std] #![no_main] #![allow(non_camel_case_types)] extern crate rex; use core::net::Ipv4Addr; use rex::sched_cls::*; use rex::utils::*; use rex::xdp::*; use rex::{rex_printk, rex_tc, rex_xdp}; #[rex_xdp] fn xdp_rx_filter(obj: &xdp, ctx: &mut xdp_md) -> Result { let mut ip_header = obj.ip_header(ctx); rex_printk!("IP saddr {}\n", Ipv4Addr::from_bits(*ip_header.saddr()))?; rex_printk!("IP daddr {}\n", Ipv4Addr::from_bits(*ip_header.daddr()))?; match u8::from_be(ip_header.protocol) as u32 { IPPROTO_TCP => { rex_printk!("TCP packet!")?; } IPPROTO_UDP => { rex_printk!("UDP packet!")?; } _ => {} }; Ok(XDP_PASS as i32) } #[rex_tc] fn xdp_tx_filter(obj: &sched_cls, skb: &mut __sk_buff) -> Result { let mut ip_header = obj.ip_header(skb); rex_printk!("IP saddr {}\n", Ipv4Addr::from_bits(*ip_header.saddr()))?; rex_printk!("IP daddr {}\n", Ipv4Addr::from_bits(*ip_header.daddr()))?; if u8::from_be(ip_header.protocol) as u32 == IPPROTO_UDP { return rex_printk!("UDP packet!"); } Ok(TC_ACT_OK as i32) } ================================================ FILE: samples/xdp_test/tests/runtest.py ================================================ #!/usr/bin/env python3 import socket import subprocess import sys import threading import time from pathlib import Path def count_bpf_programs(): """Count currently loaded BPF programs""" try: result = subprocess.run( "bpftool prog show", capture_output=True, shell=True, text=True, ) if result.stdout: output = result.stdout.strip().split("\n") programs = [line for line in output if "name" in line] return len(programs) else: return 0 except FileNotFoundError: print("bpftool is not installed or not found in the PATH.") return 0 except Exception as e: print(f"An error occurred: {e}") return 0 def generate_traffic(): """Generate some network traffic on loopback to trigger XDP program""" try: # Create a UDP socket and send data to localhost sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(b"test packet", ("127.0.0.1", 12345)) sock.close() # TCP attempt sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1) try: sock.connect(("127.0.0.1", 12346)) except (socket.error, ConnectionRefusedError): pass # Connection will likely fail, but that's okay sock.close() time.sleep(0.1) # Small delay to ensure packets are processed except Exception as e: print(f"Error generating traffic: {e}") raise e def get_trace_log(): """Monitor trace logs for XDP activity""" xdp_activity = [] keywords = ("IP saddr", "IP daddr", "TCP packet", "UDP packet") try: with open("/sys/kernel/debug/tracing/trace", "r") as f: for line in f: if any(k in line for k in keywords): s = line.rstrip("\n") xdp_activity.append(s) print(f"XDP trace: {s}") except Exception as e: print(f"Error reading trace logs: {e}") return xdp_activity def test_xdp_program(): """Main test function for XDP program""" print("Starting XDP program sanity test in QEMU environment...") # Check if we're in the right directory if not Path("./entry").exists(): print("Error: entry executable not found. Checking current directory...") print(f"Current directory: {Path.cwd()}") print(f"Directory contents: {list(Path('.').iterdir())}") return False # Count programs before old_prog_count = count_bpf_programs() print(f"BPF programs before: {old_prog_count}") # Start XDP program in background print("Starting XDP program on loopback interface...") xdp_process = None try: xdp_process = subprocess.Popen( ["./entry", "1"], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) print(f"XDP process started with PID: {xdp_process.pid}") # Wait for program to load time.sleep(3) # Check if new programs were loaded new_prog_count = count_bpf_programs() print(f"BPF programs after: {new_prog_count}") if new_prog_count <= old_prog_count: print("Warning: No new BPF programs detected") # Generate traffic to trigger XDP print("Generating test traffic...") for i in range(10): generate_traffic() time.sleep(0.3) if i % 3 == 0: print(f"Generated {i+1} traffic bursts...") # Wait a bit more for logs to appear time.sleep(2) # Start get trace logs print("Starting trace log retrieving...") xdp_activity = get_trace_log() # Check results program_loaded = new_prog_count > old_prog_count has_activity = len(xdp_activity) > 0 print(f"Program loaded: {program_loaded}") print(f"XDP activity detected: {has_activity}") print(f"Total XDP log entries: {len(xdp_activity)}") if has_activity: print("SUCCESS: XDP program is processing packets") return True else: print("FAILURE: XDP program did not load or show activity") return False except Exception as e: print(f"Error during test: {e}") return False finally: # Clean up print("Cleaning up...") if xdp_process: try: # Send SIGTERM first xdp_process.terminate() xdp_process.wait(timeout=3) print("XDP process terminated gracefully") except subprocess.TimeoutExpired: # Force kill if it doesn't respond xdp_process.kill() print("XDP process force killed") except Exception as e: print(f"Error during cleanup: {e}") def main(): """Main function""" success = test_xdp_program() # Write result to grade file with open("auto_grade.txt", "w") as f: f.write("success" if success else "fail") print(f"\nXDP program sanity test {'PASSED' if success else 'FAILED'}") return 0 if success else 1 if __name__ == "__main__": sys.exit(main()) ================================================ FILE: scripts/cargo-wrapper.pl ================================================ #!/usr/bin/env perl use strict; use warnings; my ($build_dir, @cmd) = @ARGV; my $cargo_bin = "$build_dir/cargo"; exec($cargo_bin, @cmd); ================================================ FILE: scripts/q-script/.config ================================================ # # Automatically generated file; DO NOT EDIT. # Linux/x86 6.19.0 Kernel Configuration # CONFIG_CC_VERSION_TEXT="clang version 21.1.8" CONFIG_GCC_VERSION=0 CONFIG_CC_IS_CLANG=y CONFIG_CLANG_VERSION=210108 CONFIG_AS_IS_LLVM=y CONFIG_AS_VERSION=210108 CONFIG_LD_VERSION=0 CONFIG_LD_IS_LLD=y CONFIG_LLD_VERSION=210108 CONFIG_RUSTC_VERSION=109301 CONFIG_RUST_IS_AVAILABLE=y CONFIG_RUSTC_LLVM_VERSION=210108 CONFIG_CC_CAN_LINK=y CONFIG_CC_HAS_ASM_GOTO_OUTPUT=y CONFIG_CC_HAS_ASM_GOTO_TIED_OUTPUT=y CONFIG_TOOLS_SUPPORT_RELR=y CONFIG_CC_HAS_ASM_INLINE=y CONFIG_CC_HAS_ASSUME=y CONFIG_CC_HAS_NO_PROFILE_FN_ATTR=y CONFIG_CC_HAS_COUNTED_BY=y CONFIG_CC_HAS_MULTIDIMENSIONAL_NONSTRING=y CONFIG_LD_CAN_USE_KEEP_IN_OVERLAY=y CONFIG_RUSTC_HAS_SLICE_AS_FLATTENED=y CONFIG_RUSTC_HAS_COERCE_POINTEE=y CONFIG_RUSTC_HAS_SPAN_FILE=y CONFIG_RUSTC_HAS_UNNECESSARY_TRANSMUTES=y CONFIG_RUSTC_HAS_FILE_WITH_NUL=y CONFIG_RUSTC_HAS_FILE_AS_C_STR=y CONFIG_PAHOLE_VERSION=130 CONFIG_IRQ_WORK=y CONFIG_BUILDTIME_TABLE_SORT=y CONFIG_THREAD_INFO_IN_TASK=y # # General setup # CONFIG_INIT_ENV_ARG_LIMIT=32 # CONFIG_COMPILE_TEST is not set # CONFIG_WERROR is not set # CONFIG_UAPI_HEADER_TEST is not set CONFIG_LOCALVERSION="-rex" # CONFIG_LOCALVERSION_AUTO is not set CONFIG_BUILD_SALT="" CONFIG_HAVE_KERNEL_GZIP=y CONFIG_HAVE_KERNEL_BZIP2=y CONFIG_HAVE_KERNEL_LZMA=y CONFIG_HAVE_KERNEL_XZ=y CONFIG_HAVE_KERNEL_LZO=y CONFIG_HAVE_KERNEL_LZ4=y CONFIG_HAVE_KERNEL_ZSTD=y # CONFIG_KERNEL_GZIP is not set # CONFIG_KERNEL_BZIP2 is not set # CONFIG_KERNEL_LZMA is not set # CONFIG_KERNEL_XZ is not set # CONFIG_KERNEL_LZO is not set # CONFIG_KERNEL_LZ4 is not set CONFIG_KERNEL_ZSTD=y CONFIG_DEFAULT_INIT="" CONFIG_DEFAULT_HOSTNAME="(none)" CONFIG_SYSVIPC=y CONFIG_SYSVIPC_SYSCTL=y CONFIG_POSIX_MQUEUE=y CONFIG_POSIX_MQUEUE_SYSCTL=y # CONFIG_WATCH_QUEUE is not set CONFIG_CROSS_MEMORY_ATTACH=y CONFIG_AUDIT=y CONFIG_HAVE_ARCH_AUDITSYSCALL=y CONFIG_AUDITSYSCALL=y # # IRQ subsystem # CONFIG_GENERIC_IRQ_PROBE=y CONFIG_GENERIC_IRQ_SHOW=y CONFIG_GENERIC_IRQ_EFFECTIVE_AFF_MASK=y CONFIG_GENERIC_PENDING_IRQ=y CONFIG_GENERIC_IRQ_MIGRATION=y CONFIG_HARDIRQS_SW_RESEND=y CONFIG_IRQ_DOMAIN=y CONFIG_IRQ_DOMAIN_HIERARCHY=y CONFIG_GENERIC_MSI_IRQ=y CONFIG_GENERIC_IRQ_MATRIX_ALLOCATOR=y CONFIG_GENERIC_IRQ_RESERVATION_MODE=y CONFIG_IRQ_FORCED_THREADING=y CONFIG_SPARSE_IRQ=y # CONFIG_GENERIC_IRQ_DEBUGFS is not set # end of IRQ subsystem CONFIG_CLOCKSOURCE_WATCHDOG=y CONFIG_ARCH_CLOCKSOURCE_INIT=y CONFIG_GENERIC_TIME_VSYSCALL=y CONFIG_GENERIC_CLOCKEVENTS=y CONFIG_GENERIC_CLOCKEVENTS_BROADCAST=y CONFIG_GENERIC_CLOCKEVENTS_BROADCAST_IDLE=y CONFIG_GENERIC_CLOCKEVENTS_MIN_ADJUST=y CONFIG_GENERIC_CMOS_UPDATE=y CONFIG_HAVE_POSIX_CPU_TIMERS_TASK_WORK=y CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y CONFIG_CONTEXT_TRACKING=y CONFIG_CONTEXT_TRACKING_IDLE=y # # Timers subsystem # CONFIG_TICK_ONESHOT=y CONFIG_NO_HZ_COMMON=y # CONFIG_HZ_PERIODIC is not set CONFIG_NO_HZ_IDLE=y # CONFIG_NO_HZ_FULL is not set CONFIG_NO_HZ=y CONFIG_HIGH_RES_TIMERS=y CONFIG_CLOCKSOURCE_WATCHDOG_MAX_SKEW_US=125 # CONFIG_POSIX_AUX_CLOCKS is not set # end of Timers subsystem CONFIG_BPF=y CONFIG_HAVE_EBPF_JIT=y CONFIG_ARCH_WANT_DEFAULT_BPF_JIT=y # # BPF subsystem # CONFIG_BPF_SYSCALL=y CONFIG_BPF_JIT=y CONFIG_BPF_JIT_ALWAYS_ON=y CONFIG_BPF_JIT_DEFAULT_ON=y CONFIG_BPF_UNPRIV_DEFAULT_OFF=y # CONFIG_BPF_PRELOAD is not set CONFIG_BPF_LSM=y # end of BPF subsystem CONFIG_PREEMPT_NONE_BUILD=y CONFIG_ARCH_HAS_PREEMPT_LAZY=y CONFIG_PREEMPT_NONE=y # CONFIG_PREEMPT_VOLUNTARY is not set # CONFIG_PREEMPT is not set # CONFIG_PREEMPT_LAZY is not set # CONFIG_PREEMPT_RT is not set # CONFIG_PREEMPT_DYNAMIC is not set # CONFIG_SCHED_CORE is not set CONFIG_SCHED_CLASS_EXT=y # # CPU/Task time and stats accounting # CONFIG_TICK_CPU_ACCOUNTING=y # CONFIG_VIRT_CPU_ACCOUNTING_GEN is not set # CONFIG_IRQ_TIME_ACCOUNTING is not set CONFIG_BSD_PROCESS_ACCT=y # CONFIG_BSD_PROCESS_ACCT_V3 is not set CONFIG_TASKSTATS=y CONFIG_TASK_DELAY_ACCT=y CONFIG_TASK_XACCT=y CONFIG_TASK_IO_ACCOUNTING=y # CONFIG_PSI is not set # end of CPU/Task time and stats accounting CONFIG_CPU_ISOLATION=y # # RCU Subsystem # CONFIG_TREE_RCU=y # CONFIG_RCU_EXPERT is not set CONFIG_TREE_SRCU=y CONFIG_TASKS_RCU_GENERIC=y CONFIG_NEED_TASKS_RCU=y CONFIG_TASKS_RUDE_RCU=y CONFIG_TASKS_TRACE_RCU=y CONFIG_RCU_STALL_COMMON=y CONFIG_RCU_NEED_SEGCBLIST=y # end of RCU Subsystem # CONFIG_IKCONFIG is not set # CONFIG_IKHEADERS is not set CONFIG_LOG_BUF_SHIFT=18 CONFIG_LOG_CPU_MAX_BUF_SHIFT=12 CONFIG_PRINTK_INDEX=y CONFIG_HAVE_UNSTABLE_SCHED_CLOCK=y # # Scheduler features # # CONFIG_UCLAMP_TASK is not set # end of Scheduler features CONFIG_ARCH_SUPPORTS_NUMA_BALANCING=y CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH=y CONFIG_CC_HAS_INT128=y CONFIG_CC_IMPLICIT_FALLTHROUGH="-Wimplicit-fallthrough" CONFIG_GCC10_NO_ARRAY_BOUNDS=y CONFIG_GCC_NO_STRINGOP_OVERFLOW=y CONFIG_ARCH_SUPPORTS_INT128=y # CONFIG_NUMA_BALANCING is not set CONFIG_SLAB_OBJ_EXT=y CONFIG_CGROUPS=y CONFIG_PAGE_COUNTER=y # CONFIG_CGROUP_FAVOR_DYNMODS is not set CONFIG_MEMCG=y # CONFIG_MEMCG_V1 is not set CONFIG_BLK_CGROUP=y CONFIG_CGROUP_WRITEBACK=y CONFIG_CGROUP_SCHED=y CONFIG_GROUP_SCHED_WEIGHT=y CONFIG_GROUP_SCHED_BANDWIDTH=y CONFIG_FAIR_GROUP_SCHED=y CONFIG_CFS_BANDWIDTH=y # CONFIG_RT_GROUP_SCHED is not set CONFIG_EXT_GROUP_SCHED=y CONFIG_SCHED_MM_CID=y CONFIG_CGROUP_PIDS=y # CONFIG_CGROUP_RDMA is not set # CONFIG_CGROUP_DMEM is not set CONFIG_CGROUP_FREEZER=y CONFIG_CGROUP_HUGETLB=y CONFIG_CPUSETS=y # CONFIG_CPUSETS_V1 is not set CONFIG_CGROUP_DEVICE=y CONFIG_CGROUP_CPUACCT=y CONFIG_CGROUP_PERF=y CONFIG_CGROUP_BPF=y # CONFIG_CGROUP_MISC is not set # CONFIG_CGROUP_DEBUG is not set CONFIG_SOCK_CGROUP_DATA=y CONFIG_NAMESPACES=y CONFIG_UTS_NS=y CONFIG_TIME_NS=y CONFIG_IPC_NS=y CONFIG_USER_NS=y CONFIG_PID_NS=y CONFIG_NET_NS=y # CONFIG_CHECKPOINT_RESTORE is not set # CONFIG_SCHED_AUTOGROUP is not set CONFIG_RELAY=y CONFIG_BLK_DEV_INITRD=y CONFIG_INITRAMFS_SOURCE="" CONFIG_RD_GZIP=y CONFIG_RD_BZIP2=y CONFIG_RD_LZMA=y CONFIG_RD_XZ=y CONFIG_RD_LZO=y CONFIG_RD_LZ4=y CONFIG_RD_ZSTD=y # CONFIG_BOOT_CONFIG is not set CONFIG_CMDLINE_LOG_WRAP_IDEAL_LEN=1021 CONFIG_INITRAMFS_PRESERVE_MTIME=y CONFIG_CC_OPTIMIZE_FOR_PERFORMANCE=y # CONFIG_CC_OPTIMIZE_FOR_SIZE is not set CONFIG_LD_ORPHAN_WARN=y CONFIG_LD_ORPHAN_WARN_LEVEL="warn" CONFIG_SYSCTL=y CONFIG_SYSCTL_EXCEPTION_TRACE=y CONFIG_SYSFS_SYSCALL=y CONFIG_HAVE_PCSPKR_PLATFORM=y CONFIG_EXPERT=y CONFIG_MULTIUSER=y CONFIG_SGETMASK_SYSCALL=y CONFIG_FHANDLE=y CONFIG_POSIX_TIMERS=y CONFIG_PRINTK=y CONFIG_BUG=y CONFIG_ELF_CORE=y CONFIG_PCSPKR_PLATFORM=y # CONFIG_BASE_SMALL is not set CONFIG_FUTEX=y CONFIG_FUTEX_PI=y CONFIG_FUTEX_PRIVATE_HASH=y CONFIG_FUTEX_MPOL=y CONFIG_EPOLL=y CONFIG_SIGNALFD=y CONFIG_TIMERFD=y CONFIG_EVENTFD=y CONFIG_SHMEM=y CONFIG_AIO=y CONFIG_IO_URING=y # CONFIG_IO_URING_MOCK_FILE is not set CONFIG_ADVISE_SYSCALLS=y CONFIG_MEMBARRIER=y CONFIG_KCMP=y CONFIG_RSEQ=y # CONFIG_RSEQ_STATS is not set # CONFIG_RSEQ_DEBUG_DEFAULT_ENABLE is not set CONFIG_CACHESTAT_SYSCALL=y CONFIG_KALLSYMS=y # CONFIG_KALLSYMS_SELFTEST is not set CONFIG_KALLSYMS_ALL=y CONFIG_ARCH_HAS_MEMBARRIER_SYNC_CORE=y CONFIG_ARCH_SUPPORTS_MSEAL_SYSTEM_MAPPINGS=y CONFIG_HAVE_PERF_EVENTS=y # # Kernel Performance Events And Counters # CONFIG_PERF_EVENTS=y # CONFIG_DEBUG_PERF_USE_VMALLOC is not set # end of Kernel Performance Events And Counters CONFIG_SYSTEM_DATA_VERIFICATION=y CONFIG_PROFILING=y CONFIG_TRACEPOINTS=y # # Kexec and crash features # CONFIG_CRASH_RESERVE=y CONFIG_VMCORE_INFO=y CONFIG_KEXEC_CORE=y CONFIG_KEXEC=y # CONFIG_KEXEC_FILE is not set # CONFIG_KEXEC_JUMP is not set CONFIG_CRASH_DUMP=y CONFIG_CRASH_HOTPLUG=y CONFIG_CRASH_MAX_MEMORY_RANGES=8192 # end of Kexec and crash features # # Live Update and Kexec HandOver # # CONFIG_KEXEC_HANDOVER is not set # end of Live Update and Kexec HandOver # end of General setup CONFIG_64BIT=y CONFIG_X86_64=y CONFIG_X86=y CONFIG_INSTRUCTION_DECODER=y CONFIG_OUTPUT_FORMAT="elf64-x86-64" CONFIG_LOCKDEP_SUPPORT=y CONFIG_STACKTRACE_SUPPORT=y CONFIG_MMU=y CONFIG_ARCH_MMAP_RND_BITS_MIN=28 CONFIG_ARCH_MMAP_RND_BITS_MAX=32 CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN=8 CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX=16 CONFIG_GENERIC_ISA_DMA=y CONFIG_GENERIC_BUG=y CONFIG_GENERIC_BUG_RELATIVE_POINTERS=y CONFIG_ARCH_MAY_HAVE_PC_FDC=y CONFIG_GENERIC_CALIBRATE_DELAY=y CONFIG_ARCH_HAS_CPU_RELAX=y CONFIG_ARCH_HIBERNATION_POSSIBLE=y CONFIG_ARCH_SUSPEND_POSSIBLE=y CONFIG_AUDIT_ARCH=y CONFIG_HAVE_INTEL_TXT=y CONFIG_ARCH_SUPPORTS_UPROBES=y CONFIG_FIX_EARLYCON_MEM=y CONFIG_PGTABLE_LEVELS=5 # # Processor type and features # CONFIG_SMP=y # CONFIG_X86_X2APIC is not set CONFIG_X86_MPPARSE=y # CONFIG_X86_CPU_RESCTRL is not set CONFIG_X86_FRED=y CONFIG_X86_EXTENDED_PLATFORM=y # CONFIG_X86_VSMP is not set # CONFIG_X86_INTEL_MID is not set # CONFIG_X86_GOLDFISH is not set CONFIG_X86_INTEL_LPSS=y # CONFIG_X86_AMD_PLATFORM_DEVICE is not set CONFIG_IOSF_MBI=y # CONFIG_IOSF_MBI_DEBUG is not set CONFIG_X86_SUPPORTS_MEMORY_FAILURE=y CONFIG_SCHED_OMIT_FRAME_POINTER=y CONFIG_HYPERVISOR_GUEST=y CONFIG_PARAVIRT=y CONFIG_PARAVIRT_DEBUG=y CONFIG_PARAVIRT_SPINLOCKS=y CONFIG_X86_HV_CALLBACK_VECTOR=y # CONFIG_XEN is not set CONFIG_KVM_GUEST=y CONFIG_ARCH_CPUIDLE_HALTPOLL=y # CONFIG_PVH is not set # CONFIG_PARAVIRT_TIME_ACCOUNTING is not set CONFIG_PARAVIRT_CLOCK=y # CONFIG_JAILHOUSE_GUEST is not set # CONFIG_ACRN_GUEST is not set # CONFIG_BHYVE_GUEST is not set CONFIG_CC_HAS_MARCH_NATIVE=y CONFIG_X86_NATIVE_CPU=y CONFIG_X86_INTERNODE_CACHE_SHIFT=6 CONFIG_X86_L1_CACHE_SHIFT=6 CONFIG_X86_TSC=y CONFIG_X86_HAVE_PAE=y CONFIG_X86_CX8=y CONFIG_X86_CMOV=y CONFIG_X86_MINIMUM_CPU_FAMILY=64 CONFIG_X86_DEBUGCTLMSR=y CONFIG_IA32_FEAT_CTL=y CONFIG_X86_VMX_FEATURE_NAMES=y # CONFIG_PROCESSOR_SELECT is not set CONFIG_BROADCAST_TLB_FLUSH=y CONFIG_CPU_SUP_INTEL=y CONFIG_CPU_SUP_AMD=y CONFIG_CPU_SUP_HYGON=y CONFIG_CPU_SUP_CENTAUR=y CONFIG_CPU_SUP_ZHAOXIN=y CONFIG_HPET_TIMER=y CONFIG_HPET_EMULATE_RTC=y CONFIG_DMI=y # CONFIG_GART_IOMMU is not set CONFIG_BOOT_VESA_SUPPORT=y # CONFIG_MAXSMP is not set CONFIG_NR_CPUS_RANGE_BEGIN=2 CONFIG_NR_CPUS_RANGE_END=512 CONFIG_NR_CPUS_DEFAULT=64 CONFIG_NR_CPUS=64 CONFIG_SCHED_MC_PRIO=y CONFIG_X86_LOCAL_APIC=y CONFIG_ACPI_MADT_WAKEUP=y CONFIG_X86_IO_APIC=y CONFIG_X86_REROUTE_FOR_BROKEN_BOOT_IRQS=y CONFIG_X86_MCE=y # CONFIG_X86_MCELOG_LEGACY is not set CONFIG_X86_MCE_INTEL=y CONFIG_X86_MCE_AMD=y CONFIG_X86_MCE_THRESHOLD=y # CONFIG_X86_MCE_INJECT is not set # # Performance monitoring # CONFIG_PERF_EVENTS_INTEL_UNCORE=y CONFIG_PERF_EVENTS_INTEL_RAPL=y CONFIG_PERF_EVENTS_INTEL_CSTATE=y # CONFIG_PERF_EVENTS_AMD_POWER is not set CONFIG_PERF_EVENTS_AMD_UNCORE=y # CONFIG_PERF_EVENTS_AMD_BRS is not set # end of Performance monitoring CONFIG_X86_16BIT=y CONFIG_X86_ESPFIX64=y CONFIG_X86_VSYSCALL_EMULATION=y CONFIG_X86_IOPL_IOPERM=y CONFIG_MICROCODE=y # CONFIG_MICROCODE_LATE_LOADING is not set # CONFIG_MICROCODE_DBG is not set CONFIG_X86_MSR=y CONFIG_X86_CPUID=y CONFIG_X86_DIRECT_GBPAGES=y # CONFIG_X86_CPA_STATISTICS is not set CONFIG_NUMA=y CONFIG_AMD_NUMA=y CONFIG_X86_64_ACPI_NUMA=y CONFIG_NODES_SHIFT=6 CONFIG_ARCH_SPARSEMEM_ENABLE=y CONFIG_ARCH_SPARSEMEM_DEFAULT=y CONFIG_ARCH_PROC_KCORE_TEXT=y CONFIG_ILLEGAL_POINTER_VALUE=0xdead000000000000 # CONFIG_X86_PMEM_LEGACY is not set CONFIG_X86_CHECK_BIOS_CORRUPTION=y CONFIG_X86_BOOTPARAM_MEMORY_CORRUPTION_CHECK=y CONFIG_MTRR=y # CONFIG_MTRR_SANITIZER is not set CONFIG_X86_PAT=y CONFIG_X86_UMIP=y CONFIG_CC_HAS_IBT=y # CONFIG_X86_KERNEL_IBT is not set CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS=y CONFIG_ARCH_PKEY_BITS=4 CONFIG_X86_INTEL_TSX_MODE_OFF=y # CONFIG_X86_INTEL_TSX_MODE_ON is not set # CONFIG_X86_INTEL_TSX_MODE_AUTO is not set # CONFIG_X86_USER_SHADOW_STACK is not set CONFIG_EFI=y # CONFIG_EFI_STUB is not set CONFIG_EFI_RUNTIME_MAP=y # CONFIG_HZ_100 is not set # CONFIG_HZ_250 is not set # CONFIG_HZ_300 is not set CONFIG_HZ_1000=y CONFIG_HZ=1000 CONFIG_SCHED_HRTICK=y CONFIG_ARCH_SUPPORTS_KEXEC=y CONFIG_ARCH_SUPPORTS_KEXEC_FILE=y CONFIG_ARCH_SUPPORTS_KEXEC_PURGATORY=y CONFIG_ARCH_SUPPORTS_KEXEC_SIG=y CONFIG_ARCH_SUPPORTS_KEXEC_SIG_FORCE=y CONFIG_ARCH_SUPPORTS_KEXEC_BZIMAGE_VERIFY_SIG=y CONFIG_ARCH_SUPPORTS_KEXEC_JUMP=y CONFIG_ARCH_SUPPORTS_KEXEC_HANDOVER=y CONFIG_ARCH_SUPPORTS_CRASH_DUMP=y CONFIG_ARCH_DEFAULT_CRASH_DUMP=y CONFIG_ARCH_SUPPORTS_CRASH_HOTPLUG=y CONFIG_ARCH_HAS_GENERIC_CRASHKERNEL_RESERVATION=y CONFIG_PHYSICAL_START=0x1000000 CONFIG_RELOCATABLE=y # CONFIG_RANDOMIZE_BASE is not set CONFIG_PHYSICAL_ALIGN=0x200000 # CONFIG_ADDRESS_MASKING is not set CONFIG_HOTPLUG_CPU=y CONFIG_LEGACY_VSYSCALL_XONLY=y # CONFIG_LEGACY_VSYSCALL_NONE is not set # CONFIG_CMDLINE_BOOL is not set CONFIG_MODIFY_LDT_SYSCALL=y # CONFIG_STRICT_SIGALTSTACK_SIZE is not set CONFIG_HAVE_LIVEPATCH=y # CONFIG_LIVEPATCH is not set CONFIG_HAVE_KLP_BUILD=y CONFIG_X86_BUS_LOCK_DETECT=y # end of Processor type and features CONFIG_CC_HAS_NAMED_AS_FIXED_SANITIZERS=y CONFIG_CC_HAS_SLS=y CONFIG_CC_HAS_RETURN_THUNK=y CONFIG_CC_HAS_ENTRY_PADDING=y CONFIG_CC_HAS_KCFI_ARITY=y CONFIG_FUNCTION_PADDING_CFI=11 CONFIG_FUNCTION_PADDING_BYTES=11 # CONFIG_CPU_MITIGATIONS is not set CONFIG_ARCH_HAS_ADD_PAGES=y # # Power management and ACPI options # CONFIG_ARCH_HIBERNATION_HEADER=y CONFIG_SUSPEND=y CONFIG_SUSPEND_FREEZER=y # CONFIG_SUSPEND_SKIP_SYNC is not set CONFIG_HIBERNATE_CALLBACKS=y CONFIG_HIBERNATION=y CONFIG_HIBERNATION_SNAPSHOT_DEV=y CONFIG_HIBERNATION_COMP_LZO=y CONFIG_HIBERNATION_DEF_COMP="lzo" CONFIG_PM_STD_PARTITION="" CONFIG_PM_SLEEP=y CONFIG_PM_SLEEP_SMP=y # CONFIG_PM_AUTOSLEEP is not set # CONFIG_PM_USERSPACE_AUTOSLEEP is not set # CONFIG_PM_WAKELOCKS is not set # CONFIG_PM_QOS_CPU_SYSTEM_WAKEUP is not set CONFIG_PM=y CONFIG_PM_DEBUG=y # CONFIG_PM_ADVANCED_DEBUG is not set # CONFIG_PM_TEST_SUSPEND is not set CONFIG_PM_SLEEP_DEBUG=y CONFIG_PM_TRACE=y CONFIG_PM_TRACE_RTC=y CONFIG_PM_CLK=y # CONFIG_WQ_POWER_EFFICIENT_DEFAULT is not set # CONFIG_ENERGY_MODEL is not set CONFIG_ARCH_SUPPORTS_ACPI=y CONFIG_ACPI=y CONFIG_ACPI_LEGACY_TABLES_LOOKUP=y CONFIG_ARCH_MIGHT_HAVE_ACPI_PDC=y CONFIG_ACPI_SYSTEM_POWER_STATES_SUPPORT=y CONFIG_ACPI_THERMAL_LIB=y # CONFIG_ACPI_DEBUGGER is not set CONFIG_ACPI_SPCR_TABLE=y # CONFIG_ACPI_FPDT is not set CONFIG_ACPI_LPIT=y CONFIG_ACPI_SLEEP=y CONFIG_ACPI_REV_OVERRIDE_POSSIBLE=y CONFIG_ACPI_EC=y # CONFIG_ACPI_EC_DEBUGFS is not set CONFIG_ACPI_AC=y CONFIG_ACPI_BATTERY=y CONFIG_ACPI_BUTTON=y CONFIG_ACPI_FAN=y # CONFIG_ACPI_TAD is not set CONFIG_ACPI_DOCK=y CONFIG_ACPI_CPU_FREQ_PSS=y CONFIG_ACPI_PROCESSOR_CSTATE=y CONFIG_ACPI_PROCESSOR_IDLE=y CONFIG_ACPI_CPPC_LIB=y CONFIG_ACPI_PROCESSOR=y CONFIG_ACPI_HOTPLUG_CPU=y # CONFIG_ACPI_PROCESSOR_AGGREGATOR is not set CONFIG_ACPI_THERMAL=y CONFIG_ARCH_HAS_ACPI_TABLE_UPGRADE=y CONFIG_ACPI_TABLE_UPGRADE=y # CONFIG_ACPI_DEBUG is not set # CONFIG_ACPI_PCI_SLOT is not set CONFIG_ACPI_CONTAINER=y CONFIG_ACPI_HOTPLUG_IOAPIC=y # CONFIG_ACPI_SBS is not set # CONFIG_ACPI_HED is not set CONFIG_ACPI_BGRT=y # CONFIG_ACPI_REDUCED_HARDWARE_ONLY is not set # CONFIG_ACPI_NFIT is not set CONFIG_ACPI_NUMA=y # CONFIG_ACPI_HMAT is not set CONFIG_HAVE_ACPI_APEI=y CONFIG_HAVE_ACPI_APEI_NMI=y # CONFIG_ACPI_APEI is not set # CONFIG_ACPI_DPTF is not set # CONFIG_ACPI_EXTLOG is not set # CONFIG_ACPI_CONFIGFS is not set # CONFIG_ACPI_PFRUT is not set # CONFIG_ACPI_PCC is not set # CONFIG_ACPI_FFH is not set CONFIG_ACPI_MRRM=y # CONFIG_PMIC_OPREGION is not set CONFIG_ACPI_PRMT=y CONFIG_X86_PM_TIMER=y # # CPU Frequency scaling # CONFIG_CPU_FREQ=y CONFIG_CPU_FREQ_GOV_ATTR_SET=y CONFIG_CPU_FREQ_GOV_COMMON=y CONFIG_CPU_FREQ_STAT=y CONFIG_CPU_FREQ_DEFAULT_GOV_PERFORMANCE=y # CONFIG_CPU_FREQ_DEFAULT_GOV_POWERSAVE is not set # CONFIG_CPU_FREQ_DEFAULT_GOV_USERSPACE is not set # CONFIG_CPU_FREQ_DEFAULT_GOV_SCHEDUTIL is not set CONFIG_CPU_FREQ_GOV_PERFORMANCE=y # CONFIG_CPU_FREQ_GOV_POWERSAVE is not set CONFIG_CPU_FREQ_GOV_USERSPACE=y CONFIG_CPU_FREQ_GOV_ONDEMAND=y # CONFIG_CPU_FREQ_GOV_CONSERVATIVE is not set CONFIG_CPU_FREQ_GOV_SCHEDUTIL=y # # CPU frequency scaling drivers # CONFIG_X86_INTEL_PSTATE=y CONFIG_X86_PCC_CPUFREQ=y CONFIG_X86_AMD_PSTATE=y CONFIG_X86_AMD_PSTATE_DEFAULT_MODE=3 # CONFIG_X86_AMD_PSTATE_UT is not set CONFIG_X86_ACPI_CPUFREQ=y CONFIG_X86_ACPI_CPUFREQ_CPB=y # CONFIG_X86_POWERNOW_K8 is not set # CONFIG_X86_AMD_FREQ_SENSITIVITY is not set # CONFIG_X86_SPEEDSTEP_CENTRINO is not set # CONFIG_X86_P4_CLOCKMOD is not set # # shared options # CONFIG_CPUFREQ_ARCH_CUR_FREQ=y # end of CPU Frequency scaling # # CPU Idle # CONFIG_CPU_IDLE=y # CONFIG_CPU_IDLE_GOV_LADDER is not set CONFIG_CPU_IDLE_GOV_MENU=y # CONFIG_CPU_IDLE_GOV_TEO is not set CONFIG_CPU_IDLE_GOV_HALTPOLL=y CONFIG_HALTPOLL_CPUIDLE=y # end of CPU Idle # CONFIG_INTEL_IDLE is not set # end of Power management and ACPI options # # Bus options (PCI etc.) # CONFIG_PCI_DIRECT=y CONFIG_PCI_MMCONFIG=y CONFIG_MMCONF_FAM10H=y # CONFIG_ISA_BUS is not set CONFIG_ISA_DMA_API=y CONFIG_AMD_NB=y CONFIG_AMD_NODE=y # end of Bus options (PCI etc.) # # Binary Emulations # # CONFIG_IA32_EMULATION is not set # end of Binary Emulations # CONFIG_VIRTUALIZATION is not set CONFIG_X86_REQUIRED_FEATURE_ALWAYS=y CONFIG_X86_REQUIRED_FEATURE_NOPL=y CONFIG_X86_REQUIRED_FEATURE_CX8=y CONFIG_X86_REQUIRED_FEATURE_CMOV=y CONFIG_X86_REQUIRED_FEATURE_CPUID=y CONFIG_X86_REQUIRED_FEATURE_FPU=y CONFIG_X86_REQUIRED_FEATURE_PAE=y CONFIG_X86_REQUIRED_FEATURE_PSE=y CONFIG_X86_REQUIRED_FEATURE_PGE=y CONFIG_X86_REQUIRED_FEATURE_MSR=y CONFIG_X86_REQUIRED_FEATURE_FXSR=y CONFIG_X86_REQUIRED_FEATURE_XMM=y CONFIG_X86_REQUIRED_FEATURE_XMM2=y CONFIG_X86_REQUIRED_FEATURE_LM=y CONFIG_X86_DISABLED_FEATURE_VME=y CONFIG_X86_DISABLED_FEATURE_K6_MTRR=y CONFIG_X86_DISABLED_FEATURE_CYRIX_ARR=y CONFIG_X86_DISABLED_FEATURE_CENTAUR_MCR=y CONFIG_X86_DISABLED_FEATURE_PTI=y CONFIG_X86_DISABLED_FEATURE_RETPOLINE=y CONFIG_X86_DISABLED_FEATURE_RETPOLINE_LFENCE=y CONFIG_X86_DISABLED_FEATURE_RETHUNK=y CONFIG_X86_DISABLED_FEATURE_UNRET=y CONFIG_X86_DISABLED_FEATURE_CALL_DEPTH=y CONFIG_X86_DISABLED_FEATURE_LAM=y CONFIG_X86_DISABLED_FEATURE_ENQCMD=y CONFIG_X86_DISABLED_FEATURE_SGX=y CONFIG_X86_DISABLED_FEATURE_XENPV=y CONFIG_X86_DISABLED_FEATURE_TDX_GUEST=y CONFIG_X86_DISABLED_FEATURE_USER_SHSTK=y CONFIG_X86_DISABLED_FEATURE_IBT=y CONFIG_X86_DISABLED_FEATURE_SEV_SNP=y CONFIG_AS_WRUSS=y CONFIG_ARCH_CONFIGURES_CPU_MITIGATIONS=y # # General architecture-dependent options # CONFIG_HOTPLUG_SMT=y CONFIG_ARCH_SUPPORTS_SCHED_SMT=y CONFIG_ARCH_SUPPORTS_SCHED_CLUSTER=y CONFIG_ARCH_SUPPORTS_SCHED_MC=y CONFIG_SCHED_SMT=y CONFIG_SCHED_CLUSTER=y CONFIG_SCHED_MC=y CONFIG_HOTPLUG_CORE_SYNC=y CONFIG_HOTPLUG_CORE_SYNC_DEAD=y CONFIG_HOTPLUG_CORE_SYNC_FULL=y CONFIG_HOTPLUG_SPLIT_STARTUP=y CONFIG_HOTPLUG_PARALLEL=y CONFIG_GENERIC_IRQ_ENTRY=y CONFIG_GENERIC_SYSCALL=y CONFIG_GENERIC_ENTRY=y CONFIG_KPROBES=y CONFIG_JUMP_LABEL=y # CONFIG_STATIC_KEYS_SELFTEST is not set # CONFIG_STATIC_CALL_SELFTEST is not set CONFIG_OPTPROBES=y CONFIG_KPROBES_ON_FTRACE=y CONFIG_UPROBES=y CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS=y CONFIG_ARCH_USE_BUILTIN_BSWAP=y CONFIG_KRETPROBES=y CONFIG_KRETPROBE_ON_RETHOOK=y CONFIG_HAVE_IOREMAP_PROT=y CONFIG_HAVE_KPROBES=y CONFIG_HAVE_KRETPROBES=y CONFIG_HAVE_OPTPROBES=y CONFIG_HAVE_KPROBES_ON_FTRACE=y CONFIG_ARCH_CORRECT_STACKTRACE_ON_KRETPROBE=y CONFIG_HAVE_FUNCTION_ERROR_INJECTION=y CONFIG_HAVE_NMI=y CONFIG_TRACE_IRQFLAGS_SUPPORT=y CONFIG_TRACE_IRQFLAGS_NMI_SUPPORT=y CONFIG_HAVE_ARCH_TRACEHOOK=y CONFIG_HAVE_DMA_CONTIGUOUS=y CONFIG_GENERIC_SMP_IDLE_THREAD=y CONFIG_ARCH_HAS_FORTIFY_SOURCE=y CONFIG_ARCH_HAS_SET_MEMORY=y CONFIG_ARCH_HAS_SET_DIRECT_MAP=y CONFIG_ARCH_HAS_CPU_FINALIZE_INIT=y CONFIG_ARCH_HAS_CPU_PASID=y CONFIG_HAVE_ARCH_THREAD_STRUCT_WHITELIST=y CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT=y CONFIG_ARCH_WANTS_NO_INSTR=y CONFIG_HAVE_ASM_MODVERSIONS=y CONFIG_HAVE_REGS_AND_STACK_ACCESS_API=y CONFIG_HAVE_RSEQ=y CONFIG_HAVE_RUST=y CONFIG_HAVE_FUNCTION_ARG_ACCESS_API=y CONFIG_HAVE_HW_BREAKPOINT=y CONFIG_HAVE_MIXED_BREAKPOINTS_REGS=y CONFIG_HAVE_USER_RETURN_NOTIFIER=y CONFIG_HAVE_PERF_EVENTS_NMI=y CONFIG_HAVE_HARDLOCKUP_DETECTOR_PERF=y CONFIG_UNWIND_USER=y CONFIG_HAVE_UNWIND_USER_FP=y CONFIG_HAVE_PERF_REGS=y CONFIG_HAVE_PERF_USER_STACK_DUMP=y CONFIG_HAVE_ARCH_JUMP_LABEL=y CONFIG_HAVE_ARCH_JUMP_LABEL_RELATIVE=y CONFIG_MMU_GATHER_TABLE_FREE=y CONFIG_MMU_GATHER_RCU_TABLE_FREE=y CONFIG_MMU_GATHER_MERGE_VMAS=y CONFIG_ARCH_WANT_IRQS_OFF_ACTIVATE_MM=y CONFIG_MMU_LAZY_TLB_REFCOUNT=y CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG=y CONFIG_ARCH_HAVE_EXTRA_ELF_NOTES=y CONFIG_ARCH_HAS_NMI_SAFE_THIS_CPU_OPS=y CONFIG_HAVE_ALIGNED_STRUCT_PAGE=y CONFIG_HAVE_CMPXCHG_LOCAL=y CONFIG_HAVE_CMPXCHG_DOUBLE=y CONFIG_HAVE_ARCH_SECCOMP=y CONFIG_HAVE_ARCH_SECCOMP_FILTER=y CONFIG_SECCOMP=y CONFIG_SECCOMP_FILTER=y # CONFIG_SECCOMP_CACHE_DEBUG is not set CONFIG_HAVE_ARCH_KSTACK_ERASE=y CONFIG_HAVE_STACKPROTECTOR=y CONFIG_STACKPROTECTOR=y CONFIG_STACKPROTECTOR_STRONG=y CONFIG_LTO=y CONFIG_LTO_CLANG=y CONFIG_ARCH_SUPPORTS_LTO_CLANG=y CONFIG_ARCH_SUPPORTS_LTO_CLANG_THIN=y CONFIG_HAS_LTO_CLANG=y # CONFIG_LTO_NONE is not set # CONFIG_LTO_CLANG_FULL is not set CONFIG_LTO_CLANG_THIN=y CONFIG_ARCH_SUPPORTS_AUTOFDO_CLANG=y # CONFIG_AUTOFDO_CLANG is not set CONFIG_ARCH_SUPPORTS_PROPELLER_CLANG=y # CONFIG_PROPELLER_CLANG is not set CONFIG_ARCH_SUPPORTS_CFI=y CONFIG_ARCH_USES_CFI_TRAPS=y CONFIG_CFI=y CONFIG_CFI_ICALL_NORMALIZE_INTEGERS=y CONFIG_HAVE_CFI_ICALL_NORMALIZE_INTEGERS=y CONFIG_HAVE_CFI_ICALL_NORMALIZE_INTEGERS_RUSTC=y # CONFIG_CFI_PERMISSIVE is not set CONFIG_HAVE_ARCH_WITHIN_STACK_FRAMES=y CONFIG_HAVE_CONTEXT_TRACKING_USER=y CONFIG_HAVE_CONTEXT_TRACKING_USER_OFFSTACK=y CONFIG_HAVE_VIRT_CPU_ACCOUNTING_GEN=y CONFIG_HAVE_IRQ_TIME_ACCOUNTING=y CONFIG_HAVE_MOVE_PUD=y CONFIG_HAVE_MOVE_PMD=y CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE=y CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD=y CONFIG_HAVE_ARCH_HUGE_VMAP=y CONFIG_HAVE_ARCH_HUGE_VMALLOC=y CONFIG_ARCH_WANT_HUGE_PMD_SHARE=y CONFIG_HAVE_ARCH_SOFT_DIRTY=y CONFIG_HAVE_MOD_ARCH_SPECIFIC=y CONFIG_MODULES_USE_ELF_RELA=y CONFIG_ARCH_HAS_EXECMEM_ROX=y CONFIG_HAVE_IRQ_EXIT_ON_IRQ_STACK=y CONFIG_HAVE_SOFTIRQ_ON_OWN_STACK=y CONFIG_SOFTIRQ_ON_OWN_STACK=y CONFIG_ARCH_HAS_ELF_RANDOMIZE=y CONFIG_HAVE_ARCH_MMAP_RND_BITS=y CONFIG_HAVE_EXIT_THREAD=y CONFIG_ARCH_MMAP_RND_BITS=28 CONFIG_HAVE_PAGE_SIZE_4KB=y CONFIG_PAGE_SIZE_4KB=y CONFIG_PAGE_SIZE_LESS_THAN_64KB=y CONFIG_PAGE_SIZE_LESS_THAN_256KB=y CONFIG_PAGE_SHIFT=12 CONFIG_HAVE_OBJTOOL=y CONFIG_HAVE_JUMP_LABEL_HACK=y CONFIG_HAVE_NOINSTR_HACK=y CONFIG_HAVE_NOINSTR_VALIDATION=y CONFIG_HAVE_UACCESS_VALIDATION=y CONFIG_HAVE_STACK_VALIDATION=y CONFIG_HAVE_RELIABLE_STACKTRACE=y # CONFIG_COMPAT_32BIT_TIME is not set CONFIG_ARCH_SUPPORTS_RT=y CONFIG_HAVE_ARCH_VMAP_STACK=y CONFIG_VMAP_STACK=y CONFIG_HAVE_ARCH_RANDOMIZE_KSTACK_OFFSET=y # CONFIG_RANDOMIZE_KSTACK_OFFSET is not set CONFIG_ARCH_HAS_STRICT_KERNEL_RWX=y CONFIG_STRICT_KERNEL_RWX=y CONFIG_ARCH_HAS_STRICT_MODULE_RWX=y CONFIG_STRICT_MODULE_RWX=y CONFIG_HAVE_ARCH_PREL32_RELOCATIONS=y CONFIG_ARCH_USE_MEMREMAP_PROT=y # CONFIG_LOCK_EVENT_COUNTS is not set CONFIG_ARCH_HAS_MEM_ENCRYPT=y CONFIG_HAVE_STATIC_CALL=y CONFIG_HAVE_STATIC_CALL_INLINE=y CONFIG_HAVE_PREEMPT_DYNAMIC=y CONFIG_HAVE_PREEMPT_DYNAMIC_CALL=y CONFIG_ARCH_WANT_LD_ORPHAN_WARN=y CONFIG_ARCH_SUPPORTS_DEBUG_PAGEALLOC=y CONFIG_ARCH_SUPPORTS_PAGE_TABLE_CHECK=y CONFIG_ARCH_HAS_ELFCORE_COMPAT=y CONFIG_ARCH_HAS_PARANOID_L1D_FLUSH=y CONFIG_DYNAMIC_SIGFRAME=y CONFIG_ARCH_HAS_HW_PTE_YOUNG=y CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG=y CONFIG_ARCH_HAS_KERNEL_FPU_SUPPORT=y CONFIG_HAVE_GENERIC_TIF_BITS=y # # GCOV-based kernel profiling # # CONFIG_GCOV_KERNEL is not set CONFIG_ARCH_HAS_GCOV_PROFILE_ALL=y # end of GCOV-based kernel profiling CONFIG_HAVE_GCC_PLUGINS=y CONFIG_FUNCTION_ALIGNMENT_4B=y CONFIG_FUNCTION_ALIGNMENT_16B=y CONFIG_FUNCTION_ALIGNMENT=16 CONFIG_CC_HAS_SANE_FUNCTION_ALIGNMENT=y # end of General architecture-dependent options CONFIG_RT_MUTEXES=y CONFIG_MODULES=y # CONFIG_MODULE_DEBUG is not set # CONFIG_MODULE_FORCE_LOAD is not set CONFIG_MODULE_UNLOAD=y CONFIG_MODULE_FORCE_UNLOAD=y # CONFIG_MODULE_UNLOAD_TAINT_TRACKING is not set CONFIG_MODVERSIONS=y CONFIG_GENKSYMS=y CONFIG_ASM_MODVERSIONS=y # CONFIG_EXTENDED_MODVERSIONS is not set CONFIG_BASIC_MODVERSIONS=y # CONFIG_MODULE_SRCVERSION_ALL is not set # CONFIG_MODULE_SIG is not set CONFIG_MODULE_COMPRESS=y # CONFIG_MODULE_COMPRESS_GZIP is not set # CONFIG_MODULE_COMPRESS_XZ is not set CONFIG_MODULE_COMPRESS_ZSTD=y CONFIG_MODULE_COMPRESS_ALL=y CONFIG_MODULE_DECOMPRESS=y # CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS is not set CONFIG_MODPROBE_PATH="/sbin/modprobe" # CONFIG_TRIM_UNUSED_KSYMS is not set CONFIG_MODULES_TREE_LOOKUP=y CONFIG_BLOCK=y CONFIG_BLOCK_LEGACY_AUTOLOAD=y CONFIG_BLK_CGROUP_RWSTAT=y CONFIG_BLK_DEV_BSG_COMMON=y # CONFIG_BLK_DEV_BSGLIB is not set # CONFIG_BLK_DEV_INTEGRITY is not set CONFIG_BLK_DEV_WRITE_MOUNTED=y # CONFIG_BLK_DEV_ZONED is not set CONFIG_BLK_DEV_THROTTLING=y # CONFIG_BLK_WBT is not set # CONFIG_BLK_CGROUP_IOLATENCY is not set # CONFIG_BLK_CGROUP_IOCOST is not set # CONFIG_BLK_CGROUP_IOPRIO is not set CONFIG_BLK_DEBUG_FS=y # CONFIG_BLK_SED_OPAL is not set # CONFIG_BLK_INLINE_ENCRYPTION is not set # # Partition Types # CONFIG_PARTITION_ADVANCED=y # CONFIG_ACORN_PARTITION is not set # CONFIG_AIX_PARTITION is not set # CONFIG_OSF_PARTITION is not set # CONFIG_AMIGA_PARTITION is not set # CONFIG_ATARI_PARTITION is not set # CONFIG_MAC_PARTITION is not set CONFIG_MSDOS_PARTITION=y # CONFIG_BSD_DISKLABEL is not set # CONFIG_MINIX_SUBPARTITION is not set # CONFIG_SOLARIS_X86_PARTITION is not set # CONFIG_UNIXWARE_DISKLABEL is not set # CONFIG_LDM_PARTITION is not set # CONFIG_SGI_PARTITION is not set # CONFIG_ULTRIX_PARTITION is not set # CONFIG_SUN_PARTITION is not set # CONFIG_KARMA_PARTITION is not set CONFIG_EFI_PARTITION=y # CONFIG_SYSV68_PARTITION is not set # CONFIG_CMDLINE_PARTITION is not set # end of Partition Types CONFIG_BLK_PM=y CONFIG_BLOCK_HOLDER_DEPRECATED=y CONFIG_BLK_MQ_STACKING=y # # IO Schedulers # CONFIG_MQ_IOSCHED_DEADLINE=y CONFIG_MQ_IOSCHED_KYBER=y # CONFIG_IOSCHED_BFQ is not set # end of IO Schedulers CONFIG_PADATA=y CONFIG_ASN1=y CONFIG_INLINE_SPIN_UNLOCK_IRQ=y CONFIG_INLINE_READ_UNLOCK=y CONFIG_INLINE_READ_UNLOCK_IRQ=y CONFIG_INLINE_WRITE_UNLOCK=y CONFIG_INLINE_WRITE_UNLOCK_IRQ=y CONFIG_ARCH_SUPPORTS_ATOMIC_RMW=y CONFIG_MUTEX_SPIN_ON_OWNER=y CONFIG_RWSEM_SPIN_ON_OWNER=y CONFIG_LOCK_SPIN_ON_OWNER=y CONFIG_ARCH_USE_QUEUED_SPINLOCKS=y CONFIG_QUEUED_SPINLOCKS=y CONFIG_ARCH_USE_QUEUED_RWLOCKS=y CONFIG_QUEUED_RWLOCKS=y CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE=y CONFIG_ARCH_HAS_SYNC_CORE_BEFORE_USERMODE=y CONFIG_ARCH_HAS_SYSCALL_WRAPPER=y CONFIG_FREEZER=y # # Executable file formats # CONFIG_BINFMT_ELF=y CONFIG_ELFCORE=y CONFIG_CORE_DUMP_DEFAULT_ELF_HEADERS=y CONFIG_BINFMT_SCRIPT=y CONFIG_BINFMT_MISC=y CONFIG_COREDUMP=y # end of Executable file formats # # Memory Management options # CONFIG_SWAP=y # CONFIG_ZSWAP is not set # # Slab allocator options # CONFIG_SLUB=y CONFIG_KVFREE_RCU_BATCHED=y # CONFIG_SLUB_TINY is not set CONFIG_SLAB_MERGE_DEFAULT=y # CONFIG_SLAB_FREELIST_RANDOM is not set # CONFIG_SLAB_FREELIST_HARDENED is not set # CONFIG_SLAB_BUCKETS is not set # CONFIG_SLUB_STATS is not set CONFIG_SLUB_CPU_PARTIAL=y # CONFIG_RANDOM_KMALLOC_CACHES is not set # end of Slab allocator options # CONFIG_SHUFFLE_PAGE_ALLOCATOR is not set # CONFIG_COMPAT_BRK is not set CONFIG_SPARSEMEM=y CONFIG_SPARSEMEM_EXTREME=y CONFIG_SPARSEMEM_VMEMMAP_ENABLE=y CONFIG_SPARSEMEM_VMEMMAP=y CONFIG_SPARSEMEM_VMEMMAP_PREINIT=y CONFIG_ARCH_WANT_OPTIMIZE_DAX_VMEMMAP=y CONFIG_ARCH_WANT_OPTIMIZE_HUGETLB_VMEMMAP=y CONFIG_ARCH_WANT_HUGETLB_VMEMMAP_PREINIT=y CONFIG_HAVE_GUP_FAST=y CONFIG_EXCLUSIVE_SYSTEM_RAM=y CONFIG_ARCH_ENABLE_MEMORY_HOTPLUG=y # CONFIG_MEMORY_HOTPLUG is not set CONFIG_ARCH_MHP_MEMMAP_ON_MEMORY_ENABLE=y CONFIG_SPLIT_PTE_PTLOCKS=y CONFIG_ARCH_ENABLE_SPLIT_PMD_PTLOCK=y CONFIG_SPLIT_PMD_PTLOCKS=y CONFIG_COMPACTION=y CONFIG_COMPACT_UNEVICTABLE_DEFAULT=1 # CONFIG_PAGE_REPORTING is not set CONFIG_MIGRATION=y CONFIG_ARCH_ENABLE_HUGEPAGE_MIGRATION=y CONFIG_PCP_BATCH_SCALE_MAX=5 CONFIG_PHYS_ADDR_T_64BIT=y CONFIG_MMU_NOTIFIER=y # CONFIG_KSM is not set CONFIG_DEFAULT_MMAP_MIN_ADDR=4096 CONFIG_ARCH_SUPPORTS_MEMORY_FAILURE=y # CONFIG_MEMORY_FAILURE is not set CONFIG_ARCH_WANT_GENERAL_HUGETLB=y CONFIG_ARCH_WANTS_THP_SWAP=y # CONFIG_TRANSPARENT_HUGEPAGE is not set CONFIG_PAGE_MAPCOUNT=y CONFIG_PGTABLE_HAS_HUGE_LEAVES=y CONFIG_HAVE_GIGANTIC_FOLIOS=y CONFIG_ASYNC_KERNEL_PGTABLE_FREE=y CONFIG_NEED_PER_CPU_EMBED_FIRST_CHUNK=y CONFIG_NEED_PER_CPU_PAGE_FIRST_CHUNK=y CONFIG_USE_PERCPU_NUMA_NODE_ID=y CONFIG_HAVE_SETUP_PER_CPU_AREA=y # CONFIG_CMA is not set CONFIG_PAGE_BLOCK_MAX_ORDER=10 CONFIG_GENERIC_EARLY_IOREMAP=y # CONFIG_DEFERRED_STRUCT_PAGE_INIT is not set # CONFIG_IDLE_PAGE_TRACKING is not set CONFIG_ARCH_HAS_CACHE_LINE_SIZE=y CONFIG_ARCH_HAS_CURRENT_STACK_POINTER=y CONFIG_ARCH_HAS_ZONE_DMA_SET=y CONFIG_ZONE_DMA=y CONFIG_ZONE_DMA32=y CONFIG_ARCH_USES_HIGH_VMA_FLAGS=y CONFIG_ARCH_HAS_PKEYS=y CONFIG_ARCH_USES_PG_ARCH_2=y CONFIG_VM_EVENT_COUNTERS=y # CONFIG_PERCPU_STATS is not set # CONFIG_GUP_TEST is not set # CONFIG_DMAPOOL_TEST is not set CONFIG_ARCH_HAS_PTE_SPECIAL=y CONFIG_MEMFD_CREATE=y CONFIG_SECRETMEM=y # CONFIG_ANON_VMA_NAME is not set # CONFIG_USERFAULTFD is not set # CONFIG_LRU_GEN is not set CONFIG_ARCH_SUPPORTS_PER_VMA_LOCK=y CONFIG_PER_VMA_LOCK=y CONFIG_LOCK_MM_AND_FIND_VMA=y CONFIG_IOMMU_MM_DATA=y CONFIG_EXECMEM=y CONFIG_NUMA_MEMBLKS=y # CONFIG_NUMA_EMU is not set CONFIG_ARCH_SUPPORTS_PT_RECLAIM=y CONFIG_PT_RECLAIM=y # # Data Access Monitoring # # CONFIG_DAMON is not set # end of Data Access Monitoring # end of Memory Management options CONFIG_NET=y CONFIG_NET_INGRESS=y CONFIG_NET_EGRESS=y CONFIG_NET_XGRESS=y CONFIG_SKB_EXTENSIONS=y CONFIG_NET_DEVMEM=y CONFIG_NET_SHAPER=y CONFIG_NET_CRC32C=y # # Networking options # CONFIG_PACKET=y # CONFIG_PACKET_DIAG is not set # CONFIG_INET_PSP is not set CONFIG_UNIX=y CONFIG_AF_UNIX_OOB=y # CONFIG_UNIX_DIAG is not set # CONFIG_TLS is not set CONFIG_XFRM=y CONFIG_XFRM_ALGO=y CONFIG_XFRM_USER=y # CONFIG_XFRM_INTERFACE is not set # CONFIG_XFRM_SUB_POLICY is not set # CONFIG_XFRM_MIGRATE is not set # CONFIG_XFRM_STATISTICS is not set CONFIG_XFRM_AH=y CONFIG_XFRM_ESP=y # CONFIG_NET_KEY is not set # CONFIG_XFRM_IPTFS is not set # CONFIG_DIBS is not set CONFIG_XDP_SOCKETS=y # CONFIG_XDP_SOCKETS_DIAG is not set CONFIG_NET_HANDSHAKE=y CONFIG_INET=y CONFIG_IP_MULTICAST=y CONFIG_IP_ADVANCED_ROUTER=y # CONFIG_IP_FIB_TRIE_STATS is not set CONFIG_IP_MULTIPLE_TABLES=y CONFIG_IP_ROUTE_MULTIPATH=y CONFIG_IP_ROUTE_VERBOSE=y CONFIG_IP_PNP=y CONFIG_IP_PNP_DHCP=y CONFIG_IP_PNP_BOOTP=y CONFIG_IP_PNP_RARP=y CONFIG_NET_IPIP=y CONFIG_NET_IPGRE_DEMUX=y CONFIG_NET_IP_TUNNEL=y CONFIG_NET_IPGRE=y # CONFIG_NET_IPGRE_BROADCAST is not set CONFIG_IP_MROUTE_COMMON=y CONFIG_IP_MROUTE=y # CONFIG_IP_MROUTE_MULTIPLE_TABLES is not set CONFIG_IP_PIMSM_V1=y CONFIG_IP_PIMSM_V2=y CONFIG_SYN_COOKIES=y # CONFIG_NET_IPVTI is not set CONFIG_NET_UDP_TUNNEL=y CONFIG_NET_FOU=y CONFIG_NET_FOU_IP_TUNNELS=y # CONFIG_INET_AH is not set # CONFIG_INET_ESP is not set # CONFIG_INET_IPCOMP is not set CONFIG_INET_TABLE_PERTURB_ORDER=16 CONFIG_INET_TUNNEL=y # CONFIG_INET_DIAG is not set CONFIG_TCP_CONG_ADVANCED=y # CONFIG_TCP_CONG_BIC is not set CONFIG_TCP_CONG_CUBIC=y # CONFIG_TCP_CONG_WESTWOOD is not set # CONFIG_TCP_CONG_HTCP is not set # CONFIG_TCP_CONG_HSTCP is not set # CONFIG_TCP_CONG_HYBLA is not set # CONFIG_TCP_CONG_VEGAS is not set # CONFIG_TCP_CONG_NV is not set # CONFIG_TCP_CONG_SCALABLE is not set # CONFIG_TCP_CONG_LP is not set # CONFIG_TCP_CONG_VENO is not set # CONFIG_TCP_CONG_YEAH is not set # CONFIG_TCP_CONG_ILLINOIS is not set # CONFIG_TCP_CONG_DCTCP is not set # CONFIG_TCP_CONG_CDG is not set # CONFIG_TCP_CONG_BBR is not set CONFIG_DEFAULT_CUBIC=y # CONFIG_DEFAULT_RENO is not set CONFIG_DEFAULT_TCP_CONG="cubic" # CONFIG_TCP_AO is not set CONFIG_TCP_MD5SIG=y CONFIG_IPV6=y # CONFIG_IPV6_ROUTER_PREF is not set # CONFIG_IPV6_OPTIMISTIC_DAD is not set CONFIG_INET6_AH=y CONFIG_INET6_ESP=y # CONFIG_INET6_ESP_OFFLOAD is not set # CONFIG_INET6_ESPINTCP is not set # CONFIG_INET6_IPCOMP is not set # CONFIG_IPV6_MIP6 is not set # CONFIG_IPV6_ILA is not set CONFIG_INET6_TUNNEL=y # CONFIG_IPV6_VTI is not set CONFIG_IPV6_SIT=y # CONFIG_IPV6_SIT_6RD is not set CONFIG_IPV6_NDISC_NODETYPE=y CONFIG_IPV6_TUNNEL=y CONFIG_IPV6_GRE=y CONFIG_IPV6_FOU=y CONFIG_IPV6_FOU_TUNNEL=y # CONFIG_IPV6_MULTIPLE_TABLES is not set # CONFIG_IPV6_MROUTE is not set # CONFIG_IPV6_SEG6_LWTUNNEL is not set # CONFIG_IPV6_SEG6_HMAC is not set # CONFIG_IPV6_RPL_LWTUNNEL is not set # CONFIG_IPV6_IOAM6_LWTUNNEL is not set CONFIG_NETLABEL=y # CONFIG_MPTCP is not set CONFIG_NETWORK_SECMARK=y CONFIG_NET_PTP_CLASSIFY=y # CONFIG_NETWORK_PHY_TIMESTAMPING is not set CONFIG_NETFILTER=y CONFIG_NETFILTER_ADVANCED=y CONFIG_BRIDGE_NETFILTER=y # # Core Netfilter Configuration # CONFIG_NETFILTER_INGRESS=y CONFIG_NETFILTER_EGRESS=y CONFIG_NETFILTER_SKIP_EGRESS=y CONFIG_NETFILTER_NETLINK=y CONFIG_NETFILTER_FAMILY_BRIDGE=y CONFIG_NETFILTER_BPF_LINK=y # CONFIG_NETFILTER_NETLINK_ACCT is not set # CONFIG_NETFILTER_NETLINK_QUEUE is not set CONFIG_NETFILTER_NETLINK_LOG=y # CONFIG_NETFILTER_NETLINK_OSF is not set CONFIG_NF_CONNTRACK=y CONFIG_NF_LOG_SYSLOG=y # CONFIG_NF_CONNTRACK_MARK is not set CONFIG_NF_CONNTRACK_SECMARK=y # CONFIG_NF_CONNTRACK_ZONES is not set CONFIG_NF_CONNTRACK_PROCFS=y # CONFIG_NF_CONNTRACK_EVENTS is not set # CONFIG_NF_CONNTRACK_TIMEOUT is not set # CONFIG_NF_CONNTRACK_TIMESTAMP is not set # CONFIG_NF_CONNTRACK_LABELS is not set CONFIG_NF_CT_PROTO_SCTP=y CONFIG_NF_CT_PROTO_UDPLITE=y # CONFIG_NF_CONNTRACK_AMANDA is not set CONFIG_NF_CONNTRACK_FTP=y # CONFIG_NF_CONNTRACK_H323 is not set CONFIG_NF_CONNTRACK_IRC=y # CONFIG_NF_CONNTRACK_NETBIOS_NS is not set # CONFIG_NF_CONNTRACK_SNMP is not set # CONFIG_NF_CONNTRACK_PPTP is not set # CONFIG_NF_CONNTRACK_SANE is not set CONFIG_NF_CONNTRACK_SIP=y # CONFIG_NF_CONNTRACK_TFTP is not set CONFIG_NF_CT_NETLINK=y # CONFIG_NETFILTER_NETLINK_GLUE_CT is not set CONFIG_NF_NAT=y CONFIG_NF_NAT_FTP=y CONFIG_NF_NAT_IRC=y CONFIG_NF_NAT_SIP=y CONFIG_NF_NAT_MASQUERADE=y # CONFIG_NF_TABLES is not set CONFIG_NETFILTER_XTABLES=y # CONFIG_NETFILTER_XTABLES_LEGACY is not set # # Xtables combined modules # CONFIG_NETFILTER_XT_MARK=y # CONFIG_NETFILTER_XT_CONNMARK is not set # # Xtables targets # # CONFIG_NETFILTER_XT_TARGET_AUDIT is not set # CONFIG_NETFILTER_XT_TARGET_CLASSIFY is not set # CONFIG_NETFILTER_XT_TARGET_CONNMARK is not set CONFIG_NETFILTER_XT_TARGET_CONNSECMARK=y # CONFIG_NETFILTER_XT_TARGET_HMARK is not set # CONFIG_NETFILTER_XT_TARGET_IDLETIMER is not set CONFIG_NETFILTER_XT_TARGET_LOG=y # CONFIG_NETFILTER_XT_TARGET_MARK is not set CONFIG_NETFILTER_XT_NAT=y # CONFIG_NETFILTER_XT_TARGET_NETMAP is not set CONFIG_NETFILTER_XT_TARGET_NFLOG=y # CONFIG_NETFILTER_XT_TARGET_NFQUEUE is not set # CONFIG_NETFILTER_XT_TARGET_RATEEST is not set # CONFIG_NETFILTER_XT_TARGET_REDIRECT is not set CONFIG_NETFILTER_XT_TARGET_MASQUERADE=y # CONFIG_NETFILTER_XT_TARGET_TEE is not set CONFIG_NETFILTER_XT_TARGET_SECMARK=y CONFIG_NETFILTER_XT_TARGET_TCPMSS=y # # Xtables matches # CONFIG_NETFILTER_XT_MATCH_ADDRTYPE=y CONFIG_NETFILTER_XT_MATCH_BPF=y # CONFIG_NETFILTER_XT_MATCH_CGROUP is not set # CONFIG_NETFILTER_XT_MATCH_CLUSTER is not set CONFIG_NETFILTER_XT_MATCH_COMMENT=y # CONFIG_NETFILTER_XT_MATCH_CONNBYTES is not set # CONFIG_NETFILTER_XT_MATCH_CONNLABEL is not set # CONFIG_NETFILTER_XT_MATCH_CONNLIMIT is not set # CONFIG_NETFILTER_XT_MATCH_CONNMARK is not set CONFIG_NETFILTER_XT_MATCH_CONNTRACK=y # CONFIG_NETFILTER_XT_MATCH_CPU is not set # CONFIG_NETFILTER_XT_MATCH_DCCP is not set # CONFIG_NETFILTER_XT_MATCH_DEVGROUP is not set # CONFIG_NETFILTER_XT_MATCH_DSCP is not set # CONFIG_NETFILTER_XT_MATCH_ECN is not set # CONFIG_NETFILTER_XT_MATCH_ESP is not set # CONFIG_NETFILTER_XT_MATCH_HASHLIMIT is not set # CONFIG_NETFILTER_XT_MATCH_HELPER is not set # CONFIG_NETFILTER_XT_MATCH_HL is not set # CONFIG_NETFILTER_XT_MATCH_IPCOMP is not set # CONFIG_NETFILTER_XT_MATCH_IPRANGE is not set CONFIG_NETFILTER_XT_MATCH_IPVS=y # CONFIG_NETFILTER_XT_MATCH_L2TP is not set # CONFIG_NETFILTER_XT_MATCH_LENGTH is not set # CONFIG_NETFILTER_XT_MATCH_LIMIT is not set # CONFIG_NETFILTER_XT_MATCH_MAC is not set CONFIG_NETFILTER_XT_MATCH_MARK=y CONFIG_NETFILTER_XT_MATCH_MULTIPORT=y # CONFIG_NETFILTER_XT_MATCH_NFACCT is not set # CONFIG_NETFILTER_XT_MATCH_OSF is not set # CONFIG_NETFILTER_XT_MATCH_OWNER is not set CONFIG_NETFILTER_XT_MATCH_POLICY=y # CONFIG_NETFILTER_XT_MATCH_PHYSDEV is not set # CONFIG_NETFILTER_XT_MATCH_PKTTYPE is not set # CONFIG_NETFILTER_XT_MATCH_QUOTA is not set # CONFIG_NETFILTER_XT_MATCH_RATEEST is not set # CONFIG_NETFILTER_XT_MATCH_REALM is not set # CONFIG_NETFILTER_XT_MATCH_RECENT is not set # CONFIG_NETFILTER_XT_MATCH_SCTP is not set # CONFIG_NETFILTER_XT_MATCH_SOCKET is not set CONFIG_NETFILTER_XT_MATCH_STATE=y # CONFIG_NETFILTER_XT_MATCH_STATISTIC is not set # CONFIG_NETFILTER_XT_MATCH_STRING is not set # CONFIG_NETFILTER_XT_MATCH_TCPMSS is not set # CONFIG_NETFILTER_XT_MATCH_TIME is not set # CONFIG_NETFILTER_XT_MATCH_U32 is not set # end of Core Netfilter Configuration # CONFIG_IP_SET is not set CONFIG_IP_VS=y # CONFIG_IP_VS_IPV6 is not set # CONFIG_IP_VS_DEBUG is not set CONFIG_IP_VS_TAB_BITS=12 # # IPVS transport protocol load balancing support # CONFIG_IP_VS_PROTO_TCP=y CONFIG_IP_VS_PROTO_UDP=y # CONFIG_IP_VS_PROTO_ESP is not set # CONFIG_IP_VS_PROTO_AH is not set # CONFIG_IP_VS_PROTO_SCTP is not set # # IPVS scheduler # CONFIG_IP_VS_RR=y # CONFIG_IP_VS_WRR is not set # CONFIG_IP_VS_LC is not set # CONFIG_IP_VS_WLC is not set # CONFIG_IP_VS_FO is not set # CONFIG_IP_VS_OVF is not set # CONFIG_IP_VS_LBLC is not set # CONFIG_IP_VS_LBLCR is not set # CONFIG_IP_VS_DH is not set # CONFIG_IP_VS_SH is not set # CONFIG_IP_VS_MH is not set # CONFIG_IP_VS_SED is not set # CONFIG_IP_VS_NQ is not set # CONFIG_IP_VS_TWOS is not set # # IPVS SH scheduler # CONFIG_IP_VS_SH_TAB_BITS=8 # # IPVS MH scheduler # CONFIG_IP_VS_MH_TAB_INDEX=12 # # IPVS application helper # # CONFIG_IP_VS_FTP is not set CONFIG_IP_VS_NFCT=y # CONFIG_IP_VS_PE_SIP is not set # # IP: Netfilter Configuration # CONFIG_NF_DEFRAG_IPV4=y # CONFIG_NF_SOCKET_IPV4 is not set # CONFIG_NF_TPROXY_IPV4 is not set # CONFIG_NF_DUP_IPV4 is not set CONFIG_NF_LOG_ARP=y CONFIG_NF_LOG_IPV4=y CONFIG_NF_REJECT_IPV4=y CONFIG_IP_NF_IPTABLES=y # CONFIG_IP_NF_MATCH_AH is not set # CONFIG_IP_NF_MATCH_ECN is not set # CONFIG_IP_NF_MATCH_TTL is not set # CONFIG_IP_NF_TARGET_SYNPROXY is not set # end of IP: Netfilter Configuration # # IPv6: Netfilter Configuration # # CONFIG_NF_SOCKET_IPV6 is not set # CONFIG_NF_TPROXY_IPV6 is not set # CONFIG_NF_DUP_IPV6 is not set CONFIG_NF_REJECT_IPV6=y CONFIG_NF_LOG_IPV6=y CONFIG_IP6_NF_IPTABLES=y # CONFIG_IP6_NF_MATCH_AH is not set # CONFIG_IP6_NF_MATCH_EUI64 is not set # CONFIG_IP6_NF_MATCH_FRAG is not set # CONFIG_IP6_NF_MATCH_OPTS is not set # CONFIG_IP6_NF_MATCH_HL is not set CONFIG_IP6_NF_MATCH_IPV6HEADER=y # CONFIG_IP6_NF_MATCH_MH is not set # CONFIG_IP6_NF_MATCH_RT is not set # CONFIG_IP6_NF_MATCH_SRH is not set # CONFIG_IP6_NF_TARGET_SYNPROXY is not set # end of IPv6: Netfilter Configuration CONFIG_NF_DEFRAG_IPV6=y # CONFIG_NF_CONNTRACK_BRIDGE is not set # CONFIG_BRIDGE_NF_EBTABLES is not set # CONFIG_IP_SCTP is not set # CONFIG_RDS is not set # CONFIG_TIPC is not set # CONFIG_ATM is not set # CONFIG_L2TP is not set CONFIG_STP=y CONFIG_BRIDGE=y CONFIG_BRIDGE_IGMP_SNOOPING=y # CONFIG_BRIDGE_MRP is not set # CONFIG_BRIDGE_CFM is not set # CONFIG_NET_DSA is not set # CONFIG_VLAN_8021Q is not set CONFIG_LLC=y # CONFIG_LLC2 is not set # CONFIG_ATALK is not set # CONFIG_X25 is not set # CONFIG_LAPB is not set # CONFIG_PHONET is not set # CONFIG_6LOWPAN is not set # CONFIG_IEEE802154 is not set CONFIG_NET_SCHED=y # # Queueing/Scheduling # # CONFIG_NET_SCH_HTB is not set # CONFIG_NET_SCH_HFSC is not set # CONFIG_NET_SCH_PRIO is not set # CONFIG_NET_SCH_MULTIQ is not set # CONFIG_NET_SCH_RED is not set # CONFIG_NET_SCH_SFB is not set # CONFIG_NET_SCH_SFQ is not set # CONFIG_NET_SCH_TEQL is not set # CONFIG_NET_SCH_TBF is not set # CONFIG_NET_SCH_CBS is not set # CONFIG_NET_SCH_ETF is not set # CONFIG_NET_SCH_TAPRIO is not set # CONFIG_NET_SCH_GRED is not set # CONFIG_NET_SCH_NETEM is not set # CONFIG_NET_SCH_DRR is not set # CONFIG_NET_SCH_MQPRIO is not set # CONFIG_NET_SCH_SKBPRIO is not set # CONFIG_NET_SCH_CHOKE is not set # CONFIG_NET_SCH_QFQ is not set # CONFIG_NET_SCH_CODEL is not set # CONFIG_NET_SCH_FQ_CODEL is not set # CONFIG_NET_SCH_CAKE is not set # CONFIG_NET_SCH_FQ is not set # CONFIG_NET_SCH_HHF is not set # CONFIG_NET_SCH_PIE is not set CONFIG_NET_SCH_INGRESS=y # CONFIG_NET_SCH_PLUG is not set # CONFIG_NET_SCH_ETS is not set CONFIG_NET_SCH_BPF=y # CONFIG_NET_SCH_DUALPI2 is not set # CONFIG_NET_SCH_DEFAULT is not set # # Classification # CONFIG_NET_CLS=y # CONFIG_NET_CLS_BASIC is not set # CONFIG_NET_CLS_ROUTE4 is not set # CONFIG_NET_CLS_FW is not set # CONFIG_NET_CLS_U32 is not set # CONFIG_NET_CLS_FLOW is not set CONFIG_NET_CLS_CGROUP=y CONFIG_NET_CLS_BPF=y CONFIG_NET_CLS_FLOWER=y # CONFIG_NET_CLS_MATCHALL is not set CONFIG_NET_EMATCH=y CONFIG_NET_EMATCH_STACK=32 # CONFIG_NET_EMATCH_CMP is not set # CONFIG_NET_EMATCH_NBYTE is not set # CONFIG_NET_EMATCH_U32 is not set # CONFIG_NET_EMATCH_META is not set # CONFIG_NET_EMATCH_TEXT is not set # CONFIG_NET_EMATCH_IPT is not set CONFIG_NET_CLS_ACT=y # CONFIG_NET_ACT_POLICE is not set # CONFIG_NET_ACT_GACT is not set # CONFIG_NET_ACT_MIRRED is not set # CONFIG_NET_ACT_SAMPLE is not set # CONFIG_NET_ACT_NAT is not set # CONFIG_NET_ACT_PEDIT is not set # CONFIG_NET_ACT_SIMP is not set # CONFIG_NET_ACT_SKBEDIT is not set # CONFIG_NET_ACT_CSUM is not set # CONFIG_NET_ACT_MPLS is not set # CONFIG_NET_ACT_VLAN is not set # CONFIG_NET_ACT_BPF is not set # CONFIG_NET_ACT_SKBMOD is not set # CONFIG_NET_ACT_IFE is not set # CONFIG_NET_ACT_TUNNEL_KEY is not set # CONFIG_NET_ACT_GATE is not set # CONFIG_NET_TC_SKB_EXT is not set CONFIG_NET_SCH_FIFO=y # CONFIG_DCB is not set CONFIG_DNS_RESOLVER=y # CONFIG_BATMAN_ADV is not set # CONFIG_OPENVSWITCH is not set # CONFIG_VSOCKETS is not set # CONFIG_NETLINK_DIAG is not set CONFIG_MPLS=y CONFIG_NET_MPLS_GSO=y CONFIG_MPLS_ROUTING=y CONFIG_MPLS_IPTUNNEL=y # CONFIG_NET_NSH is not set # CONFIG_HSR is not set # CONFIG_NET_SWITCHDEV is not set CONFIG_NET_L3_MASTER_DEV=y # CONFIG_QRTR is not set # CONFIG_NET_NCSI is not set CONFIG_PCPU_DEV_REFCNT=y CONFIG_MAX_SKB_FRAGS=17 CONFIG_RPS=y CONFIG_RFS_ACCEL=y CONFIG_SOCK_RX_QUEUE_MAPPING=y CONFIG_XPS=y CONFIG_CGROUP_NET_PRIO=y CONFIG_CGROUP_NET_CLASSID=y CONFIG_NET_RX_BUSY_POLL=y CONFIG_BQL=y CONFIG_BPF_STREAM_PARSER=y CONFIG_NET_FLOW_LIMIT=y # # Network testing # # CONFIG_NET_PKTGEN is not set # CONFIG_NET_DROP_MONITOR is not set # end of Network testing # end of Networking options # CONFIG_HAMRADIO is not set # CONFIG_CAN is not set # CONFIG_BT is not set # CONFIG_AF_RXRPC is not set # CONFIG_AF_KCM is not set CONFIG_STREAM_PARSER=y # CONFIG_MCTP is not set CONFIG_FIB_RULES=y CONFIG_WIRELESS=y CONFIG_CFG80211=y # CONFIG_NL80211_TESTMODE is not set # CONFIG_CFG80211_DEVELOPER_WARNINGS is not set # CONFIG_CFG80211_CERTIFICATION_ONUS is not set CONFIG_CFG80211_REQUIRE_SIGNED_REGDB=y CONFIG_CFG80211_USE_KERNEL_REGDB_KEYS=y CONFIG_CFG80211_DEFAULT_PS=y # CONFIG_CFG80211_DEBUGFS is not set CONFIG_CFG80211_CRDA_SUPPORT=y # CONFIG_CFG80211_WEXT is not set CONFIG_MAC80211=y CONFIG_MAC80211_HAS_RC=y CONFIG_MAC80211_RC_MINSTREL=y CONFIG_MAC80211_RC_DEFAULT_MINSTREL=y CONFIG_MAC80211_RC_DEFAULT="minstrel_ht" # CONFIG_MAC80211_MESH is not set # CONFIG_MAC80211_MESSAGE_TRACING is not set # CONFIG_MAC80211_DEBUG_MENU is not set CONFIG_MAC80211_STA_HASH_MAX_SIZE=0 CONFIG_RFKILL=y # CONFIG_RFKILL_INPUT is not set CONFIG_NET_9P=y CONFIG_NET_9P_FD=y CONFIG_NET_9P_VIRTIO=y # CONFIG_NET_9P_DEBUG is not set # CONFIG_CAIF is not set # CONFIG_CEPH_LIB is not set # CONFIG_NFC is not set # CONFIG_PSAMPLE is not set # CONFIG_NET_IFE is not set CONFIG_LWTUNNEL=y CONFIG_LWTUNNEL_BPF=y CONFIG_DST_CACHE=y CONFIG_GRO_CELLS=y CONFIG_NET_SELFTESTS=y CONFIG_NET_SOCK_MSG=y CONFIG_NET_DEVLINK=y CONFIG_PAGE_POOL=y # CONFIG_PAGE_POOL_STATS is not set CONFIG_FAILOVER=y CONFIG_ETHTOOL_NETLINK=y # # Device Drivers # CONFIG_HAVE_PCI=y CONFIG_GENERIC_PCI_IOMAP=y CONFIG_PCI=y CONFIG_PCI_DOMAINS=y CONFIG_PCIEPORTBUS=y # CONFIG_HOTPLUG_PCI_PCIE is not set # CONFIG_PCIEAER is not set CONFIG_PCIEASPM=y CONFIG_PCIEASPM_DEFAULT=y # CONFIG_PCIEASPM_POWERSAVE is not set # CONFIG_PCIEASPM_POWER_SUPERSAVE is not set # CONFIG_PCIEASPM_PERFORMANCE is not set CONFIG_PCIE_PME=y # CONFIG_PCIE_PTM is not set CONFIG_PCI_MSI=y CONFIG_PCI_QUIRKS=y # CONFIG_PCI_DEBUG is not set # CONFIG_PCI_STUB is not set CONFIG_PCI_ATS=y # CONFIG_PCI_TSM is not set # CONFIG_PCI_DOE is not set CONFIG_PCI_LOCKLESS_CONFIG=y # CONFIG_PCI_IOV is not set CONFIG_PCI_PRI=y CONFIG_PCI_PASID=y # CONFIG_PCIE_TPH is not set CONFIG_PCI_LABEL=y # CONFIG_PCIE_BUS_TUNE_OFF is not set CONFIG_PCIE_BUS_DEFAULT=y # CONFIG_PCIE_BUS_SAFE is not set # CONFIG_PCIE_BUS_PERFORMANCE is not set # CONFIG_PCIE_BUS_PEER2PEER is not set CONFIG_VGA_ARB=y CONFIG_VGA_ARB_MAX_GPUS=16 CONFIG_HOTPLUG_PCI=y # CONFIG_HOTPLUG_PCI_ACPI is not set # CONFIG_HOTPLUG_PCI_CPCI is not set # CONFIG_HOTPLUG_PCI_OCTEONEP is not set # CONFIG_HOTPLUG_PCI_SHPC is not set # # PCI controller drivers # # CONFIG_VMD is not set # # Cadence-based PCIe controllers # # end of Cadence-based PCIe controllers # # DesignWare-based PCIe controllers # # CONFIG_PCI_MESON is not set # CONFIG_PCIE_DW_PLAT_HOST is not set # end of DesignWare-based PCIe controllers # # Mobiveil-based PCIe controllers # # end of Mobiveil-based PCIe controllers # # PLDA-based PCIe controllers # # end of PLDA-based PCIe controllers # end of PCI controller drivers # # PCI Endpoint # # CONFIG_PCI_ENDPOINT is not set # end of PCI Endpoint # # PCI switch controller drivers # # CONFIG_PCI_SW_SWITCHTEC is not set # end of PCI switch controller drivers # CONFIG_PCI_PWRCTRL_SLOT is not set # CONFIG_PCI_PWRCTRL_TC9563 is not set # CONFIG_CXL_BUS is not set CONFIG_PCCARD=y CONFIG_PCMCIA=y CONFIG_PCMCIA_LOAD_CIS=y CONFIG_CARDBUS=y # # PC-card bridges # CONFIG_YENTA=y CONFIG_YENTA_O2=y CONFIG_YENTA_RICOH=y CONFIG_YENTA_TI=y CONFIG_YENTA_ENE_TUNE=y CONFIG_YENTA_TOSHIBA=y # CONFIG_PD6729 is not set # CONFIG_I82092 is not set CONFIG_PCCARD_NONSTATIC=y # CONFIG_RAPIDIO is not set # CONFIG_PC104 is not set # # Generic Driver Options # # CONFIG_UEVENT_HELPER is not set CONFIG_DEVTMPFS=y CONFIG_DEVTMPFS_MOUNT=y # CONFIG_DEVTMPFS_SAFE is not set CONFIG_STANDALONE=y CONFIG_PREVENT_FIRMWARE_BUILD=y # # Firmware loader # CONFIG_FW_LOADER=y CONFIG_EXTRA_FIRMWARE="" # CONFIG_FW_LOADER_USER_HELPER is not set # CONFIG_FW_LOADER_COMPRESS is not set CONFIG_FW_CACHE=y # CONFIG_FW_UPLOAD is not set # end of Firmware loader CONFIG_ALLOW_DEV_COREDUMP=y # CONFIG_DEBUG_DRIVER is not set CONFIG_DEBUG_DEVRES=y # CONFIG_DEBUG_TEST_DRIVER_REMOVE is not set # CONFIG_TEST_ASYNC_DRIVER_PROBE is not set CONFIG_GENERIC_CPU_DEVICES=y CONFIG_GENERIC_CPU_AUTOPROBE=y CONFIG_GENERIC_CPU_VULNERABILITIES=y CONFIG_DMA_SHARED_BUFFER=y # CONFIG_DMA_FENCE_TRACE is not set # CONFIG_FW_DEVLINK_SYNC_STATE_TIMEOUT is not set # end of Generic Driver Options # # Bus devices # # CONFIG_MHI_BUS is not set # CONFIG_MHI_BUS_EP is not set # end of Bus devices CONFIG_CONNECTOR=y CONFIG_PROC_EVENTS=y # # Firmware Drivers # # # ARM System Control and Management Interface Protocol # # end of ARM System Control and Management Interface Protocol # CONFIG_EDD is not set CONFIG_FIRMWARE_MEMMAP=y CONFIG_DMIID=y # CONFIG_DMI_SYSFS is not set CONFIG_DMI_SCAN_MACHINE_NON_EFI_FALLBACK=y # CONFIG_FW_CFG_SYSFS is not set CONFIG_SYSFB=y # CONFIG_SYSFB_SIMPLEFB is not set # CONFIG_GOOGLE_FIRMWARE is not set # # EFI (Extensible Firmware Interface) Support # CONFIG_EFI_ESRT=y CONFIG_EFI_RUNTIME_WRAPPERS=y # CONFIG_EFI_BOOTLOADER_CONTROL is not set # CONFIG_EFI_CAPSULE_LOADER is not set # CONFIG_EFI_TEST is not set # CONFIG_EFI_RCI2_TABLE is not set # CONFIG_EFI_DISABLE_PCI_DMA is not set CONFIG_EFI_EARLYCON=y CONFIG_EFI_CUSTOM_SSDT_OVERLAYS=y # CONFIG_EFI_DISABLE_RUNTIME is not set # CONFIG_EFI_COCO_SECRET is not set # CONFIG_OVMF_DEBUG_LOG is not set # end of EFI (Extensible Firmware Interface) Support # # Qualcomm firmware drivers # # end of Qualcomm firmware drivers # # Tegra firmware driver # # end of Tegra firmware driver # end of Firmware Drivers # CONFIG_FWCTL is not set # CONFIG_GNSS is not set # CONFIG_MTD is not set # CONFIG_OF is not set CONFIG_ARCH_MIGHT_HAVE_PC_PARPORT=y # CONFIG_PARPORT is not set CONFIG_PNP=y CONFIG_PNP_DEBUG_MESSAGES=y # # Protocols # CONFIG_PNPACPI=y CONFIG_BLK_DEV=y # CONFIG_BLK_DEV_NULL_BLK is not set # CONFIG_BLK_DEV_FD is not set CONFIG_CDROM=y # CONFIG_BLK_DEV_PCIESSD_MTIP32XX is not set # CONFIG_ZRAM is not set CONFIG_BLK_DEV_LOOP=y CONFIG_BLK_DEV_LOOP_MIN_COUNT=8 # CONFIG_BLK_DEV_DRBD is not set # CONFIG_BLK_DEV_NBD is not set # CONFIG_BLK_DEV_RAM is not set # CONFIG_ATA_OVER_ETH is not set # CONFIG_VIRTIO_BLK is not set # CONFIG_BLK_DEV_RBD is not set # CONFIG_BLK_DEV_UBLK is not set # # NVME Support # CONFIG_NVME_CORE=y CONFIG_BLK_DEV_NVME=y # CONFIG_NVME_MULTIPATH is not set # CONFIG_NVME_VERBOSE_ERRORS is not set # CONFIG_NVME_HWMON is not set # CONFIG_NVME_FC is not set # CONFIG_NVME_TCP is not set # CONFIG_NVME_HOST_AUTH is not set # CONFIG_NVME_TARGET is not set # end of NVME Support # # Misc devices # # CONFIG_AD525X_DPOT is not set # CONFIG_DUMMY_IRQ is not set # CONFIG_IBM_ASM is not set # CONFIG_PHANTOM is not set # CONFIG_RPMB is not set # CONFIG_TI_FPC202 is not set # CONFIG_TIFM_CORE is not set # CONFIG_ICS932S401 is not set # CONFIG_ENCLOSURE_SERVICES is not set # CONFIG_HP_ILO is not set # CONFIG_APDS9802ALS is not set # CONFIG_ISL29003 is not set # CONFIG_ISL29020 is not set # CONFIG_SENSORS_TSL2550 is not set # CONFIG_SENSORS_BH1770 is not set # CONFIG_SENSORS_APDS990X is not set # CONFIG_HMC6352 is not set # CONFIG_DS1682 is not set # CONFIG_SRAM is not set # CONFIG_DW_XDATA_PCIE is not set # CONFIG_PCI_ENDPOINT_TEST is not set # CONFIG_XILINX_SDFEC is not set # CONFIG_NTSYNC is not set # CONFIG_NSM is not set # CONFIG_C2PORT is not set # # EEPROM support # # CONFIG_EEPROM_AT24 is not set # CONFIG_EEPROM_MAX6875 is not set CONFIG_EEPROM_93CX6=y # CONFIG_EEPROM_IDT_89HPESX is not set # CONFIG_EEPROM_EE1004 is not set # CONFIG_EEPROM_M24LR is not set # end of EEPROM support # CONFIG_CB710_CORE is not set # CONFIG_SENSORS_LIS3_I2C is not set # CONFIG_ALTERA_STAPL is not set # CONFIG_INTEL_MEI is not set # CONFIG_VMWARE_VMCI is not set # CONFIG_GENWQE is not set # CONFIG_BCM_VK is not set # CONFIG_MISC_ALCOR_PCI is not set # CONFIG_MISC_RTSX_PCI is not set # CONFIG_MISC_RTSX_USB is not set # CONFIG_UACCE is not set # CONFIG_PVPANIC is not set # CONFIG_KEBA_CP500 is not set # end of Misc devices # # SCSI device support # CONFIG_SCSI_MOD=y # CONFIG_RAID_ATTRS is not set CONFIG_SCSI_COMMON=y CONFIG_SCSI=y CONFIG_SCSI_DMA=y CONFIG_SCSI_PROC_FS=y # # SCSI support type (disk, tape, CD-ROM) # CONFIG_BLK_DEV_SD=y # CONFIG_CHR_DEV_ST is not set CONFIG_BLK_DEV_SR=y CONFIG_CHR_DEV_SG=y CONFIG_BLK_DEV_BSG=y # CONFIG_CHR_DEV_SCH is not set CONFIG_SCSI_CONSTANTS=y # CONFIG_SCSI_LOGGING is not set # CONFIG_SCSI_SCAN_ASYNC is not set # # SCSI Transports # CONFIG_SCSI_SPI_ATTRS=y # CONFIG_SCSI_FC_ATTRS is not set # CONFIG_SCSI_ISCSI_ATTRS is not set # CONFIG_SCSI_SAS_ATTRS is not set # CONFIG_SCSI_SAS_LIBSAS is not set # CONFIG_SCSI_SRP_ATTRS is not set # end of SCSI Transports # CONFIG_SCSI_LOWLEVEL is not set # CONFIG_SCSI_DH is not set # end of SCSI device support CONFIG_ATA=y CONFIG_SATA_HOST=y CONFIG_PATA_TIMINGS=y CONFIG_ATA_VERBOSE_ERROR=y CONFIG_ATA_FORCE=y CONFIG_ATA_ACPI=y # CONFIG_SATA_ZPODD is not set CONFIG_SATA_PMP=y # # Controllers with non-SFF native interface # CONFIG_SATA_AHCI=y CONFIG_SATA_MOBILE_LPM_POLICY=0 # CONFIG_SATA_AHCI_PLATFORM is not set # CONFIG_AHCI_DWC is not set # CONFIG_SATA_INIC162X is not set # CONFIG_SATA_ACARD_AHCI is not set # CONFIG_SATA_SIL24 is not set CONFIG_ATA_SFF=y # # SFF controllers with custom DMA interface # # CONFIG_PDC_ADMA is not set # CONFIG_SATA_QSTOR is not set # CONFIG_SATA_SX4 is not set CONFIG_ATA_BMDMA=y # # SATA SFF controllers with BMDMA # CONFIG_ATA_PIIX=y # CONFIG_SATA_DWC is not set # CONFIG_SATA_MV is not set # CONFIG_SATA_NV is not set # CONFIG_SATA_PROMISE is not set # CONFIG_SATA_SIL is not set # CONFIG_SATA_SIS is not set # CONFIG_SATA_SVW is not set # CONFIG_SATA_ULI is not set # CONFIG_SATA_VIA is not set # CONFIG_SATA_VITESSE is not set # # PATA SFF controllers with BMDMA # # CONFIG_PATA_ALI is not set CONFIG_PATA_AMD=y # CONFIG_PATA_ARTOP is not set # CONFIG_PATA_ATIIXP is not set # CONFIG_PATA_ATP867X is not set # CONFIG_PATA_CMD64X is not set # CONFIG_PATA_CYPRESS is not set # CONFIG_PATA_EFAR is not set # CONFIG_PATA_HPT366 is not set # CONFIG_PATA_HPT37X is not set # CONFIG_PATA_HPT3X2N is not set # CONFIG_PATA_HPT3X3 is not set # CONFIG_PATA_IT8213 is not set # CONFIG_PATA_IT821X is not set # CONFIG_PATA_JMICRON is not set # CONFIG_PATA_MARVELL is not set # CONFIG_PATA_NETCELL is not set # CONFIG_PATA_NINJA32 is not set # CONFIG_PATA_NS87415 is not set CONFIG_PATA_OLDPIIX=y # CONFIG_PATA_OPTIDMA is not set # CONFIG_PATA_PDC2027X is not set # CONFIG_PATA_PDC_OLD is not set # CONFIG_PATA_RADISYS is not set # CONFIG_PATA_RDC is not set CONFIG_PATA_SCH=y # CONFIG_PATA_SERVERWORKS is not set # CONFIG_PATA_SIL680 is not set # CONFIG_PATA_SIS is not set # CONFIG_PATA_TOSHIBA is not set # CONFIG_PATA_TRIFLEX is not set # CONFIG_PATA_VIA is not set # CONFIG_PATA_WINBOND is not set # # PIO-only SFF controllers # # CONFIG_PATA_CMD640_PCI is not set # CONFIG_PATA_MPIIX is not set # CONFIG_PATA_NS87410 is not set # CONFIG_PATA_OPTI is not set # CONFIG_PATA_PCMCIA is not set # CONFIG_PATA_RZ1000 is not set # # Generic fallback / legacy drivers # # CONFIG_PATA_ACPI is not set # CONFIG_ATA_GENERIC is not set # CONFIG_PATA_LEGACY is not set CONFIG_MD=y CONFIG_BLK_DEV_MD=y CONFIG_MD_BITMAP=y # CONFIG_MD_LLBITMAP is not set CONFIG_MD_AUTODETECT=y # CONFIG_MD_BITMAP_FILE is not set # CONFIG_MD_LINEAR is not set # CONFIG_MD_RAID0 is not set # CONFIG_MD_RAID1 is not set # CONFIG_MD_RAID10 is not set # CONFIG_MD_RAID456 is not set # CONFIG_BCACHE is not set CONFIG_BLK_DEV_DM_BUILTIN=y CONFIG_BLK_DEV_DM=y # CONFIG_DM_DEBUG is not set # CONFIG_DM_UNSTRIPED is not set # CONFIG_DM_CRYPT is not set # CONFIG_DM_SNAPSHOT is not set # CONFIG_DM_THIN_PROVISIONING is not set # CONFIG_DM_CACHE is not set # CONFIG_DM_WRITECACHE is not set # CONFIG_DM_EBS is not set # CONFIG_DM_ERA is not set # CONFIG_DM_CLONE is not set CONFIG_DM_MIRROR=y # CONFIG_DM_LOG_USERSPACE is not set # CONFIG_DM_RAID is not set CONFIG_DM_ZERO=y # CONFIG_DM_MULTIPATH is not set # CONFIG_DM_DELAY is not set # CONFIG_DM_DUST is not set # CONFIG_DM_INIT is not set # CONFIG_DM_UEVENT is not set # CONFIG_DM_FLAKEY is not set # CONFIG_DM_VERITY is not set # CONFIG_DM_SWITCH is not set # CONFIG_DM_LOG_WRITES is not set # CONFIG_DM_INTEGRITY is not set # CONFIG_DM_AUDIT is not set # CONFIG_DM_VDO is not set # CONFIG_TARGET_CORE is not set # CONFIG_FUSION is not set # # IEEE 1394 (FireWire) support # # CONFIG_FIREWIRE is not set # CONFIG_FIREWIRE_NOSY is not set # end of IEEE 1394 (FireWire) support # CONFIG_MACINTOSH_DRIVERS is not set CONFIG_NETDEVICES=y CONFIG_MII=y CONFIG_NET_CORE=y # CONFIG_BONDING is not set CONFIG_DUMMY=y # CONFIG_WIREGUARD is not set # CONFIG_OVPN is not set # CONFIG_EQUALIZER is not set # CONFIG_NET_FC is not set # CONFIG_NET_TEAM is not set CONFIG_MACVLAN=y # CONFIG_MACVTAP is not set CONFIG_IPVLAN_L3S=y CONFIG_IPVLAN=y # CONFIG_IPVTAP is not set CONFIG_VXLAN=y CONFIG_GENEVE=y # CONFIG_BAREUDP is not set # CONFIG_GTP is not set # CONFIG_PFCP is not set # CONFIG_AMT is not set # CONFIG_MACSEC is not set CONFIG_NETCONSOLE=y # CONFIG_NETCONSOLE_DYNAMIC is not set # CONFIG_NETCONSOLE_EXTENDED_LOG is not set CONFIG_NETPOLL=y CONFIG_NET_POLL_CONTROLLER=y CONFIG_TUN=y # CONFIG_TUN_VNET_CROSS_LE is not set CONFIG_VETH=y CONFIG_VIRTIO_NET=y # CONFIG_NLMON is not set CONFIG_NETKIT=y # CONFIG_ARCNET is not set CONFIG_ETHERNET=y CONFIG_NET_VENDOR_3COM=y # CONFIG_PCMCIA_3C574 is not set # CONFIG_PCMCIA_3C589 is not set # CONFIG_VORTEX is not set # CONFIG_TYPHOON is not set CONFIG_NET_VENDOR_ADAPTEC=y # CONFIG_ADAPTEC_STARFIRE is not set CONFIG_NET_VENDOR_AGERE=y # CONFIG_ET131X is not set CONFIG_NET_VENDOR_ALACRITECH=y # CONFIG_SLICOSS is not set CONFIG_NET_VENDOR_ALTEON=y # CONFIG_ACENIC is not set # CONFIG_ALTERA_TSE is not set CONFIG_NET_VENDOR_AMAZON=y # CONFIG_ENA_ETHERNET is not set CONFIG_NET_VENDOR_AMD=y # CONFIG_AMD8111_ETH is not set # CONFIG_PCNET32 is not set # CONFIG_PCMCIA_NMCLAN is not set # CONFIG_AMD_XGBE is not set # CONFIG_PDS_CORE is not set CONFIG_NET_VENDOR_AQUANTIA=y # CONFIG_AQTION is not set CONFIG_NET_VENDOR_ARC=y # CONFIG_NET_VENDOR_ASIX is not set CONFIG_NET_VENDOR_ATHEROS=y # CONFIG_ATL2 is not set # CONFIG_ATL1 is not set # CONFIG_ATL1E is not set # CONFIG_ATL1C is not set # CONFIG_ALX is not set # CONFIG_CX_ECAT is not set CONFIG_NET_VENDOR_BROADCOM=y # CONFIG_B44 is not set # CONFIG_BCMGENET is not set # CONFIG_BNX2 is not set # CONFIG_CNIC is not set CONFIG_TIGON3=y CONFIG_TIGON3_HWMON=y # CONFIG_BNX2X is not set # CONFIG_SYSTEMPORT is not set # CONFIG_BNXT is not set # CONFIG_BNGE is not set CONFIG_NET_VENDOR_CADENCE=y # CONFIG_MACB is not set CONFIG_NET_VENDOR_CAVIUM=y # CONFIG_THUNDER_NIC_PF is not set # CONFIG_THUNDER_NIC_VF is not set # CONFIG_THUNDER_NIC_BGX is not set # CONFIG_THUNDER_NIC_RGX is not set # CONFIG_CAVIUM_PTP is not set # CONFIG_LIQUIDIO is not set # CONFIG_LIQUIDIO_VF is not set CONFIG_NET_VENDOR_CHELSIO=y # CONFIG_CHELSIO_T1 is not set # CONFIG_CHELSIO_T3 is not set # CONFIG_CHELSIO_T4 is not set # CONFIG_CHELSIO_T4VF is not set CONFIG_NET_VENDOR_CISCO=y # CONFIG_ENIC is not set CONFIG_NET_VENDOR_CORTINA=y # CONFIG_NET_VENDOR_DAVICOM is not set # CONFIG_DNET is not set CONFIG_NET_VENDOR_DEC=y CONFIG_NET_TULIP=y # CONFIG_DE2104X is not set # CONFIG_TULIP is not set # CONFIG_WINBOND_840 is not set # CONFIG_DM9102 is not set # CONFIG_ULI526X is not set # CONFIG_PCMCIA_XIRCOM is not set CONFIG_NET_VENDOR_DLINK=y # CONFIG_DL2K is not set # CONFIG_SUNDANCE is not set CONFIG_NET_VENDOR_EMULEX=y # CONFIG_BE2NET is not set # CONFIG_NET_VENDOR_ENGLEDER is not set CONFIG_NET_VENDOR_EZCHIP=y CONFIG_NET_VENDOR_FUJITSU=y # CONFIG_PCMCIA_FMVJ18X is not set # CONFIG_NET_VENDOR_FUNGIBLE is not set CONFIG_NET_VENDOR_GOOGLE=y # CONFIG_GVE is not set CONFIG_NET_VENDOR_HISILICON=y # CONFIG_HIBMCGE is not set CONFIG_NET_VENDOR_HUAWEI=y # CONFIG_HINIC is not set # CONFIG_HINIC3 is not set CONFIG_NET_VENDOR_I825XX=y CONFIG_NET_VENDOR_INTEL=y CONFIG_E100=y CONFIG_E1000=y CONFIG_E1000E=y CONFIG_E1000E_HWTS=y # CONFIG_IGB is not set # CONFIG_IGBVF is not set # CONFIG_IXGBE is not set # CONFIG_IXGBEVF is not set # CONFIG_I40E is not set # CONFIG_I40EVF is not set # CONFIG_ICE is not set # CONFIG_FM10K is not set # CONFIG_IGC is not set # CONFIG_IDPF is not set # CONFIG_JME is not set CONFIG_NET_VENDOR_LITEX=y CONFIG_NET_VENDOR_MARVELL=y # CONFIG_MVMDIO is not set # CONFIG_SKGE is not set CONFIG_SKY2=y # CONFIG_SKY2_DEBUG is not set # CONFIG_OCTEON_EP is not set # CONFIG_OCTEON_EP_VF is not set CONFIG_NET_VENDOR_MELLANOX=y # CONFIG_MLX4_EN is not set # CONFIG_MLX5_CORE is not set # CONFIG_MLXSW_CORE is not set # CONFIG_MLXFW is not set # CONFIG_NET_VENDOR_META is not set CONFIG_NET_VENDOR_MICREL=y # CONFIG_KS8842 is not set # CONFIG_KS8851_MLL is not set # CONFIG_KSZ884X_PCI is not set CONFIG_NET_VENDOR_MICROCHIP=y # CONFIG_LAN743X is not set # CONFIG_VCAP is not set CONFIG_NET_VENDOR_MICROSEMI=y CONFIG_NET_VENDOR_MICROSOFT=y # CONFIG_NET_VENDOR_MUCSE is not set CONFIG_NET_VENDOR_MYRI=y # CONFIG_MYRI10GE is not set # CONFIG_FEALNX is not set CONFIG_NET_VENDOR_NI=y # CONFIG_NI_XGE_MANAGEMENT_ENET is not set CONFIG_NET_VENDOR_NATSEMI=y # CONFIG_NATSEMI is not set # CONFIG_NS83820 is not set CONFIG_NET_VENDOR_NETERION=y # CONFIG_S2IO is not set CONFIG_NET_VENDOR_NETRONOME=y # CONFIG_NFP is not set CONFIG_NET_VENDOR_8390=y # CONFIG_PCMCIA_AXNET is not set # CONFIG_NE2K_PCI is not set # CONFIG_PCMCIA_PCNET is not set CONFIG_NET_VENDOR_NVIDIA=y CONFIG_FORCEDETH=y CONFIG_NET_VENDOR_OKI=y # CONFIG_ETHOC is not set CONFIG_NET_VENDOR_PACKET_ENGINES=y # CONFIG_HAMACHI is not set # CONFIG_YELLOWFIN is not set CONFIG_NET_VENDOR_PENSANDO=y # CONFIG_IONIC is not set CONFIG_NET_VENDOR_QLOGIC=y # CONFIG_QLA3XXX is not set # CONFIG_QLCNIC is not set # CONFIG_NETXEN_NIC is not set # CONFIG_QED is not set CONFIG_NET_VENDOR_BROCADE=y # CONFIG_BNA is not set CONFIG_NET_VENDOR_QUALCOMM=y # CONFIG_QCOM_EMAC is not set # CONFIG_RMNET is not set CONFIG_NET_VENDOR_RDC=y # CONFIG_R6040 is not set CONFIG_NET_VENDOR_REALTEK=y # CONFIG_8139CP is not set CONFIG_8139TOO=y CONFIG_8139TOO_PIO=y # CONFIG_8139TOO_TUNE_TWISTER is not set # CONFIG_8139TOO_8129 is not set # CONFIG_8139_OLD_RX_RESET is not set CONFIG_R8169=y # CONFIG_RTASE is not set CONFIG_NET_VENDOR_RENESAS=y CONFIG_NET_VENDOR_ROCKER=y CONFIG_NET_VENDOR_SAMSUNG=y # CONFIG_SXGBE_ETH is not set CONFIG_NET_VENDOR_SEEQ=y CONFIG_NET_VENDOR_SILAN=y # CONFIG_SC92031 is not set CONFIG_NET_VENDOR_SIS=y # CONFIG_SIS900 is not set # CONFIG_SIS190 is not set CONFIG_NET_VENDOR_SOLARFLARE=y # CONFIG_SFC is not set # CONFIG_SFC_FALCON is not set # CONFIG_SFC_SIENA is not set CONFIG_NET_VENDOR_SMSC=y # CONFIG_PCMCIA_SMC91C92 is not set # CONFIG_EPIC100 is not set # CONFIG_SMSC911X is not set # CONFIG_SMSC9420 is not set CONFIG_NET_VENDOR_SOCIONEXT=y CONFIG_NET_VENDOR_STMICRO=y # CONFIG_STMMAC_ETH is not set CONFIG_NET_VENDOR_SUN=y # CONFIG_HAPPYMEAL is not set # CONFIG_SUNGEM is not set # CONFIG_CASSINI is not set # CONFIG_NIU is not set CONFIG_NET_VENDOR_SYNOPSYS=y # CONFIG_DWC_XLGMAC is not set CONFIG_NET_VENDOR_TEHUTI=y # CONFIG_TEHUTI is not set # CONFIG_TEHUTI_TN40 is not set CONFIG_NET_VENDOR_TI=y # CONFIG_TI_CPSW_PHY_SEL is not set # CONFIG_TLAN is not set # CONFIG_NET_VENDOR_VERTEXCOM is not set CONFIG_NET_VENDOR_VIA=y # CONFIG_VIA_RHINE is not set # CONFIG_VIA_VELOCITY is not set # CONFIG_NET_VENDOR_WANGXUN is not set CONFIG_NET_VENDOR_WIZNET=y # CONFIG_WIZNET_W5100 is not set # CONFIG_WIZNET_W5300 is not set CONFIG_NET_VENDOR_XILINX=y # CONFIG_XILINX_EMACLITE is not set # CONFIG_XILINX_LL_TEMAC is not set CONFIG_NET_VENDOR_XIRCOM=y # CONFIG_PCMCIA_XIRC2PS is not set # CONFIG_FDDI is not set # CONFIG_HIPPI is not set CONFIG_MDIO_BUS=y CONFIG_PHYLIB=y CONFIG_SWPHY=y CONFIG_FIXED_PHY=y # # MII PHY device drivers # # CONFIG_AS21XXX_PHY is not set # CONFIG_AIR_EN8811H_PHY is not set # CONFIG_AMD_PHY is not set # CONFIG_ADIN_PHY is not set # CONFIG_ADIN1100_PHY is not set # CONFIG_AQUANTIA_PHY is not set # CONFIG_AX88796B_PHY is not set # CONFIG_BROADCOM_PHY is not set # CONFIG_BCM54140_PHY is not set # CONFIG_BCM7XXX_PHY is not set # CONFIG_BCM84881_PHY is not set # CONFIG_BCM87XX_PHY is not set # CONFIG_CICADA_PHY is not set # CONFIG_CORTINA_PHY is not set # CONFIG_DAVICOM_PHY is not set # CONFIG_ICPLUS_PHY is not set # CONFIG_LXT_PHY is not set # CONFIG_INTEL_XWAY_PHY is not set # CONFIG_LSI_ET1011C_PHY is not set # CONFIG_MARVELL_PHY is not set # CONFIG_MARVELL_10G_PHY is not set # CONFIG_MARVELL_88Q2XXX_PHY is not set # CONFIG_MARVELL_88X2222_PHY is not set # CONFIG_MAXLINEAR_GPHY is not set # CONFIG_MAXLINEAR_86110_PHY is not set # CONFIG_MEDIATEK_GE_PHY is not set # CONFIG_MICREL_PHY is not set # CONFIG_MICROCHIP_T1S_PHY is not set # CONFIG_MICROCHIP_PHY is not set # CONFIG_MICROCHIP_T1_PHY is not set # CONFIG_MICROSEMI_PHY is not set # CONFIG_MOTORCOMM_PHY is not set # CONFIG_NATIONAL_PHY is not set # CONFIG_NXP_CBTX_PHY is not set # CONFIG_NXP_C45_TJA11XX_PHY is not set # CONFIG_NXP_TJA11XX_PHY is not set # CONFIG_NCN26000_PHY is not set # CONFIG_QCA83XX_PHY is not set # CONFIG_QCA808X_PHY is not set # CONFIG_QSEMI_PHY is not set CONFIG_REALTEK_PHY=y CONFIG_REALTEK_PHY_HWMON=y # CONFIG_RENESAS_PHY is not set # CONFIG_ROCKCHIP_PHY is not set # CONFIG_SMSC_PHY is not set # CONFIG_STE10XP is not set # CONFIG_TERANETICS_PHY is not set # CONFIG_DP83822_PHY is not set # CONFIG_DP83TC811_PHY is not set # CONFIG_DP83848_PHY is not set # CONFIG_DP83867_PHY is not set # CONFIG_DP83869_PHY is not set # CONFIG_DP83TD510_PHY is not set # CONFIG_DP83TG720_PHY is not set # CONFIG_VITESSE_PHY is not set # CONFIG_XILINX_GMII2RGMII is not set CONFIG_FWNODE_MDIO=y CONFIG_ACPI_MDIO=y # CONFIG_MDIO_BITBANG is not set # CONFIG_MDIO_BCM_UNIMAC is not set # CONFIG_MDIO_MVUSB is not set # CONFIG_MDIO_THUNDER is not set # # MDIO Multiplexers # # # PCS device drivers # # CONFIG_PCS_XPCS is not set # end of PCS device drivers CONFIG_PPP=y # CONFIG_PPP_BSDCOMP is not set # CONFIG_PPP_DEFLATE is not set # CONFIG_PPP_FILTER is not set # CONFIG_PPP_MPPE is not set # CONFIG_PPP_MULTILINK is not set # CONFIG_PPPOE is not set CONFIG_PPPOE_HASH_BITS=4 # CONFIG_PPTP is not set CONFIG_PPP_ASYNC=y CONFIG_PPP_SYNC_TTY=y # CONFIG_SLIP is not set CONFIG_SLHC=y CONFIG_USB_NET_DRIVERS=y # CONFIG_USB_CATC is not set # CONFIG_USB_KAWETH is not set # CONFIG_USB_PEGASUS is not set # CONFIG_USB_RTL8150 is not set # CONFIG_USB_RTL8152 is not set # CONFIG_USB_LAN78XX is not set # CONFIG_USB_USBNET is not set # CONFIG_USB_HSO is not set # CONFIG_USB_IPHETH is not set CONFIG_WLAN=y CONFIG_WLAN_VENDOR_ADMTEK=y # CONFIG_ADM8211 is not set CONFIG_WLAN_VENDOR_ATH=y # CONFIG_ATH_DEBUG is not set # CONFIG_ATH5K is not set # CONFIG_ATH5K_PCI is not set # CONFIG_ATH9K is not set # CONFIG_ATH9K_HTC is not set # CONFIG_CARL9170 is not set # CONFIG_ATH6KL is not set # CONFIG_AR5523 is not set # CONFIG_WIL6210 is not set # CONFIG_ATH10K is not set # CONFIG_WCN36XX is not set # CONFIG_ATH11K is not set # CONFIG_ATH12K is not set CONFIG_WLAN_VENDOR_ATMEL=y # CONFIG_AT76C50X_USB is not set CONFIG_WLAN_VENDOR_BROADCOM=y # CONFIG_B43 is not set # CONFIG_B43LEGACY is not set # CONFIG_BRCMSMAC is not set # CONFIG_BRCMFMAC is not set CONFIG_WLAN_VENDOR_INTEL=y # CONFIG_IPW2100 is not set # CONFIG_IPW2200 is not set # CONFIG_IWLWIFI is not set CONFIG_WLAN_VENDOR_INTERSIL=y # CONFIG_P54_COMMON is not set CONFIG_WLAN_VENDOR_MARVELL=y # CONFIG_LIBERTAS is not set # CONFIG_LIBERTAS_THINFIRM is not set # CONFIG_MWIFIEX is not set # CONFIG_MWL8K is not set CONFIG_WLAN_VENDOR_MEDIATEK=y # CONFIG_MT7601U is not set # CONFIG_MT76x0U is not set # CONFIG_MT76x0E is not set # CONFIG_MT76x2E is not set # CONFIG_MT76x2U is not set # CONFIG_MT7603E is not set # CONFIG_MT7615E is not set # CONFIG_MT7663U is not set # CONFIG_MT7915E is not set # CONFIG_MT7921E is not set # CONFIG_MT7921U is not set # CONFIG_MT7996E is not set # CONFIG_MT7925E is not set # CONFIG_MT7925U is not set CONFIG_WLAN_VENDOR_MICROCHIP=y # CONFIG_WLAN_VENDOR_PURELIFI is not set CONFIG_WLAN_VENDOR_RALINK=y # CONFIG_RT2X00 is not set CONFIG_WLAN_VENDOR_REALTEK=y # CONFIG_RTL8180 is not set # CONFIG_RTL8187 is not set CONFIG_RTL_CARDS=y # CONFIG_RTL8192CE is not set # CONFIG_RTL8192SE is not set # CONFIG_RTL8192DE is not set # CONFIG_RTL8723AE is not set # CONFIG_RTL8723BE is not set # CONFIG_RTL8188EE is not set # CONFIG_RTL8192EE is not set # CONFIG_RTL8821AE is not set # CONFIG_RTL8192CU is not set # CONFIG_RTL8192DU is not set # CONFIG_RTW88 is not set # CONFIG_RTW89 is not set CONFIG_WLAN_VENDOR_RSI=y # CONFIG_RSI_91X is not set # CONFIG_WLAN_VENDOR_SILABS is not set CONFIG_WLAN_VENDOR_ST=y # CONFIG_CW1200 is not set CONFIG_WLAN_VENDOR_TI=y # CONFIG_WL1251 is not set # CONFIG_WL12XX is not set # CONFIG_WL18XX is not set # CONFIG_WLCORE is not set CONFIG_WLAN_VENDOR_ZYDAS=y # CONFIG_ZD1211RW is not set CONFIG_WLAN_VENDOR_QUANTENNA=y # CONFIG_QTNFMAC_PCIE is not set # CONFIG_MAC80211_HWSIM is not set # CONFIG_VIRT_WIFI is not set # CONFIG_WAN is not set # # Wireless WAN # # CONFIG_WWAN is not set # end of Wireless WAN # CONFIG_VMXNET3 is not set # CONFIG_FUJITSU_ES is not set CONFIG_NETDEVSIM=y CONFIG_NET_FAILOVER=y # CONFIG_ISDN is not set # # Input device support # CONFIG_INPUT=y CONFIG_INPUT_FF_MEMLESS=y CONFIG_INPUT_SPARSEKMAP=y # CONFIG_INPUT_MATRIXKMAP is not set CONFIG_INPUT_VIVALDIFMAP=y # # Userland interfaces # # CONFIG_INPUT_MOUSEDEV is not set # CONFIG_INPUT_JOYDEV is not set CONFIG_INPUT_EVDEV=y # # Input Device Drivers # CONFIG_INPUT_KEYBOARD=y # CONFIG_KEYBOARD_ADP5588 is not set CONFIG_KEYBOARD_ATKBD=y # CONFIG_KEYBOARD_QT1050 is not set # CONFIG_KEYBOARD_QT1070 is not set # CONFIG_KEYBOARD_QT2160 is not set # CONFIG_KEYBOARD_DLINK_DIR685 is not set # CONFIG_KEYBOARD_LKKBD is not set # CONFIG_KEYBOARD_TCA8418 is not set # CONFIG_KEYBOARD_LM8333 is not set # CONFIG_KEYBOARD_MAX7359 is not set # CONFIG_KEYBOARD_MPR121 is not set # CONFIG_KEYBOARD_NEWTON is not set # CONFIG_KEYBOARD_OPENCORES is not set # CONFIG_KEYBOARD_SAMSUNG is not set # CONFIG_KEYBOARD_STOWAWAY is not set # CONFIG_KEYBOARD_SUNKBD is not set # CONFIG_KEYBOARD_XTKBD is not set # CONFIG_KEYBOARD_CYPRESS_SF is not set CONFIG_INPUT_MOUSE=y CONFIG_MOUSE_PS2=y CONFIG_MOUSE_PS2_ALPS=y CONFIG_MOUSE_PS2_BYD=y CONFIG_MOUSE_PS2_LOGIPS2PP=y CONFIG_MOUSE_PS2_SYNAPTICS=y CONFIG_MOUSE_PS2_SYNAPTICS_SMBUS=y CONFIG_MOUSE_PS2_CYPRESS=y CONFIG_MOUSE_PS2_LIFEBOOK=y CONFIG_MOUSE_PS2_TRACKPOINT=y # CONFIG_MOUSE_PS2_ELANTECH is not set # CONFIG_MOUSE_PS2_SENTELIC is not set # CONFIG_MOUSE_PS2_TOUCHKIT is not set CONFIG_MOUSE_PS2_FOCALTECH=y # CONFIG_MOUSE_PS2_VMMOUSE is not set CONFIG_MOUSE_PS2_SMBUS=y # CONFIG_MOUSE_SERIAL is not set # CONFIG_MOUSE_APPLETOUCH is not set # CONFIG_MOUSE_BCM5974 is not set # CONFIG_MOUSE_CYAPA is not set # CONFIG_MOUSE_ELAN_I2C is not set # CONFIG_MOUSE_VSXXXAA is not set # CONFIG_MOUSE_SYNAPTICS_I2C is not set # CONFIG_MOUSE_SYNAPTICS_USB is not set CONFIG_INPUT_JOYSTICK=y # CONFIG_JOYSTICK_ANALOG is not set # CONFIG_JOYSTICK_A3D is not set # CONFIG_JOYSTICK_ADI is not set # CONFIG_JOYSTICK_COBRA is not set # CONFIG_JOYSTICK_GF2K is not set # CONFIG_JOYSTICK_GRIP is not set # CONFIG_JOYSTICK_GRIP_MP is not set # CONFIG_JOYSTICK_GUILLEMOT is not set # CONFIG_JOYSTICK_INTERACT is not set # CONFIG_JOYSTICK_SIDEWINDER is not set # CONFIG_JOYSTICK_TMDC is not set # CONFIG_JOYSTICK_IFORCE is not set # CONFIG_JOYSTICK_WARRIOR is not set # CONFIG_JOYSTICK_MAGELLAN is not set # CONFIG_JOYSTICK_SPACEORB is not set # CONFIG_JOYSTICK_SPACEBALL is not set # CONFIG_JOYSTICK_STINGER is not set # CONFIG_JOYSTICK_TWIDJOY is not set # CONFIG_JOYSTICK_ZHENHUA is not set # CONFIG_JOYSTICK_AS5011 is not set # CONFIG_JOYSTICK_JOYDUMP is not set # CONFIG_JOYSTICK_XPAD is not set # CONFIG_JOYSTICK_PXRC is not set # CONFIG_JOYSTICK_QWIIC is not set # CONFIG_JOYSTICK_FSIA6B is not set # CONFIG_JOYSTICK_SENSEHAT is not set # CONFIG_JOYSTICK_SEESAW is not set CONFIG_INPUT_TABLET=y # CONFIG_TABLET_USB_ACECAD is not set # CONFIG_TABLET_USB_AIPTEK is not set # CONFIG_TABLET_USB_HANWANG is not set # CONFIG_TABLET_USB_KBTAB is not set # CONFIG_TABLET_USB_PEGASUS is not set # CONFIG_TABLET_SERIAL_WACOM4 is not set CONFIG_INPUT_TOUCHSCREEN=y # CONFIG_TOUCHSCREEN_AD7879 is not set # CONFIG_TOUCHSCREEN_ATMEL_MXT is not set # CONFIG_TOUCHSCREEN_BU21013 is not set # CONFIG_TOUCHSCREEN_BU21029 is not set # CONFIG_TOUCHSCREEN_CHIPONE_ICN8505 is not set # CONFIG_TOUCHSCREEN_CY8CTMA140 is not set # CONFIG_TOUCHSCREEN_CYTTSP_CORE is not set # CONFIG_TOUCHSCREEN_CYTTSP5 is not set # CONFIG_TOUCHSCREEN_DYNAPRO is not set # CONFIG_TOUCHSCREEN_HAMPSHIRE is not set # CONFIG_TOUCHSCREEN_EETI is not set # CONFIG_TOUCHSCREEN_EGALAX_SERIAL is not set # CONFIG_TOUCHSCREEN_EXC3000 is not set # CONFIG_TOUCHSCREEN_FUJITSU is not set # CONFIG_TOUCHSCREEN_GOODIX_BERLIN_I2C is not set # CONFIG_TOUCHSCREEN_HIDEEP is not set # CONFIG_TOUCHSCREEN_HIMAX_HX852X is not set # CONFIG_TOUCHSCREEN_HYCON_HY46XX is not set # CONFIG_TOUCHSCREEN_HYNITRON_CSTXXX is not set # CONFIG_TOUCHSCREEN_HYNITRON_CST816X is not set # CONFIG_TOUCHSCREEN_ILI210X is not set # CONFIG_TOUCHSCREEN_ILITEK is not set # CONFIG_TOUCHSCREEN_S6SY761 is not set # CONFIG_TOUCHSCREEN_GUNZE is not set # CONFIG_TOUCHSCREEN_EKTF2127 is not set # CONFIG_TOUCHSCREEN_ELAN is not set # CONFIG_TOUCHSCREEN_ELO is not set # CONFIG_TOUCHSCREEN_WACOM_W8001 is not set # CONFIG_TOUCHSCREEN_WACOM_I2C is not set # CONFIG_TOUCHSCREEN_MAX11801 is not set # CONFIG_TOUCHSCREEN_MMS114 is not set # CONFIG_TOUCHSCREEN_MELFAS_MIP4 is not set # CONFIG_TOUCHSCREEN_MTOUCH is not set # CONFIG_TOUCHSCREEN_NOVATEK_NVT_TS is not set # CONFIG_TOUCHSCREEN_IMAGIS is not set # CONFIG_TOUCHSCREEN_INEXIO is not set # CONFIG_TOUCHSCREEN_PENMOUNT is not set # CONFIG_TOUCHSCREEN_EDT_FT5X06 is not set # CONFIG_TOUCHSCREEN_TOUCHRIGHT is not set # CONFIG_TOUCHSCREEN_TOUCHWIN is not set # CONFIG_TOUCHSCREEN_PIXCIR is not set # CONFIG_TOUCHSCREEN_WDT87XX_I2C is not set # CONFIG_TOUCHSCREEN_USB_COMPOSITE is not set # CONFIG_TOUCHSCREEN_TOUCHIT213 is not set # CONFIG_TOUCHSCREEN_TSC_SERIO is not set # CONFIG_TOUCHSCREEN_TSC2004 is not set # CONFIG_TOUCHSCREEN_TSC2007 is not set # CONFIG_TOUCHSCREEN_SILEAD is not set # CONFIG_TOUCHSCREEN_ST1232 is not set # CONFIG_TOUCHSCREEN_SX8654 is not set # CONFIG_TOUCHSCREEN_TPS6507X is not set # CONFIG_TOUCHSCREEN_ZET6223 is not set # CONFIG_TOUCHSCREEN_ROHM_BU21023 is not set # CONFIG_TOUCHSCREEN_IQS5XX is not set # CONFIG_TOUCHSCREEN_IQS7211 is not set # CONFIG_TOUCHSCREEN_ZINITIX is not set # CONFIG_TOUCHSCREEN_HIMAX_HX83112B is not set CONFIG_INPUT_MISC=y # CONFIG_INPUT_AD714X is not set # CONFIG_INPUT_AW86927 is not set # CONFIG_INPUT_BMA150 is not set # CONFIG_INPUT_E3X0_BUTTON is not set # CONFIG_INPUT_PCSPKR is not set # CONFIG_INPUT_MMA8450 is not set # CONFIG_INPUT_ATLAS_BTNS is not set # CONFIG_INPUT_ATI_REMOTE2 is not set # CONFIG_INPUT_KEYSPAN_REMOTE is not set # CONFIG_INPUT_KXTJ9 is not set # CONFIG_INPUT_POWERMATE is not set # CONFIG_INPUT_YEALINK is not set # CONFIG_INPUT_CM109 is not set # CONFIG_INPUT_UINPUT is not set # CONFIG_INPUT_PCF8574 is not set # CONFIG_INPUT_DA7280_HAPTICS is not set # CONFIG_INPUT_ADXL34X is not set # CONFIG_INPUT_IQS269A is not set # CONFIG_INPUT_IQS626A is not set # CONFIG_INPUT_IQS7222 is not set # CONFIG_INPUT_CMA3000 is not set # CONFIG_INPUT_IDEAPAD_SLIDEBAR is not set # CONFIG_INPUT_DRV2665_HAPTICS is not set # CONFIG_INPUT_DRV2667_HAPTICS is not set # CONFIG_RMI4_CORE is not set # # Hardware I/O ports # CONFIG_SERIO=y CONFIG_ARCH_MIGHT_HAVE_PC_SERIO=y CONFIG_SERIO_I8042=y CONFIG_SERIO_SERPORT=y # CONFIG_SERIO_CT82C710 is not set # CONFIG_SERIO_PCIPS2 is not set CONFIG_SERIO_LIBPS2=y # CONFIG_SERIO_RAW is not set # CONFIG_SERIO_ALTERA_PS2 is not set # CONFIG_SERIO_PS2MULT is not set # CONFIG_SERIO_ARC_PS2 is not set # CONFIG_USERIO is not set # CONFIG_GAMEPORT is not set # end of Hardware I/O ports # end of Input device support # # Character devices # CONFIG_TTY=y CONFIG_VT=y CONFIG_CONSOLE_TRANSLATIONS=y CONFIG_VT_CONSOLE=y CONFIG_VT_CONSOLE_SLEEP=y CONFIG_VT_HW_CONSOLE_BINDING=y CONFIG_UNIX98_PTYS=y # CONFIG_LEGACY_PTYS is not set CONFIG_LEGACY_TIOCSTI=y CONFIG_LDISC_AUTOLOAD=y # # Serial drivers # CONFIG_SERIAL_EARLYCON=y CONFIG_SERIAL_8250=y CONFIG_SERIAL_8250_PNP=y # CONFIG_SERIAL_8250_16550A_VARIANTS is not set # CONFIG_SERIAL_8250_FINTEK is not set CONFIG_SERIAL_8250_CONSOLE=y CONFIG_SERIAL_8250_DMA=y CONFIG_SERIAL_8250_PCILIB=y CONFIG_SERIAL_8250_PCI=y CONFIG_SERIAL_8250_EXAR=y # CONFIG_SERIAL_8250_CS is not set CONFIG_SERIAL_8250_NR_UARTS=32 CONFIG_SERIAL_8250_RUNTIME_UARTS=4 CONFIG_SERIAL_8250_EXTENDED=y CONFIG_SERIAL_8250_MANY_PORTS=y # CONFIG_SERIAL_8250_PCI1XXXX is not set CONFIG_SERIAL_8250_SHARE_IRQ=y CONFIG_SERIAL_8250_DETECT_IRQ=y CONFIG_SERIAL_8250_RSA=y CONFIG_SERIAL_8250_DWLIB=y # CONFIG_SERIAL_8250_DW is not set # CONFIG_SERIAL_8250_RT288X is not set CONFIG_SERIAL_8250_LPSS=y CONFIG_SERIAL_8250_MID=y # CONFIG_SERIAL_8250_PERICOM is not set # CONFIG_SERIAL_8250_NI is not set # # Non-8250 serial port support # # CONFIG_SERIAL_UARTLITE is not set CONFIG_SERIAL_CORE=y CONFIG_SERIAL_CORE_CONSOLE=y # CONFIG_SERIAL_JSM is not set # CONFIG_SERIAL_LANTIQ is not set # CONFIG_SERIAL_SCCNXP is not set # CONFIG_SERIAL_SC16IS7XX is not set # CONFIG_SERIAL_ALTERA_JTAGUART is not set # CONFIG_SERIAL_ALTERA_UART is not set # CONFIG_SERIAL_ARC is not set # CONFIG_SERIAL_RP2 is not set # CONFIG_SERIAL_FSL_LPUART is not set # CONFIG_SERIAL_FSL_LINFLEXUART is not set # CONFIG_SERIAL_SPRD is not set # end of Serial drivers CONFIG_SERIAL_NONSTANDARD=y # CONFIG_MOXA_INTELLIO is not set # CONFIG_MOXA_SMARTIO is not set # CONFIG_N_HDLC is not set # CONFIG_IPWIRELESS is not set # CONFIG_N_GSM is not set # CONFIG_NOZOMI is not set # CONFIG_NULL_TTY is not set # CONFIG_SERIAL_DEV_BUS is not set # CONFIG_TTY_PRINTK is not set # CONFIG_VIRTIO_CONSOLE is not set # CONFIG_IPMI_HANDLER is not set CONFIG_HW_RANDOM=y # CONFIG_HW_RANDOM_TIMERIOMEM is not set # CONFIG_HW_RANDOM_INTEL is not set # CONFIG_HW_RANDOM_AMD is not set # CONFIG_HW_RANDOM_BA431 is not set CONFIG_HW_RANDOM_VIA=y # CONFIG_HW_RANDOM_VIRTIO is not set # CONFIG_HW_RANDOM_XIPHERA is not set # CONFIG_APPLICOM is not set # CONFIG_MWAVE is not set CONFIG_DEVMEM=y CONFIG_NVRAM=y CONFIG_DEVPORT=y CONFIG_HPET=y # CONFIG_HPET_MMAP is not set # CONFIG_HANGCHECK_TIMER is not set CONFIG_TCG_TPM=y # CONFIG_TCG_TPM2_HMAC is not set CONFIG_HW_RANDOM_TPM=y CONFIG_TCG_TIS_CORE=y CONFIG_TCG_TIS=y # CONFIG_TCG_TIS_I2C is not set # CONFIG_TCG_TIS_I2C_CR50 is not set # CONFIG_TCG_TIS_I2C_ATMEL is not set # CONFIG_TCG_TIS_I2C_INFINEON is not set # CONFIG_TCG_TIS_I2C_NUVOTON is not set # CONFIG_TCG_NSC is not set # CONFIG_TCG_ATMEL is not set # CONFIG_TCG_INFINEON is not set CONFIG_TCG_CRB=y # CONFIG_TCG_VTPM_PROXY is not set # CONFIG_TCG_TIS_ST33ZP24_I2C is not set # CONFIG_TELCLOCK is not set # CONFIG_XILLYBUS is not set # CONFIG_XILLYUSB is not set # end of Character devices # # I2C support # CONFIG_I2C=y CONFIG_ACPI_I2C_OPREGION=y CONFIG_I2C_BOARDINFO=y # CONFIG_I2C_CHARDEV is not set # CONFIG_I2C_MUX is not set CONFIG_I2C_HELPER_AUTO=y CONFIG_I2C_SMBUS=y # # I2C Hardware Bus support # # # PC SMBus host controller drivers # # CONFIG_I2C_ALI1535 is not set # CONFIG_I2C_ALI1563 is not set # CONFIG_I2C_ALI15X3 is not set # CONFIG_I2C_AMD756 is not set # CONFIG_I2C_AMD8111 is not set # CONFIG_I2C_AMD_MP2 is not set CONFIG_I2C_I801=y # CONFIG_I2C_ISCH is not set # CONFIG_I2C_ISMT is not set # CONFIG_I2C_PIIX4 is not set # CONFIG_I2C_NFORCE2 is not set # CONFIG_I2C_NVIDIA_GPU is not set # CONFIG_I2C_SIS5595 is not set # CONFIG_I2C_SIS630 is not set # CONFIG_I2C_SIS96X is not set # CONFIG_I2C_VIA is not set # CONFIG_I2C_VIAPRO is not set # CONFIG_I2C_ZHAOXIN is not set # # ACPI drivers # # CONFIG_I2C_SCMI is not set # # I2C system bus drivers (mostly embedded / system-on-chip) # # CONFIG_I2C_DESIGNWARE_CORE is not set # CONFIG_I2C_EMEV2 is not set # CONFIG_I2C_OCORES is not set # CONFIG_I2C_PCA_PLATFORM is not set # CONFIG_I2C_SIMTEC is not set # CONFIG_I2C_XILINX is not set # # External I2C/SMBus adapter drivers # # CONFIG_I2C_DIOLAN_U2C is not set # CONFIG_I2C_CP2615 is not set # CONFIG_I2C_PCI1XXXX is not set # CONFIG_I2C_ROBOTFUZZ_OSIF is not set # CONFIG_I2C_TAOS_EVM is not set # CONFIG_I2C_TINY_USB is not set # # Other I2C/SMBus bus drivers # # CONFIG_I2C_MLXCPLD is not set # CONFIG_I2C_VIRTIO is not set # end of I2C Hardware Bus support # CONFIG_I2C_STUB is not set # CONFIG_I2C_SLAVE is not set # CONFIG_I2C_DEBUG_CORE is not set # CONFIG_I2C_DEBUG_ALGO is not set # CONFIG_I2C_DEBUG_BUS is not set # end of I2C support # CONFIG_I3C is not set # CONFIG_SPI is not set # CONFIG_SPMI is not set # CONFIG_HSI is not set CONFIG_PPS=y # CONFIG_PPS_DEBUG is not set # # PPS clients support # # CONFIG_PPS_CLIENT_KTIMER is not set # CONFIG_PPS_CLIENT_LDISC is not set # CONFIG_PPS_CLIENT_GPIO is not set # CONFIG_PPS_GENERATOR is not set # # PTP clock support # CONFIG_PTP_1588_CLOCK=y CONFIG_PTP_1588_CLOCK_OPTIONAL=y # # Enable PHYLIB and NETWORK_PHY_TIMESTAMPING to see the additional clocks. # CONFIG_PTP_1588_CLOCK_KVM=y CONFIG_PTP_1588_CLOCK_VMCLOCK=y # CONFIG_PTP_1588_CLOCK_IDT82P33 is not set # CONFIG_PTP_1588_CLOCK_IDTCM is not set # CONFIG_PTP_1588_CLOCK_FC3W is not set # CONFIG_PTP_1588_CLOCK_MOCK is not set # CONFIG_PTP_1588_CLOCK_VMW is not set # CONFIG_PTP_NETC_V4_TIMER is not set # end of PTP clock support # # DPLL device support # # CONFIG_ZL3073X_I2C is not set # end of DPLL device support CONFIG_PINCTRL=y # CONFIG_DEBUG_PINCTRL is not set # CONFIG_PINCTRL_AMD is not set # CONFIG_PINCTRL_CY8C95X0 is not set # CONFIG_PINCTRL_MCP23S08 is not set # CONFIG_PINCTRL_SX150X is not set # # Intel pinctrl drivers # # CONFIG_PINCTRL_BAYTRAIL is not set # CONFIG_PINCTRL_CHERRYVIEW is not set # CONFIG_PINCTRL_LYNXPOINT is not set # CONFIG_PINCTRL_INTEL_PLATFORM is not set # CONFIG_PINCTRL_ALDERLAKE is not set # CONFIG_PINCTRL_BROXTON is not set # CONFIG_PINCTRL_CANNONLAKE is not set # CONFIG_PINCTRL_CEDARFORK is not set # CONFIG_PINCTRL_DENVERTON is not set # CONFIG_PINCTRL_ELKHARTLAKE is not set # CONFIG_PINCTRL_EMMITSBURG is not set # CONFIG_PINCTRL_GEMINILAKE is not set # CONFIG_PINCTRL_ICELAKE is not set # CONFIG_PINCTRL_JASPERLAKE is not set # CONFIG_PINCTRL_LAKEFIELD is not set # CONFIG_PINCTRL_LEWISBURG is not set # CONFIG_PINCTRL_METEORLAKE is not set # CONFIG_PINCTRL_METEORPOINT is not set # CONFIG_PINCTRL_SUNRISEPOINT is not set # CONFIG_PINCTRL_TIGERLAKE is not set # end of Intel pinctrl drivers # # Renesas pinctrl drivers # # end of Renesas pinctrl drivers CONFIG_GPIOLIB_LEGACY=y # CONFIG_GPIOLIB is not set # CONFIG_W1 is not set # CONFIG_POWER_RESET is not set # CONFIG_POWER_SEQUENCING is not set CONFIG_POWER_SUPPLY=y # CONFIG_POWER_SUPPLY_DEBUG is not set CONFIG_POWER_SUPPLY_HWMON=y # CONFIG_IP5XXX_POWER is not set # CONFIG_TEST_POWER is not set # CONFIG_CHARGER_ADP5061 is not set # CONFIG_BATTERY_CW2015 is not set # CONFIG_BATTERY_DS2780 is not set # CONFIG_BATTERY_DS2781 is not set # CONFIG_BATTERY_DS2782 is not set # CONFIG_BATTERY_SAMSUNG_SDI is not set # CONFIG_BATTERY_SBS is not set # CONFIG_CHARGER_SBS is not set # CONFIG_BATTERY_BQ27XXX is not set # CONFIG_BATTERY_MAX17042 is not set # CONFIG_BATTERY_MAX1720X is not set # CONFIG_CHARGER_MAX8903 is not set # CONFIG_CHARGER_LP8727 is not set # CONFIG_CHARGER_LTC4162L is not set # CONFIG_CHARGER_MAX77976 is not set # CONFIG_CHARGER_MAX8971 is not set # CONFIG_CHARGER_BQ2415X is not set # CONFIG_BATTERY_GAUGE_LTC2941 is not set # CONFIG_BATTERY_GOLDFISH is not set # CONFIG_BATTERY_RT5033 is not set # CONFIG_CHARGER_RT9756 is not set # CONFIG_CHARGER_BD99954 is not set # CONFIG_BATTERY_UG3105 is not set # CONFIG_FUEL_GAUGE_MM8013 is not set CONFIG_HWMON=y # CONFIG_HWMON_DEBUG_CHIP is not set # # Native drivers # # CONFIG_SENSORS_ABITUGURU is not set # CONFIG_SENSORS_ABITUGURU3 is not set # CONFIG_SENSORS_AD7414 is not set # CONFIG_SENSORS_AD7418 is not set # CONFIG_SENSORS_ADM1025 is not set # CONFIG_SENSORS_ADM1026 is not set # CONFIG_SENSORS_ADM1029 is not set # CONFIG_SENSORS_ADM1031 is not set # CONFIG_SENSORS_ADM1177 is not set # CONFIG_SENSORS_ADM9240 is not set # CONFIG_SENSORS_ADT7410 is not set # CONFIG_SENSORS_ADT7411 is not set # CONFIG_SENSORS_ADT7462 is not set # CONFIG_SENSORS_ADT7470 is not set # CONFIG_SENSORS_ADT7475 is not set # CONFIG_SENSORS_AHT10 is not set # CONFIG_SENSORS_AQUACOMPUTER_D5NEXT is not set # CONFIG_SENSORS_AS370 is not set # CONFIG_SENSORS_ASC7621 is not set # CONFIG_SENSORS_ASUS_ROG_RYUJIN is not set # CONFIG_SENSORS_AXI_FAN_CONTROL is not set # CONFIG_SENSORS_K8TEMP is not set # CONFIG_SENSORS_K10TEMP is not set # CONFIG_SENSORS_FAM15H_POWER is not set # CONFIG_SENSORS_APPLESMC is not set # CONFIG_SENSORS_ASB100 is not set # CONFIG_SENSORS_ATXP1 is not set # CONFIG_SENSORS_CHIPCAP2 is not set # CONFIG_SENSORS_CORSAIR_CPRO is not set # CONFIG_SENSORS_CORSAIR_PSU is not set # CONFIG_SENSORS_DRIVETEMP is not set # CONFIG_SENSORS_DS620 is not set # CONFIG_SENSORS_DS1621 is not set # CONFIG_SENSORS_I5K_AMB is not set # CONFIG_SENSORS_F71805F is not set # CONFIG_SENSORS_F71882FG is not set # CONFIG_SENSORS_F75375S is not set # CONFIG_SENSORS_FSCHMD is not set # CONFIG_SENSORS_FTSTEUTATES is not set # CONFIG_SENSORS_GIGABYTE_WATERFORCE is not set # CONFIG_SENSORS_GL518SM is not set # CONFIG_SENSORS_GL520SM is not set # CONFIG_SENSORS_GPD is not set # CONFIG_SENSORS_G760A is not set # CONFIG_SENSORS_G762 is not set # CONFIG_SENSORS_HIH6130 is not set # CONFIG_SENSORS_HS3001 is not set # CONFIG_SENSORS_HTU31 is not set # CONFIG_SENSORS_I5500 is not set # CONFIG_SENSORS_CORETEMP is not set # CONFIG_SENSORS_ISL28022 is not set # CONFIG_SENSORS_IT87 is not set # CONFIG_SENSORS_JC42 is not set # CONFIG_SENSORS_POWERZ is not set # CONFIG_SENSORS_POWR1220 is not set # CONFIG_SENSORS_LENOVO_EC is not set # CONFIG_SENSORS_LINEAGE is not set # CONFIG_SENSORS_LTC2945 is not set # CONFIG_SENSORS_LTC2947_I2C is not set # CONFIG_SENSORS_LTC2990 is not set # CONFIG_SENSORS_LTC2991 is not set # CONFIG_SENSORS_LTC4151 is not set # CONFIG_SENSORS_LTC4215 is not set # CONFIG_SENSORS_LTC4222 is not set # CONFIG_SENSORS_LTC4245 is not set # CONFIG_SENSORS_LTC4260 is not set # CONFIG_SENSORS_LTC4261 is not set # CONFIG_SENSORS_LTC4282 is not set # CONFIG_SENSORS_MAX127 is not set # CONFIG_SENSORS_MAX16065 is not set # CONFIG_SENSORS_MAX1619 is not set # CONFIG_SENSORS_MAX1668 is not set # CONFIG_SENSORS_MAX197 is not set # CONFIG_SENSORS_MAX31730 is not set # CONFIG_SENSORS_MAX31760 is not set # CONFIG_MAX31827 is not set # CONFIG_SENSORS_MAX6620 is not set # CONFIG_SENSORS_MAX6621 is not set # CONFIG_SENSORS_MAX6639 is not set # CONFIG_SENSORS_MAX6650 is not set # CONFIG_SENSORS_MAX6697 is not set # CONFIG_SENSORS_MAX31790 is not set # CONFIG_SENSORS_MC34VR500 is not set # CONFIG_SENSORS_MCP3021 is not set # CONFIG_SENSORS_TC654 is not set # CONFIG_SENSORS_TPS23861 is not set # CONFIG_SENSORS_MR75203 is not set # CONFIG_SENSORS_LM63 is not set # CONFIG_SENSORS_LM73 is not set # CONFIG_SENSORS_LM75 is not set # CONFIG_SENSORS_LM77 is not set # CONFIG_SENSORS_LM78 is not set # CONFIG_SENSORS_LM80 is not set # CONFIG_SENSORS_LM83 is not set # CONFIG_SENSORS_LM85 is not set # CONFIG_SENSORS_LM87 is not set # CONFIG_SENSORS_LM90 is not set # CONFIG_SENSORS_LM92 is not set # CONFIG_SENSORS_LM93 is not set # CONFIG_SENSORS_LM95234 is not set # CONFIG_SENSORS_LM95241 is not set # CONFIG_SENSORS_LM95245 is not set # CONFIG_SENSORS_PC87360 is not set # CONFIG_SENSORS_PC87427 is not set # CONFIG_SENSORS_NCT6683 is not set # CONFIG_SENSORS_NCT6775 is not set # CONFIG_SENSORS_NCT6775_I2C is not set # CONFIG_SENSORS_NCT7363 is not set # CONFIG_SENSORS_NCT7802 is not set # CONFIG_SENSORS_NCT7904 is not set # CONFIG_SENSORS_NPCM7XX is not set # CONFIG_SENSORS_NZXT_KRAKEN2 is not set # CONFIG_SENSORS_NZXT_KRAKEN3 is not set # CONFIG_SENSORS_NZXT_SMART2 is not set # CONFIG_SENSORS_OCC_P8_I2C is not set # CONFIG_SENSORS_PCF8591 is not set # CONFIG_PMBUS is not set # CONFIG_SENSORS_PT5161L is not set # CONFIG_SENSORS_SBTSI is not set # CONFIG_SENSORS_SHT21 is not set # CONFIG_SENSORS_SHT3x is not set # CONFIG_SENSORS_SHT4x is not set # CONFIG_SENSORS_SHTC1 is not set # CONFIG_SENSORS_SIS5595 is not set # CONFIG_SENSORS_DME1737 is not set # CONFIG_SENSORS_EMC1403 is not set # CONFIG_SENSORS_EMC2103 is not set # CONFIG_SENSORS_EMC2305 is not set # CONFIG_SENSORS_EMC6W201 is not set # CONFIG_SENSORS_SMSC47M1 is not set # CONFIG_SENSORS_SMSC47M192 is not set # CONFIG_SENSORS_SMSC47B397 is not set # CONFIG_SENSORS_SCH5627 is not set # CONFIG_SENSORS_SCH5636 is not set # CONFIG_SENSORS_STTS751 is not set # CONFIG_SENSORS_ADC128D818 is not set # CONFIG_SENSORS_ADS7828 is not set # CONFIG_SENSORS_AMC6821 is not set # CONFIG_SENSORS_INA209 is not set # CONFIG_SENSORS_INA2XX is not set # CONFIG_SENSORS_INA238 is not set # CONFIG_SENSORS_INA3221 is not set # CONFIG_SENSORS_SPD5118 is not set # CONFIG_SENSORS_TC74 is not set # CONFIG_SENSORS_THMC50 is not set # CONFIG_SENSORS_TMP102 is not set # CONFIG_SENSORS_TMP103 is not set # CONFIG_SENSORS_TMP108 is not set # CONFIG_SENSORS_TMP401 is not set # CONFIG_SENSORS_TMP421 is not set # CONFIG_SENSORS_TMP464 is not set # CONFIG_SENSORS_TMP513 is not set # CONFIG_SENSORS_TSC1641 is not set # CONFIG_SENSORS_VIA_CPUTEMP is not set # CONFIG_SENSORS_VIA686A is not set # CONFIG_SENSORS_VT1211 is not set # CONFIG_SENSORS_VT8231 is not set # CONFIG_SENSORS_W83773G is not set # CONFIG_SENSORS_W83781D is not set # CONFIG_SENSORS_W83791D is not set # CONFIG_SENSORS_W83792D is not set # CONFIG_SENSORS_W83793 is not set # CONFIG_SENSORS_W83795 is not set # CONFIG_SENSORS_W83L785TS is not set # CONFIG_SENSORS_W83L786NG is not set # CONFIG_SENSORS_W83627HF is not set # CONFIG_SENSORS_W83627EHF is not set # CONFIG_SENSORS_XGENE is not set # # ACPI drivers # # CONFIG_SENSORS_ACPI_POWER is not set # CONFIG_SENSORS_ATK0110 is not set # CONFIG_SENSORS_ASUS_EC is not set CONFIG_THERMAL=y # CONFIG_THERMAL_NETLINK is not set # CONFIG_THERMAL_STATISTICS is not set # CONFIG_THERMAL_DEBUGFS is not set # CONFIG_THERMAL_CORE_TESTING is not set CONFIG_THERMAL_EMERGENCY_POWEROFF_DELAY_MS=0 CONFIG_THERMAL_HWMON=y CONFIG_THERMAL_DEFAULT_GOV_STEP_WISE=y # CONFIG_THERMAL_DEFAULT_GOV_FAIR_SHARE is not set # CONFIG_THERMAL_DEFAULT_GOV_USER_SPACE is not set # CONFIG_THERMAL_GOV_FAIR_SHARE is not set CONFIG_THERMAL_GOV_STEP_WISE=y # CONFIG_THERMAL_GOV_BANG_BANG is not set CONFIG_THERMAL_GOV_USER_SPACE=y # CONFIG_PCIE_THERMAL is not set # CONFIG_THERMAL_EMULATION is not set # # Intel thermal drivers # # CONFIG_INTEL_POWERCLAMP is not set CONFIG_X86_THERMAL_VECTOR=y # CONFIG_X86_PKG_TEMP_THERMAL is not set # CONFIG_INTEL_SOC_DTS_THERMAL is not set # # ACPI INT340X thermal drivers # # CONFIG_INT340X_THERMAL is not set # end of ACPI INT340X thermal drivers # CONFIG_INTEL_PCH_THERMAL is not set # CONFIG_INTEL_TCC_COOLING is not set # CONFIG_INTEL_HFI_THERMAL is not set # end of Intel thermal drivers CONFIG_WATCHDOG=y # CONFIG_WATCHDOG_CORE is not set # CONFIG_WATCHDOG_NOWAYOUT is not set CONFIG_WATCHDOG_HANDLE_BOOT_ENABLED=y CONFIG_WATCHDOG_OPEN_TIMEOUT=0 # CONFIG_WATCHDOG_SYSFS is not set # CONFIG_WATCHDOG_HRTIMER_PRETIMEOUT is not set # # Watchdog Pretimeout Governors # # # Watchdog Device Drivers # # CONFIG_SOFT_WATCHDOG is not set # CONFIG_LENOVO_SE10_WDT is not set # CONFIG_LENOVO_SE30_WDT is not set # CONFIG_WDAT_WDT is not set # CONFIG_XILINX_WATCHDOG is not set # CONFIG_ZIIRAVE_WATCHDOG is not set # CONFIG_CADENCE_WATCHDOG is not set # CONFIG_DW_WATCHDOG is not set # CONFIG_MAX63XX_WATCHDOG is not set # CONFIG_ACQUIRE_WDT is not set # CONFIG_ADVANTECH_WDT is not set # CONFIG_ADVANTECH_EC_WDT is not set # CONFIG_ALIM1535_WDT is not set # CONFIG_ALIM7101_WDT is not set # CONFIG_EBC_C384_WDT is not set # CONFIG_EXAR_WDT is not set # CONFIG_F71808E_WDT is not set # CONFIG_SP5100_TCO is not set # CONFIG_SBC_FITPC2_WATCHDOG is not set # CONFIG_EUROTECH_WDT is not set # CONFIG_IB700_WDT is not set # CONFIG_IBMASR is not set # CONFIG_WAFER_WDT is not set # CONFIG_I6300ESB_WDT is not set # CONFIG_IE6XX_WDT is not set # CONFIG_INTEL_OC_WATCHDOG is not set # CONFIG_ITCO_WDT is not set # CONFIG_IT8712F_WDT is not set # CONFIG_IT87_WDT is not set # CONFIG_HP_WATCHDOG is not set # CONFIG_SC1200_WDT is not set # CONFIG_PC87413_WDT is not set # CONFIG_NV_TCO is not set # CONFIG_60XX_WDT is not set # CONFIG_SMSC_SCH311X_WDT is not set # CONFIG_SMSC37B787_WDT is not set # CONFIG_TQMX86_WDT is not set # CONFIG_VIA_WDT is not set # CONFIG_W83627HF_WDT is not set # CONFIG_W83877F_WDT is not set # CONFIG_W83977F_WDT is not set # CONFIG_MACHZ_WDT is not set # CONFIG_SBC_EPX_C3_WATCHDOG is not set # CONFIG_NI903X_WDT is not set # CONFIG_NIC7018_WDT is not set # # PCI-based Watchdog Cards # # CONFIG_PCIPCWATCHDOG is not set # CONFIG_WDTPCI is not set # # USB-based Watchdog Cards # # CONFIG_USBPCWATCHDOG is not set CONFIG_SSB_POSSIBLE=y # CONFIG_SSB is not set CONFIG_BCMA_POSSIBLE=y # CONFIG_BCMA is not set # # Multifunction device drivers # # CONFIG_MFD_AS3711 is not set # CONFIG_MFD_SMPRO is not set # CONFIG_PMIC_ADP5520 is not set # CONFIG_MFD_BCM590XX is not set # CONFIG_MFD_BD9571MWV is not set # CONFIG_MFD_AXP20X_I2C is not set # CONFIG_MFD_CGBC is not set # CONFIG_MFD_CS40L50_I2C is not set # CONFIG_MFD_CS42L43_I2C is not set # CONFIG_MFD_MADERA is not set # CONFIG_PMIC_DA903X is not set # CONFIG_MFD_DA9052_I2C is not set # CONFIG_MFD_DA9055 is not set # CONFIG_MFD_DA9062 is not set # CONFIG_MFD_DA9063 is not set # CONFIG_MFD_DA9150 is not set # CONFIG_MFD_DLN2 is not set # CONFIG_MFD_MC13XXX_I2C is not set # CONFIG_MFD_MP2629 is not set # CONFIG_MFD_INTEL_QUARK_I2C_GPIO is not set # CONFIG_LPC_ICH is not set # CONFIG_LPC_SCH is not set # CONFIG_MFD_INTEL_LPSS_ACPI is not set # CONFIG_MFD_INTEL_LPSS_PCI is not set # CONFIG_MFD_INTEL_PMC_BXT is not set # CONFIG_MFD_IQS62X is not set # CONFIG_MFD_JANZ_CMODIO is not set # CONFIG_MFD_KEMPLD is not set # CONFIG_MFD_88PM800 is not set # CONFIG_MFD_88PM805 is not set # CONFIG_MFD_88PM860X is not set # CONFIG_MFD_MAX5970 is not set # CONFIG_MFD_MAX14577 is not set # CONFIG_MFD_MAX77541 is not set # CONFIG_MFD_MAX77693 is not set # CONFIG_MFD_MAX77705 is not set # CONFIG_MFD_MAX77843 is not set # CONFIG_MFD_MAX8907 is not set # CONFIG_MFD_MAX8925 is not set # CONFIG_MFD_MAX8997 is not set # CONFIG_MFD_MAX8998 is not set # CONFIG_MFD_MT6360 is not set # CONFIG_MFD_MT6370 is not set # CONFIG_MFD_MT6397 is not set # CONFIG_MFD_MENF21BMC is not set # CONFIG_MFD_NCT6694 is not set # CONFIG_MFD_VIPERBOARD is not set # CONFIG_MFD_RETU is not set # CONFIG_MFD_SY7636A is not set # CONFIG_MFD_RDC321X is not set # CONFIG_MFD_RT4831 is not set # CONFIG_MFD_RT5033 is not set # CONFIG_MFD_RT5120 is not set # CONFIG_MFD_RC5T583 is not set # CONFIG_MFD_SI476X_CORE is not set # CONFIG_MFD_SM501 is not set # CONFIG_MFD_SKY81452 is not set # CONFIG_MFD_SYSCON is not set # CONFIG_MFD_LP3943 is not set # CONFIG_MFD_LP8788 is not set # CONFIG_MFD_TI_LMU is not set # CONFIG_MFD_BQ257XX is not set # CONFIG_MFD_PALMAS is not set # CONFIG_TPS6105X is not set # CONFIG_TPS6507X is not set # CONFIG_MFD_TPS65086 is not set # CONFIG_MFD_TPS65090 is not set # CONFIG_MFD_TI_LP873X is not set # CONFIG_MFD_TPS6586X is not set # CONFIG_MFD_TPS65912_I2C is not set # CONFIG_MFD_TPS6594_I2C is not set # CONFIG_TWL4030_CORE is not set # CONFIG_TWL6040_CORE is not set # CONFIG_MFD_LM3533 is not set # CONFIG_MFD_TQMX86 is not set # CONFIG_MFD_VX855 is not set # CONFIG_MFD_ARIZONA_I2C is not set # CONFIG_MFD_WM8400 is not set # CONFIG_MFD_WM831X_I2C is not set # CONFIG_MFD_WM8350_I2C is not set # CONFIG_MFD_WM8994 is not set # CONFIG_MFD_ATC260X_I2C is not set # CONFIG_MFD_UPBOARD_FPGA is not set # CONFIG_MFD_MAX7360 is not set # end of Multifunction device drivers # CONFIG_REGULATOR is not set # CONFIG_RC_CORE is not set # # CEC support # # CONFIG_MEDIA_CEC_SUPPORT is not set # end of CEC support # CONFIG_MEDIA_SUPPORT is not set # # Graphics support # CONFIG_APERTURE_HELPERS=y CONFIG_SCREEN_INFO=y CONFIG_VIDEO=y # CONFIG_AUXDISPLAY is not set CONFIG_AGP=y CONFIG_AGP_AMD64=y CONFIG_AGP_INTEL=y # CONFIG_AGP_SIS is not set # CONFIG_AGP_VIA is not set CONFIG_INTEL_GTT=y # CONFIG_VGA_SWITCHEROO is not set CONFIG_DRM=y # # DRM debugging options # # CONFIG_DRM_WERROR is not set # CONFIG_DRM_DEBUG_MM is not set # end of DRM debugging options # CONFIG_DRM_PANIC is not set # CONFIG_DRM_DEBUG_DP_MST_TOPOLOGY_REFS is not set # CONFIG_DRM_DEBUG_MODESET_LOCK is not set # CONFIG_DRM_LOAD_EDID_FIRMWARE is not set # # Drivers for system framebuffers # # CONFIG_DRM_EFIDRM is not set # CONFIG_DRM_SIMPLEDRM is not set # CONFIG_DRM_VESADRM is not set # end of Drivers for system framebuffers # # ARM devices # # end of ARM devices # CONFIG_DRM_RADEON is not set # CONFIG_DRM_AMDGPU is not set # CONFIG_DRM_NOUVEAU is not set # CONFIG_DRM_I915 is not set # CONFIG_DRM_XE is not set # CONFIG_DRM_VGEM is not set # CONFIG_DRM_VKMS is not set # CONFIG_DRM_VMWGFX is not set # CONFIG_DRM_GMA500 is not set # CONFIG_DRM_UDL is not set # CONFIG_DRM_AST is not set # CONFIG_DRM_MGAG200 is not set # CONFIG_DRM_QXL is not set # CONFIG_DRM_VIRTIO_GPU is not set CONFIG_DRM_PANEL=y # # Display Panels # # end of Display Panels CONFIG_DRM_BRIDGE=y CONFIG_DRM_PANEL_BRIDGE=y # # Display Interface Bridges # # CONFIG_DRM_I2C_NXP_TDA998X is not set # CONFIG_DRM_ANALOGIX_ANX78XX is not set # end of Display Interface Bridges # CONFIG_DRM_ETNAVIV is not set # CONFIG_DRM_HISI_HIBMC is not set # CONFIG_DRM_APPLETBDRM is not set # CONFIG_DRM_BOCHS is not set # CONFIG_DRM_CIRRUS_QEMU is not set # CONFIG_DRM_GM12U320 is not set # CONFIG_DRM_VBOXVIDEO is not set # CONFIG_DRM_GUD is not set # CONFIG_DRM_ST7571_I2C is not set # CONFIG_DRM_SSD130X is not set CONFIG_DRM_PANEL_ORIENTATION_QUIRKS=y # # Frame buffer Devices # CONFIG_FB=y # CONFIG_FB_CIRRUS is not set # CONFIG_FB_PM2 is not set # CONFIG_FB_CYBER2000 is not set # CONFIG_FB_ARC is not set # CONFIG_FB_ASILIANT is not set # CONFIG_FB_IMSTT is not set # CONFIG_FB_VGA16 is not set # CONFIG_FB_UVESA is not set # CONFIG_FB_VESA is not set CONFIG_FB_EFI=y # CONFIG_FB_N411 is not set # CONFIG_FB_HGA is not set # CONFIG_FB_OPENCORES is not set # CONFIG_FB_S1D13XXX is not set # CONFIG_FB_NVIDIA is not set # CONFIG_FB_RIVA is not set # CONFIG_FB_I740 is not set # CONFIG_FB_MATROX is not set # CONFIG_FB_RADEON is not set # CONFIG_FB_ATY128 is not set # CONFIG_FB_ATY is not set # CONFIG_FB_S3 is not set # CONFIG_FB_SAVAGE is not set # CONFIG_FB_SIS is not set # CONFIG_FB_NEOMAGIC is not set # CONFIG_FB_KYRO is not set # CONFIG_FB_3DFX is not set # CONFIG_FB_VOODOO1 is not set # CONFIG_FB_VT8623 is not set # CONFIG_FB_TRIDENT is not set # CONFIG_FB_ARK is not set # CONFIG_FB_PM3 is not set # CONFIG_FB_CARMINE is not set # CONFIG_FB_SMSCUFX is not set # CONFIG_FB_UDL is not set # CONFIG_FB_IBM_GXT4500 is not set # CONFIG_FB_VIRTUAL is not set # CONFIG_FB_METRONOME is not set # CONFIG_FB_MB862XX is not set # CONFIG_FB_SIMPLE is not set # CONFIG_FB_SM712 is not set CONFIG_FB_CORE=y CONFIG_FB_NOTIFY=y CONFIG_FB_DEVICE=y CONFIG_FB_CFB_FILLRECT=y CONFIG_FB_CFB_COPYAREA=y CONFIG_FB_CFB_IMAGEBLIT=y # CONFIG_FB_FOREIGN_ENDIAN is not set CONFIG_FB_IOMEM_FOPS=y CONFIG_FB_IOMEM_HELPERS=y CONFIG_FB_TILEBLITTING=y # end of Frame buffer Devices # # Backlight & LCD device support # # CONFIG_LCD_CLASS_DEVICE is not set CONFIG_BACKLIGHT_CLASS_DEVICE=y # CONFIG_BACKLIGHT_AW99706 is not set # CONFIG_BACKLIGHT_KTZ8866 is not set # CONFIG_BACKLIGHT_APPLE is not set # CONFIG_BACKLIGHT_QCOM_WLED is not set # CONFIG_BACKLIGHT_SAHARA is not set # CONFIG_BACKLIGHT_ADP8860 is not set # CONFIG_BACKLIGHT_ADP8870 is not set # CONFIG_BACKLIGHT_LM3509 is not set # CONFIG_BACKLIGHT_LM3639 is not set # CONFIG_BACKLIGHT_LV5207LP is not set # CONFIG_BACKLIGHT_BD6107 is not set # CONFIG_BACKLIGHT_ARCXCNN is not set # end of Backlight & LCD device support CONFIG_HDMI=y # CONFIG_FIRMWARE_EDID is not set # # Console display driver support # CONFIG_VGA_CONSOLE=y CONFIG_DUMMY_CONSOLE=y CONFIG_DUMMY_CONSOLE_COLUMNS=80 CONFIG_DUMMY_CONSOLE_ROWS=25 CONFIG_FRAMEBUFFER_CONSOLE=y # CONFIG_FRAMEBUFFER_CONSOLE_LEGACY_ACCELERATION is not set CONFIG_FRAMEBUFFER_CONSOLE_DETECT_PRIMARY=y # CONFIG_FRAMEBUFFER_CONSOLE_ROTATION is not set CONFIG_FRAMEBUFFER_CONSOLE_DEFERRED_TAKEOVER=y # end of Console display driver support CONFIG_LOGO=y # CONFIG_LOGO_LINUX_MONO is not set # CONFIG_LOGO_LINUX_VGA16 is not set CONFIG_LOGO_LINUX_CLUT224=y # CONFIG_TRACE_GPU_MEM is not set # end of Graphics support # CONFIG_DRM_ACCEL is not set # CONFIG_SOUND is not set CONFIG_HID_SUPPORT=y CONFIG_HID=y CONFIG_HID_BATTERY_STRENGTH=y CONFIG_HIDRAW=y # CONFIG_UHID is not set CONFIG_HID_GENERIC=y # CONFIG_HID_HAPTIC is not set # # Special HID drivers # # CONFIG_HID_A4TECH is not set # CONFIG_HID_ACCUTOUCH is not set # CONFIG_HID_ACRUX is not set # CONFIG_HID_APPLEIR is not set # CONFIG_HID_APPLETB_BL is not set # CONFIG_HID_APPLETB_KBD is not set # CONFIG_HID_AUREAL is not set # CONFIG_HID_BELKIN is not set # CONFIG_HID_BETOP_FF is not set # CONFIG_HID_CHERRY is not set # CONFIG_HID_CHICONY is not set # CONFIG_HID_COUGAR is not set # CONFIG_HID_MACALLY is not set # CONFIG_HID_CMEDIA is not set # CONFIG_HID_CREATIVE_SB0540 is not set # CONFIG_HID_CYPRESS is not set # CONFIG_HID_DRAGONRISE is not set # CONFIG_HID_EMS_FF is not set # CONFIG_HID_ELECOM is not set # CONFIG_HID_ELO is not set # CONFIG_HID_EVISION is not set # CONFIG_HID_EZKEY is not set # CONFIG_HID_FT260 is not set # CONFIG_HID_GEMBIRD is not set # CONFIG_HID_GFRM is not set # CONFIG_HID_GLORIOUS is not set # CONFIG_HID_HOLTEK is not set # CONFIG_HID_GOOGLE_STADIA_FF is not set # CONFIG_HID_VIVALDI is not set # CONFIG_HID_KEYTOUCH is not set # CONFIG_HID_KYE is not set # CONFIG_HID_KYSONA is not set # CONFIG_HID_UCLOGIC is not set # CONFIG_HID_WALTOP is not set # CONFIG_HID_VIEWSONIC is not set # CONFIG_HID_VRC2 is not set # CONFIG_HID_XIAOMI is not set CONFIG_HID_GYRATION=y # CONFIG_HID_ICADE is not set # CONFIG_HID_ITE is not set # CONFIG_HID_JABRA is not set # CONFIG_HID_TWINHAN is not set # CONFIG_HID_KENSINGTON is not set # CONFIG_HID_LCPOWER is not set # CONFIG_HID_LENOVO is not set # CONFIG_HID_LETSKETCH is not set # CONFIG_HID_MAGICMOUSE is not set # CONFIG_HID_MALTRON is not set # CONFIG_HID_MAYFLASH is not set # CONFIG_HID_MEGAWORLD_FF is not set # CONFIG_HID_REDRAGON is not set # CONFIG_HID_MICROSOFT is not set # CONFIG_HID_MONTEREY is not set # CONFIG_HID_MULTITOUCH is not set # CONFIG_HID_NTI is not set CONFIG_HID_NTRIG=y # CONFIG_HID_ORTEK is not set CONFIG_HID_PANTHERLORD=y CONFIG_PANTHERLORD_FF=y # CONFIG_HID_PENMOUNT is not set CONFIG_HID_PETALYNX=y # CONFIG_HID_PICOLCD is not set # CONFIG_HID_PLANTRONICS is not set # CONFIG_HID_PXRC is not set # CONFIG_HID_RAZER is not set # CONFIG_HID_PRIMAX is not set # CONFIG_HID_RETRODE is not set # CONFIG_HID_ROCCAT is not set # CONFIG_HID_SAITEK is not set CONFIG_HID_SAMSUNG=y # CONFIG_HID_SEMITEK is not set # CONFIG_HID_SIGMAMICRO is not set # CONFIG_HID_SPEEDLINK is not set # CONFIG_HID_STEAM is not set # CONFIG_HID_STEELSERIES is not set CONFIG_HID_SUNPLUS=y # CONFIG_HID_RMI is not set # CONFIG_HID_GREENASIA is not set # CONFIG_HID_SMARTJOYPLUS is not set # CONFIG_HID_TIVO is not set CONFIG_HID_TOPSEED=y # CONFIG_HID_TOPRE is not set # CONFIG_HID_THRUSTMASTER is not set # CONFIG_HID_UDRAW_PS3 is not set # CONFIG_HID_UNIVERSAL_PIDFF is not set # CONFIG_HID_WACOM is not set # CONFIG_HID_XINMO is not set # CONFIG_HID_ZEROPLUS is not set # CONFIG_HID_ZYDACRON is not set # CONFIG_HID_SENSOR_HUB is not set # CONFIG_HID_ALPS is not set # CONFIG_HID_MCP2221 is not set # end of Special HID drivers # # HID-BPF support # CONFIG_HID_BPF=y # end of HID-BPF support CONFIG_I2C_HID=y # CONFIG_I2C_HID_ACPI is not set # CONFIG_I2C_HID_OF is not set # # Intel ISH HID support # # CONFIG_INTEL_ISH_HID is not set # end of Intel ISH HID support # # AMD SFH HID Support # # CONFIG_AMD_SFH_HID is not set # end of AMD SFH HID Support # # Intel THC HID Support # # CONFIG_INTEL_THC_HID is not set # end of Intel THC HID Support # # USB HID support # CONFIG_USB_HID=y CONFIG_HID_PID=y CONFIG_USB_HIDDEV=y # end of USB HID support CONFIG_USB_OHCI_LITTLE_ENDIAN=y CONFIG_USB_SUPPORT=y CONFIG_USB_COMMON=y # CONFIG_USB_ULPI_BUS is not set CONFIG_USB_ARCH_HAS_HCD=y CONFIG_USB=y CONFIG_USB_PCI=y CONFIG_USB_PCI_AMD=y CONFIG_USB_ANNOUNCE_NEW_DEVICES=y # # Miscellaneous USB options # CONFIG_USB_DEFAULT_PERSIST=y # CONFIG_USB_FEW_INIT_RETRIES is not set # CONFIG_USB_DYNAMIC_MINORS is not set # CONFIG_USB_OTG is not set # CONFIG_USB_OTG_PRODUCTLIST is not set # CONFIG_USB_OTG_DISABLE_EXTERNAL_HUB is not set CONFIG_USB_AUTOSUSPEND_DELAY=2 CONFIG_USB_DEFAULT_AUTHORIZATION_MODE=1 CONFIG_USB_MON=y # # USB Host Controller Drivers # # CONFIG_USB_C67X00_HCD is not set # CONFIG_USB_XHCI_HCD is not set # CONFIG_USB_EHCI_HCD is not set # CONFIG_USB_OXU210HP_HCD is not set # CONFIG_USB_ISP116X_HCD is not set CONFIG_USB_OHCI_HCD=y CONFIG_USB_OHCI_HCD_PCI=y # CONFIG_USB_OHCI_HCD_PLATFORM is not set CONFIG_USB_UHCI_HCD=y # CONFIG_USB_SL811_HCD is not set # CONFIG_USB_R8A66597_HCD is not set # CONFIG_USB_HCD_TEST_MODE is not set # # USB Device Class drivers # # CONFIG_USB_ACM is not set CONFIG_USB_PRINTER=y # CONFIG_USB_WDM is not set # CONFIG_USB_TMC is not set # # NOTE: USB_STORAGE depends on SCSI but BLK_DEV_SD may also be needed; see USB_STORAGE Help for more info # CONFIG_USB_STORAGE=y # CONFIG_USB_STORAGE_DEBUG is not set # CONFIG_USB_STORAGE_REALTEK is not set # CONFIG_USB_STORAGE_DATAFAB is not set # CONFIG_USB_STORAGE_FREECOM is not set # CONFIG_USB_STORAGE_ISD200 is not set # CONFIG_USB_STORAGE_USBAT is not set # CONFIG_USB_STORAGE_SDDR09 is not set # CONFIG_USB_STORAGE_SDDR55 is not set # CONFIG_USB_STORAGE_JUMPSHOT is not set # CONFIG_USB_STORAGE_ALAUDA is not set # CONFIG_USB_STORAGE_ONETOUCH is not set # CONFIG_USB_STORAGE_KARMA is not set # CONFIG_USB_STORAGE_CYPRESS_ATACB is not set # CONFIG_USB_STORAGE_ENE_UB6250 is not set # CONFIG_USB_UAS is not set # # USB Imaging devices # # CONFIG_USB_MDC800 is not set # CONFIG_USB_MICROTEK is not set # CONFIG_USBIP_CORE is not set # # USB dual-mode controller drivers # # CONFIG_USB_CDNS_SUPPORT is not set # CONFIG_USB_MUSB_HDRC is not set # CONFIG_USB_DWC3 is not set # CONFIG_USB_DWC2 is not set # CONFIG_USB_ISP1760 is not set # # USB port drivers # # CONFIG_USB_SERIAL is not set # # USB Miscellaneous drivers # # CONFIG_USB_EMI62 is not set # CONFIG_USB_EMI26 is not set # CONFIG_USB_ADUTUX is not set # CONFIG_USB_SEVSEG is not set # CONFIG_USB_LEGOTOWER is not set # CONFIG_USB_LCD is not set # CONFIG_USB_CYPRESS_CY7C63 is not set # CONFIG_USB_CYTHERM is not set # CONFIG_USB_IDMOUSE is not set # CONFIG_USB_APPLEDISPLAY is not set # CONFIG_APPLE_MFI_FASTCHARGE is not set # CONFIG_USB_LJCA is not set # CONFIG_USB_USBIO is not set # CONFIG_USB_LD is not set # CONFIG_USB_TRANCEVIBRATOR is not set # CONFIG_USB_IOWARRIOR is not set # CONFIG_USB_TEST is not set # CONFIG_USB_EHSET_TEST_FIXTURE is not set # CONFIG_USB_ISIGHTFW is not set # CONFIG_USB_YUREX is not set # CONFIG_USB_EZUSB_FX2 is not set # CONFIG_USB_HUB_USB251XB is not set # CONFIG_USB_HSIC_USB3503 is not set # CONFIG_USB_HSIC_USB4604 is not set # CONFIG_USB_LINK_LAYER_TEST is not set # CONFIG_USB_CHAOSKEY is not set # # USB Physical Layer drivers # # CONFIG_NOP_USB_XCEIV is not set # CONFIG_USB_ISP1301 is not set # end of USB Physical Layer drivers # CONFIG_USB_GADGET is not set # CONFIG_TYPEC is not set # CONFIG_USB_ROLE_SWITCH is not set # CONFIG_MMC is not set # CONFIG_SCSI_UFSHCD is not set # CONFIG_MEMSTICK is not set # CONFIG_NEW_LEDS is not set # CONFIG_ACCESSIBILITY is not set # CONFIG_INFINIBAND is not set CONFIG_EDAC_ATOMIC_SCRUB=y CONFIG_EDAC_SUPPORT=y CONFIG_EDAC=y # CONFIG_EDAC_DEBUG is not set CONFIG_EDAC_DECODE_MCE=y # CONFIG_EDAC_SCRUB is not set # CONFIG_EDAC_ECS is not set # CONFIG_EDAC_MEM_REPAIR is not set # CONFIG_EDAC_AMD64 is not set # CONFIG_EDAC_E752X is not set # CONFIG_EDAC_I82975X is not set # CONFIG_EDAC_I3000 is not set # CONFIG_EDAC_I3200 is not set # CONFIG_EDAC_IE31200 is not set # CONFIG_EDAC_X38 is not set # CONFIG_EDAC_I5400 is not set # CONFIG_EDAC_I7CORE is not set # CONFIG_EDAC_I5100 is not set # CONFIG_EDAC_I7300 is not set # CONFIG_EDAC_SBRIDGE is not set # CONFIG_EDAC_SKX is not set # CONFIG_EDAC_I10NM is not set # CONFIG_EDAC_IMH is not set # CONFIG_EDAC_PND2 is not set # CONFIG_EDAC_IGEN6 is not set CONFIG_RTC_LIB=y CONFIG_RTC_MC146818_LIB=y CONFIG_RTC_CLASS=y # CONFIG_RTC_HCTOSYS is not set CONFIG_RTC_SYSTOHC=y CONFIG_RTC_SYSTOHC_DEVICE="rtc0" # CONFIG_RTC_DEBUG is not set CONFIG_RTC_NVMEM=y # # RTC interfaces # CONFIG_RTC_INTF_SYSFS=y CONFIG_RTC_INTF_PROC=y CONFIG_RTC_INTF_DEV=y # CONFIG_RTC_INTF_DEV_UIE_EMUL is not set # CONFIG_RTC_DRV_TEST is not set # # I2C RTC drivers # # CONFIG_RTC_DRV_ABB5ZES3 is not set # CONFIG_RTC_DRV_ABEOZ9 is not set # CONFIG_RTC_DRV_ABX80X is not set # CONFIG_RTC_DRV_DS1307 is not set # CONFIG_RTC_DRV_DS1374 is not set # CONFIG_RTC_DRV_DS1672 is not set # CONFIG_RTC_DRV_MAX6900 is not set # CONFIG_RTC_DRV_MAX31335 is not set # CONFIG_RTC_DRV_NVIDIA_VRS10 is not set # CONFIG_RTC_DRV_RS5C372 is not set # CONFIG_RTC_DRV_ISL1208 is not set # CONFIG_RTC_DRV_ISL12022 is not set # CONFIG_RTC_DRV_X1205 is not set # CONFIG_RTC_DRV_PCF8523 is not set # CONFIG_RTC_DRV_PCF85363 is not set # CONFIG_RTC_DRV_PCF8563 is not set # CONFIG_RTC_DRV_PCF8583 is not set # CONFIG_RTC_DRV_M41T80 is not set # CONFIG_RTC_DRV_BQ32K is not set # CONFIG_RTC_DRV_S35390A is not set # CONFIG_RTC_DRV_FM3130 is not set # CONFIG_RTC_DRV_RX8010 is not set # CONFIG_RTC_DRV_RX8111 is not set # CONFIG_RTC_DRV_RX8581 is not set # CONFIG_RTC_DRV_RX8025 is not set # CONFIG_RTC_DRV_EM3027 is not set # CONFIG_RTC_DRV_RV3028 is not set # CONFIG_RTC_DRV_RV3032 is not set # CONFIG_RTC_DRV_RV8803 is not set # CONFIG_RTC_DRV_SD2405AL is not set # CONFIG_RTC_DRV_SD3078 is not set # # SPI RTC drivers # CONFIG_RTC_I2C_AND_SPI=y # # SPI and I2C RTC drivers # # CONFIG_RTC_DRV_DS3232 is not set # CONFIG_RTC_DRV_PCF2127 is not set # CONFIG_RTC_DRV_PCF85063 is not set # CONFIG_RTC_DRV_RV3029C2 is not set # CONFIG_RTC_DRV_RX6110 is not set # # Platform RTC drivers # CONFIG_RTC_DRV_CMOS=y # CONFIG_RTC_DRV_DS1286 is not set # CONFIG_RTC_DRV_DS1511 is not set # CONFIG_RTC_DRV_DS1553 is not set # CONFIG_RTC_DRV_DS1685_FAMILY is not set # CONFIG_RTC_DRV_DS1742 is not set # CONFIG_RTC_DRV_DS2404 is not set # CONFIG_RTC_DRV_STK17TA8 is not set # CONFIG_RTC_DRV_M48T86 is not set # CONFIG_RTC_DRV_M48T35 is not set # CONFIG_RTC_DRV_M48T59 is not set # CONFIG_RTC_DRV_MSM6242 is not set # CONFIG_RTC_DRV_RP5C01 is not set # # on-CPU RTC drivers # # CONFIG_RTC_DRV_FTRTC010 is not set # CONFIG_RTC_DRV_GOLDFISH is not set # # HID Sensor RTC drivers # CONFIG_DMADEVICES=y # CONFIG_DMADEVICES_DEBUG is not set # # DMA Devices # CONFIG_DMA_ENGINE=y CONFIG_DMA_VIRTUAL_CHANNELS=y CONFIG_DMA_ACPI=y # CONFIG_ALTERA_MSGDMA is not set # CONFIG_INTEL_IDMA64 is not set # CONFIG_INTEL_IDXD is not set # CONFIG_INTEL_IDXD_COMPAT is not set # CONFIG_INTEL_IOATDMA is not set # CONFIG_PLX_DMA is not set # CONFIG_XILINX_DMA is not set # CONFIG_XILINX_XDMA is not set # CONFIG_AMD_PTDMA is not set # CONFIG_AMD_QDMA is not set # CONFIG_QCOM_HIDMA_MGMT is not set # CONFIG_QCOM_HIDMA is not set CONFIG_DW_DMAC_CORE=y # CONFIG_DW_DMAC is not set CONFIG_DW_DMAC_PCI=y # CONFIG_DW_EDMA is not set CONFIG_HSU_DMA=y # CONFIG_SF_PDMA is not set # CONFIG_INTEL_LDMA is not set # # DMA Clients # # CONFIG_ASYNC_TX_DMA is not set # CONFIG_DMATEST is not set # # DMABUF options # CONFIG_SYNC_FILE=y # CONFIG_SW_SYNC is not set # CONFIG_UDMABUF is not set # CONFIG_DMABUF_MOVE_NOTIFY is not set # CONFIG_DMABUF_DEBUG is not set # CONFIG_DMABUF_SELFTESTS is not set # CONFIG_DMABUF_HEAPS is not set # CONFIG_DMABUF_SYSFS_STATS is not set # end of DMABUF options # CONFIG_UIO is not set # CONFIG_VFIO is not set # CONFIG_VIRT_DRIVERS is not set CONFIG_VIRTIO_ANCHOR=y CONFIG_VIRTIO=y CONFIG_VIRTIO_PCI_LIB=y CONFIG_VIRTIO_PCI_LIB_LEGACY=y CONFIG_VIRTIO_MENU=y CONFIG_VIRTIO_PCI=y CONFIG_VIRTIO_PCI_ADMIN_LEGACY=y CONFIG_VIRTIO_PCI_LEGACY=y # CONFIG_VIRTIO_BALLOON is not set # CONFIG_VIRTIO_INPUT is not set # CONFIG_VIRTIO_MMIO is not set # CONFIG_VIRTIO_DEBUG is not set # CONFIG_VIRTIO_RTC is not set # CONFIG_VDPA is not set CONFIG_VHOST_IOTLB=y CONFIG_VHOST_TASK=y CONFIG_VHOST=y CONFIG_VHOST_MENU=y CONFIG_VHOST_NET=y # CONFIG_VHOST_CROSS_ENDIAN_LEGACY is not set CONFIG_VHOST_ENABLE_FORK_OWNER_CONTROL=y # # Microsoft Hyper-V guest support # # CONFIG_HYPERV is not set # end of Microsoft Hyper-V guest support # CONFIG_GREYBUS is not set # CONFIG_COMEDI is not set # CONFIG_GPIB is not set # CONFIG_STAGING is not set # CONFIG_GOLDFISH is not set # CONFIG_CHROME_PLATFORMS is not set # CONFIG_MELLANOX_PLATFORM is not set # CONFIG_SURFACE_PLATFORMS is not set CONFIG_X86_PLATFORM_DEVICES=y # CONFIG_X86_PLATFORM_DRIVERS_UNIWILL is not set # CONFIG_ACERHDF is not set # CONFIG_ACER_WIRELESS is not set # # AMD HSMP Driver # # CONFIG_AMD_HSMP_ACPI is not set # CONFIG_AMD_HSMP_PLAT is not set # end of AMD HSMP Driver # CONFIG_AMD_PMC is not set # CONFIG_AMD_HFI is not set # CONFIG_AMD_3D_VCACHE is not set # CONFIG_AMD_WBRF is not set # CONFIG_AMD_ISP_PLATFORM is not set # CONFIG_ADV_SWBUTTON is not set # CONFIG_APPLE_GMUX is not set # CONFIG_ASUS_LAPTOP is not set # CONFIG_ASUS_WIRELESS is not set # CONFIG_AYANEO_EC is not set # CONFIG_EEEPC_LAPTOP is not set # CONFIG_X86_PLATFORM_DRIVERS_DELL is not set # CONFIG_AMILO_RFKILL is not set # CONFIG_FUJITSU_LAPTOP is not set # CONFIG_FUJITSU_TABLET is not set # CONFIG_GPD_POCKET_FAN is not set # CONFIG_X86_PLATFORM_DRIVERS_HP is not set # CONFIG_WIRELESS_HOTKEY is not set # CONFIG_IBM_RTL is not set # CONFIG_SENSORS_HDAPS is not set # CONFIG_INTEL_ATOMISP2_PM is not set # CONFIG_INTEL_IFS is not set # CONFIG_INTEL_SAR_INT1092 is not set # # Intel Speed Select Technology interface support # # CONFIG_INTEL_SPEED_SELECT_INTERFACE is not set # end of Intel Speed Select Technology interface support # # Intel Uncore Frequency Control # # CONFIG_INTEL_UNCORE_FREQ_CONTROL is not set # end of Intel Uncore Frequency Control # CONFIG_INTEL_HID_EVENT is not set # CONFIG_INTEL_VBTN is not set # CONFIG_INTEL_EHL_PSE_IO is not set # CONFIG_INTEL_OAKTRAIL is not set # CONFIG_INTEL_PUNIT_IPC is not set # CONFIG_INTEL_RST is not set # CONFIG_INTEL_SMARTCONNECT is not set # CONFIG_INTEL_TURBO_MAX_3 is not set # CONFIG_INTEL_VSEC is not set # CONFIG_IDEAPAD_LAPTOP is not set # CONFIG_THINKPAD_ACPI is not set # CONFIG_ACPI_QUICKSTART is not set # CONFIG_MSI_EC is not set # CONFIG_MSI_LAPTOP is not set # CONFIG_SAMSUNG_LAPTOP is not set # CONFIG_SAMSUNG_Q10 is not set # CONFIG_TOSHIBA_BT_RFKILL is not set # CONFIG_TOSHIBA_HAPS is not set # CONFIG_ACPI_CMPC is not set # CONFIG_COMPAL_LAPTOP is not set # CONFIG_PANASONIC_LAPTOP is not set # CONFIG_SONY_LAPTOP is not set # CONFIG_SYSTEM76_ACPI is not set # CONFIG_TOPSTAR_LAPTOP is not set # CONFIG_SERIAL_MULTI_INSTANTIATE is not set # CONFIG_DASHARO_ACPI is not set # CONFIG_INTEL_IPS is not set # CONFIG_INTEL_SCU_PCI is not set # CONFIG_INTEL_SCU_PLATFORM is not set # CONFIG_SIEMENS_SIMATIC_IPC is not set # CONFIG_WINMATE_FM07_KEYS is not set # CONFIG_OXP_EC is not set CONFIG_P2SB=y # CONFIG_ACPI_WMI is not set CONFIG_HAVE_CLK=y CONFIG_HAVE_CLK_PREPARE=y CONFIG_COMMON_CLK=y # CONFIG_COMMON_CLK_MAX9485 is not set # CONFIG_COMMON_CLK_SI5341 is not set # CONFIG_COMMON_CLK_SI5351 is not set # CONFIG_COMMON_CLK_SI544 is not set # CONFIG_COMMON_CLK_CDCE706 is not set # CONFIG_COMMON_CLK_CS2000_CP is not set # CONFIG_XILINX_VCU is not set # CONFIG_HWSPINLOCK is not set # # Clock Source drivers # CONFIG_CLKEVT_I8253=y CONFIG_I8253_LOCK=y CONFIG_CLKBLD_I8253=y # end of Clock Source drivers CONFIG_MAILBOX=y CONFIG_PCC=y # CONFIG_ALTERA_MBOX is not set CONFIG_IOMMU_IOVA=y CONFIG_IOMMU_API=y CONFIG_IOMMU_SUPPORT=y # # Generic IOMMU Pagetable Support # # end of Generic IOMMU Pagetable Support # CONFIG_IOMMU_DEBUGFS is not set # CONFIG_IOMMU_DEFAULT_DMA_STRICT is not set CONFIG_IOMMU_DEFAULT_DMA_LAZY=y # CONFIG_IOMMU_DEFAULT_PASSTHROUGH is not set CONFIG_IOMMU_DMA=y CONFIG_IOMMU_SVA=y CONFIG_IOMMU_IOPF=y CONFIG_AMD_IOMMU=y CONFIG_DMAR_TABLE=y CONFIG_INTEL_IOMMU=y # CONFIG_INTEL_IOMMU_SVM is not set # CONFIG_INTEL_IOMMU_DEFAULT_ON is not set # CONFIG_INTEL_IOMMU_SCALABLE_MODE_DEFAULT_ON is not set CONFIG_INTEL_IOMMU_PERF_EVENTS=y # CONFIG_IOMMUFD is not set # CONFIG_IRQ_REMAP is not set # CONFIG_VIRTIO_IOMMU is not set CONFIG_GENERIC_PT=y # CONFIG_DEBUG_GENERIC_PT is not set CONFIG_IOMMU_PT=y CONFIG_IOMMU_PT_AMDV1=y CONFIG_IOMMU_PT_VTDSS=y CONFIG_IOMMU_PT_X86_64=y # # Remoteproc drivers # # CONFIG_REMOTEPROC is not set # end of Remoteproc drivers # # Rpmsg drivers # # CONFIG_RPMSG_QCOM_GLINK_RPM is not set # CONFIG_RPMSG_VIRTIO is not set # end of Rpmsg drivers # # SOC (System On Chip) specific Drivers # # # Amlogic SoC drivers # # end of Amlogic SoC drivers # # Broadcom SoC drivers # # end of Broadcom SoC drivers # # NXP/Freescale QorIQ SoC drivers # # end of NXP/Freescale QorIQ SoC drivers # # fujitsu SoC drivers # # end of fujitsu SoC drivers # # i.MX SoC drivers # # end of i.MX SoC drivers # # Enable LiteX SoC Builder specific drivers # # end of Enable LiteX SoC Builder specific drivers # CONFIG_WPCM450_SOC is not set # # Qualcomm SoC drivers # # end of Qualcomm SoC drivers # CONFIG_SOC_TI is not set # # Xilinx SoC drivers # # end of Xilinx SoC drivers # end of SOC (System On Chip) specific Drivers # # PM Domains # # # Amlogic PM Domains # # end of Amlogic PM Domains # # Broadcom PM Domains # # end of Broadcom PM Domains # # i.MX PM Domains # # end of i.MX PM Domains # # Qualcomm PM Domains # # end of Qualcomm PM Domains # end of PM Domains # CONFIG_PM_DEVFREQ is not set # CONFIG_EXTCON is not set # CONFIG_MEMORY is not set # CONFIG_IIO is not set # CONFIG_NTB is not set # CONFIG_PWM is not set # # IRQ chip support # CONFIG_IRQ_MSI_LIB=y # end of IRQ chip support # CONFIG_IPACK_BUS is not set # CONFIG_RESET_CONTROLLER is not set # # PHY Subsystem # # CONFIG_GENERIC_PHY is not set # CONFIG_USB_LGM_PHY is not set # CONFIG_PHY_CAN_TRANSCEIVER is not set # # PHY drivers for Broadcom platforms # # CONFIG_BCM_KONA_USB2_PHY is not set # end of PHY drivers for Broadcom platforms # CONFIG_PHY_PXA_28NM_HSIC is not set # CONFIG_PHY_PXA_28NM_USB2 is not set # CONFIG_PHY_INTEL_LGM_EMMC is not set # end of PHY Subsystem # CONFIG_POWERCAP is not set # CONFIG_MCB is not set # # Performance monitor support # # CONFIG_DWC_PCIE_PMU is not set # end of Performance monitor support CONFIG_RAS=y # CONFIG_USB4 is not set # # Android # # CONFIG_ANDROID_BINDER_IPC is not set # end of Android # CONFIG_LIBNVDIMM is not set # CONFIG_DAX is not set CONFIG_NVMEM=y CONFIG_NVMEM_SYSFS=y # CONFIG_NVMEM_LAYOUTS is not set # CONFIG_NVMEM_RMEM is not set # # HW tracing support # # CONFIG_STM is not set # CONFIG_INTEL_TH is not set # end of HW tracing support # CONFIG_FPGA is not set # CONFIG_TEE is not set # CONFIG_SIOX is not set # CONFIG_SLIMBUS is not set # CONFIG_INTERCONNECT is not set # CONFIG_COUNTER is not set # CONFIG_MOST is not set # CONFIG_PECI is not set # CONFIG_HTE is not set # end of Device Drivers # # File systems # CONFIG_DCACHE_WORD_ACCESS=y # CONFIG_VALIDATE_FS_PARSER is not set CONFIG_FS_IOMAP=y CONFIG_FS_STACK=y CONFIG_BUFFER_HEAD=y CONFIG_LEGACY_DIRECT_IO=y # CONFIG_EXT2_FS is not set # CONFIG_EXT4_FS is not set # CONFIG_JFS_FS is not set # CONFIG_XFS_FS is not set # CONFIG_GFS2_FS is not set # CONFIG_OCFS2_FS is not set # CONFIG_BTRFS_FS is not set # CONFIG_NILFS2_FS is not set # CONFIG_F2FS_FS is not set CONFIG_FS_POSIX_ACL=y CONFIG_EXPORTFS=y # CONFIG_EXPORTFS_BLOCK_OPS is not set CONFIG_FILE_LOCKING=y # CONFIG_FS_ENCRYPTION is not set # CONFIG_FS_VERITY is not set CONFIG_FSNOTIFY=y CONFIG_DNOTIFY=y CONFIG_INOTIFY_USER=y CONFIG_FANOTIFY=y # CONFIG_FANOTIFY_ACCESS_PERMISSIONS is not set CONFIG_QUOTA=y CONFIG_QUOTA_NETLINK_INTERFACE=y # CONFIG_QUOTA_DEBUG is not set CONFIG_QUOTA_TREE=y # CONFIG_QFMT_V1 is not set CONFIG_QFMT_V2=y CONFIG_QUOTACTL=y CONFIG_AUTOFS_FS=y CONFIG_FUSE_FS=y CONFIG_CUSE=y CONFIG_VIRTIO_FS=y CONFIG_FUSE_PASSTHROUGH=y CONFIG_FUSE_IO_URING=y CONFIG_OVERLAY_FS=y # CONFIG_OVERLAY_FS_REDIRECT_DIR is not set CONFIG_OVERLAY_FS_REDIRECT_ALWAYS_FOLLOW=y # CONFIG_OVERLAY_FS_INDEX is not set # CONFIG_OVERLAY_FS_XINO_AUTO is not set # CONFIG_OVERLAY_FS_METACOPY is not set # CONFIG_OVERLAY_FS_DEBUG is not set # # Caches # CONFIG_NETFS_SUPPORT=y # CONFIG_NETFS_STATS is not set # CONFIG_NETFS_DEBUG is not set # CONFIG_FSCACHE is not set # end of Caches # # CD-ROM/DVD Filesystems # CONFIG_ISO9660_FS=y CONFIG_JOLIET=y CONFIG_ZISOFS=y # CONFIG_UDF_FS is not set # end of CD-ROM/DVD Filesystems # # DOS/FAT/EXFAT/NT Filesystems # CONFIG_FAT_FS=y CONFIG_MSDOS_FS=y CONFIG_VFAT_FS=y CONFIG_FAT_DEFAULT_CODEPAGE=437 CONFIG_FAT_DEFAULT_IOCHARSET="iso8859-1" # CONFIG_FAT_DEFAULT_UTF8 is not set # CONFIG_EXFAT_FS is not set # CONFIG_NTFS3_FS is not set # CONFIG_NTFS_FS is not set # end of DOS/FAT/EXFAT/NT Filesystems # # Pseudo filesystems # CONFIG_PROC_FS=y CONFIG_PROC_KCORE=y CONFIG_PROC_VMCORE=y # CONFIG_PROC_VMCORE_DEVICE_DUMP is not set CONFIG_PROC_SYSCTL=y CONFIG_PROC_PAGE_MONITOR=y CONFIG_PROC_CHILDREN=y CONFIG_PROC_PID_ARCH_STATUS=y CONFIG_KERNFS=y CONFIG_SYSFS=y CONFIG_TMPFS=y CONFIG_TMPFS_POSIX_ACL=y CONFIG_TMPFS_XATTR=y # CONFIG_TMPFS_INODE64 is not set # CONFIG_TMPFS_QUOTA is not set CONFIG_ARCH_SUPPORTS_HUGETLBFS=y CONFIG_HUGETLBFS=y # CONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP_DEFAULT_ON is not set CONFIG_HUGETLB_PAGE=y CONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP=y CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING=y CONFIG_ARCH_HAS_GIGANTIC_PAGE=y CONFIG_CONFIGFS_FS=y CONFIG_EFIVAR_FS=y # end of Pseudo filesystems CONFIG_MISC_FILESYSTEMS=y # CONFIG_ORANGEFS_FS is not set # CONFIG_ADFS_FS is not set # CONFIG_AFFS_FS is not set # CONFIG_ECRYPT_FS is not set # CONFIG_HFS_FS is not set # CONFIG_HFSPLUS_FS is not set # CONFIG_BEFS_FS is not set # CONFIG_BFS_FS is not set # CONFIG_EFS_FS is not set # CONFIG_CRAMFS is not set # CONFIG_SQUASHFS is not set # CONFIG_VXFS_FS is not set # CONFIG_MINIX_FS is not set # CONFIG_OMFS_FS is not set # CONFIG_HPFS_FS is not set # CONFIG_QNX4FS_FS is not set # CONFIG_QNX6FS_FS is not set # CONFIG_ROMFS_FS is not set # CONFIG_PSTORE is not set # CONFIG_UFS_FS is not set # CONFIG_EROFS_FS is not set CONFIG_NETWORK_FILESYSTEMS=y CONFIG_NFS_FS=y CONFIG_NFS_V2=y CONFIG_NFS_V3=y CONFIG_NFS_V3_ACL=y CONFIG_NFS_V4=y # CONFIG_NFS_SWAP is not set # CONFIG_NFS_V4_1 is not set CONFIG_ROOT_NFS=y # CONFIG_NFS_FSCACHE is not set # CONFIG_NFS_USE_LEGACY_DNS is not set CONFIG_NFS_USE_KERNEL_DNS=y CONFIG_NFS_DISABLE_UDP_SUPPORT=y # CONFIG_NFSD is not set CONFIG_GRACE_PERIOD=y CONFIG_LOCKD=y CONFIG_LOCKD_V4=y CONFIG_NFS_ACL_SUPPORT=y CONFIG_NFS_COMMON=y CONFIG_SUNRPC=y # CONFIG_RPCSEC_GSS_KRB5 is not set # CONFIG_SUNRPC_DEBUG is not set # CONFIG_CEPH_FS is not set # CONFIG_CIFS is not set # CONFIG_SMB_SERVER is not set # CONFIG_CODA_FS is not set # CONFIG_AFS_FS is not set CONFIG_9P_FS=y CONFIG_9P_FS_POSIX_ACL=y CONFIG_9P_FS_SECURITY=y CONFIG_NLS=y CONFIG_NLS_DEFAULT="utf8" CONFIG_NLS_CODEPAGE_437=y # CONFIG_NLS_CODEPAGE_737 is not set # CONFIG_NLS_CODEPAGE_775 is not set # CONFIG_NLS_CODEPAGE_850 is not set # CONFIG_NLS_CODEPAGE_852 is not set # CONFIG_NLS_CODEPAGE_855 is not set # CONFIG_NLS_CODEPAGE_857 is not set # CONFIG_NLS_CODEPAGE_860 is not set # CONFIG_NLS_CODEPAGE_861 is not set # CONFIG_NLS_CODEPAGE_862 is not set # CONFIG_NLS_CODEPAGE_863 is not set # CONFIG_NLS_CODEPAGE_864 is not set # CONFIG_NLS_CODEPAGE_865 is not set # CONFIG_NLS_CODEPAGE_866 is not set # CONFIG_NLS_CODEPAGE_869 is not set # CONFIG_NLS_CODEPAGE_936 is not set # CONFIG_NLS_CODEPAGE_950 is not set # CONFIG_NLS_CODEPAGE_932 is not set # CONFIG_NLS_CODEPAGE_949 is not set # CONFIG_NLS_CODEPAGE_874 is not set # CONFIG_NLS_ISO8859_8 is not set # CONFIG_NLS_CODEPAGE_1250 is not set # CONFIG_NLS_CODEPAGE_1251 is not set CONFIG_NLS_ASCII=y CONFIG_NLS_ISO8859_1=y # CONFIG_NLS_ISO8859_2 is not set # CONFIG_NLS_ISO8859_3 is not set # CONFIG_NLS_ISO8859_4 is not set # CONFIG_NLS_ISO8859_5 is not set # CONFIG_NLS_ISO8859_6 is not set # CONFIG_NLS_ISO8859_7 is not set # CONFIG_NLS_ISO8859_9 is not set # CONFIG_NLS_ISO8859_13 is not set # CONFIG_NLS_ISO8859_14 is not set # CONFIG_NLS_ISO8859_15 is not set # CONFIG_NLS_KOI8_R is not set # CONFIG_NLS_KOI8_U is not set # CONFIG_NLS_MAC_ROMAN is not set # CONFIG_NLS_MAC_CELTIC is not set # CONFIG_NLS_MAC_CENTEURO is not set # CONFIG_NLS_MAC_CROATIAN is not set # CONFIG_NLS_MAC_CYRILLIC is not set # CONFIG_NLS_MAC_GAELIC is not set # CONFIG_NLS_MAC_GREEK is not set # CONFIG_NLS_MAC_ICELAND is not set # CONFIG_NLS_MAC_INUIT is not set # CONFIG_NLS_MAC_ROMANIAN is not set # CONFIG_NLS_MAC_TURKISH is not set CONFIG_NLS_UTF8=y # CONFIG_DLM is not set # CONFIG_UNICODE is not set CONFIG_IO_WQ=y # end of File systems # # Security options # CONFIG_KEYS=y # CONFIG_KEYS_REQUEST_CACHE is not set # CONFIG_PERSISTENT_KEYRINGS is not set # CONFIG_BIG_KEYS is not set # CONFIG_TRUSTED_KEYS is not set # CONFIG_ENCRYPTED_KEYS is not set # CONFIG_KEY_DH_OPERATIONS is not set # CONFIG_SECURITY_DMESG_RESTRICT is not set CONFIG_PROC_MEM_ALWAYS_FORCE=y # CONFIG_PROC_MEM_FORCE_PTRACE is not set # CONFIG_PROC_MEM_NO_FORCE is not set # CONFIG_MSEAL_SYSTEM_MAPPINGS is not set CONFIG_SECURITY=y CONFIG_HAS_SECURITY_AUDIT=y CONFIG_SECURITYFS=y CONFIG_SECURITY_NETWORK=y # CONFIG_SECURITY_NETWORK_XFRM is not set CONFIG_SECURITY_PATH=y # CONFIG_INTEL_TXT is not set # CONFIG_STATIC_USERMODEHELPER is not set # CONFIG_SECURITY_SELINUX is not set # CONFIG_SECURITY_SMACK is not set # CONFIG_SECURITY_TOMOYO is not set # CONFIG_SECURITY_APPARMOR is not set # CONFIG_SECURITY_LOADPIN is not set CONFIG_SECURITY_YAMA=y # CONFIG_SECURITY_SAFESETID is not set # CONFIG_SECURITY_LOCKDOWN_LSM is not set # CONFIG_SECURITY_LANDLOCK is not set # CONFIG_SECURITY_IPE is not set CONFIG_INTEGRITY=y # CONFIG_INTEGRITY_SIGNATURE is not set CONFIG_INTEGRITY_AUDIT=y CONFIG_IMA=y CONFIG_IMA_MEASURE_PCR_IDX=10 CONFIG_IMA_NG_TEMPLATE=y # CONFIG_IMA_SIG_TEMPLATE is not set CONFIG_IMA_DEFAULT_TEMPLATE="ima-ng" CONFIG_IMA_DEFAULT_HASH_SHA1=y # CONFIG_IMA_DEFAULT_HASH_SHA256 is not set # CONFIG_IMA_DEFAULT_HASH_SHA512 is not set CONFIG_IMA_DEFAULT_HASH="sha1" CONFIG_IMA_WRITE_POLICY=y CONFIG_IMA_READ_POLICY=y # CONFIG_IMA_APPRAISE is not set CONFIG_IMA_MEASURE_ASYMMETRIC_KEYS=y CONFIG_IMA_QUEUE_EARLY_BOOT_KEYS=y # CONFIG_IMA_SECURE_AND_OR_TRUSTED_BOOT is not set # CONFIG_IMA_DISABLE_HTABLE is not set # CONFIG_EVM is not set CONFIG_DEFAULT_SECURITY_DAC=y CONFIG_LSM="lockdown,yama,loadpin,safesetid,integrity,selinux,smack,tomoyo,apparmor,bpf" # # Kernel hardening options # # # Memory initialization # CONFIG_CC_HAS_AUTO_VAR_INIT_PATTERN=y CONFIG_CC_HAS_AUTO_VAR_INIT_ZERO_BARE=y CONFIG_CC_HAS_AUTO_VAR_INIT_ZERO=y CONFIG_INIT_STACK_NONE=y # CONFIG_INIT_STACK_ALL_PATTERN is not set # CONFIG_INIT_STACK_ALL_ZERO is not set CONFIG_CC_HAS_SANCOV_STACK_DEPTH_CALLBACK=y # CONFIG_KSTACK_ERASE is not set # CONFIG_INIT_ON_ALLOC_DEFAULT_ON is not set # CONFIG_INIT_ON_FREE_DEFAULT_ON is not set CONFIG_CC_HAS_ZERO_CALL_USED_REGS=y # CONFIG_ZERO_CALL_USED_REGS is not set # end of Memory initialization # # Bounds checking # # CONFIG_FORTIFY_SOURCE is not set # CONFIG_HARDENED_USERCOPY is not set # end of Bounds checking # # Hardening of kernel data structures # # CONFIG_LIST_HARDENED is not set # CONFIG_BUG_ON_DATA_CORRUPTION is not set # end of Hardening of kernel data structures CONFIG_CC_HAS_RANDSTRUCT=y CONFIG_RANDSTRUCT_NONE=y # CONFIG_RANDSTRUCT_FULL is not set # end of Kernel hardening options # end of Security options CONFIG_CRYPTO=y # # Crypto core or helper # CONFIG_CRYPTO_ALGAPI=y CONFIG_CRYPTO_ALGAPI2=y CONFIG_CRYPTO_AEAD=y CONFIG_CRYPTO_AEAD2=y CONFIG_CRYPTO_SIG=y CONFIG_CRYPTO_SIG2=y CONFIG_CRYPTO_SKCIPHER=y CONFIG_CRYPTO_SKCIPHER2=y CONFIG_CRYPTO_HASH=y CONFIG_CRYPTO_HASH2=y CONFIG_CRYPTO_RNG=y CONFIG_CRYPTO_RNG2=y CONFIG_CRYPTO_RNG_DEFAULT=y CONFIG_CRYPTO_AKCIPHER2=y CONFIG_CRYPTO_AKCIPHER=y CONFIG_CRYPTO_KPP2=y CONFIG_CRYPTO_ACOMP2=y CONFIG_CRYPTO_MANAGER=y CONFIG_CRYPTO_MANAGER2=y # CONFIG_CRYPTO_USER is not set # CONFIG_CRYPTO_SELFTESTS is not set CONFIG_CRYPTO_NULL=y # CONFIG_CRYPTO_PCRYPT is not set # CONFIG_CRYPTO_CRYPTD is not set CONFIG_CRYPTO_AUTHENC=y # CONFIG_CRYPTO_KRB5ENC is not set # CONFIG_CRYPTO_BENCHMARK is not set # end of Crypto core or helper # # Public-key cryptography # CONFIG_CRYPTO_RSA=y # CONFIG_CRYPTO_DH is not set # CONFIG_CRYPTO_ECDH is not set # CONFIG_CRYPTO_ECDSA is not set # CONFIG_CRYPTO_ECRDSA is not set # end of Public-key cryptography # # Block ciphers # CONFIG_CRYPTO_AES=y # CONFIG_CRYPTO_AES_TI is not set # CONFIG_CRYPTO_ANUBIS is not set # CONFIG_CRYPTO_ARIA is not set # CONFIG_CRYPTO_BLOWFISH is not set # CONFIG_CRYPTO_CAMELLIA is not set # CONFIG_CRYPTO_CAST5 is not set # CONFIG_CRYPTO_CAST6 is not set # CONFIG_CRYPTO_DES is not set # CONFIG_CRYPTO_FCRYPT is not set # CONFIG_CRYPTO_KHAZAD is not set # CONFIG_CRYPTO_SEED is not set # CONFIG_CRYPTO_SERPENT is not set # CONFIG_CRYPTO_SM4_GENERIC is not set # CONFIG_CRYPTO_TEA is not set # CONFIG_CRYPTO_TWOFISH is not set # end of Block ciphers # # Length-preserving ciphers and modes # # CONFIG_CRYPTO_ADIANTUM is not set # CONFIG_CRYPTO_ARC4 is not set # CONFIG_CRYPTO_CHACHA20 is not set CONFIG_CRYPTO_CBC=y CONFIG_CRYPTO_CTR=y # CONFIG_CRYPTO_CTS is not set CONFIG_CRYPTO_ECB=y # CONFIG_CRYPTO_HCTR2 is not set # CONFIG_CRYPTO_LRW is not set # CONFIG_CRYPTO_PCBC is not set # CONFIG_CRYPTO_XTS is not set # end of Length-preserving ciphers and modes # # AEAD (authenticated encryption with associated data) ciphers # # CONFIG_CRYPTO_AEGIS128 is not set # CONFIG_CRYPTO_CHACHA20POLY1305 is not set CONFIG_CRYPTO_CCM=y CONFIG_CRYPTO_GCM=y CONFIG_CRYPTO_GENIV=y CONFIG_CRYPTO_SEQIV=y CONFIG_CRYPTO_ECHAINIV=y # CONFIG_CRYPTO_ESSIV is not set # end of AEAD (authenticated encryption with associated data) ciphers # # Hashes, digests, and MACs # CONFIG_CRYPTO_BLAKE2B=y CONFIG_CRYPTO_CMAC=y CONFIG_CRYPTO_GHASH=y CONFIG_CRYPTO_HMAC=y # CONFIG_CRYPTO_MD4 is not set CONFIG_CRYPTO_MD5=y # CONFIG_CRYPTO_MICHAEL_MIC is not set # CONFIG_CRYPTO_RMD160 is not set CONFIG_CRYPTO_SHA1=y CONFIG_CRYPTO_SHA256=y CONFIG_CRYPTO_SHA512=y CONFIG_CRYPTO_SHA3=y # CONFIG_CRYPTO_SM3_GENERIC is not set # CONFIG_CRYPTO_STREEBOG is not set # CONFIG_CRYPTO_WP512 is not set # CONFIG_CRYPTO_XCBC is not set CONFIG_CRYPTO_XXHASH=y # end of Hashes, digests, and MACs # # CRCs (cyclic redundancy checks) # CONFIG_CRYPTO_CRC32C=y # CONFIG_CRYPTO_CRC32 is not set # end of CRCs (cyclic redundancy checks) # # Compression # # CONFIG_CRYPTO_DEFLATE is not set CONFIG_CRYPTO_LZO=y # CONFIG_CRYPTO_842 is not set # CONFIG_CRYPTO_LZ4 is not set # CONFIG_CRYPTO_LZ4HC is not set # CONFIG_CRYPTO_ZSTD is not set # end of Compression # # Random number generation # CONFIG_CRYPTO_DRBG_MENU=y CONFIG_CRYPTO_DRBG_HMAC=y # CONFIG_CRYPTO_DRBG_HASH is not set # CONFIG_CRYPTO_DRBG_CTR is not set CONFIG_CRYPTO_DRBG=y CONFIG_CRYPTO_JITTERENTROPY=y CONFIG_CRYPTO_JITTERENTROPY_MEMORY_BLOCKS=64 CONFIG_CRYPTO_JITTERENTROPY_MEMORY_BLOCKSIZE=32 CONFIG_CRYPTO_JITTERENTROPY_OSR=1 # end of Random number generation # # Userspace interface # CONFIG_CRYPTO_USER_API=y CONFIG_CRYPTO_USER_API_HASH=y # CONFIG_CRYPTO_USER_API_SKCIPHER is not set # CONFIG_CRYPTO_USER_API_RNG is not set # CONFIG_CRYPTO_USER_API_AEAD is not set CONFIG_CRYPTO_USER_API_ENABLE_OBSOLETE=y # end of Userspace interface # # Accelerated Cryptographic Algorithms for CPU (x86) # # CONFIG_CRYPTO_AES_NI_INTEL is not set # CONFIG_CRYPTO_BLOWFISH_X86_64 is not set # CONFIG_CRYPTO_CAMELLIA_X86_64 is not set # CONFIG_CRYPTO_CAMELLIA_AESNI_AVX_X86_64 is not set # CONFIG_CRYPTO_CAMELLIA_AESNI_AVX2_X86_64 is not set # CONFIG_CRYPTO_CAST5_AVX_X86_64 is not set # CONFIG_CRYPTO_CAST6_AVX_X86_64 is not set # CONFIG_CRYPTO_DES3_EDE_X86_64 is not set # CONFIG_CRYPTO_SERPENT_SSE2_X86_64 is not set # CONFIG_CRYPTO_SERPENT_AVX_X86_64 is not set # CONFIG_CRYPTO_SERPENT_AVX2_X86_64 is not set # CONFIG_CRYPTO_SM4_AESNI_AVX_X86_64 is not set # CONFIG_CRYPTO_SM4_AESNI_AVX2_X86_64 is not set # CONFIG_CRYPTO_TWOFISH_X86_64 is not set # CONFIG_CRYPTO_TWOFISH_X86_64_3WAY is not set # CONFIG_CRYPTO_TWOFISH_AVX_X86_64 is not set # CONFIG_CRYPTO_ARIA_AESNI_AVX_X86_64 is not set # CONFIG_CRYPTO_ARIA_AESNI_AVX2_X86_64 is not set # CONFIG_CRYPTO_ARIA_GFNI_AVX512_X86_64 is not set # CONFIG_CRYPTO_AEGIS128_AESNI_SSE2 is not set # CONFIG_CRYPTO_NHPOLY1305_SSE2 is not set # CONFIG_CRYPTO_NHPOLY1305_AVX2 is not set # CONFIG_CRYPTO_SM3_AVX_X86_64 is not set # CONFIG_CRYPTO_GHASH_CLMUL_NI_INTEL is not set # end of Accelerated Cryptographic Algorithms for CPU (x86) CONFIG_CRYPTO_HW=y # CONFIG_CRYPTO_DEV_PADLOCK is not set # CONFIG_CRYPTO_DEV_ATMEL_ECC is not set # CONFIG_CRYPTO_DEV_ATMEL_SHA204A is not set # CONFIG_CRYPTO_DEV_CCP is not set # CONFIG_CRYPTO_DEV_NITROX_CNN55XX is not set # CONFIG_CRYPTO_DEV_QAT_DH895xCC is not set # CONFIG_CRYPTO_DEV_QAT_C3XXX is not set # CONFIG_CRYPTO_DEV_QAT_C62X is not set # CONFIG_CRYPTO_DEV_QAT_4XXX is not set # CONFIG_CRYPTO_DEV_QAT_420XX is not set # CONFIG_CRYPTO_DEV_QAT_6XXX is not set # CONFIG_CRYPTO_DEV_QAT_DH895xCCVF is not set # CONFIG_CRYPTO_DEV_QAT_C3XXXVF is not set # CONFIG_CRYPTO_DEV_QAT_C62XVF is not set # CONFIG_CRYPTO_DEV_VIRTIO is not set # CONFIG_CRYPTO_DEV_SAFEXCEL is not set # CONFIG_CRYPTO_DEV_AMLOGIC_GXL is not set CONFIG_ASYMMETRIC_KEY_TYPE=y CONFIG_ASYMMETRIC_PUBLIC_KEY_SUBTYPE=y CONFIG_X509_CERTIFICATE_PARSER=y # CONFIG_PKCS8_PRIVATE_KEY_PARSER is not set CONFIG_PKCS7_MESSAGE_PARSER=y # CONFIG_PKCS7_TEST_KEY is not set # CONFIG_SIGNED_PE_FILE_VERIFICATION is not set # CONFIG_FIPS_SIGNATURE_SELFTEST is not set # # Certificates for signature checking # CONFIG_SYSTEM_TRUSTED_KEYRING=y CONFIG_SYSTEM_TRUSTED_KEYS="" # CONFIG_SYSTEM_EXTRA_CERTIFICATE is not set # CONFIG_SECONDARY_TRUSTED_KEYRING is not set # CONFIG_SYSTEM_BLACKLIST_KEYRING is not set # end of Certificates for signature checking # CONFIG_CRYPTO_KRB5 is not set CONFIG_BINARY_PRINTF=y # # Library routines # # CONFIG_PACKING is not set CONFIG_BITREVERSE=y CONFIG_GENERIC_STRNCPY_FROM_USER=y CONFIG_GENERIC_STRNLEN_USER=y CONFIG_GENERIC_NET_UTILS=y # CONFIG_CORDIC is not set # CONFIG_PRIME_NUMBERS is not set CONFIG_RATIONAL=y CONFIG_GENERIC_IOMAP=y CONFIG_ARCH_USE_CMPXCHG_LOCKREF=y CONFIG_ARCH_HAS_FAST_MULTIPLIER=y CONFIG_ARCH_USE_SYM_ANNOTATIONS=y CONFIG_CRC_CCITT=y CONFIG_CRC32=y CONFIG_CRC32_ARCH=y CONFIG_CRC_OPTIMIZATIONS=y # # Crypto library routines # CONFIG_CRYPTO_HASH_INFO=y CONFIG_CRYPTO_LIB_UTILS=y CONFIG_CRYPTO_LIB_AES=y CONFIG_CRYPTO_LIB_ARC4=y CONFIG_CRYPTO_LIB_GF128MUL=y CONFIG_CRYPTO_LIB_BLAKE2B=y CONFIG_CRYPTO_LIB_BLAKE2S_ARCH=y CONFIG_CRYPTO_LIB_MD5=y CONFIG_CRYPTO_LIB_POLY1305_RSIZE=11 CONFIG_CRYPTO_LIB_SHA1=y CONFIG_CRYPTO_LIB_SHA1_ARCH=y CONFIG_CRYPTO_LIB_SHA256=y CONFIG_CRYPTO_LIB_SHA256_ARCH=y CONFIG_CRYPTO_LIB_SHA512=y CONFIG_CRYPTO_LIB_SHA512_ARCH=y CONFIG_CRYPTO_LIB_SHA3=y # end of Crypto library routines CONFIG_XXHASH=y # CONFIG_RANDOM32_SELFTEST is not set CONFIG_ZLIB_INFLATE=y CONFIG_LZO_COMPRESS=y CONFIG_LZO_DECOMPRESS=y CONFIG_LZ4_DECOMPRESS=y CONFIG_ZSTD_COMMON=y CONFIG_ZSTD_DECOMPRESS=y CONFIG_XZ_DEC=y CONFIG_XZ_DEC_X86=y CONFIG_XZ_DEC_POWERPC=y CONFIG_XZ_DEC_ARM=y CONFIG_XZ_DEC_ARMTHUMB=y CONFIG_XZ_DEC_ARM64=y CONFIG_XZ_DEC_SPARC=y CONFIG_XZ_DEC_RISCV=y # CONFIG_XZ_DEC_MICROLZMA is not set CONFIG_XZ_DEC_BCJ=y # CONFIG_XZ_DEC_TEST is not set CONFIG_DECOMPRESS_GZIP=y CONFIG_DECOMPRESS_BZIP2=y CONFIG_DECOMPRESS_LZMA=y CONFIG_DECOMPRESS_XZ=y CONFIG_DECOMPRESS_LZO=y CONFIG_DECOMPRESS_LZ4=y CONFIG_DECOMPRESS_ZSTD=y CONFIG_GENERIC_ALLOCATOR=y CONFIG_INTERVAL_TREE=y CONFIG_XARRAY_MULTI=y CONFIG_ASSOCIATIVE_ARRAY=y CONFIG_HAS_IOMEM=y CONFIG_HAS_IOPORT=y CONFIG_HAS_IOPORT_MAP=y CONFIG_HAS_DMA=y CONFIG_DMA_OPS_HELPERS=y CONFIG_NEED_SG_DMA_FLAGS=y CONFIG_NEED_SG_DMA_LENGTH=y CONFIG_NEED_DMA_MAP_STATE=y CONFIG_ARCH_DMA_ADDR_T_64BIT=y CONFIG_SWIOTLB=y # CONFIG_SWIOTLB_DYNAMIC is not set CONFIG_DMA_NEED_SYNC=y # CONFIG_DMA_API_DEBUG is not set # CONFIG_DMA_MAP_BENCHMARK is not set CONFIG_SGL_ALLOC=y CONFIG_CHECK_SIGNATURE=y CONFIG_CPU_RMAP=y CONFIG_DQL=y CONFIG_GLOB=y # CONFIG_GLOB_SELFTEST is not set CONFIG_NLATTR=y CONFIG_CLZ_TAB=y # CONFIG_IRQ_POLL is not set CONFIG_MPILIB=y CONFIG_DIMLIB=y CONFIG_OID_REGISTRY=y CONFIG_UCS2_STRING=y CONFIG_HAVE_GENERIC_VDSO=y CONFIG_GENERIC_GETTIMEOFDAY=y CONFIG_GENERIC_VDSO_OVERFLOW_PROTECT=y CONFIG_VDSO_GETRANDOM=y CONFIG_FONT_SUPPORT=y # CONFIG_FONTS is not set CONFIG_FONT_8x8=y CONFIG_FONT_8x16=y CONFIG_SG_POOL=y CONFIG_ARCH_HAS_PMEM_API=y CONFIG_ARCH_HAS_CPU_CACHE_INVALIDATE_MEMREGION=y CONFIG_ARCH_HAS_UACCESS_FLUSHCACHE=y CONFIG_ARCH_HAS_COPY_MC=y CONFIG_ARCH_STACKWALK=y CONFIG_STACKDEPOT=y CONFIG_STACKDEPOT_MAX_FRAMES=64 CONFIG_SBITMAP=y # CONFIG_LWQ_TEST is not set # end of Library routines CONFIG_FIRMWARE_TABLE=y CONFIG_UNION_FIND=y # # Kernel hacking # # # printk and dmesg options # CONFIG_PRINTK_TIME=y CONFIG_PRINTK_CALLER=y # CONFIG_STACKTRACE_BUILD_ID is not set CONFIG_CONSOLE_LOGLEVEL_DEFAULT=7 CONFIG_CONSOLE_LOGLEVEL_QUIET=4 CONFIG_MESSAGE_LOGLEVEL_DEFAULT=4 # CONFIG_BOOT_PRINTK_DELAY is not set # CONFIG_DYNAMIC_DEBUG is not set # CONFIG_DYNAMIC_DEBUG_CORE is not set CONFIG_SYMBOLIC_ERRNAME=y CONFIG_DEBUG_BUGVERBOSE=y CONFIG_DEBUG_BUGVERBOSE_DETAILED=y # end of printk and dmesg options CONFIG_DEBUG_KERNEL=y CONFIG_DEBUG_MISC=y # # Compile-time checks and compiler options # CONFIG_DEBUG_INFO=y CONFIG_AS_HAS_NON_CONST_ULEB128=y # CONFIG_DEBUG_INFO_NONE is not set CONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT=y # CONFIG_DEBUG_INFO_DWARF4 is not set # CONFIG_DEBUG_INFO_DWARF5 is not set # CONFIG_DEBUG_INFO_REDUCED is not set CONFIG_DEBUG_INFO_COMPRESSED_NONE=y # CONFIG_DEBUG_INFO_COMPRESSED_ZLIB is not set # CONFIG_DEBUG_INFO_COMPRESSED_ZSTD is not set # CONFIG_DEBUG_INFO_SPLIT is not set CONFIG_DEBUG_INFO_BTF=y CONFIG_PAHOLE_HAS_SPLIT_BTF=y CONFIG_PAHOLE_HAS_BTF_TAG=y CONFIG_PAHOLE_HAS_LANG_EXCLUDE=y CONFIG_DEBUG_INFO_BTF_MODULES=y # CONFIG_MODULE_ALLOW_BTF_MISMATCH is not set CONFIG_GDB_SCRIPTS=y CONFIG_FRAME_WARN=2048 CONFIG_STRIP_ASM_SYMS=y CONFIG_HEADERS_INSTALL=y # CONFIG_SECTION_MISMATCH_WARN_ONLY is not set # CONFIG_DEBUG_FORCE_FUNCTION_ALIGN_64B is not set CONFIG_OBJTOOL=y # CONFIG_OBJTOOL_WERROR is not set CONFIG_VMLINUX_MAP=y # CONFIG_DEBUG_FORCE_WEAK_PER_CPU is not set # end of Compile-time checks and compiler options # # Generic Kernel Debugging Instruments # CONFIG_MAGIC_SYSRQ=y CONFIG_MAGIC_SYSRQ_DEFAULT_ENABLE=0x1 CONFIG_MAGIC_SYSRQ_SERIAL=y CONFIG_MAGIC_SYSRQ_SERIAL_SEQUENCE="" CONFIG_DEBUG_FS=y CONFIG_DEBUG_FS_ALLOW_ALL=y # CONFIG_DEBUG_FS_ALLOW_NONE is not set CONFIG_HAVE_ARCH_KGDB=y # CONFIG_KGDB is not set CONFIG_ARCH_HAS_UBSAN=y # CONFIG_UBSAN is not set CONFIG_HAVE_ARCH_KCSAN=y CONFIG_HAVE_KCSAN_COMPILER=y # CONFIG_KCSAN is not set # end of Generic Kernel Debugging Instruments # # Networking Debugging # # CONFIG_NET_DEV_REFCNT_TRACKER is not set # CONFIG_NET_NS_REFCNT_TRACKER is not set # CONFIG_DEBUG_NET is not set # CONFIG_DEBUG_NET_SMALL_RTNL is not set # end of Networking Debugging # # Memory Debugging # # CONFIG_PAGE_EXTENSION is not set # CONFIG_DEBUG_PAGEALLOC is not set CONFIG_SLUB_DEBUG=y # CONFIG_SLUB_DEBUG_ON is not set # CONFIG_PAGE_OWNER is not set # CONFIG_PAGE_TABLE_CHECK is not set # CONFIG_PAGE_POISONING is not set # CONFIG_DEBUG_PAGE_REF is not set # CONFIG_DEBUG_RODATA_TEST is not set CONFIG_ARCH_HAS_DEBUG_WX=y # CONFIG_DEBUG_WX is not set CONFIG_ARCH_HAS_PTDUMP=y # CONFIG_PTDUMP_DEBUGFS is not set CONFIG_HAVE_DEBUG_KMEMLEAK=y # CONFIG_DEBUG_KMEMLEAK is not set # CONFIG_PER_VMA_LOCK_STATS is not set # CONFIG_DEBUG_OBJECTS is not set # CONFIG_SHRINKER_DEBUG is not set CONFIG_DEBUG_STACK_USAGE=y # CONFIG_SCHED_STACK_END_CHECK is not set CONFIG_ARCH_HAS_DEBUG_VM_PGTABLE=y # CONFIG_DEBUG_VFS is not set # CONFIG_DEBUG_VM is not set # CONFIG_DEBUG_VM_PGTABLE is not set CONFIG_ARCH_HAS_DEBUG_VIRTUAL=y # CONFIG_DEBUG_VIRTUAL is not set # CONFIG_DEBUG_MEMORY_INIT is not set # CONFIG_DEBUG_PER_CPU_MAPS is not set CONFIG_ARCH_SUPPORTS_KMAP_LOCAL_FORCE_MAP=y # CONFIG_DEBUG_KMAP_LOCAL_FORCE_MAP is not set # CONFIG_MEM_ALLOC_PROFILING is not set CONFIG_HAVE_ARCH_KASAN=y CONFIG_HAVE_ARCH_KASAN_VMALLOC=y CONFIG_CC_HAS_KASAN_GENERIC=y CONFIG_CC_HAS_KASAN_SW_TAGS=y CONFIG_CC_HAS_WORKING_NOSANITIZE_ADDRESS=y # CONFIG_KASAN is not set CONFIG_HAVE_ARCH_KFENCE=y # CONFIG_KFENCE is not set CONFIG_HAVE_ARCH_KMSAN=y CONFIG_HAVE_KMSAN_COMPILER=y # CONFIG_KMSAN is not set # end of Memory Debugging # CONFIG_DEBUG_SHIRQ is not set # # Debug Oops, Lockups and Hangs # CONFIG_PANIC_ON_OOPS=y CONFIG_PANIC_TIMEOUT=0 # CONFIG_SOFTLOCKUP_DETECTOR is not set CONFIG_HAVE_HARDLOCKUP_DETECTOR_BUDDY=y # CONFIG_HARDLOCKUP_DETECTOR is not set CONFIG_HARDLOCKUP_CHECK_TIMESTAMP=y # CONFIG_DETECT_HUNG_TASK is not set # CONFIG_WQ_WATCHDOG is not set # CONFIG_WQ_CPU_INTENSIVE_REPORT is not set # CONFIG_TEST_LOCKUP is not set # end of Debug Oops, Lockups and Hangs # # Scheduler Debugging # CONFIG_SCHED_INFO=y CONFIG_SCHEDSTATS=y # end of Scheduler Debugging # # Lock Debugging (spinlocks, mutexes, etc...) # CONFIG_LOCK_DEBUGGING_SUPPORT=y # CONFIG_PROVE_LOCKING is not set # CONFIG_LOCK_STAT is not set # CONFIG_DEBUG_RT_MUTEXES is not set # CONFIG_DEBUG_SPINLOCK is not set # CONFIG_DEBUG_MUTEXES is not set # CONFIG_DEBUG_WW_MUTEX_SLOWPATH is not set # CONFIG_DEBUG_RWSEMS is not set # CONFIG_DEBUG_LOCK_ALLOC is not set # CONFIG_DEBUG_ATOMIC_SLEEP is not set # CONFIG_DEBUG_LOCKING_API_SELFTESTS is not set # CONFIG_LOCK_TORTURE_TEST is not set # CONFIG_WW_MUTEX_SELFTEST is not set # CONFIG_SCF_TORTURE_TEST is not set # CONFIG_CSD_LOCK_WAIT_DEBUG is not set # end of Lock Debugging (spinlocks, mutexes, etc...) # CONFIG_NMI_CHECK_CPU is not set # CONFIG_DEBUG_IRQFLAGS is not set CONFIG_STACKTRACE=y # CONFIG_WARN_ALL_UNSEEDED_RANDOM is not set # CONFIG_DEBUG_KOBJECT is not set # # Debug kernel data structures # # CONFIG_DEBUG_LIST is not set # CONFIG_DEBUG_PLIST is not set # CONFIG_DEBUG_SG is not set # CONFIG_DEBUG_NOTIFIERS is not set # CONFIG_DEBUG_MAPLE_TREE is not set # end of Debug kernel data structures # # RCU Debugging # # CONFIG_RCU_SCALE_TEST is not set # CONFIG_RCU_TORTURE_TEST is not set # CONFIG_RCU_REF_SCALE_TEST is not set CONFIG_RCU_CPU_STALL_TIMEOUT=21 CONFIG_RCU_EXP_CPU_STALL_TIMEOUT=0 # CONFIG_RCU_CPU_STALL_CPUTIME is not set CONFIG_RCU_TRACE=y # CONFIG_RCU_EQS_DEBUG is not set # end of RCU Debugging # CONFIG_DEBUG_WQ_FORCE_RR_CPU is not set # CONFIG_CPU_HOTPLUG_STATE_CONTROL is not set # CONFIG_LATENCYTOP is not set # CONFIG_DEBUG_CGROUP_REF is not set CONFIG_USER_STACKTRACE_SUPPORT=y CONFIG_NOP_TRACER=y CONFIG_HAVE_RETHOOK=y CONFIG_RETHOOK=y CONFIG_HAVE_FUNCTION_TRACER=y CONFIG_HAVE_FUNCTION_GRAPH_TRACER=y CONFIG_HAVE_FUNCTION_GRAPH_FREGS=y CONFIG_HAVE_FTRACE_GRAPH_FUNC=y CONFIG_HAVE_DYNAMIC_FTRACE=y CONFIG_HAVE_DYNAMIC_FTRACE_WITH_REGS=y CONFIG_HAVE_DYNAMIC_FTRACE_WITH_DIRECT_CALLS=y CONFIG_HAVE_DYNAMIC_FTRACE_WITH_ARGS=y CONFIG_HAVE_FTRACE_REGS_HAVING_PT_REGS=y CONFIG_HAVE_DYNAMIC_FTRACE_NO_PATCHABLE=y CONFIG_HAVE_DYNAMIC_FTRACE_WITH_JMP=y CONFIG_HAVE_SYSCALL_TRACEPOINTS=y CONFIG_HAVE_FENTRY=y CONFIG_HAVE_OBJTOOL_MCOUNT=y CONFIG_HAVE_OBJTOOL_NOP_MCOUNT=y CONFIG_HAVE_C_RECORDMCOUNT=y CONFIG_HAVE_BUILDTIME_MCOUNT_SORT=y CONFIG_BUILDTIME_MCOUNT_SORT=y CONFIG_TRACE_CLOCK=y CONFIG_RING_BUFFER=y CONFIG_EVENT_TRACING=y CONFIG_CONTEXT_SWITCH_TRACER=y CONFIG_TRACING=y CONFIG_GENERIC_TRACER=y CONFIG_TRACING_SUPPORT=y CONFIG_FTRACE=y CONFIG_TRACEFS_AUTOMOUNT_DEPRECATED=y # CONFIG_BOOTTIME_TRACING is not set CONFIG_FUNCTION_TRACER=y CONFIG_FUNCTION_GRAPH_TRACER=y CONFIG_FUNCTION_GRAPH_RETVAL=y CONFIG_FUNCTION_GRAPH_RETADDR=y CONFIG_FUNCTION_TRACE_ARGS=y CONFIG_DYNAMIC_FTRACE=y CONFIG_DYNAMIC_FTRACE_WITH_REGS=y CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS=y CONFIG_DYNAMIC_FTRACE_WITH_ARGS=y CONFIG_DYNAMIC_FTRACE_WITH_JMP=y CONFIG_FUNCTION_SELF_TRACING=y CONFIG_FPROBE=y # CONFIG_FUNCTION_PROFILER is not set # CONFIG_STACK_TRACER is not set # CONFIG_IRQSOFF_TRACER is not set # CONFIG_SCHED_TRACER is not set # CONFIG_HWLAT_TRACER is not set # CONFIG_OSNOISE_TRACER is not set # CONFIG_TIMERLAT_TRACER is not set # CONFIG_MMIOTRACE is not set CONFIG_FTRACE_SYSCALLS=y CONFIG_TRACE_SYSCALL_BUF_SIZE_DEFAULT=63 # CONFIG_TRACER_SNAPSHOT is not set CONFIG_BRANCH_PROFILE_NONE=y # CONFIG_PROFILE_ANNOTATED_BRANCHES is not set # CONFIG_PROFILE_ALL_BRANCHES is not set CONFIG_BLK_DEV_IO_TRACE=y CONFIG_FPROBE_EVENTS=y CONFIG_PROBE_EVENTS_BTF_ARGS=y CONFIG_KPROBE_EVENTS=y # CONFIG_KPROBE_EVENTS_ON_NOTRACE is not set CONFIG_UPROBE_EVENTS=y CONFIG_EPROBE_EVENTS=y CONFIG_BPF_EVENTS=y CONFIG_DYNAMIC_EVENTS=y CONFIG_PROBE_EVENTS=y CONFIG_BPF_KPROBE_OVERRIDE=y CONFIG_FTRACE_MCOUNT_USE_OBJTOOL=y # CONFIG_SYNTH_EVENTS is not set # CONFIG_USER_EVENTS is not set # CONFIG_HIST_TRIGGERS is not set # CONFIG_TRACE_EVENT_INJECT is not set # CONFIG_TRACEPOINT_BENCHMARK is not set # CONFIG_RING_BUFFER_BENCHMARK is not set # CONFIG_TRACE_EVAL_MAP_FILE is not set # CONFIG_FTRACE_RECORD_RECURSION is not set # CONFIG_FTRACE_VALIDATE_RCU_IS_WATCHING is not set # CONFIG_FTRACE_STARTUP_TEST is not set # CONFIG_FTRACE_SORT_STARTUP_TEST is not set # CONFIG_RING_BUFFER_STARTUP_TEST is not set # CONFIG_RING_BUFFER_VALIDATE_TIME_DELTAS is not set # CONFIG_PREEMPTIRQ_DELAY_TEST is not set # CONFIG_KPROBE_EVENT_GEN_TEST is not set # CONFIG_RV is not set CONFIG_PROVIDE_OHCI1394_DMA_INIT=y CONFIG_SAMPLES=y # CONFIG_SAMPLE_AUXDISPLAY is not set # CONFIG_SAMPLE_TRACE_EVENTS is not set # CONFIG_SAMPLE_TRACE_CUSTOM_EVENTS is not set # CONFIG_SAMPLE_TRACE_PRINTK is not set # CONFIG_SAMPLE_FTRACE_DIRECT is not set # CONFIG_SAMPLE_FTRACE_DIRECT_MULTI is not set # CONFIG_SAMPLE_FTRACE_OPS is not set # CONFIG_SAMPLE_TRACE_ARRAY is not set # CONFIG_SAMPLE_KOBJECT is not set CONFIG_SAMPLE_KPROBES=m CONFIG_SAMPLE_KRETPROBES=m # CONFIG_SAMPLE_HW_BREAKPOINT is not set # CONFIG_SAMPLE_FPROBE is not set # CONFIG_SAMPLE_KFIFO is not set # CONFIG_SAMPLE_CONFIGFS is not set # CONFIG_SAMPLE_CONNECTOR is not set # CONFIG_SAMPLE_FANOTIFY_ERROR is not set # CONFIG_SAMPLE_HIDRAW is not set # CONFIG_SAMPLE_LANDLOCK is not set # CONFIG_SAMPLE_PIDFD is not set # CONFIG_SAMPLE_SECCOMP is not set # CONFIG_SAMPLE_TIMER is not set # CONFIG_SAMPLE_TSM_MR is not set # CONFIG_SAMPLE_UHID is not set # CONFIG_SAMPLE_VFIO_MDEV_MDPY_FB is not set # CONFIG_SAMPLE_ANDROID_BINDERFS is not set # CONFIG_SAMPLE_VFS is not set # CONFIG_SAMPLE_TPS6594_PFSM is not set # CONFIG_SAMPLE_WATCHDOG is not set # CONFIG_SAMPLE_WATCH_QUEUE is not set # CONFIG_SAMPLE_CGROUP is not set # CONFIG_SAMPLE_CHECK_EXEC is not set # # DAMON Samples # # end of DAMON Samples CONFIG_HAVE_SAMPLE_FTRACE_DIRECT=y CONFIG_HAVE_SAMPLE_FTRACE_DIRECT_MULTI=y CONFIG_ARCH_HAS_DEVMEM_IS_ALLOWED=y CONFIG_STRICT_DEVMEM=y # CONFIG_IO_STRICT_DEVMEM is not set # # x86 Debugging # CONFIG_EARLY_PRINTK_USB=y CONFIG_X86_VERBOSE_BOOTUP=y CONFIG_EARLY_PRINTK=y CONFIG_EARLY_PRINTK_DBGP=y # CONFIG_EARLY_PRINTK_USB_XDBC is not set # CONFIG_EFI_PGT_DUMP is not set # CONFIG_DEBUG_TLBFLUSH is not set CONFIG_HAVE_MMIOTRACE_SUPPORT=y # CONFIG_X86_DECODER_SELFTEST is not set CONFIG_IO_DELAY_0X80=y # CONFIG_IO_DELAY_0XED is not set # CONFIG_IO_DELAY_UDELAY is not set # CONFIG_IO_DELAY_NONE is not set CONFIG_DEBUG_BOOT_PARAMS=y # CONFIG_CPA_DEBUG is not set # CONFIG_DEBUG_ENTRY is not set # CONFIG_DEBUG_NMI_SELFTEST is not set CONFIG_X86_DEBUG_FPU=y # CONFIG_PUNIT_ATOM_DEBUG is not set CONFIG_UNWINDER_ORC=y # CONFIG_UNWINDER_FRAME_POINTER is not set # end of x86 Debugging # # Kernel Testing and Coverage # # CONFIG_KUNIT is not set # CONFIG_NOTIFIER_ERROR_INJECTION is not set CONFIG_FUNCTION_ERROR_INJECTION=y # CONFIG_FAULT_INJECTION is not set CONFIG_ARCH_HAS_KCOV=y # CONFIG_KCOV is not set CONFIG_RUNTIME_TESTING_MENU=y # CONFIG_TEST_DHRY is not set # CONFIG_LKDTM is not set # CONFIG_TEST_MIN_HEAP is not set # CONFIG_TEST_DIV64 is not set # CONFIG_TEST_MULDIV64 is not set # CONFIG_BACKTRACE_SELF_TEST is not set # CONFIG_TEST_REF_TRACKER is not set # CONFIG_RBTREE_TEST is not set # CONFIG_REED_SOLOMON_TEST is not set # CONFIG_INTERVAL_TREE_TEST is not set # CONFIG_PERCPU_TEST is not set # CONFIG_ATOMIC64_SELFTEST is not set # CONFIG_TEST_HEXDUMP is not set # CONFIG_TEST_KSTRTOX is not set # CONFIG_TEST_BITMAP is not set # CONFIG_TEST_UUID is not set # CONFIG_TEST_XARRAY is not set # CONFIG_TEST_MAPLE_TREE is not set # CONFIG_TEST_RHASHTABLE is not set # CONFIG_TEST_IDA is not set # CONFIG_TEST_LKM is not set # CONFIG_TEST_BITOPS is not set # CONFIG_TEST_VMALLOC is not set # CONFIG_TEST_BPF is not set # CONFIG_FIND_BIT_BENCHMARK is not set # CONFIG_TEST_FIRMWARE is not set # CONFIG_TEST_SYSCTL is not set # CONFIG_TEST_UDELAY is not set # CONFIG_TEST_STATIC_KEYS is not set # CONFIG_TEST_KMOD is not set # CONFIG_TEST_KALLSYMS is not set # CONFIG_TEST_MEMCAT_P is not set # CONFIG_TEST_MEMINIT is not set # CONFIG_TEST_FREE_PAGES is not set # CONFIG_TEST_FPU is not set # CONFIG_TEST_CLOCKSOURCE_WATCHDOG is not set # CONFIG_TEST_OBJPOOL is not set CONFIG_ARCH_USE_MEMTEST=y # CONFIG_MEMTEST is not set # end of Kernel Testing and Coverage # # Rust hacking # # end of Rust hacking # end of Kernel hacking CONFIG_IO_URING_ZCRX=y ================================================ FILE: scripts/q-script/nix-q ================================================ #!/usr/bin/env bash # based on: https://github.com/fomichev/dotfiles/blob/master/bin/q usage() { echo "q [options] [path to bzImage] [script]" echo echo "Run it from the kernel directory (make sure .config is there)" echo echo "options:" echo " m - run depmod and modprobe" echo " c - pass extra kernel cmdline options" echo " s - start SSH server" exit 1 } # This function is called _BEFORE_ QEMU starts (on host). host() { local kernel="$1" shift if [ -z "$kernel" ]; then if [ -e "arch/x86/boot/bzImage" ]; then kernel="arch/x86/boot/bzImage" fi [ -n "$kernel" ] || usage fi [ -e ".config" ] || usage local cmdline local fs fs+=" -nodefaults" fs+=" -fsdev local,multidevs=remap,id=vfs1,path=/,security_model=none,readonly=on" fs+=" -fsdev local,multidevs=remap,id=vfs2,path=$(pwd),security_model=none" fs+=" -device virtio-9p-pci,fsdev=vfs1,mount_tag=/dev/root" fs+=" -device virtio-9p-pci,fsdev=vfs2,mount_tag=/dev/kernel" local console console+=" -display none" console+=" -serial mon:stdio" console+=" -serial tcp::1235,server,nowait" cmdline+=" earlyprintk=serial,ttyS0,115200" cmdline+=" console=ttyS0,115200" cmdline+=" kgdboc=ttyS1,115200" local net if [ "$SSH" = "y" ]; then net+=" -netdev user,id=virtual,hostfwd=tcp:127.0.0.1:52222-:22,hostfwd=tcp::11211-:11211,hostfwd=udp::11211-:11211" else net+=" -netdev user,id=virtual" fi net+=" -device virtio-net-pci,netdev=virtual" local opts [ "$MODULES" = "y" ] && opts+=" -m" [ "$SSH" = "y" ] && opts+=" -s" cmdline+=" rootfstype=9p" cmdline+=" rootflags=version=9p2000.L,trans=virtio,msize=104857600,access=any" cmdline+=" ro" cmdline+=" nokaslr" cmdline+=" $CMDLINE" cmdline+=" init=/usr/bin/env sh -- -c \"$(realpath $0) -g $opts -H $HOME -k '$(pwd)' -a '$*'\"" qemu-system-x86_64 \ -nodefaults \ -no-reboot \ -machine accel=kvm:tcg \ -device i6300esb \ -device virtio-rng-pci \ -cpu host \ -smp $NRCPU \ -m $MEMORY \ $fs \ $console \ $net \ $QEMUARG \ -kernel "$kernel" \ -append "$cmdline" -s # qemu-system-x86_64 \ # -nodefaults \ # -d int \ # -machine accel=tcg \ # -watchdog i6300esb \ # -device virtio-rng-pci \ # -cpu max \ # -smp $NRCPU \ # -m $MEMORY \ # $fs \ # $console \ # $net \ # $QEMUARG \ # -kernel "$kernel" \ # -append "$cmdline" -s } say() { trap 'tput sgr0' 2 #SIGINT tput setaf 2 echo ">" "$@" tput sgr0 } # This function is called _AFTER_ QEMU starts (on guest). guest() { export PATH=/bin:/sbin:/usr/bin:/usr/sbin export PATH=$HOME/.nix-profile/bin:$PATH if [[ -f "$KERNEL/nix_path" ]]; then NEW_PATHS=$(/usr/bin/env bat "$KERNEL/nix_path") export PATH="${NEW_PATHS}:${PATH}" fi say pivot root mount -n -t proc -o nosuid,noexec,nodev proc /proc/ mount -n -t tmpfs tmpfs /tmp mkdir -p /tmp/rootdir-overlay/{lower,upper,work,mnt} mount --bind / /tmp/rootdir-overlay/lower mount -t overlay overlay -o lowerdir=/tmp/rootdir-overlay/lower,upperdir=/tmp/rootdir-overlay/upper,workdir=/tmp/rootdir-overlay/work /tmp/rootdir-overlay/mnt pivot_root /tmp/rootdir-overlay/mnt{,/mnt} cd / say early setup mount -n -t sysfs -o nosuid,noexec,nodev sys /sys/ mount -n -t tmpfs tmpfs /tmp mount -n -t tmpfs tmpfs /var/log mount -n -t tmpfs tmpfs /run rm -f /etc/fstab touch /etc/fstab mount -n -t proc -o nosuid,noexec,nodev proc /proc/ mount -n -t configfs configfs /sys/kernel/config mount -n -t debugfs debugfs /sys/kernel/debug mount -n -t securityfs security /sys/kernel/security mount -n -t devtmpfs -o mode=0755,nosuid,noexec devtmpfs /dev mkdir -p -m 0755 /dev/shm /dev/pts mount -n -t devpts -o gid=tty,mode=620,noexec,nosuid devpts /dev/pts mount -n -t tmpfs -o mode=1777,nosuid,nodev tmpfs /dev/shm ln -s /proc/self/fd /dev/fd mount --move /mnt /tmp mount -n -t tmpfs tmpfs /mnt mkdir /mnt/base-root mount --move /tmp /mnt/base-root local kver="`uname -r`" local mods="$(find /sys/devices -type f -name modalias -print0 | xargs -0 cat | sort | uniq)" local mods_nr=$(echo "$mods" | wc -w) say modules /lib/modules/$kver $mods_nr modules mount -n -t 9p -o version=9p2000.L,trans=virtio,msize=104857600 /dev/kernel $KERNEL # Create lib/modules if on NixOS mkdir -p /lib/modules mount -n -t tmpfs tmpfs /lib/modules mkdir "/lib/modules/$kver" ln -s $KERNEL "/lib/modules/$kver/source" ln -s $KERNEL "/lib/modules/$kver/build" ln -s $KERNEL "/lib/modules/$kver/kernel" cp $KERNEL/modules.builtin "/lib/modules/$kver/modules.builtin" cp $KERNEL/modules.builtin.modinfo "/lib/modules/$kver/modules.builtin.modinfo" cp $KERNEL/modules.order "/lib/modules/$kver/modules.order" # make sure config points to the right place mount -n -t tmpfs tmpfs /boot ln -s $KERNEL/.config /boot/config-$kver if [ "$MODULES" = "y" ]; then if [ ! -e $KERNEL/modules.dep.bin ]; then say modules.dep.bin not found, running depmod, may take awhile depmod -a 2>/dev/null fi modprobe -q -a -- $mods fi say networking hostname q rm -f /etc/hostname echo q > /etc/hostname ip link set dev lo up rm -f /etc/resolv.conf echo "nameserver 8.8.8.8" > /etc/resolv.conf local dev=$(ls -d /sys/bus/virtio/drivers/virtio_net/virtio* |sort -g |head -n1) local iface=$(ls $dev/net) say dhcp on iface $iface ip link set dev $iface up # busybox udhcpc -i $iface -p /run/udhcpc \ # -s /usr/share/udhcpc/default.script -q -t 1 -n -f say setup cgroups sysctl -q kernel.allow_bpf_attach_netcg=0 &>/dev/null mount -t cgroup2 none /sys/fs/cgroup say setup bpf sysctl -q net.core.bpf_jit_enable=1 sysctl -q net.core.bpf_jit_kallsyms=1 sysctl -q net.core.bpf_jit_harden=0 mount -t bpf bpffs /sys/fs/bpf ulimit -l unlimited &>/dev/null # EINVAL when loading more than 3 bpf programs ulimit -n 819200 &>/dev/null ulimit -a &>/dev/null say root passwd rm -f /etc/{shadow,gshadow} pwconv grpconv mount --bind / /mnt usermod -R /mnt -d "$HOME" root umount /mnt # For system cannot get ip addr by udhcpc local ip_address=$(ip -4 addr show $iface | grep -oP '(?<=inet\s)\d+(\.\d+){3}') local default_route=$(ip route | grep default) if [[ -z "$ip_address" ]]; then ip a add 10.0.2.15/24 dev eth0 fi if [[ -z "$default_route" ]]; then ip route add default via 10.0.2.2 fi if [ "$SSH" = "y" ]; then say setup sshd: '$ ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@localhost -p 52222' mask-dir () { touch "$1" setfattr -n trusted.overlay.opaque -v y /mnt/base-root/tmp/rootdir-overlay/upper/"$1" mount -o remount / } mask-dir /etc/ssh/ cat << 'EOF' > /etc/pam.d/sshd account sufficient pam_permit.so auth sufficient pam_permit.so password sufficient pam_permit.so session sufficient pam_permit.so EOF ssh-keygen -A mkdir -p /run/sshd `which sshd` -p 22 -o UsePAM=yes -o PermitRootLogin=yes -f /dev/null -E /var/log/sshd fi say root environment cat << EOF >> $HOME/.profile export KERNEL=$KERNEL export PATH=\$HOME/local/bin:\$PATH export PATH=\$KERNEL/tools/bpf/bpftool:\$PATH export PATH=\$KERNEL/tools/perf:\$PATH export PATH=\$HOME/.nix-profile/bin:\$PATH EOF cat << EOF >> $HOME/.bashrc mask-dir () { touch "\$1" setfattr -n trusted.overlay.opaque -v y /mnt/base-root/tmp/rootdir-overlay/upper/"\$1" mount -o remount / } source $KERNEL/tools/bpf/bpftool/bash-completion/bpftool eval \$(resize) EOF cd $KERNEL if [ -n "$ARGS" ]; then say non-interactive bash script setsid bash -l -c "$ARGS" if [ ! $? -eq 0 ]; then say script failed, starting interactive console setsid bash -l 0<>"/dev/ttyS0" 1>&0 2>&0 fi else say interactive bash setsid bash -l 0<>"/dev/ttyS0" 1>&0 2>&0 fi echo say poweroff poweroff -f echo o > /proc/sysrq-trigger sleep 30 } GUEST=n MODULES=n SSH=n CMDLINE="" QEMUARG="" NRCPU=4 MEMORY=8192 while getopts "hgmsk:c:a:H:N:M:q:" opt; do case $opt in h) usage ;; g) GUEST=y ;; m) MODULES=y ;; s) SSH=y ;; k) KERNEL="$OPTARG" ;; c) CMDLINE="$OPTARG" ;; a) ARGS="$OPTARG" ;; H) export HOME=$OPTARG ;; M) MEMORY="$OPTARG" ;; N) NRCPU="$OPTARG" ;; q) QEMUARG="$OPTARG" ;; esac done shift $((OPTIND -1)) [ "$GUEST" = "y" ] && guest "$@" || host "$@" ================================================ FILE: scripts/q-script/sanity-test-q ================================================ #!/bin/bash # based on: https://github.com/fomichev/dotfiles/blob/master/bin/q # External variables, users can override: # {{{ SSH_PORT=${SSH_PORT:-52222} NRCPU=${NRCPU:-2} MEMORY=${MEMORY:-4096} TAP_QUEUES=${TAP_QUEUES:-$NRCPU} TAP_MQ=${TAP_MQ:-true} V4_ADDR=${V4_ADDR:-"10.0.2.15"} # dhcp by default V4_PREFIX=${V4_PREFIX:-"24"} # dhcp by default V4_ROUTE=${V4_ROUTE:-"10.0.2.2"} V6_ADDR=${V6_ADDR:-"2002:ad6:c2c4::1"} V6_PREFIX=${V6_PREFIX:-128} HOST=${HOST:-q} # }}} # Internal variables: # {{{ DIR_Q="$(dirname $0)" DIR_EXPORT=/media DIR_ROOT=${DIR_ROOT:-/} DIR_KERNEL=${DIR_KERNEL:-} IMAGE=${IMAGE:-} IMAGE_PART="sda1" IMAGE_INIT="/sbin/init.real" SCRIPT=${SCRIPT:-} ENVIRON_ARG=${ENVIRON_ARG:-} GDB=${GDB:-false} GUEST=${GUEST:-false} MODULES=${MODULES:-false} TTY=${TTY:-ttyS0} SSH=${SSH:-false} FWD_PORT=${FWD_PORT:-} NET_USER=${NET_USER:-true} NET_TAP=${NET_TAP:-false} NET_VHOST=${NET_VHOST:-false} # }}} usage() { if [[ -n "$*" ]]; then echo "error: $@" echo fi echo "q [options] [path to bzImage]" echo echo "Run it from the kernel directory (make sure .config is there)" echo echo "options:" echo " i - use specified disk image instead of rootfs" echo " g - support attaching with gdb" echo " m - run depmod and modprobe" echo " c - pass extra kernel cmdline options" echo " d - start SSH server" echo " s - run script instead of interactive bash" echo " 2 - disable cgroup v1, run only v2" echo " f - forward given localhost port (comma-separated list)" echo " n - networking mode (user,tap,vhost)" exit 1 } fixup() { local stage="$1" if [[ -z "$IMAGE_FIXUP" ]]; then return fi say FIXUP $stage ${stage}_fixup } # This function is called _BEFORE_ QEMU starts (on host). host() { local kernel="$1" [[ -e ".config" ]] || usage local cmdline local fs fs+=" -fsdev local,multidevs=remap,id=vfs1,path=$DIR_ROOT,security_model=none,readonly=on" fs+=" -fsdev local,id=vfs2,path=$(pwd),security_model=none" # fs+=" -fsdev local,id=vfs3,path=$DIR_EXPORT,security_model=none" fs+=" -fsdev local,id=vfs4,path=$DIR_Q,security_model=none,readonly=on" fs+=" -device virtio-9p-pci,fsdev=vfs1,mount_tag=/dev/root" fs+=" -device virtio-9p-pci,fsdev=vfs2,mount_tag=/dev/kernel" # fs+=" -device virtio-9p-pci,fsdev=vfs3,mount_tag=$DIR_EXPORT" fs+=" -device virtio-9p-pci,fsdev=vfs4,mount_tag=/tmp/dir_q" local console console+=" -display none" console+=" -serial mon:stdio" cmdline+=" earlyprintk=serial,ttyS0,115200" if [[ "${ARCH}" != "arm64" ]]; then cmdline+=" console=ttyS0" cmdline+=" kgdboc=ttyS1,115200" fi cmdline+=" oops=panic retbleed=off" local net if $NET_USER; then net+=" -netdev user,id=virtual" if $SSH; then net+=",hostfwd=tcp:127.0.0.1:$SSH_PORT-:22" fi if [[ ! -z "$FWD_PORT" ]]; then for p in $(echo "$FWD_PORT" | tr ',' ' '); do net+=",hostfwd=tcp::${p}-:$p" done fi net+=" -device virtio-net-pci,netdev=virtual" fi if $NET_TAP; then local dev="qtap1" if $TAP_MQ; then dev="qtap0" fi local vhost="" if $NET_VHOST; then vhost=",vhost=on" fi net+=" -netdev tap,id=virtual,ifname=$dev,script=no$vhost" if $TAP_MQ; then net+=",queues=${TAP_QUEUES}" fi net+=" -device virtio-net-pci,netdev=virtual" if $TAP_MQ; then net+=",mq=on" fi fi cmdline+=" $CMDLINE" cmdline+=" rootfstype=9p" cmdline+=" rootflags=version=9p2000.L,trans=virtio,access=any" cmdline+=" ro" cmdline+=" nokaslr" local gdb $GDB && gdb+=" -s" if [[ ! -z "$IMAGE" ]]; then fs+=" -drive format=raw,file=$IMAGE" fi local accel if [[ "$(uname -m)" = "${ARCH}" ]]; then if [[ -e /dev/kvm ]]; then accel+=" -machine accel=kvm:tcg" accel+=" -enable-kvm" fi fi fixup host local cpu local qemu_flavor=$ARCH case "${ARCH}" in x86_64) if [[ "$(uname -m)" = "${ARCH}" ]]; then if [[ -e /dev/kvm ]]; then cpu="host" else cpu="max" fi fi ;; arm64) if [[ "$(uname -m)" = "${ARCH}" ]]; then cpu="host" else accel+=" -machine virt -accel tcg " cpu="max" fi qemu_flavor=aarch64 TTY=ttyAMA0 ;; esac local init # init+="mount -n -t tmpfs tmpfs /tmp" # init+=" && " # init+="mkdir -p /tmp/dir_q" # init+=" && " # init+="mount -n -t 9p -o trans=virtio /tmp/dir_q /tmp/dir_q" # init+=" && " init+="GUEST='true' " init+="IMAGE='$IMAGE' " init+="GDB='$GDB' " init+="TTY='$TTY' " init+="HOSTNAME='$HOSTNAME' " init+="HOME='$HOME' " init+="DIR_ROOT='$DIR_ROOT' " init+="DIR_KERNEL='$(pwd)' " init+="MODULES='$MODULES' " init+="SSH='$SSH' " init+="FWD_PORT='$FWD_PORT' " init+="V4_ADDR='$V4_ADDR' " init+="V4_PREFIX='$V4_PREFIX' " init+="V6_ADDR='$V6_ADDR' " init+="V6_PREFIX='$V6_PREFIX' " init+="NET_USER='$NET_USER' " init+="NET_TAP='$NET_TAP' " init+="NET_VHOST='$NET_VHOST' " init+="SCRIPT='$SCRIPT' " init+="$ENVIRON_ARG " # grading script specific init+="TEST_PATH='$TEST_PATH' " init+=" $(realpath $0) " cmdline+=" init=/bin/sh -- -c \"$init\"" if [[ -z "$cpu" ]]; then echo "unknown cpu for ${ARCH} arch" exit 1 fi qemu-system-${qemu_flavor} \ -nographic \ -no-reboot \ $accel \ -device i6300esb,id=watchdog0 \ -watchdog-action pause \ -device virtio-rng-pci \ -cpu $cpu \ -smp $NRCPU \ -m $MEMORY \ $fs \ $console \ $net \ $gdb \ -kernel "$kernel" \ -append "$cmdline" } say() { trap 'tput sgr0' 2 #SIGINT # tput setaf 2 printf "\33[32m" echo ">" "$@" # tput sgr0 printf "\33(B\33[m" } mask-dir() { local upper_dir="/mnt/base-root/tmp/rootdir-overlay/upper/$1" mkdir -p "$upper_dir" setfattr -n trusted.overlay.opaque -v y "$upper_dir" mount -o remount / } append_to_hosts() { local addr="$1" local prefix=$(echo "$HOSTNAME" | cut -d. -f1) local suffix=$(echo "$HOSTNAME" | cut -d. -f2-) if [[ ! -z "$suffix" ]]; then suffix=".${suffix}" fi if ! echo "$addr" | grep -q ':'; then prefix="${prefix}-v4" fi echo "$addr ${prefix}${suffix} ${prefix}" >>/etc/hosts } # This function is called _AFTER_ QEMU starts (on guest). guest() { export PATH=/bin:/sbin:/usr/bin:/usr/sbin say pivot root local overlay="/tmp/rootdir-overlay" mount -n -t proc -o nosuid,noexec,nodev proc /proc/ mount -n -t tmpfs tmpfs /tmp mkdir -p $overlay/{lower,upper,work,mnt} mount --bind / $overlay/lower mount -t overlay overlay -o lowerdir=$overlay/lower,upperdir=$overlay/upper,workdir=$overlay/work $overlay/mnt pivot_root $overlay/mnt{,/tmp} cd / mount -n -t proc -o nosuid,noexec,nodev proc /proc/ mount -n -t tmpfs tmpfs /mnt mkdir /mnt/base-root mount --move /tmp /mnt/base-root say early setup mount -n -t sysfs -o nosuid,noexec,nodev sys /sys/ mount -n -t tmpfs tmpfs /tmp mount -n -t tmpfs tmpfs /var/log mount -n -t tmpfs tmpfs /run if [[ -d /export ]]; then mount -n -t tmpfs tmpfs /export mkdir -p $DIR_EXPORT mount -n -t 9p -o trans=virtio $DIR_EXPORT $DIR_EXPORT else say "$/expor mount point doesn't exist, not mounting $DIR_EXPORT" fi >/etc/fstab mount -n -t configfs configfs /sys/kernel/config mount -n -t debugfs debugfs /sys/kernel/debug if [[ -d /sys/kernel/security ]]; then mount -n -t securityfs security /sys/kernel/security fi mount -n -t devtmpfs -o mode=0755,nosuid,noexec devtmpfs /dev mkdir -p -m 0755 /dev/shm /dev/pts /dev/cgroup mkdir -p -m 0755 /dev/cgroup/{cpu,cpuset,net} 2>/dev/null mount -n -t devpts -o gid=tty,mode=620,noexec,nosuid devpts /dev/pts mount -n -t tmpfs -o mode=1777,nosuid,nodev tmpfs /dev/shm if [[ -d "$DIR_KERNEL" ]]; then local kver="$(uname -r)" local mods="$(find /sys/devices -type f -name modalias -print0 | xargs -0 cat | sort | uniq)" local mods_nr=$(echo "$mods" | wc -w) say modules /lib/modules/$kver $mods_nr modules mount -n -t 9p -o trans=virtio /dev/kernel "$DIR_KERNEL" mount -n -t tmpfs tmpfs /lib/modules mkdir "/lib/modules/$kver" ln -s "$DIR_KERNEL" "/lib/modules/$kver/source" ln -s "$DIR_KERNEL" "/lib/modules/$kver/build" ln -s "$DIR_KERNEL" "/lib/modules/$kver/kernel" cp "$DIR_KERNEL/modules.builtin" "/lib/modules/$kver/modules.builtin" cp "$DIR_KERNEL/modules.order" "/lib/modules/$kver/modules.order" # make sure config points to the right place mount -n -t tmpfs tmpfs /boot ln -s "$DIR_KERNEL/.config" /boot/config-$kver if $MODULES; then if [[ ! -e "$DIR_KERNEL/modules.dep.bin" ]]; then say modules.dep.bin not found, running depmod, may take awhile depmod -a 2>/dev/null fi modprobe -q -a -- $mods fi else say "$DIR_KERNEL mount point doesn't exist, not mounting" fi say networking as $HOSTNAME if [[ -n "$(command -v hostname)" ]]; then hostname "$HOSTNAME" echo "$HOSTNAME" >/etc/hostname else say "hostname is not found, don't set hostname" fi ip link set dev lo up if $NET_USER; then if [[ -n "$(command -v busybox)" ]]; then if [[ -e "/etc/udhcpc/default.script" ]]; then mask-dir /etc/resolvconf/run mkdir -p /run/resolvconf echo "nameserver 8.8.8.8" >/run/resolvconf/resolv.conf local dev=$(ls -d /sys/bus/virtio/drivers/virtio_net/virtio* | sort -g | head -n1) local iface=$(ls $dev/net) say dhcp on iface $iface ip link set dev $iface up dhcpcd $iface busybox udhcpc -i $iface -p /run/udhcpc \ -s /etc/udhcpc/default.script -q -t 1 -n -f append_to_hosts "$v4_addr" else say "busybox is found, but no /etc/udhcpc/default.script, use assigned ip address" if [[ ! -z "$V4_ADDR" ]]; then mask-dir /etc/resolvconf/run mkdir -p /run/resolvconf echo "nameserver 8.8.8.8" >/run/resolvconf/resolv.conf local dev=$(ls -d /sys/bus/virtio/drivers/virtio_net/virtio* | sort -g | head -n1) local iface=$(ls $dev/net) ip link set dev $iface up ip -4 addr add "${V4_ADDR}/${V4_PREFIX}" dev $iface ip -4 route add default via $V4_ROUTE append_to_hosts "$V4_ADDR" fi fi else say "busybox is not found, skipping udhcpc" fi fi if $NET_TAP; then ip link set dev eth0 up fi if [[ ! -z "$V6_ADDR" ]]; then ip -6 addr add "${V6_ADDR}/${V6_PREFIX}" dev eth0 append_to_hosts "$V6_ADDR" fi if [[ ! -z "$V4_ADDR" ]]; then ip -4 addr add "${V4_ADDR}/${V4_PREFIX}" dev eth0 append_to_hosts "$V4_ADDR" fi if [[ ! -z "$IMAGE" ]]; then say fsck fsck -T -y -v -r "/dev/$IMAGE_PART" say mount disk mkdir /mnt/root mount -n "/dev/$IMAGE_PART" /mnt/root fixup guest_pre_pivot say pivot root pivot_root /mnt/root{,/tmp} cd / umount /tmp/{tmp,var/log,run} mkdir -p /root/9p-overlay mount --move /tmp /root/9p-overlay mount -n -t tmpfs tmpfs /root/9p-overlay fixup guest_post_pivot say exec init mount -n -o remount,ro / exec "$IMAGE_INIT" fi say setup cgroups mount -t cgroup -o cpu,cpuacct none /dev/cgroup/cpu mount -t cgroup -o cpuset none /dev/cgroup/cpuset mount -t cgroup -o net_cls none /dev/cgroup/net &>/dev/null sysctl -q kernel.allow_bpf_attach_netcg=0 &>/dev/null mount -t cgroup2 none /sys/fs/cgroup say setup bpf sysctl -q net.core.bpf_jit_enable=1 sysctl -q net.core.bpf_jit_kallsyms=1 sysctl -q net.core.bpf_jit_harden=0 mount -t bpf bpffs /sys/fs/bpf ulimit -l unlimited &>/dev/null # EINVAL when loading more than 3 bpf programs ulimit -n 819200 &>/dev/null ulimit -a &>/dev/null if $SSH; then say setup sshd say ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@localhost -p $SSH_PORT mask-dir /etc/ssh mask-dir /etc/pam.d mkdir -p /var/run/sshd cat <<'EOF' >/etc/pam.d/sshd account sufficient pam_permit.so auth sufficient pam_permit.so password sufficient pam_permit.so session sufficient pam_permit.so EOF echo "root:x:0:0:root:/:/bin/bash" >/etc/passwd echo "sshd:x:123:65534::/var/run/sshd:/usr/sbin/nologin" >>/etc/passwd echo "root:*:17785:0:99999:7:::" >/etc/shadow echo "" >/etc/group cat $HOME/.ssh/id_rsa.pub >>/etc/ssh/authorized_keys ssh-keygen -A $(which sshd) \ -p 22 \ -o UsePAM=yes \ -o PermitRootLogin=yes \ -o AuthorizedKeysFile=/etc/ssh/authorized_keys \ -f /dev/null \ -E /var/log/sshd fi if $GDB; then local kconfig=$(zcat /proc/config.gz | grep CONFIG_GDB_SCRIPT) if [[ ! "$kconfig" = "CONFIG_GDB_SCRIPTS=y" ]]; then say requested GDB, but missing CONFIG_GDB_SCRIPTS=y fi fi say root environment touch /etc/{profile,bash.bashrc} >/etc/profile >/etc/bash.bashrc mkdir -pm 0755 /root touch /root/.bashrc &>/dev/null touch /root/.bash_profile &>/dev/null local rcfile=/tmp/.bashrc export PATH=$HOME/local/bin:$PATH if [[ -d "$DIR_KERNEL" ]]; then export PATH="$DIR_KERNEL/tools/bpf/bpftool:$PATH" export PATH="$DIR_KERNEL/tools/perf:$PATH" fi export NO_BASE16=true # hack for my bashrc to disable colors cat <$rcfile export DIR_KERNEL="$DIR_KERNEL" export PATH=\$HOME/local/bin:\$PATH export PATH=\$DIR_KERNEL/tools/bpf/bpftool:\$PATH export PATH=\$DIR_KERNEL/tools/perf:\$PATH mask-dir () { local upper_dir="/mnt/base-root/tmp/rootdir-overlay/upper/\$1" mkdir -p "\$upper_dir" setfattr -n trusted.overlay.opaque -v y "\$upper_dir" mount -o remount / } if [[ -e "\$HOME/.bashrc" ]]; then source \$HOME/.bashrc fi if [[ -e "\$DIR_KERNEL" ]]; then source "\$DIR_KERNEL/tools/bpf/bpftool/bash-completion/bpftool" fi if [[ -n "\$(command -v resize)" ]]; then resize &>/dev/null fi EOF if [[ -d "$DIR_KERNEL" ]]; then source "$DIR_KERNEL/tools/bpf/bpftool/bash-completion/bpftool" cd "$DIR_KERNEL" fi SAMPLE_PATH=$(dirname $TEST_PATH) cd $SAMPLE_PATH echo $TEST_PATH pwd python3 ${TEST_PATH} cp auto_grade.txt ${DIR_KERNEL} poweroff -f if [[ -n "$SCRIPT" ]]; then say non-interactive bash script setsid bash --rcfile $rcfile -c "$SCRIPT" if [[ ! $? -eq 0 ]]; then say script failed, starting interactive console setsid bash --rcfile $rcfile 0<>"/dev/$TTY" 1>&0 2>&0 fi else say interactive bash $rcfile setsid bash --rcfile $rcfile 0<>"/dev/$TTY" 1>&0 2>&0 fi echo say poweroff echo o >/proc/sysrq-trigger sleep 30 } while getopts "2i:dhgms:c:f:t:n" opt; do case $opt in h) usage ;; 2) CMDLINE+=" cgroup_no_v1=all" ;; i) IMAGE="$OPTARG" ;; g) GDB=true ;; m) MODULES=true ;; c) CMDLINE="$OPTARG" ;; d) SSH=true ;; s) SCRIPT="$OPTARG" ;; f) FWD_PORT="$OPTARG" ;; t) TEST_PATH="$OPTARG" ;; n) case "$OPTARG" in user) ;; tap) NET_USER=false NET_TAP=true ;; vhost) NET_USER=false NET_TAP=true NET_VHOST=true ;; *) echo "Invalid net '$OPTARG'" exit 1 ;; esac ;; esac done shift $((OPTIND - 1)) echo $TEST_PATH if [[ ! -z "$IMAGE" && -e "${IMAGE/.img/.fixup}" ]]; then IMAGE_FIXUP="${IMAGE/.img/.fixup}" fi if [[ ! -z "$IMAGE_FIXUP" ]]; then say Using fixup script ${IMAGE_FIXUP}! . "$IMAGE_FIXUP" fi if $GUEST; then guest else kernel="$1" shift export HOSTNAME="$HOST" if $NET_TAP; then if ! ip link show dev qtap0 &>/dev/null; then echo "Couldn't find qtap0 tap device, do:" echo "$ sudo ip tuntap add dev qtap0 mode tap multi_queue" echo "$ sudo ip addr add 10.10.10.1/24 dev qtap0" echo "$ sudo ip link set dev qtap0 up" echo "$ sudo ip tuntap add dev qtap1 mode tap" echo "$ sudo ip addr add 10.10.11.1/24 dev qtap1" echo "$ sudo ip link set dev qtap1 up" exit 1 fi if $TAP_MQ; then V4_ADDR=10.10.10.2 V4_PREFIX=24 else V4_ADDR=10.10.11.2 V4_PREFIX=24 fi fi if [[ -z "$kernel" ]]; then if [[ -e "arch/x86/boot/bzImage" ]]; then kernel="arch/x86/boot/bzImage" elif [[ -e "arch/arm64/boot/Image" ]]; then kernel="arch/arm64/boot/Image" fi fi if [[ -z "$ARCH" ]]; then if file $kernel | grep -q x86; then ARCH=x86_64 elif file $kernel | grep -q ARM64; then ARCH=arm64 fi fi [ -n "$ARCH" ] || usage "unknown arch" host "$kernel" fi ================================================ FILE: scripts/q-script/yifei-q ================================================ #!/bin/bash # based on: https://github.com/fomichev/dotfiles/blob/master/bin/q usage() { echo "q [options] [path to bzImage] [script]" echo echo "Run it from the kernel directory (make sure .config is there)" echo echo "options:" echo " m - run depmod and modprobe" echo " c - pass extra kernel cmdline options" echo " s - start SSH server" exit 1 } # This function is called _BEFORE_ QEMU starts (on host). host() { local kernel="$1" shift if [ -z "$kernel" ]; then if [ -e "arch/x86/boot/bzImage" ]; then kernel="arch/x86/boot/bzImage" fi [ -n "$kernel" ] || usage fi [ -e ".config" ] || usage local cmdline local fs fs+=" -nodefaults" fs+=" -fsdev local,multidevs=remap,id=vfs1,path=/,security_model=none,readonly=on" fs+=" -fsdev local,multidevs=remap,id=vfs2,path=$(pwd),security_model=none" fs+=" -device virtio-9p-pci,fsdev=vfs1,mount_tag=/dev/root" fs+=" -device virtio-9p-pci,fsdev=vfs2,mount_tag=/dev/kernel" local console console+=" -display none" console+=" -serial mon:stdio" console+=" -serial tcp::1235,server,nowait" cmdline+=" earlyprintk=serial,ttyS0,115200" cmdline+=" console=ttyS0,115200" cmdline+=" kgdboc=ttyS1,115200" local net if [ "$SSH" = "y" ]; then # check container env assume docker net+=" -netdev user,id=virtual,hostfwd=tcp:127.0.0.1:52222-:22,hostfwd=tcp::11211-:11211,hostfwd=udp::11211-:11211" else net+=" -netdev user,id=virtual" fi net+=" -device virtio-net-pci,netdev=virtual" local opts [ "$MODULES" = "y" ] && opts+=" -m" [ "$SSH" = "y" ] && opts+=" -s" cmdline+=" rootfstype=9p" cmdline+=" rootflags=version=9p2000.L,trans=virtio,msize=104857600,access=any" cmdline+=" ro" cmdline+=" nokaslr" cmdline+=" $CMDLINE" cmdline+=" init=/bin/sh -- -c \"$(realpath $0) -g $opts -H $HOME -k '$(pwd)' -a '$*'\"" qemu-system-x86_64 \ -nodefaults \ -no-reboot \ -machine accel=kvm:tcg \ -device i6300esb \ -device virtio-rng-pci \ -cpu host \ -smp $NRCPU \ -m $MEMORY \ $fs \ $console \ $net \ $QEMUARG \ -kernel "$kernel" \ -append "$cmdline" -s # qemu-system-x86_64 \ # -nodefaults \ # -d int \ # -machine accel=tcg \ # -watchdog i6300esb \ # -device virtio-rng-pci \ # -cpu max \ # -smp $NRCPU \ # -m $MEMORY \ # $fs \ # $console \ # $net \ # $QEMUARG \ # -kernel "$kernel" \ # -append "$cmdline" -s } say() { trap 'tput sgr0' 2 #SIGINT tput setaf 2 echo ">" "$@" tput sgr0 } # This function is called _AFTER_ QEMU starts (on guest). guest() { export PATH=/bin:/sbin:/usr/bin:/usr/sbin say pivot root mount -n -t proc -o nosuid,noexec,nodev proc /proc/ mount -n -t tmpfs tmpfs /tmp mkdir -p /tmp/rootdir-overlay/{lower,upper,work,mnt} mount --bind / /tmp/rootdir-overlay/lower mount -t overlay overlay -o lowerdir=/tmp/rootdir-overlay/lower,upperdir=/tmp/rootdir-overlay/upper,workdir=/tmp/rootdir-overlay/work /tmp/rootdir-overlay/mnt pivot_root /tmp/rootdir-overlay/mnt{,/mnt} cd / say early setup mount -n -t sysfs -o nosuid,noexec,nodev sys /sys/ mount -n -t tmpfs tmpfs /tmp mount -n -t tmpfs tmpfs /var/log mount -n -t tmpfs tmpfs /run rm -f /etc/fstab touch /etc/fstab mount -n -t proc -o nosuid,noexec,nodev proc /proc/ mount -n -t configfs configfs /sys/kernel/config mount -n -t debugfs debugfs /sys/kernel/debug mount -n -t securityfs security /sys/kernel/security mount -n -t devtmpfs -o mode=0755,nosuid,noexec devtmpfs /dev mkdir -p -m 0755 /dev/shm /dev/pts mount -n -t devpts -o gid=tty,mode=620,noexec,nosuid devpts /dev/pts mount -n -t tmpfs -o mode=1777,nosuid,nodev tmpfs /dev/shm ln -s /proc/self/fd /dev/fd mount --move /mnt /tmp mount -n -t tmpfs tmpfs /mnt mkdir /mnt/base-root mount --move /tmp /mnt/base-root local kver="`uname -r`" local mods="$(find /sys/devices -type f -name modalias -print0 | xargs -0 cat | sort | uniq)" local mods_nr=$(echo "$mods" | wc -w) say modules /lib/modules/$kver $mods_nr modules mount -n -t 9p -o version=9p2000.L,trans=virtio,msize=104857600 /dev/kernel $KERNEL mount -n -t tmpfs tmpfs /lib/modules mkdir "/lib/modules/$kver" ln -s $KERNEL "/lib/modules/$kver/source" ln -s $KERNEL "/lib/modules/$kver/build" ln -s $KERNEL "/lib/modules/$kver/kernel" cp $KERNEL/modules.builtin "/lib/modules/$kver/modules.builtin" cp $KERNEL/modules.builtin.modinfo "/lib/modules/$kver/modules.builtin.modinfo" cp $KERNEL/modules.order "/lib/modules/$kver/modules.order" # make sure config points to the right place mount -n -t tmpfs tmpfs /boot ln -s $KERNEL/.config /boot/config-$kver if [ "$MODULES" = "y" ]; then if [ ! -e $KERNEL/modules.dep.bin ]; then say modules.dep.bin not found, running depmod, may take awhile depmod -a 2>/dev/null fi modprobe -q -a -- $mods fi say networking hostname q rm -f /etc/hostname echo q > /etc/hostname ip link set dev lo up rm -f /etc/resolv.conf echo "nameserver 8.8.8.8" > /etc/resolv.conf local dev=$(ls -d /sys/bus/virtio/drivers/virtio_net/virtio* |sort -g |head -n1) local iface=$(ls $dev/net) say dhcp on iface $iface ip link set dev $iface up busybox udhcpc -i $iface -p /run/udhcpc \ -s /usr/share/udhcpc/default.script -q -t 1 -n -f say setup cgroups sysctl -q kernel.allow_bpf_attach_netcg=0 &>/dev/null mount -t cgroup2 none /sys/fs/cgroup say setup bpf sysctl -q net.core.bpf_jit_enable=1 sysctl -q net.core.bpf_jit_kallsyms=1 sysctl -q net.core.bpf_jit_harden=0 mount -t bpf bpffs /sys/fs/bpf ulimit -l unlimited &>/dev/null # EINVAL when loading more than 3 bpf programs ulimit -n 819200 &>/dev/null ulimit -a &>/dev/null say root passwd rm -f /etc/{shadow,gshadow} pwconv grpconv mount --bind / /mnt usermod -R /mnt -d "$HOME" root umount /mnt # For system cannot get ip addr by udhcpc local ip_address=$(ip -4 addr show $iface | grep -oP '(?<=inet\s)\d+(\.\d+){3}') local default_route=$(ip route | grep default) if [[ -z "$ip_address" ]]; then ip a add 10.0.2.15/24 dev eth0 fi if [[ -z "$default_route" ]]; then ip route add default via 10.0.2.2 fi if [ "$SSH" = "y" ]; then say setup sshd: '$ ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@localhost -p 52222' mask-dir () { touch "$1" setfattr -n trusted.overlay.opaque -v y /mnt/base-root/tmp/rootdir-overlay/upper/"$1" mount -o remount / } mask-dir /etc/ssh/ cat << 'EOF' > /etc/pam.d/sshd account sufficient pam_permit.so auth sufficient pam_permit.so password sufficient pam_permit.so session sufficient pam_permit.so EOF ssh-keygen -A mkdir -p /run/sshd `which sshd` -p 22 -o UsePAM=yes -o PermitRootLogin=yes -f /dev/null -E /var/log/sshd fi say root environment cat << EOF >> $HOME/.profile export KERNEL=$KERNEL export PATH=\$HOME/local/bin:\$PATH export PATH=\$KERNEL/tools/bpf/bpftool:\$PATH export PATH=\$KERNEL/tools/perf:\$PATH export LD_LIBRARY_PATH=/inner_unikernels/libiu:/inner_unikernels/tools/lib/bpf:$LD_LIBRARY_PATH EOF cat << EOF >> $HOME/.bashrc mask-dir () { touch "\$1" setfattr -n trusted.overlay.opaque -v y /mnt/base-root/tmp/rootdir-overlay/upper/"\$1" mount -o remount / } source $KERNEL/tools/bpf/bpftool/bash-completion/bpftool eval \$(resize) EOF cd $KERNEL if [ -n "$ARGS" ]; then say non-interactive bash script setsid bash -l -c "$ARGS" if [ ! $? -eq 0 ]; then say script failed, starting interactive console setsid bash -l 0<>"/dev/ttyS0" 1>&0 2>&0 fi else say interactive bash setsid bash -l 0<>"/dev/ttyS0" 1>&0 2>&0 fi echo say poweroff poweroff -f echo o > /proc/sysrq-trigger sleep 30 } GUEST=n MODULES=n SSH=n CMDLINE="" QEMUARG="" NRCPU=4 MEMORY=8192 while getopts "hgmsk:c:a:H:N:M:q:" opt; do case $opt in h) usage ;; g) GUEST=y ;; m) MODULES=y ;; s) SSH=y ;; k) KERNEL="$OPTARG" ;; c) CMDLINE="$OPTARG" ;; a) ARGS="$OPTARG" ;; H) export HOME=$OPTARG ;; M) MEMORY="$OPTARG" ;; N) NRCPU="$OPTARG" ;; q) QEMUARG="$OPTARG" ;; esac done shift $((OPTIND -1)) [ "$GUEST" = "y" ] && guest "$@" || host "$@" ================================================ FILE: scripts/sanity_tests/run_tests.py ================================================ #!/usr/bin/env bash ''':' ; exec "$(command -v python)" "$0" "$@" ''' import os import subprocess import sys from pathlib import Path sample_path = os.environ.get("SAMPLE_PATH") if not sample_path: print("Error: SAMPLE_PATH environment variable is required") sys.exit(1) sample = Path(sample_path) q_script_env = os.environ.get("Q_SCRIPT") if not q_script_env: print("Error: Q_SCRIPT environment variable is required") sys.exit(1) q_script = Path(q_script_env) # Set Path env kernel_path_env = os.environ.get("KERNEL_PATH") if not kernel_path_env: print("Error: KERNEL_PATH environment variable is required") sys.exit(1) kernel_path = Path(kernel_path_env) def main(): os.chdir(kernel_path) test_path = sample.joinpath("runtest.py") cmd = " ".join([str(q_script), "-t", str(test_path)]) try: # print(cmd) result = subprocess.run( cmd, timeout=180, shell=True, capture_output=True, text=True ) # Debug: save QEMU output for troubleshooting with open("qemu_stdout.log", "w") as f: f.write(result.stdout) with open("qemu_stderr.log", "w") as f: f.write(result.stderr) print(f"QEMU exit code: {result.returncode}", file=sys.stderr) output = subprocess.run( "cat auto_grade.txt | grep success", capture_output=True, text=True, shell=True, ) if output.stdout.strip() != "success": print("", end="\x1b[1K\r") print(" \033[91mFailed\033[0m %s" % sample.name) exit(1) except Exception: print(f"{sample.name} test run failed", file=sys.stderr) subprocess.run("pkill qemu-system-x86", shell=True) finally: subprocess.run("rm auto_grade.txt", shell=True, check=True) if __name__ == "__main__": main() ================================================ FILE: tools/memcached_benchmark/.cargo/config.toml ================================================ [env] CC = { value = "clang", force = true } [target.x86_64-unknown-linux-gnu] linker = "clang" rustflags = [ "-Zthreads=8", "-Ctarget-cpu=native", "-Clinker-plugin-lto", "-Clink-args=-flto=thin -fuse-ld=mold -Wl,-O1 -Wl,--as-needed -Wl,--gc-sections", ] ================================================ FILE: tools/memcached_benchmark/.gitignore ================================================ /target bmc-results.csv # Devenv .devenv* devenv.local.nix # direnv .direnv # pre-commit .pre-commit-config.yaml ================================================ FILE: tools/memcached_benchmark/Cargo.toml ================================================ [package] name = "memcached_benchmark" version = "0.2.0" edition = "2024" authors = ["Ruowen Qin ruowenq2@illinois.edu"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] memcache = { version = "0.19", default-features = false } rand = "0" rand_distr = "0" clap = { version = "4", features = ["derive"] } rayon = "1" tokio = { version = "1", features = ["full"] } zstd = { version = "0", features = ["zstdmt", "thin-lto"] } serde = { version = "1", features = ["derive"] } serde_yaml = "0.9" serde_json = "1" memcache-async = "0.10" tokio-util = { version = "0.7", features = ["rt", "compat"] } chacha20 = "0" log = "0" env_logger = { version = "0" } mimalloc = "0" anyhow = "1" [dev-dependencies] assert_cmd = "2" predicates = "3" tempfile = "3" test-log = "0" duct = "1" [profile.release] opt-level = 3 debug = false codegen-units = 1 panic = "abort" strip = true ================================================ FILE: tools/memcached_benchmark/LICENSE ================================================ MIT License Copyright (c) 2024 Ruowen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: tools/memcached_benchmark/README.md ================================================ # memcached_benchmark ================================================ FILE: tools/memcached_benchmark/bench.py ================================================ import csv import resource import subprocess CLIENT_IP = "192.168.50.253" import numpy as np from tqdm import tqdm from pathlib import Path class MemcachedCtx: def __init__(self, start, stop): self.start = start self.stop = stop def __enter__(self): subprocess.run(self.start, check=True, capture_output=True) def __exit__(self, *args): subprocess.run(self.stop, check=True, capture_output=True) def increase_fd_limit(new_limit): # Get the current soft and hard limits soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE) print(f"Current Limits - Soft: {soft_limit}, Hard: {hard_limit}") # Check if the new limit is within the permissible range if new_limit <= hard_limit: # Set the new soft limit resource.setrlimit(resource.RLIMIT_NOFILE, (new_limit, hard_limit)) soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE) print(f"File descriptor soft_limit increased to { soft_limit }") print(f"File descriptor hard_limit increased to { hard_limit }") else: print("Requested limit exceeds the hard limit. Cannot increase beyond the hard limit.") def run_bench(): # cmd = 'cargo run -r -- bench -n 200000000 -t 40 -s 10.0.1.1 -p 11211'.split() cmd = 'cargo run -r -- bench -n 100000000 -t 32 -s 10.0.1.1 -p 11211 | tee /tmp/run_bench_temp' subprocess.run(cmd, check=True, capture_output=False, text=True, shell=True) output = Path("/tmp/run_bench_temp").read_text().split("\n") output = list(filter(lambda x: "Throughput across all threads" in x, output)) assert len(output) == 1 return np.float64(output[0].split(": ")[1].split()[0]) def run_vanilla(nr_threads): start = [*f'ssh {CLIENT_IP} -t'.split(), 'sudo /root/run-memcached.sh %d' % nr_threads] stop = [*f'ssh {CLIENT_IP} -t'.split(), 'sudo /root/stop-memcached.sh %d' % nr_threads] with MemcachedCtx(start, stop): result = run_bench() return result def run_bpf(nr_threads): start = [*f'ssh {CLIENT_IP} -t'.split(), 'sudo /root/attach-bpf.sh %d' % nr_threads] stop = [*f'ssh {CLIENT_IP} -t'.split(), 'sudo /root/detach-bpf.sh %d' % nr_threads] with MemcachedCtx(start, stop): result = run_bench() return result def run_rust(nr_threads): start = [*f'ssh {CLIENT_IP} -t'.split(), 'sudo /root/attach-rust.sh %d' % nr_threads] stop = [*f'ssh {CLIENT_IP} -t'.split(), 'sudo /root/detach-rust.sh %d' % nr_threads] with MemcachedCtx(start, stop): result = run_bench() return result def main(): max_cpu = 8 rounds = 10 increase_fd_limit(202400) data = { 'vanilla': [[0 for j in range(rounds)] for i in range(max_cpu)], 'bpf': [[0 for j in range(rounds)] for i in range(max_cpu)], 'rust': [[0 for j in range(rounds)] for i in range(max_cpu)], } for i in tqdm(range(max_cpu), desc=" outer loop", position=0): for j in tqdm(range(rounds), desc=" inner loop", position=1, leave=False): data['vanilla'][i][j] = run_vanilla(i + 1) data['bpf'][i][j] = run_bpf(i + 1) data['rust'][i][j] = run_rust(i + 1) result = [('nr_cpu', *data.keys(), *list(map(lambda x: x + '-stdev', data.keys())))] for i in range(max_cpu): row = [i] for v in data.values(): row.append(np.mean(v[i])) for v in data.values(): row.append(np.std(v[i])) result.append(tuple(row)) with open('bmc-results.csv', 'w', newline='') as out_f: writer = csv.writer(out_f) writer.writerows(result) return 0 if __name__ == '__main__': exit(main()) ================================================ FILE: tools/memcached_benchmark/flake.nix ================================================ { description = "Rust development environment"; inputs = { nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; rust-overlay.url = "github:oxalica/rust-overlay"; flake-utils.url = "github:numtide/flake-utils"; }; outputs = { self, nixpkgs, rust-overlay, flake-utils, ... }: flake-utils.lib.eachDefaultSystem (system: let overlays = [ (import rust-overlay) ]; pkgs = import nixpkgs { inherit system overlays; }; # 1. Replicate languages.rust rustToolchain = pkgs.rust-bin.nightly.latest.default.override { extensions = [ "rust-src" "rustc" "clippy" "rust-analyzer" "rustfmt" ]; }; # Extract LLVM major version from the Rust toolchain via IFD rustcLlvmVersion = pkgs.runCommand "rustc-llvm-version" { nativeBuildInputs = [ rustToolchain ]; } '' rustc -vV | sed -n 's/LLVM version: \([0-9]*\).*/\1/p' | tr -d '\n' > $out ''; llvmMajor = builtins.readFile rustcLlvmVersion; llvmPackages = pkgs."llvmPackages_${llvmMajor}"; in { devShells.default = pkgs.mkShell { buildInputs = [ pkgs.git pkgs.mold llvmPackages.clangUseLLVM pkgs.memcached rustToolchain ]; shellHook = '' # enterShell logic clang --version rustc --version ''; }; } ); } ================================================ FILE: tools/memcached_benchmark/rustfmt.toml ================================================ max_width = 80 binop_separator = "Back" reorder_impl_items = true wrap_comments = true imports_granularity = "Module" group_imports = "StdExternalCrate" ================================================ FILE: tools/memcached_benchmark/src/cli.rs ================================================ use clap::{Parser, Subcommand}; use crate::Protocol; #[derive(Parser)] #[command(author, version, about, long_about = None)] pub(crate) struct Cli { #[command(subcommand)] pub(crate) command: Commands, } #[derive(Debug, Subcommand)] pub(crate) enum Commands { #[command(arg_required_else_help = true)] Bench { /// memcached server addr #[arg(short, long, required = true)] server_address: String, #[arg(short, long, default_value = "11211")] port: String, /// key size to generate random memcached key #[arg(short, long, default_value = "16")] key_size: usize, /// value size to generate random memcached value #[arg(short, long, default_value = "32")] value_size: usize, /// verify the value after get command #[arg(long, default_value = "false")] validate: bool, /// number of test entries to generate #[arg(short, long, default_value = "100000")] nums: usize, /// number of threads to run #[arg(short, long, default_value = "4")] threads: usize, /// udp or tcp protocol for memcached #[arg(short = 'l', long, default_value_t = Protocol::Udp , value_enum)] protocol: Protocol, /// number of dict entries to generate #[arg(short, long, default_value = "1000000")] dict_entries: usize, /// load the prepared test_entries from disk #[arg(long, default_value = "false")] load_bench_entries: bool, /// skip set memcached value if the data is already imported #[arg(long, default_value = "false")] skip_set: bool, /// bounded mpsc channel for communicating between asynchronous tasks /// with backpressure #[arg(long, default_value = "200")] pipeline: usize, /// connection pool size for TCP operations #[arg(long, default_value = "64")] tcp_pool_size: usize, /// connection pool size for UDP operations #[arg(long, default_value = "128")] udp_pool_size: usize, /// timeout in milliseconds for operations #[arg(long, default_value = "1000")] timeout_ms: u64, /// dict path to load #[arg( short = 'f', long, default_value = "test_dict.yml.zst", conflicts_with = "key_size", conflicts_with = "dict_entries" )] dict_path: String, }, GenTestdict { /// key size to generate random memcached key #[arg(short, long, default_value = "16")] key_size: usize, /// value size to generate random memcached value #[arg(short, long, default_value = "32")] value_size: usize, /// number of dict entries to generate #[arg(short, long, default_value = "1000000")] dict_entries: usize, /// dict path to store #[arg(short = 'f', long, default_value = "test_dict.yml.zst")] dict_path: String, }, } ================================================ FILE: tools/memcached_benchmark/src/dict.rs ================================================ use std::collections::HashMap; use std::mem::size_of_val; use std::sync::Arc; use chacha20::ChaCha8Rng; use log::{debug, info}; use rand::distr::{Alphanumeric, SampleString}; use rand::{RngExt, SeedableRng}; use rand_distr::Zipf; use rayon::prelude::*; use crate::Protocol; use crate::fs::write_hashmap_to_file; const SEED: u64 = 12312; /// Generate random string of specified length pub(crate) fn generate_random_str(len: usize) -> String { Alphanumeric.sample_string(&mut rand::rng(), len) } /// Generate test dictionary for memcached with random keys and values pub(crate) fn generate_memcached_test_dict( key_size: usize, value_size: usize, nums: usize, ) -> HashMap { // random generate dict for memcached test (0..nums) .into_par_iter() .map(|_| { ( generate_random_str(key_size), generate_random_str(value_size), ) }) .collect() } /// Generate test dict and write to disk /// # Arguments /// * `key_size` - key size /// * `value_size` - value size /// * `nums` - number of entries /// * `dict_path` - dict path to store /// # Returns /// * `Result` - Result, anyhow::Error> /// # Example /// ```rust /// let test_dict = generate_test_dict_write_to_disk(16, 32, 100000, "test_dict.yml.zst"); /// ``` pub(crate) fn generate_test_dict_write_to_disk( key_size: usize, value_size: usize, nums: usize, dict_path: &str, ) -> anyhow::Result> { let test_dict = generate_memcached_test_dict(key_size, value_size, nums); debug!("test dict len: {}", test_dict.len()); if let Some((key, value)) = test_dict.iter().next() { debug!("test dict key size: {}", size_of_val(key.as_str())); debug!("test dict value size: {}", size_of_val(value.as_str())); } else { return Err(anyhow::anyhow!("test dict is empty")); } write_hashmap_to_file(&test_dict, dict_path)?; info!("write test dict to path {}", dict_path); Ok(test_dict) } /// Generate test entries with Zipf distribution for benchmarking pub(crate) fn generate_test_entries( test_dict: Arc, Arc>>, nums: usize, ) -> Vec<(Arc, Arc, Protocol)> { let mut rng = ChaCha8Rng::seed_from_u64(SEED); let zipf = Zipf::new((test_dict.len() - 1) as f64, 0.99).unwrap(); let keys: Vec> = test_dict.keys().cloned().collect(); (0..nums) .map(|idx| { let key = &keys[rng.sample(zipf) as usize]; let value = test_dict.get(key).unwrap(); // every 31 element is tcp. udp:tcp = 30:1 let protocol = if idx % 31 == 30 { Protocol::Tcp } else { Protocol::Udp }; (key.clone(), value.clone(), protocol) }) .collect() } /// Analyze the statistics of test entries #[allow(dead_code)] pub(crate) fn test_entries_statistics( test_entries: Arc>, ) { let mut udp_count: usize = 0; let mut tcp_count: usize = 0; // analyze the key distribution base on the frequency let mut key_frequency = HashMap::new(); // only get the first element in the tuple test_entries.iter().for_each(|(key, _, proto)| { *key_frequency.entry(key.to_string()).or_insert(0) += 1; if *proto == Protocol::Udp { udp_count += 1; } else { tcp_count += 1; } }); // sort by frequency let mut key_frequency: Vec<_> = key_frequency.into_iter().collect(); key_frequency.sort_by(|a, b| a.1.cmp(&b.1)); // Display the frequency of each item for (key, count) in &key_frequency { if *count < key_frequency.len() / 1000 { continue; } info!("{}: {}", key, count); } info!("tcp count: {}, udp count: {}", tcp_count, udp_count); } ================================================ FILE: tools/memcached_benchmark/src/fs.rs ================================================ use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Write}; use std::path::Path; use anyhow::Result; use log::{debug, info}; use serde::Serialize; use crate::Protocol; /// Write hashmap to a compressed file using zstd /// # Arguments /// * `hashmap` - hashmap to write to file /// * `file_path` - file path to write /// # Returns /// * `Result` - Result<(), anyhow::Error> pub(crate) fn write_hashmap_to_file( hashmap: &T, file_path: &str, ) -> Result<()> { // Serialize the hashmap to a YAML string let serialized = serde_yaml::to_string(hashmap).expect("Failed to serialize"); // Create or open the file let file = File::create(file_path)?; // Create a zstd encoder with compression level 7 let mut encoder = zstd::stream::write::Encoder::new(file, 7)?; // Write the YAML string to the file encoder.write_all(serialized.as_bytes())?; encoder.finish()?; Ok(()) } /// Loads benchmark entries from disk from a zstd-compressed YAML file. /// /// Although the entries are typically selected randomly from a test dictionary, /// there are cases where a fixed sequence of entries is needed to ensure /// consistent performance comparisons, and this function is utilized to /// retrieve the stored benchmark entries pub(crate) fn load_bench_entries_from_disk( path: &Path, ) -> Vec<(String, String, Protocol)> { let file = std::fs::File::open(path).unwrap(); let decoder = zstd::stream::read::Decoder::new(file).unwrap(); let reader = std::io::BufReader::new(decoder); let test_entries: Vec<(String, String, Protocol)> = serde_yaml::from_reader(reader).unwrap(); test_entries } /// Load test dictionary from disk /// /// This function opens a file located at `test_dict_path`, which is expected to /// be a zstd-compressed and valid YAML document key-value pair /// (`HashMap`). pub(crate) fn load_test_dict( test_dict_path: &std::path::Path, ) -> anyhow::Result> { // load dict from file if dict_path is not empty info!("loading dict from path {:?}", test_dict_path); let file = std::fs::File::open(test_dict_path)?; let decoder = zstd::stream::read::Decoder::new(file)?; let reader = BufReader::new(decoder); // Deserialize the string into a HashMap let mut test_dict = HashMap::new(); reader.lines().for_each(|line| { let line = line.unwrap(); // Assuming each line in your file is a valid YAML representing a // key-value pair let deserialized_map: HashMap = serde_yaml::from_str(&line).unwrap(); test_dict.extend(deserialized_map); }); debug!("test dict len: {}", test_dict.len()); if let Some(key) = test_dict.keys().next() { debug!("test dict key size: {}", key.len()); } if let Some(value) = test_dict.values().next() { debug!("test dict value size: {}", value.len()); } Ok(test_dict) } ================================================ FILE: tools/memcached_benchmark/src/get_values.rs ================================================ use std::collections::HashMap; use std::sync::Arc; use std::sync::atomic::*; use anyhow::Result; use clap::ValueEnum; use log::{info, trace}; use memcache_async::ascii::Protocol as MemcacheProtocol; use serde::{Deserialize, Serialize}; use tokio::net::{TcpStream, UdpSocket}; use tokio::sync::mpsc; use tokio::time::timeout; use tokio_util::compat::TokioAsyncReadCompatExt; use tokio_util::task::TaskTracker; use crate::{BUFFER_SIZE, TIMEOUT_COUNTER}; #[derive( ValueEnum, Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize, )] pub(crate) enum Protocol { Udp, Tcp, } struct TaskData { seq: u16, addr: Arc, key: Arc, test_dict: Arc, Arc>>, validate: bool, key_size: usize, value_size: usize, counter: usize, } fn wrap_get_command(key: Arc, seq: u16) -> Vec { let mut bytes: Vec = vec![0, 0, 0, 1, 0, 0]; let mut command = format!("get {}\r\n", key).into_bytes(); let mut seq_bytes = seq.to_be_bytes().to_vec(); seq_bytes.append(&mut bytes); seq_bytes.append(&mut command); trace!("bytes: {:?}", seq_bytes); seq_bytes } async fn socket_task( sockets_pool: Arc>, mut rx: mpsc::Receiver, tracker: TaskTracker, ) { let mut cnt = 0u64; while let Some(TaskData { seq, addr, key, test_dict, validate, key_size, value_size, counter, }) = rx.recv().await { let socket_pool_clone = Arc::clone(&sockets_pool); cnt += 1; tracker.spawn(async move { let send_timeout = tokio::time::Duration::from_millis(500); // Send let socket: &UdpSocket = &socket_pool_clone[counter & 0x1F]; let packet = wrap_get_command(key.clone(), seq); // Add timeout action if (timeout( send_timeout, socket.send_to(&packet[..], addr.as_str()), ) .await) .is_err() { TIMEOUT_COUNTER.fetch_add(1, Ordering::Relaxed); return; }; // Then receive let mut buf = [0; BUFFER_SIZE]; let my_duration = tokio::time::Duration::from_millis(500); if let Ok(Ok((amt, _))) = timeout(my_duration, socket.recv_from(&mut buf)).await { if !validate { return; } if let Some(value) = test_dict.get(&*key) { let received = String::from_utf8_lossy(&buf[..amt]) .split("VALUE ") .nth(1) .unwrap_or_default() [6 + key_size + 1..6 + key_size + value_size + 1] .to_string(); if received != *value.to_string() { info!( "response not match key {} buf: {} , value: {}", key, received, value ); } } } else { // Timeout occurred - increment the counter TIMEOUT_COUNTER.fetch_add(1, Ordering::Relaxed); } }); } info!("processed tasks: {}", cnt); } pub(crate) async fn get_command_benchmark( test_dict: Arc, Arc>>, send_commands: Vec<(Arc, u16, Protocol, Arc)>, server_address: String, port: String, validate: bool, key_size: usize, value_size: usize, pipeline: usize, ) -> Result<()> { // assign client address let addr = Arc::new(format!("{}:{}", server_address, port)); let mut sockets_pool = vec![]; for _ in 0..32 { let socket = UdpSocket::bind("0.0.0.0:0") .await .expect("couldn't bind to address"); sockets_pool.push(socket); } let sockets_pool = Arc::new(sockets_pool); let tcp_addr = format!("{}:{}", server_address, port); let stream = TcpStream::connect(&tcp_addr) .await .expect("TCP memcached connection failed"); let mut client = MemcacheProtocol::new(stream.compat()); let tracker = TaskTracker::new(); let cloned_tracker = tracker.clone(); let start = std::time::Instant::now(); // Create the channel let (tx, rx) = mpsc::channel(pipeline); tracker.spawn(socket_task(sockets_pool, rx, cloned_tracker)); let mut counter = 0usize; let mut handles = vec![]; for (key, seq, proto, value) in send_commands { // if tcp, use set request if proto == Protocol::Tcp { client .set(&*key, value.as_bytes(), 0) .await .expect("memcached set command failed"); continue; } counter = counter.wrapping_add(1); let send_result = tx.send(TaskData { seq, addr: addr.clone(), key, test_dict: test_dict.clone(), validate, key_size, value_size, counter, }); handles.push(send_result); } for handle in handles { handle.await?; } // Close the channel drop(tx); // Wait for the socket task to finish tracker.close(); tracker.wait().await; let duration = start.elapsed(); info!("Time elapsed in get_command_benchmark() is: {:?}", duration); Ok(()) } ================================================ FILE: tools/memcached_benchmark/src/main.rs ================================================ #![allow(clippy::too_many_arguments)] mod cli; mod dict; mod fs; mod get_values; mod set_values; use std::collections::HashMap; use std::sync::atomic::*; use std::sync::{Arc, OnceLock}; use std::vec; // Global configuration initialized from CLI args #[derive(Debug, Clone, Copy)] pub struct BenchConfig { pub tcp_pool_size: usize, pub udp_pool_size: usize, pub timeout_ms: u64, } pub static CONFIG: OnceLock = OnceLock::new(); impl BenchConfig { pub fn get() -> &'static BenchConfig { CONFIG.get().expect("BenchConfig not initialized") } } use anyhow::{Result, anyhow}; use clap::Parser; use cli::{Cli, Commands}; use dict::{generate_test_dict_write_to_disk, generate_test_entries}; use env_logger::Target; use fs::{load_bench_entries_from_disk, load_test_dict, write_hashmap_to_file}; use get_values::{Protocol, get_command_benchmark}; use log::{LevelFilter, info}; use memcache::MemcacheError; use mimalloc::MiMalloc; use serde_json::json; use set_values::set_memcached_value; use tokio::runtime::Builder; #[global_allocator] static GLOBAL: MiMalloc = MiMalloc; const BUFFER_SIZE: usize = 1500; const BENCH_ENTRIES_PATH: &str = "bench_entries.yml.zst"; static TIMEOUT_COUNTER: AtomicUsize = AtomicUsize::new(0); fn get_server( addr: &String, port: &String, protocol: &Protocol, ) -> Result { match protocol { Protocol::Udp => memcache::connect(format!( "memcache+udp://{}:{}?timeout=10", addr, port )), Protocol::Tcp => memcache::connect(format!( "memcache://{}:{}?timeout=10", addr, port )), } } fn run_bench() -> Result<()> { let args = Cli::parse(); let Commands::Bench { server_address, port, key_size, value_size, validate, nums, threads, protocol, dict_path, load_bench_entries, dict_entries, skip_set, pipeline, tcp_pool_size, udp_pool_size, timeout_ms, } = args.command else { return Err(anyhow!("invalid command")); }; // Initialize global configuration let _ = CONFIG.set(BenchConfig { tcp_pool_size, udp_pool_size, timeout_ms, }); let server = get_server(&server_address, &port, &protocol)?; let test_dict_path = std::path::Path::new(dict_path.as_str()); let test_dict: HashMap = if !test_dict_path.exists() { // if dict_path is empty, generate dict generate_test_dict_write_to_disk( key_size, value_size, dict_entries, dict_path.as_str(), )? } else { load_test_dict(test_dict_path)? }; let test_dict: Arc, Arc>> = Arc::new( test_dict .into_iter() .map(|(k, v)| (Arc::new(k), Arc::new(v))) .collect(), ); // if memcached server is already imported, skip set memcached value if !skip_set { let rt = Builder::new_multi_thread() .enable_all() .thread_name("memcached-set") .event_interval(31) .build()?; let test_dict = test_dict.clone(); let server_address = server_address.clone(); let port = port.clone(); rt.block_on(async move { set_memcached_value(test_dict, server_address, port) .await .unwrap() }); } let test_dict_path = std::path::Path::new(BENCH_ENTRIES_PATH); let test_entries_tmp = if load_bench_entries && test_dict_path.exists() { load_bench_entries_from_disk(test_dict_path) } else { vec![] }; info!("Start to generate get commands for each thread"); let benchmark_entries = if test_entries_tmp.is_empty() { let test_entries = generate_test_entries(test_dict.clone(), nums); if load_bench_entries { let test_entries_write: Vec<(String, String, Protocol)> = test_entries .clone() .into_iter() // Iterate over the original vector .map(|(a, b, c)| { ( Arc::try_unwrap(a).unwrap_or_else(|a| (*a).clone()), Arc::try_unwrap(b).unwrap_or_else(|b| (*b).clone()), c, ) }) .collect(); write_hashmap_to_file(&test_entries_write, BENCH_ENTRIES_PATH)?; } test_entries } else { // convert to Vec<(Arc, Arc, Protocol)> test_entries_tmp .iter() .map(|(key, value, proto)| { (Arc::new(key.clone()), Arc::new(value.clone()), *proto) }) .collect() }; let benchmark_entries = Arc::new(benchmark_entries); // analyze test entries statistics // _test_entries_statistics(test_entries.clone()); let mut send_commands_vec = Vec::new(); for thread_num in 0..threads { let mut seq: u16 = 0; let mut send_commands = vec![]; for index in 0..nums / threads { let (key, value, proto) = &benchmark_entries[thread_num * nums / threads + index]; // let packet = wrap_get_command(key.clone(), seq); seq = seq.wrapping_add(1); send_commands.push((key.clone(), seq, *proto, value.clone())); } send_commands_vec.push(send_commands); } let start_time = std::time::SystemTime::now(); // let rt = Builder::new_multi_thread().enable_all().build()?; let mut handles = vec![]; info!("Start benchmark"); for tid in 0..threads { let test_dict = test_dict.clone(); let server_address = server_address.clone(); let port = port.clone(); let send_commands = send_commands_vec.pop().unwrap(); let handle = std::thread::Builder::new() .name(format!("bmc-worker-{tid}")) .spawn(move || { let rt = Builder::new_current_thread().enable_all().build().unwrap(); rt.block_on(async move { get_command_benchmark( test_dict, send_commands, server_address, port, validate, key_size, value_size, pipeline, ) .await .unwrap(); info!("Finish gen_command_bench {}", tid); }) }) .unwrap(); handles.push(handle); } for handle in handles { handle.join().unwrap(); } // wait for all tasks to complete info!("wait for all tasks to complete"); let elapsed_time = start_time.elapsed()?.as_secs_f64(); info!("Timeout counter {}", TIMEOUT_COUNTER.load(Ordering::SeqCst)); let throughput = (nums - TIMEOUT_COUNTER.load(Ordering::SeqCst)) as f64 / elapsed_time; info!( "Throughput across all threads: {:.2} reqs/sec, elapsed_time {}", throughput, elapsed_time ); macro_rules! build_stats_map { ($result:expr, $($key:expr),*) => {{ let mut map = ::std::collections::HashMap::new(); $( map.insert($key, &$result[$key]); )* map }}; } // stats let stats = server.stats()?; let result = &stats[0].1; let output = build_stats_map!( result, "cmd_get", "cmd_set", "get_hits", "get_misses", "bytes_read", "bytes_written", "curr_items", "total_items" ); let obj = json!(output); info!("{}", serde_json::to_string_pretty(&obj).unwrap()); Ok(()) } fn main() -> Result<()> { let args = Cli::parse(); env_logger::Builder::new() .target(Target::Stdout) .filter_level(LevelFilter::Info) .init(); match args.command { Commands::Bench { .. } => { run_bench()?; } Commands::GenTestdict { key_size, value_size, dict_entries, dict_path, } => { let _ = generate_test_dict_write_to_disk( key_size, value_size, dict_entries, dict_path.as_str(), )?; } } Ok(()) } ================================================ FILE: tools/memcached_benchmark/src/set_values.rs ================================================ use std::collections::HashMap; use std::sync::Arc; use anyhow::Result; use log::info; use memcache_async::ascii::Protocol; use tokio::net::TcpStream; use tokio::sync::Semaphore; use tokio::task::JoinSet; use tokio_util::compat::TokioAsyncReadCompatExt; pub(super) async fn set_memcached_value( test_dict: Arc, Arc>>, server_address: String, port: String, ) -> Result<()> { info!("Start set memcached value"); let addr = format!("{}:{}", server_address, port); let mut sockets_pool = vec![]; let concurrency_limit = 64; for _ in 0..concurrency_limit { let stream = TcpStream::connect(&addr) .await .expect("TCP memcached connection failed"); let client = Protocol::new(stream.compat()); sockets_pool.push(tokio::sync::Mutex::new(client)); } let sockets_pool = Arc::new(sockets_pool); let mut set = JoinSet::new(); let sem = Arc::new(Semaphore::new(concurrency_limit)); for (count, (key, value)) in test_dict.iter().enumerate() { let sockets_pool_clone = sockets_pool.clone(); let key_clone = key.clone(); let value_clone = value.clone(); let sem = sem.clone(); set.spawn(async move { let _permit = sem.acquire_owned().await; let mut socket = sockets_pool_clone[count & 0x3F].lock().await; socket .set(&*key_clone, value_clone.as_bytes(), 0) .await .expect("memcached set command failed"); let get_value = socket .get(&*key_clone) .await .expect("memcached get command failed"); assert_eq!(get_value, value_clone.as_bytes()); }); } while set.join_next().await.is_some() {} info!("Done set memcached value"); Ok(()) } ================================================ FILE: tools/memcached_benchmark/tests/benchmark_test.rs ================================================ use std::thread; use std::time::Duration; use anyhow::{Ok, Result}; use assert_cmd::assert::OutputAssertExt; use assert_cmd::cargo::cargo_bin_cmd; use duct::{Handle, cmd}; use log::{debug, info}; use tempfile::TempDir; use test_log::test; struct ProcessGuard { handle: Handle, } impl Drop for ProcessGuard { fn drop(&mut self) { let _ = self.handle.kill(); info!("Killed memcached process"); } } #[test] fn test_memcached_benchmark() -> Result<()> { let memcached_port = "11211"; let memcached_handle = cmd!("memcached", "-U", memcached_port, "-v").start()?; // Wrap in our guard for automatic cleanup let _process_guard = ProcessGuard { handle: memcached_handle, }; info!("Started memcached server on port {}", memcached_port); thread::sleep(Duration::from_secs(2)); let temp_dir = TempDir::new()?; let dict_path = temp_dir.path().join("test_dict.yml.zst"); debug!("temp dir path {}", dict_path.display()); let bin_path = std::env::current_exe().expect("Failed to get current exe path"); debug!("binpath {:?}", bin_path); let gen_dict = cargo_bin_cmd!(env!("CARGO_PKG_NAME")) .args([ "gen-testdict", "--key-size", "16", "--value-size", "32", "--dict-entries", "10000", ]) .unwrap(); gen_dict.assert().success(); info!("Generated test dictionary at: {}", dict_path.display()); let output = cargo_bin_cmd!(env!("CARGO_PKG_NAME")) .args([ "bench", "--server-address", "localhost", "--port", memcached_port, "--key-size", "16", "--value-size", "32", "--nums", "50000", "--threads", "2", "--protocol", "udp", "--dict-entries", "10000", "--pipeline", "100", ]) .output()?; output.clone().assert().success(); let stdout = String::from_utf8(output.stdout)?; let stderr = String::from_utf8(output.stderr)?; debug!("Benchmark stdout: {}", stdout); debug!("Benchmark stderr: {}", stderr); assert!(stdout.contains("Start set memcached value")); assert!(stdout.contains("Throughput across all threads:")); assert!(stdout.contains("Done set memcached value")); Ok(()) }