1. Oct 21, 2023
  2. Oct 20, 2023
    • Alexei Starovoitov's avatar
      Merge branch 'add-open-coded-task-css_task-and-css-iters' · bab8ac3c
      Alexei Starovoitov authored
      Chuyi Zhou says:
      
      ====================
      Add Open-coded task, css_task and css iters
      
      This is version 6 of task, css_task and css iters support.
      
      --- Changelog ---
      
      v5 -> v6:
      
      Patch #3:
       * In bpf_iter_task_next, return pos rather than goto out. (Andrii)
      Patch #2, #3, #4:
       * Add the missing __diag_ignore_all to avoid kernel build warning
      Patch #5, #6, #7:
       * Add Andrii's ack
      
      Patch #8:
       * In BPF prog iter_css_task_for_each, return -EPERM rather than 0, and
         ensure stack_mprotect() in iters.c not success. If not, it would cause
         the subsequent 'test_lsm' fail, since the 'is_stack' check in
         test_int_hook(lsm.c) would not be guaranteed.
         (https://github.com/kernel-patches/bpf/actions/runs/6489662214/job/17624665086?pr=5790)
      
      v4 -> v5:https://lore.kernel.org/lkml/20231007124522.34834-1-zhouchuyi@bytedance.com/
      
      Patch 3~4:
       * Relax the BUILD_BUG_ON check in bpf_iter_task_new and bpf_iter_css_new to avoid
         netdev/build_32bit CI error.
         (https://netdev.bots.linux.dev/static/nipa/790929/13412333/build_32bit/stderr)
      Patch 8:
       * Initialize skel pointer to fix the LLVM-16 build CI error
         (https://github.com/kernel-patches/bpf/actions/runs/6462875618/job/17545170863)
      
      v3 -> v4:https://lore.kernel.org/all/20230925105552.817513-1-zhouchuyi@bytedance.com/
      
      * Address all the comments from Andrii in patch-3 ~ patch-6
      * Collect Tejun's ack
      * Add a extra patch to rename bpf_iter_task.c to bpf_iter_tasks.c
      * Seperate three BPF program files for selftests (iters_task.c iters_css_task.c iters_css.c)
      
      v2 -> v3:https://lore.kernel.org/lkml/20230912070149.969939-1-zhouchuyi@bytedance.com/
      
      Patch 1 (cgroup: Prepare for using css_task_iter_*() in BPF)
        * Add tj's ack and Alexei's suggest-by.
      Patch 2 (bpf: Introduce css_task open-coded iterator kfuncs)
        * Use bpf_mem_alloc/bpf_mem_free rather than kzalloc()
        * Add KF_TRUSTED_ARGS for bpf_iter_css_task_new (Alexei)
        * Move bpf_iter_css_task's definition from uapi/linux/bpf.h to
          kernel/bpf/task_iter.c and we can use it from vmlinux.h
        * Move bpf_iter_css_task_XXX's declaration from bpf_helpers.h to
          bpf_experimental.h
      Patch 3 (Introduce task open coded iterator kfuncs)
        * Change th API design keep consistent with SEC("iter/task"), support
          iterating all threads(BPF_TASK_ITERATE_ALL) and threads of a
          specific task (BPF_TASK_ITERATE_THREAD).(Andrii)
        * Move bpf_iter_task's definition from uapi/linux/bpf.h to
          kernel/bpf/task_iter.c and we can use it from vmlinux.h
        * Move bpf_iter_task_XXX's declaration from bpf_helpers.h to
          bpf_experimental.h
      Patch 4 (Introduce css open-coded iterator kfuncs)
        * Change th API design keep consistent with cgroup_iters, reuse
          BPF_CGROUP_ITER_DESCENDANTS_PRE/BPF_CGROUP_ITER_DESCENDANTS_POST
          /BPF_CGROUP_ITER_ANCESTORS_UP(Andrii)
        * Add KF_TRUSTED_ARGS for bpf_iter_css_new
        * Move bpf_iter_css's definition from uapi/linux/bpf.h to
          kernel/bpf/task_iter.c and we can use it from vmlinux.h
        * Move bpf_iter_css_XXX's declaration from bpf_helpers.h to
          bpf_experimental.h
      Patch 5 (teach the verifier to enforce css_iter and task_iter in RCU CS)
        * Add KF flag KF_RCU_PROTECTED to maintain kfuncs which need RCU CS.(Andrii)
        * Consider STACK_ITER when using bpf_for_each_spilled_reg.
      Patch 6 (Let bpf_iter_task_new accept null task ptr)
        * Add this extra patch to let bpf_iter_task_new accept a 'nullable'
        * task pointer(Andrii)
      Patch 7 (selftests/bpf: Add tests for open-coded task and css iter)
        * Add failure testcase(Alexei)
      
      Changes from v1(https://lore.kernel.org/lkml/20230827072057.1591929-1-zhouchuyi@bytedance.com/):
      - Add a pre-patch to make some preparations before supporting css_task
        iters.(Alexei)
      - Add an allowlist for css_task iters(Alexei)
      - Let bpf progs do explicit bpf_rcu_read_lock() when using process
        iters and css_descendant iters.(Alexei)
      ---------------------
      
      In some BPF usage scenarios, it will be useful to iterate the process and
      css directly in the BPF program. One of the expected scenarios is
      customizable OOM victim selection via BPF[1].
      
      Inspired by Dave's task_vma iter[2], this patchset adds three types of
      open-coded iterator kfuncs:
      
      1. bpf_task_iters. It can be used to
      1) iterate all process in the system, like for_each_forcess() in kernel.
      2) iterate all threads in the system.
      3) iterate all threads of a specific task
      
      2. bpf_css_iters. It works like css_task_iter_{start, next, end} and would
      be used to iterating tasks/threads under a css.
      
      3. css_iters. It works like css_next_descendant_{pre, post} to iterating all
      descendant css.
      
      BPF programs can use these kfuncs directly or through bpf_for_each macro.
      
      link[1]: https://lore.kernel.org/lkml/20230810081319.65668-1-zhouchuyi@bytedance.com/
      link[2]: https://lore.kernel.org/all/20230810183513.684836-1-davemarchevsky@fb.com/
      ====================
      
      Link: https://lore.kernel.org/r/20231018061746.111364-1-zhouchuyi@bytedance.com
      
      
      Signed-off-by: default avatarAlexei Starovoitov <ast@kernel.org>
      bab8ac3c
    • Chuyi Zhou's avatar
      selftests/bpf: Add tests for open-coded task and css iter · 130e0f7a
      Chuyi Zhou authored
      
      
      This patch adds 4 subtests to demonstrate these patterns and validating
      correctness.
      
      subtest1:
      
      1) We use task_iter to iterate all process in the system and search for the
      current process with a given pid.
      
      2) We create some threads in current process context, and use
      BPF_TASK_ITER_PROC_THREADS to iterate all threads of current process. As
      expected, we would find all the threads of current process.
      
      3) We create some threads and use BPF_TASK_ITER_ALL_THREADS to iterate all
      threads in the system. As expected, we would find all the threads which was
      created.
      
      subtest2:
      
      We create a cgroup and add the current task to the cgroup. In the
      BPF program, we would use bpf_for_each(css_task, task, css) to iterate all
      tasks under the cgroup. As expected, we would find the current process.
      
      subtest3:
      
      1) We create a cgroup tree. In the BPF program, we use
      bpf_for_each(css, pos, root, XXX) to iterate all descendant under the root
      with pre and post order. As expected, we would find all descendant and the
      last iterating cgroup in post-order is root cgroup, the first iterating
      cgroup in pre-order is root cgroup.
      
      2) We wse BPF_CGROUP_ITER_ANCESTORS_UP to traverse the cgroup tree starting
      from leaf and root separately, and record the height. The diff of the
      hights would be the total tree-high - 1.
      
      subtest4:
      
      Add some failure testcase when using css_task, task and css iters, e.g,
      unlock when using task-iters to iterate tasks.
      
      Signed-off-by: default avatarChuyi Zhou <zhouchuyi@bytedance.com>
      Link: https://lore.kernel.org/r/20231018061746.111364-9-zhouchuyi@bytedance.com
      
      
      Signed-off-by: default avatarAlexei Starovoitov <ast@kernel.org>
      130e0f7a
    • Chuyi Zhou's avatar
      selftests/bpf: rename bpf_iter_task.c to bpf_iter_tasks.c · ddab78cb
      Chuyi Zhou authored
      
      
      The newly-added struct bpf_iter_task has a name collision with a selftest
      for the seq_file task iter's bpf skel, so the selftests/bpf/progs file is
      renamed in order to avoid the collision.
      
      Signed-off-by: default avatarChuyi Zhou <zhouchuyi@bytedance.com>
      Acked-by: default avatarAndrii Nakryiko <andrii@kernel.org>
      Link: https://lore.kernel.org/r/20231018061746.111364-8-zhouchuyi@bytedance.com
      
      
      Signed-off-by: default avatarAlexei Starovoitov <ast@kernel.org>
      ddab78cb
    • Chuyi Zhou's avatar
      bpf: Let bpf_iter_task_new accept null task ptr · cb3ecf79
      Chuyi Zhou authored
      
      
      When using task_iter to iterate all threads of a specific task, we enforce
      that the user must pass a valid task pointer to ensure safety. However,
      when iterating all threads/process in the system, BPF verifier still
      require a valid ptr instead of "nullable" pointer, even though it's
      pointless, which is a kind of surprising from usability standpoint. It
      would be nice if we could let that kfunc accept a explicit null pointer
      when we are using BPF_TASK_ITER_ALL_{PROCS, THREADS} and a valid pointer
      when using BPF_TASK_ITER_THREAD.
      
      Given a trival kfunc:
      	__bpf_kfunc void FN(struct TYPE_A *obj);
      
      BPF Prog would reject a nullptr for obj. The error info is:
      "arg#x pointer type xx xx must point to scalar, or struct with scalar"
      reported by get_kfunc_ptr_arg_type(). The reg->type is SCALAR_VALUE and
      the btf type of ref_t is not scalar or scalar_struct which leads to the
      rejection of get_kfunc_ptr_arg_type.
      
      This patch add "__nullable" annotation:
      	__bpf_kfunc void FN(struct TYPE_A *obj__nullable);
      Here __nullable indicates obj can be optional, user can pass a explicit
      nullptr or a normal TYPE_A pointer. In get_kfunc_ptr_arg_type(), we will
      detect whether the current arg is optional and register is null, If so,
      return a new kfunc_ptr_arg_type KF_ARG_PTR_TO_NULL and skip to the next
      arg in check_kfunc_args().
      
      Signed-off-by: default avatarChuyi Zhou <zhouchuyi@bytedance.com>
      Acked-by: default avatarAndrii Nakryiko <andrii@kernel.org>
      Link: https://lore.kernel.org/r/20231018061746.111364-7-zhouchuyi@bytedance.com
      
      
      Signed-off-by: default avatarAlexei Starovoitov <ast@kernel.org>
      cb3ecf79
    • Chuyi Zhou's avatar
      bpf: teach the verifier to enforce css_iter and task_iter in RCU CS · dfab99df
      Chuyi Zhou authored
      
      
      css_iter and task_iter should be used in rcu section. Specifically, in
      sleepable progs explicit bpf_rcu_read_lock() is needed before use these
      iters. In normal bpf progs that have implicit rcu_read_lock(), it's OK to
      use them directly.
      
      This patch adds a new a KF flag KF_RCU_PROTECTED for bpf_iter_task_new and
      bpf_iter_css_new. It means the kfunc should be used in RCU CS. We check
      whether we are in rcu cs before we want to invoke this kfunc. If the rcu
      protection is guaranteed, we would let st->type = PTR_TO_STACK | MEM_RCU.
      Once user do rcu_unlock during the iteration, state MEM_RCU of regs would
      be cleared. is_iter_reg_valid_init() will reject if reg->type is UNTRUSTED.
      
      It is worth noting that currently, bpf_rcu_read_unlock does not
      clear the state of the STACK_ITER reg, since bpf_for_each_spilled_reg
      only considers STACK_SPILL. This patch also let bpf_for_each_spilled_reg
      search STACK_ITER.
      
      Signed-off-by: default avatarChuyi Zhou <zhouchuyi@bytedance.com>
      Acked-by: default avatarAndrii Nakryiko <andrii@kernel.org>
      Link: https://lore.kernel.org/r/20231018061746.111364-6-zhouchuyi@bytedance.com
      
      
      Signed-off-by: default avatarAlexei Starovoitov <ast@kernel.org>
      dfab99df
    • Chuyi Zhou's avatar
      bpf: Introduce css open-coded iterator kfuncs · 7251d090
      Chuyi Zhou authored
      
      
      This Patch adds kfuncs bpf_iter_css_{new,next,destroy} which allow
      creation and manipulation of struct bpf_iter_css in open-coded iterator
      style. These kfuncs actually wrapps css_next_descendant_{pre, post}.
      css_iter can be used to:
      
      1) iterating a sepcific cgroup tree with pre/post/up order
      
      2) iterating cgroup_subsystem in BPF Prog, like
      for_each_mem_cgroup_tree/cpuset_for_each_descendant_pre in kernel.
      
      The API design is consistent with cgroup_iter. bpf_iter_css_new accepts
      parameters defining iteration order and starting css. Here we also reuse
      BPF_CGROUP_ITER_DESCENDANTS_PRE, BPF_CGROUP_ITER_DESCENDANTS_POST,
      BPF_CGROUP_ITER_ANCESTORS_UP enums.
      
      Signed-off-by: default avatarChuyi Zhou <zhouchuyi@bytedance.com>
      Acked-by: default avatarTejun Heo <tj@kernel.org>
      Link: https://lore.kernel.org/r/20231018061746.111364-5-zhouchuyi@bytedance.com
      
      
      Signed-off-by: default avatarAlexei Starovoitov <ast@kernel.org>
      7251d090
    • Chuyi Zhou's avatar
      bpf: Introduce task open coded iterator kfuncs · c68a78ff
      Chuyi Zhou authored
      
      
      This patch adds kfuncs bpf_iter_task_{new,next,destroy} which allow
      creation and manipulation of struct bpf_iter_task in open-coded iterator
      style. BPF programs can use these kfuncs or through bpf_for_each macro to
      iterate all processes in the system.
      
      The API design keep consistent with SEC("iter/task"). bpf_iter_task_new()
      accepts a specific task and iterating type which allows:
      
      1. iterating all process in the system (BPF_TASK_ITER_ALL_PROCS)
      
      2. iterating all threads in the system (BPF_TASK_ITER_ALL_THREADS)
      
      3. iterating all threads of a specific task (BPF_TASK_ITER_PROC_THREADS)
      
      Signed-off-by: default avatarChuyi Zhou <zhouchuyi@bytedance.com>
      Link: https://lore.kernel.org/r/20231018061746.111364-4-zhouchuyi@bytedance.com
      
      
      Signed-off-by: default avatarAlexei Starovoitov <ast@kernel.org>
      c68a78ff
    • Chuyi Zhou's avatar
      bpf: Introduce css_task open-coded iterator kfuncs · 9c66dc94
      Chuyi Zhou authored
      
      
      This patch adds kfuncs bpf_iter_css_task_{new,next,destroy} which allow
      creation and manipulation of struct bpf_iter_css_task in open-coded
      iterator style. These kfuncs actually wrapps css_task_iter_{start,next,
      end}. BPF programs can use these kfuncs through bpf_for_each macro for
      iteration of all tasks under a css.
      
      css_task_iter_*() would try to get the global spin-lock *css_set_lock*, so
      the bpf side has to be careful in where it allows to use this iter.
      Currently we only allow it in bpf_lsm and bpf iter-s.
      
      Signed-off-by: default avatarChuyi Zhou <zhouchuyi@bytedance.com>
      Acked-by: default avatarTejun Heo <tj@kernel.org>
      Link: https://lore.kernel.org/r/20231018061746.111364-3-zhouchuyi@bytedance.com
      
      
      Signed-off-by: default avatarAlexei Starovoitov <ast@kernel.org>
      9c66dc94
    • Chuyi Zhou's avatar
      cgroup: Prepare for using css_task_iter_*() in BPF · 6da88306
      Chuyi Zhou authored
      
      
      This patch makes some preparations for using css_task_iter_*() in BPF
      Program.
      
      1. Flags CSS_TASK_ITER_* are #define-s and it's not easy for bpf prog to
      use them. Convert them to enum so bpf prog can take them from vmlinux.h.
      
      2. In the next patch we will add css_task_iter_*() in common kfuncs which
      is not safe. Since css_task_iter_*() does spin_unlock_irq() which might
      screw up irq flags depending on the context where bpf prog is running.
      So we should use irqsave/irqrestore here and the switching is harmless.
      
      Suggested-by: default avatarAlexei Starovoitov <ast@kernel.org>
      Signed-off-by: default avatarChuyi Zhou <zhouchuyi@bytedance.com>
      Acked-by: default avatarTejun Heo <tj@kernel.org>
      Link: https://lore.kernel.org/r/20231018061746.111364-2-zhouchuyi@bytedance.com
      
      
      Signed-off-by: default avatarAlexei Starovoitov <ast@kernel.org>
      6da88306
  3. Oct 19, 2023
  4. Oct 18, 2023
    • Larysa Zaremba's avatar
      selftests/bpf: Add options and frags to xdp_hw_metadata · bb6a8888
      Larysa Zaremba authored
      This is a follow-up to the commit 9b2b8633 ("bpf: Allow to use kfunc
      XDP hints and frags together").
      
      The are some possible implementations problems that may arise when providing
      metadata specifically for multi-buffer packets, therefore there must be a
      possibility to test such option separately.
      
      Add an option to use multi-buffer AF_XDP xdp_hw_metadata and mark used XDP
      program as capable to use frags.
      
      As for now, xdp_hw_metadata accepts no options, so add simple option
      parsing logic and a help message.
      
      For quick reference, also add an ingress packet generation command to the
      help message. The command comes from [0].
      
      Example of output for multi-buffer packet:
      
        xsk_ring_cons__peek: 1
        0xead018: rx_desc[15]->addr=10000000000f000 addr=f100 comp_addr=f000
        rx_hash: 0x5789FCBB with RSS type:0x29
        rx_timestamp:  1696856851535324697 (sec:1696856851.5353)
        XDP RX-time:   1696856843158256391 (sec:1696856843.1583)
        	delta sec:-8.3771 (-8377068.306 usec)
        AF_XDP time:   1696856843158413078 (sec:1696856843.1584)
        	delta sec:0.0002 (156.687 usec)
        0xead018: complete idx=23 addr=f000
        xsk_ring_cons__peek: 1
        0xead018: rx_desc[16]->addr=100000000008000 addr=8100 comp_addr=8000
        0xead018: complete idx=24 addr=8000
        xsk_ring_cons__peek: 1
        0xead018: rx_desc[17]->addr=100000000009000 addr=9100 comp_addr=9000 EoP
        0xead018: complete idx=25 addr=9000
      
      Metadata is printed for the first packet only.
      
        [0] https://lore.kernel.org/all/20230119221536.3349901-18-sdf@google.com/
      
      
      
      Signed-off-by: default avatarLarysa Zaremba <larysa.zaremba@intel.com>
      Signed-off-by: default avatarDaniel Borkmann <daniel@iogearbox.net>
      Acked-by: default avatarStanislav Fomichev <sdf@google.com>
      Link: https://lore.kernel.org/bpf/20231017162800.24080-1-larysa.zaremba@intel.com
      bb6a8888
    • Daniel Borkmann's avatar
      selftests/bpf: Add additional mprog query test coverage · 24516309
      Daniel Borkmann authored
      
      
      Add several new test cases which assert corner cases on the mprog query
      mechanism, for example, around passing in a too small or a larger array
      than the current count.
      
        ./test_progs -t tc_opts
        #252     tc_opts_after:OK
        #253     tc_opts_append:OK
        #254     tc_opts_basic:OK
        #255     tc_opts_before:OK
        #256     tc_opts_chain_classic:OK
        #257     tc_opts_chain_mixed:OK
        #258     tc_opts_delete_empty:OK
        #259     tc_opts_demixed:OK
        #260     tc_opts_detach:OK
        #261     tc_opts_detach_after:OK
        #262     tc_opts_detach_before:OK
        #263     tc_opts_dev_cleanup:OK
        #264     tc_opts_invalid:OK
        #265     tc_opts_max:OK
        #266     tc_opts_mixed:OK
        #267     tc_opts_prepend:OK
        #268     tc_opts_query:OK
        #269     tc_opts_query_attach:OK
        #270     tc_opts_replace:OK
        #271     tc_opts_revision:OK
        Summary: 20/0 PASSED, 0 SKIPPED, 0 FAILED
      
      Signed-off-by: default avatarDaniel Borkmann <daniel@iogearbox.net>
      Signed-off-by: default avatarAndrii Nakryiko <andrii@kernel.org>
      Reviewed-by: default avatarAlan Maguire <alan.maguire@oracle.com>
      Link: https://lore.kernel.org/bpf/20231017081728.24769-1-daniel@iogearbox.net
      24516309
    • Yafang Shao's avatar
      selftests/bpf: Add selftest for bpf_task_under_cgroup() in sleepable prog · 44cb03f1
      Yafang Shao authored
      
      
      The result is as follows:
      
        $ tools/testing/selftests/bpf/test_progs --name=task_under_cgroup
        #237     task_under_cgroup:OK
        Summary: 1/0 PASSED, 0 SKIPPED, 0 FAILED
      
      Without the previous patch, there will be RCU warnings in dmesg when
      CONFIG_PROVE_RCU is enabled. While with the previous patch, there will
      be no warnings.
      
      Signed-off-by: default avatarYafang Shao <laoar.shao@gmail.com>
      Signed-off-by: default avatarDaniel Borkmann <daniel@iogearbox.net>
      Acked-by: default avatarStanislav Fomichev <sdf@google.com>
      Link: https://lore.kernel.org/bpf/20231007135945.4306-2-laoar.shao@gmail.com
      44cb03f1
    • Yafang Shao's avatar
      bpf: Fix missed rcu read lock in bpf_task_under_cgroup() · 29a7e00f
      Yafang Shao authored
      When employed within a sleepable program not under RCU protection, the
      use of 'bpf_task_under_cgroup()' may trigger a warning in the kernel log,
      particularly when CONFIG_PROVE_RCU is enabled:
      
        [ 1259.662357] WARNING: suspicious RCU usage
        [ 1259.662358] 6.5.0+ #33 Not tainted
        [ 1259.662360] -----------------------------
        [ 1259.662361] include/linux/cgroup.h:423 suspicious rcu_dereference_check() usage!
      
      Other info that might help to debug this:
      
        [ 1259.662366] rcu_scheduler_active = 2, debug_locks = 1
        [ 1259.662368] 1 lock held by trace/72954:
        [ 1259.662369]  #0: ffffffffb5e3eda0 (rcu_read_lock_trace){....}-{0:0}, at: __bpf_prog_enter_sleepable+0x0/0xb0
      
      Stack backtrace:
      
        [ 1259.662385] CPU: 50 PID: 72954 Comm: trace Kdump: loaded Not tainted 6.5.0+ #33
        [ 1259.662391] Call Trace:
        [ 1259.662393]  <TASK>
        [ 1259.662395]  dump_stack_lvl+0x6e/0x90
        [ 1259.662401]  dump_stack+0x10/0x20
        [ 1259.662404]  lockdep_rcu_suspicious+0x163/0x1b0
        [ 1259.662412]  task_css_set.part.0+0x23/0x30
        [ 1259.662417]  bpf_task_under_cgroup+0xe7/0xf0
        [ 1259.662422]  bpf_prog_7fffba481a3bcf88_lsm_run+0x5c/0x93
        [ 1259.662431]  bpf_trampoline_6442505574+0x60/0x1000
        [ 1259.662439]  bpf_lsm_bpf+0x5/0x20
        [ 1259.662443]  ? security_bpf+0x32/0x50
        [ 1259.662452]  __sys_bpf+0xe6/0xdd0
        [ 1259.662463]  __x64_sys_bpf+0x1a/0x30
        [ 1259.662467]  do_syscall_64+0x38/0x90
        [ 1259.662472]  entry_SYSCALL_64_after_hwframe+0x6e/0xd8
        [ 1259.662479] RIP: 0033:0x7f487baf8e29
        [...]
        [ 1259.662504]  </TASK>
      
      This issue can be reproduced by executing a straightforward program, as
      demonstrated below:
      
      SEC("lsm.s/bpf")
      int BPF_PROG(lsm_run, int cmd, union bpf_attr *attr, unsigned int size)
      {
              struct cgroup *cgrp = NULL;
              struct task_struct *task;
              int ret = 0;
      
              if (cmd != BPF_LINK_CREATE)
                      return 0;
      
              // The cgroup2 should be mounted first
              cgrp = bpf_cgroup_from_id(1);
              if (!cgrp)
                      goto out;
              task = bpf_get_current_task_btf();
              if (bpf_task_under_cgroup(task, cgrp))
                      ret = -1;
              bpf_cgroup_release(cgrp);
      
      out:
              return ret;
      }
      
      After running the program, if you subsequently execute another BPF program,
      you will encounter the warning.
      
      It's worth noting that task_under_cgroup_hierarchy() is also utilized by
      bpf_current_task_under_cgroup(). However, bpf_current_task_under_cgroup()
      doesn't exhibit this issue because it cannot be used in sleepable BPF
      programs.
      
      Fixes: b5ad4cdc
      
       ("bpf: Add bpf_task_under_cgroup() kfunc")
      Signed-off-by: default avatarYafang Shao <laoar.shao@gmail.com>
      Signed-off-by: default avatarDaniel Borkmann <daniel@iogearbox.net>
      Acked-by: default avatarStanislav Fomichev <sdf@google.com>
      Cc: Feng Zhou <zhoufeng.zf@bytedance.com>
      Cc: KP Singh <kpsingh@kernel.org>
      Link: https://lore.kernel.org/bpf/20231007135945.4306-1-laoar.shao@gmail.com
      29a7e00f
  5. Oct 17, 2023
  6. Oct 16, 2023
    • Daniel Borkmann's avatar
      Merge branch 'bpf-log-improvements' · 99c9991f
      Daniel Borkmann authored
      
      
      Andrii Nakryiko says:
      
      ====================
      This patch set fixes ambiguity in BPF verifier log output of SCALAR register
      in the parts that emit umin/umax, smin/smax, etc ranges. See patch #4 for
      details.
      
      Also, patch #5 fixes an issue with verifier log missing instruction context
      (state) output for conditionals that trigger precision marking. See details in
      the patch.
      
      First two patches are just improvements to two selftests that are very flaky
      locally when run in parallel mode.
      
      Patch #3 changes 'align' selftest to be less strict about exact verifier log
      output (which patch #4 changes, breaking lots of align tests as written). Now
      test does more of a register substate checks, mostly around expected var_off()
      values. This 'align' selftests is one of the more brittle ones and requires
      constant adjustment when verifier log output changes, without really catching
      any new issues. So hopefully these changes can minimize future support efforts
      for this specific set of tests.
      ====================
      
      Signed-off-by: default avatarDaniel Borkmann <daniel@iogearbox.net>
      99c9991f
    • Andrii Nakryiko's avatar
      bpf: Ensure proper register state printing for cond jumps · 1a8a315f
      Andrii Nakryiko authored
      
      
      Verifier emits relevant register state involved in any given instruction
      next to it after `;` to the right, if possible. Or, worst case, on the
      separate line repeating instruction index.
      
      E.g., a nice and simple case would be:
      
        2: (d5) if r0 s<= 0x0 goto pc+1       ; R0_w=0
      
      But if there is some intervening extra output (e.g., precision
      backtracking log) involved, we are supposed to see the state after the
      precision backtrack log:
      
        4: (75) if r0 s>= 0x0 goto pc+1
        mark_precise: frame0: last_idx 4 first_idx 0 subseq_idx -1
        mark_precise: frame0: regs=r0 stack= before 2: (d5) if r0 s<= 0x0 goto pc+1
        mark_precise: frame0: regs=r0 stack= before 1: (b7) r0 = 0
        6: R0_w=0
      
      First off, note that in `6: R0_w=0` instruction index corresponds to the
      next instruction, not to the conditional jump instruction itself, which
      is wrong and we'll get to that.
      
      But besides that, the above is a happy case that does work today. Yet,
      if it so happens that precision backtracking had to traverse some of the
      parent states, this `6: R0_w=0` state output would be missing.
      
      This is due to a quirk of print_verifier_state() routine, which performs
      mark_verifier_state_clean(env) at the end. This marks all registers as
      "non-scratched", which means that subsequent logic to print *relevant*
      registers (that is, "scratched ones") fails and doesn't see anything
      relevant to print and skips the output altogether.
      
      print_verifier_state() is used both to print instruction context, but
      also to print an **entire** verifier state indiscriminately, e.g.,
      during precision backtracking (and in a few other situations, like
      during entering or exiting subprogram).  Which means if we have to print
      entire parent state before getting to printing instruction context
      state, instruction context is marked as clean and is omitted.
      
      Long story short, this is definitely not intentional. So we fix this
      behavior in this patch by teaching print_verifier_state() to clear
      scratch state only if it was used to print instruction state, not the
      parent/callback state. This is determined by print_all option, so if
      it's not set, we don't clear scratch state. This fixes missing
      instruction state for these cases.
      
      As for the mismatched instruction index, we fix that by making sure we
      call print_insn_state() early inside check_cond_jmp_op() before we
      adjusted insn_idx based on jump branch taken logic. And with that we get
      desired correct information:
      
        9: (16) if w4 == 0x1 goto pc+9
        mark_precise: frame0: last_idx 9 first_idx 9 subseq_idx -1
        mark_precise: frame0: parent state regs=r4 stack=: R2_w=1944 R4_rw=P1 R10=fp0
        mark_precise: frame0: last_idx 8 first_idx 0 subseq_idx 9
        mark_precise: frame0: regs=r4 stack= before 8: (66) if w4 s> 0x3 goto pc+5
        mark_precise: frame0: regs=r4 stack= before 7: (b7) r4 = 1
        9: R4=1
      
      Signed-off-by: default avatarAndrii Nakryiko <andrii@kernel.org>
      Signed-off-by: default avatarDaniel Borkmann <daniel@iogearbox.net>
      Acked-by: default avatarJohn Fastabend <john.fastabend@gmail.com>
      Acked-by: default avatarEduard Zingerman <eddyz87@gmail.com>
      Link: https://lore.kernel.org/bpf/20231011223728.3188086-6-andrii@kernel.org
      1a8a315f
    • Andrii Nakryiko's avatar
      bpf: Disambiguate SCALAR register state output in verifier logs · 72f8a1de
      Andrii Nakryiko authored
      
      
      Currently the way that verifier prints SCALAR_VALUE register state (and
      PTR_TO_PACKET, which can have var_off and ranges info as well) is very
      ambiguous.
      
      In the name of brevity we are trying to eliminate "unnecessary" output
      of umin/umax, smin/smax, u32_min/u32_max, and s32_min/s32_max values, if
      possible. Current rules are that if any of those have their default
      value (which for mins is the minimal value of its respective types: 0,
      S32_MIN, or S64_MIN, while for maxs it's U32_MAX, S32_MAX, S64_MAX, or
      U64_MAX) *OR* if there is another min/max value that as matching value.
      E.g., if smin=100 and umin=100, we'll emit only umin=10, omitting smin
      altogether. This approach has a few problems, being both ambiguous and
      sort-of incorrect in some cases.
      
      Ambiguity is due to missing value could be either default value or value
      of umin/umax or smin/smax. This is especially confusing when we mix
      signed and unsigned ranges. Quite often, umin=0 and smin=0, and so we'll
      have only `umin=0` leaving anyone reading verifier log to guess whether
      smin is actually 0 or it's actually -9223372036854775808 (S64_MIN). And
      often times it's important to know, especially when debugging tricky
      issues.
      
      "Sort-of incorrectness" comes from mixing negative and positive values.
      E.g., if umin is some large positive number, it can be equal to smin
      which is, interpreted as signed value, is actually some negative value.
      Currently, that smin will be omitted and only umin will be emitted with
      a large positive value, giving an impression that smin is also positive.
      
      Anyway, ambiguity is the biggest issue making it impossible to have an
      exact understanding of register state, preventing any sort of automated
      testing of verifier state based on verifier log. This patch is
      attempting to rectify the situation by removing ambiguity, while
      minimizing the verboseness of register state output.
      
      The rules are straightforward:
        - if some of the values are missing, then it definitely has a default
        value. I.e., `umin=0` means that umin is zero, but smin is actually
        S64_MIN;
        - all the various boundaries that happen to have the same value are
        emitted in one equality separated sequence. E.g., if umin and smin are
        both 100, we'll emit `smin=umin=100`, making this explicit;
        - we do not mix negative and positive values together, and even if
        they happen to have the same bit-level value, they will be emitted
        separately with proper sign. I.e., if both umax and smax happen to be
        0xffffffffffffffff, we'll emit them both separately as
        `smax=-1,umax=18446744073709551615`;
        - in the name of a bit more uniformity and consistency,
        {u32,s32}_{min,max} are renamed to {s,u}{min,max}32, which seems to
        improve readability.
      
      The above means that in case of all 4 ranges being, say, [50, 100] range,
      we'd previously see hugely ambiguous:
      
          R1=scalar(umin=50,umax=100)
      
      Now, we'll be more explicit:
      
          R1=scalar(smin=umin=smin32=umin32=50,smax=umax=smax32=umax32=100)
      
      This is slightly more verbose, but distinct from the case when we don't
      know anything about signed boundaries and 32-bit boundaries, which under
      new rules will match the old case:
      
          R1=scalar(umin=50,umax=100)
      
      Also, in the name of simplicity of implementation and consistency, order
      for {s,u}32_{min,max} are emitted *before* var_off. Previously they were
      emitted afterwards, for unclear reasons.
      
      This patch also includes a few fixes to selftests that expect exact
      register state to accommodate slight changes to verifier format. You can
      see that the changes are pretty minimal in common cases.
      
      Note, the special case when SCALAR_VALUE register is a known constant
      isn't changed, we'll emit constant value once, interpreted as signed
      value.
      
      Signed-off-by: default avatarAndrii Nakryiko <andrii@kernel.org>
      Signed-off-by: default avatarDaniel Borkmann <daniel@iogearbox.net>
      Acked-by: default avatarJohn Fastabend <john.fastabend@gmail.com>
      Acked-by: default avatarEduard Zingerman <eddyz87@gmail.com>
      Link: https://lore.kernel.org/bpf/20231011223728.3188086-5-andrii@kernel.org
      72f8a1de
    • Andrii Nakryiko's avatar
      selftests/bpf: Make align selftests more robust · cde78514
      Andrii Nakryiko authored
      
      
      Align subtest is very specific and finicky about expected verifier log
      output and format. This is often completely unnecessary as in a bunch of
      situations test actually cares about var_off part of register state. But
      given how exact it is right now, any tiny verifier log changes can lead
      to align tests failures, requiring constant adjustment.
      
      This patch tries to make this a bit more robust by making logic first
      search for specified register and then allowing to match only portion of
      register state, not everything exactly. This will come handly with
      follow up changes to SCALAR register output disambiguation.
      
      Signed-off-by: default avatarAndrii Nakryiko <andrii@kernel.org>
      Signed-off-by: default avatarDaniel Borkmann <daniel@iogearbox.net>
      Acked-by: default avatarJohn Fastabend <john.fastabend@gmail.com>
      Acked-by: default avatarEduard Zingerman <eddyz87@gmail.com>
      Link: https://lore.kernel.org/bpf/20231011223728.3188086-4-andrii@kernel.org
      cde78514
    • Andrii Nakryiko's avatar
      selftests/bpf: Improve missed_kprobe_recursion test robustness · 08a7078f
      Andrii Nakryiko authored
      
      
      Given missed_kprobe_recursion is non-serial and uses common testing
      kfuncs to count number of recursion misses it's possible that some other
      parallel test can trigger extraneous recursion misses. So we can't
      expect exactly 1 miss. Relax conditions and expect at least one.
      
      Signed-off-by: default avatarAndrii Nakryiko <andrii@kernel.org>
      Signed-off-by: default avatarDaniel Borkmann <daniel@iogearbox.net>
      Acked-by: default avatarJiri Olsa <jolsa@kernel.org>
      Acked-by: default avatarJohn Fastabend <john.fastabend@gmail.com>
      Acked-by: default avatarEduard Zingerman <eddyz87@gmail.com>
      Link: https://lore.kernel.org/bpf/20231011223728.3188086-3-andrii@kernel.org
      08a7078f
    • Andrii Nakryiko's avatar
      selftests/bpf: Improve percpu_alloc test robustness · 2d78928c
      Andrii Nakryiko authored
      
      
      Make these non-serial tests filter BPF programs by intended PID of
      a test runner process. This makes it isolated from other parallel tests
      that might interfere accidentally.
      
      Signed-off-by: default avatarAndrii Nakryiko <andrii@kernel.org>
      Signed-off-by: default avatarDaniel Borkmann <daniel@iogearbox.net>
      Acked-by: default avatarJohn Fastabend <john.fastabend@gmail.com>
      Acked-by: default avatarEduard Zingerman <eddyz87@gmail.com>
      Link: https://lore.kernel.org/bpf/20231011223728.3188086-2-andrii@kernel.org
      2d78928c