Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.231.203 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796100158; b=Dyy+8fCnemZ5XS7DQrrFwizyNoY5bhNmGMiQIEQMeRRnef6Jxdqm1neH/ol8EAT8v74w qswmRRFN4f7XzdWQJogBm7IR61kdDwUVgJlwyZSkK9upaC6QANPT6e63ZZdrcrUj+aGEf 4tZQpcSb2uyzMfKvMmbczlyatI2mSTcN2svUXr7yf6sw5lrmfKi7g/QplFINuNKEgY2lN tg4y6adYR3bazVsT0RDfx3oNAf9r0NFRlIHjFXo629x9QHpeVkNCONntClpoRaYUjV4hR H+5j7uju/znVPcrBShOHrgeQ3zrMFThkG8cQ4a/Sng7SrNxUrMqD63vokt3J3Kn5jVw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796100158; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Gm-Message-State:X-Gm-Gg:X-Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: X-Developer-Signature:X-Developer-Key:Content-Transfer-Encoding; bh=DPaZGF2lZzgKAf0KolGuAoXnKlJ8wiC88M9W+vFP9KI=; b=OiEH3Kmu1fzx6s4N3A+P4MDxHvzxj8k7d9EXXBzVibiwf77lc4OubwSAolsc8fjwEK7E 1d9NMIYZItGnd1bmHPRFUUB+f610qgVrrMxdQyrHru7siT3PlVdBvLjkUmBg6juhpSI7H 7IzQMcRGjuokfRyS0k016F1bTNv2z+D/XVGna9jLk3anQSZTwV+rzzD5wPvSMgAdcGYFn 2sEAyObxP9ftd961m0quMrviVsJ5zaUBtKotW3zAnkBxLL6O78sdJQzxBn1LEpgmtgKV3 EnU78kFC8E7/x0f/pjTFl/dRZTi/tJ/dgjoPcOfY0Vurqr6xW+tpxGFZ3C43Q6mKDyg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=kC9nBFkL; arc=none smtp.remote-ip=74.125.231.203 Received: from mail-oi2-f11.google.com (mail-oi2-f11.google.com [74.125.231.203]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 5ADB1606A320 for ; Tue, 1 Dec 2026 04:42:37 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 5ADB1606A320 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=kC9nBFkL Received: by mail-oi2-f11.google.com with SMTP id 5614622812f47-56d3169ad31so1288782b6e.1 for ; Mon, 30 Nov 2026 20:42:37 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1796100156; x=1796704956; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to:content-type; bh=DPaZGF2lZzgKAf0KolGuAoXnKlJ8wiC88M9W+vFP9KI=; b=kC9nBFkLvrsY80OHDYTL6TzMtDxutxTtVJSHyQudyYzuyqz5EpEzClOMjHTGdEAZAe NTTKBz1XUQe8/6pW2FcVYCXfZCV610IvEQQ338t2CvtidwcDV/HmqruYVxaUD4DgDPgq I3nkT9hRByD6XfpHnrgUpRXDMMMv9kmSWW55Pwzdjb+tooAlO/86XGnnoeJ0DgQ/B8di 9sgs3olKRJRC/jWb3XPleDAmdYfFvMU4Fw4AjRk6yL/QXlJUAZAoUQRZIrOyLcFsxTvU yQTgB8sL+Yq3hQVrSbRn8fm6cq+jbqKJv5d98QyS7+h9Aua328D2E6UIN+zTs4Hm+uUb tbWA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796100156; x=1796704956; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-gg:x-gm-message-state:from :to:cc:subject:date:message-id:reply-to:content-type; bh=DPaZGF2lZzgKAf0KolGuAoXnKlJ8wiC88M9W+vFP9KI=; b=RxUKgt4UdRMv77CX8h4JyRNYtZc1ziuATdeJPr29cT3dxM8cXWfI5sP+XieRa58pC6 mj2I/MBJe1SzwTUTQlF1w8mVoh9v1sGj/RM+PYpZcE6oDYBECW3JfgszKh714zdZUJdr I7YgTk5F85LhMtVbZLVjhTd7BKQL9wGdea9rfdNrAlkhfFho0OjhTkwopmRQBO+1OtvW oNLZeckMQDjRq7bvDv6zhTkdjEJ9rLQJXVruzPhlpn3YeDVS3A9o2Ttd1NmMsLEA+FBm WfaGjdvdeOoSr9TsTi7G0D+lJYd5wV9Mb2x4tHLWdCANX3GNwNBi/95Pen//5uCD/Krf 8ayg== X-Gm-Message-State: APuU4Z+mxoG94vJkLnIeID4a3GlAhrqaoGbvhhaDupPONFDt9ko3CcQv 6uumH+skksAvgCz0G45H+9hXJgTy3TD1VUSh2D0t6OCNlGbbN9FHOjvmHPgWVXEkIXw= X-Gm-Gg: AZFdTZdWvBe5yGNskUdGCJ+HAld2WOkHGFIaj3my2aQWFKG8sc3VQ4elYLFBu757wRr Q01vatWF+2C/nzZdIpfjBYdqHfzEBgh1uNX7mNVETeAi3Zc5FkC7NypiP5DSDR11Nm0H4W5WROR p2j6TqHYmOOYQRrlooLia1Cvp8i9vKQdpSb7f5fYsPBMBrAF638r0bOLttFcCN2rtRkoddc6ToI fVRVZwrsXx35S5giMbf73CGpq5rqpoXciTm/6YJJCXdYHe+IaDR3D1RV1YZnTzcxB/MZNPmiVpL psaoLIoEZrq5PVdedPnfYi1TVg531Qhl0szWv9o7fuWF3ypaII9EHNymnDT2lzhgb5kChQUy9OP VG9yNyZQjnfN0PnFTFJMkLM85U5dhN1mUOgJTJvbKKL/vcv2UqTrWRqXQrJDitNNxNxofKkaruw K0LrxzcjZsEet2fmSu9sxQOkXBH3T5/mooL4XnksiATqFAHHwkHpUQXlDxyKwn+fPu2KSOa4z3+ U+SDQ4Du3dpvJcmF42zOzi3F8PT6TXhP6liiagm86tGMFNzXRyJnA11b7cjASfZNyH4NNco8Ryj GWBS2g+ipUAEAZsY51b2/qgQ8suwzwPcGa6ZdIGQLDSFx3ajcbtJfjcLVVb+nEr/pXNCbA6HGBZ J/NSENz5dXaa7ORBfOKeLVIsMNv1sjB4JliIz X-Received: by 2002:a05:6808:6711:b0:4c4:9f7e:92ce with SMTP id 5614622812f47-57a0af38396mr39742944b6e.38.1796100154314; Mon, 30 Nov 2026 20:42:34 -0800 (PST) Received: from localhost ([2a03:2880:10ff:5a::]) by smtp.gmail.com with ESMTPSA id 5614622812f47-57edd22ba0esm945488b6e.3.2026.11.30.20.42.31 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 30 Nov 2026 20:42:32 -0800 (PST) From: Kumar Kartikeya Dwivedi To: bpf@vger.kernel.org Cc: Alexei Starovoitov , Andrii Nakryiko , Daniel Borkmann , Eduard Zingerman , Emil Tsalapatis , Ihor Solodrai , kkd@meta.com, kernel-team@meta.com Subject: [PATCH bpf-next v1 49/73] bpf: Cancel the program when the time of its own may_goto is up Date: Tue, 1 Dec 2026 05:39:16 +0100 Message-ID: <33bbfdec2a3e0b6c2d26bfddc849feeb82d0ec2c.1796099738.git.memxor@gmail.com> X-Mailer: git-send-email 2.53.1 In-Reply-To: References: X-Mailing-List: bpf@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 X-Developer-Signature: v=1; a=openpgp-sha256; l=104035; h=from:subject:message-id; bh=EnRCIagDDr8CrU6ImIOt66wTvFgjjxxVSzLOsYxc8LY=; b=owGbwMvMwCXmrmtenRyi38x4Wi2JIZvPb2Fsgq4Dl2yjmNTrxwFMJ1lulp+vuGOwy9X4U9jHT4Xi t+93lLIwiHExyIopspT838dkfKLyd6DtMm6YOaxMIEMYuDgFYCJx7xn+J4az7+t9vkglsfnxvRnV/R LaXbOMKq+9iTrhe37NN8etAYwMu3+8mVcek553zCgl+bpdfPOJKRtXOUm+j5+cpCw65ygnFwA= X-Developer-Key: i=memxor@gmail.com; a=openpgp; fpr=B34BD741DE8494B76E2F717880EF20021D46C59B Content-Transfer-Encoding: 8bit A may_goto of the program, which can_loop and cond_break expand to, is a jump that is taken when the time slice of the invocation is over: do { p = bpf_map_lookup_elem(&map, &key); } while (!p && can_loop); v = *p; Currently the program continues at the target of the jump. Here it would continue with p == NULL, and the verifier rejects it for that. Where the verifier accepts the code at the target, the program continues with half of a result: a list that was not walked to its end, a lock that was not taken. No user of can_loop or cond_break in the selftests or in the scx schedulers is known to recover from that. A may_goto of the verifier jumps to a landing pad, and the kernel cancels the program. Do the same for a may_goto of the program. The landing pads release what the frames hold, and the program returns the value of its program type. What changes for programs that load today: - The code at the target of the jump no longer runs after a time-out. arena_spin_lock() does not return -ETIMEDOUT: the program ends in the lock. - A program is rejected if the verifier cannot generate a landing pad for a may_goto of the program, or for a call above it. - A program that was rejected for the code at the target loads, like the loop above. - A global function with such a loop can unwind, so an extension cannot replace it and fexit cannot attach to it. - The time that is up stays up for the invocation, as before. After a function that cannot be cancelled has used it up, the next may_goto in a function that can be cancelled ends the program. A may_goto of the program stays a plain jump in three cases: - It is 'may_goto +0', or it jumps over nothing but insns like itself. The verifier removes such an insn. - It is the form that counts trips, where no JIT runs the timed form. BPF_MAX_LOOPS trips are a bound of the loop, not a time that is up. - Its function cannot be cancelled. The third case is decided once for all frames of a function, because the verifier rewrites an insn in one way for all of them. The code marks such a function 'stuck'. It does so when a helper without an unwind label for its callback calls the function, and when a frame that cannot be cancelled calls it or reaches its may_goto. A frame of a marked function that has a caller in the program marks what it calls, and skip_faults() sets the same mark. A frame cannot be cancelled if its function has no exit insn, if the program is loaded without CAP_PERFMON, or if it has a caller in the program and the JIT has no unwind_exit. Three things need care: - The program can still continue after a time-out in a function that only bpf_loop() or bpf_for_each_map_elem() calls. The existing check at its start returns 1 if the time is up, the helper ends its loop, and the program continues until its next may_goto. The check is not a site. A comment at the check says why. - retarget_may_gotos() makes the insn jump to its landing pad before dead code is removed. No state takes the jump, so its old target can be dead code. The insn would become 'goto +0', and nothing would stop the loop. - The jump stays an edge of the control flow graph and of liveness. So a loop whose only exit is its may_goto is not a loop without an exit, and a register that the program reads only at the target is live at the insn, where a landing pad can use it. In the main pass check_may_goto_site() makes the insn a site of a new kind, BPF_SITE_MAY_GOTO, and hidden slots serve it like a may_goto of the verifier. A function can be marked late in a pass, after a state was cancelled at its may_goto or a frame of it made a call. The verifier then repeats the pass with the mark set from its start. The mark is kept for every later pass. That is safe, because a marked function behaves as it does today. It is also needed: a pass that does not reach the call that sets the mark could reject a program that loads today. Tests that relied on the jump now expect the value of the program type, use up the time in a function that cannot be cancelled, or give the loop a second exit. Signed-off-by: Kumar Kartikeya Dwivedi --- include/linux/bpf_verifier.h | 28 +- kernel/bpf/fixups.c | 83 ++++- kernel/bpf/pads.c | 154 +++++++- kernel/bpf/verifier.c | 189 +++++++++- .../selftests/bpf/prog_tests/may_goto_far.c | 23 +- .../selftests/bpf/prog_tests/timed_may_goto.c | 89 ++++- .../selftests/bpf/progs/may_goto_priv_stack.c | 8 +- tools/testing/selftests/bpf/progs/stream.c | 2 +- .../selftests/bpf/progs/timed_may_goto.c | 332 +++++++++++++----- .../selftests/bpf/progs/timed_may_goto_ext.c | 22 +- .../selftests/bpf/progs/timed_may_goto_user.c | 169 +++++++-- .../bpf/progs/verifier_arena_stack.c | 27 +- .../bpf/progs/verifier_bpf_fastcall.c | 12 +- .../selftests/bpf/progs/verifier_equations.c | 9 +- .../bpf/progs/verifier_iterating_callbacks.c | 25 +- .../bpf/progs/verifier_linked_scalars.c | 7 +- .../selftests/bpf/progs/verifier_may_goto_1.c | 17 +- .../selftests/bpf/progs/verifier_passes.c | 26 +- .../selftests/bpf/progs/verifier_patch_list.c | 100 ++++-- .../selftests/bpf/progs/verifier_stack_arg.c | 8 +- 20 files changed, 1082 insertions(+), 248 deletions(-) diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h index 1d4860542c42..e20df219d332 100644 --- a/include/linux/bpf_verifier.h +++ b/include/linux/bpf_verifier.h @@ -462,6 +462,7 @@ enum bpf_site_kind { BPF_SITE_CALL, BPF_SITE_FAULT, /* an access to arena that faults */ BPF_SITE_THROW, /* a call of bpf_throw() */ + BPF_SITE_MAY_GOTO, /* a may_goto of the program, see check_may_goto_site() */ }; /* The classes of resources that a landing pad releases */ @@ -1310,6 +1311,8 @@ struct bpf_insn_aux_data { /* below flags are initialized once */ u32 bb_end:1; /* last instruction of a basic block */ u32 guard_place:1; /* it is the place for may_goto if the loop needs one */ + /* a may_goto that jumps over nothing but may_gotos: bpf_opt_remove_nops() removes it */ + u32 may_goto_nop:1; /* true if instruction is a call to a helper function that * accepts callback function as a parameter. */ @@ -1548,11 +1551,27 @@ struct bpf_subprog_info { bool did_unwind: 1; /* * It did so at a site with no other way out, see bpf_pads_must_unwind(). A fault in arena - * has one: the access is skipped. + * has one: the access is skipped. So has a may_goto of the program: in a stuck subprog it + * jumps. */ bool must_unwind: 1; - /* it did so at a site that the program keeps for sure, see site_is_certain() */ + /* + * It did so at a site that the program keeps for sure, see site_is_certain(), and that is + * no access to arena. + */ bool unwinds_for_sure: 1; + /* + * may_goto_unwinds: in this pass a frame of it was cancelled at a may_goto of the program. + * stuck: it cannot be cancelled. In all its frames, in this pass and in every later one, a + * may_goto of the program jumps, see stuck_frame_calls(). + */ + bool may_goto_unwinds: 1; + bool stuck: 1; + /* + * In this pass a frame of it made a call that did not mark the callee stuck. If the subprog + * is marked stuck later, the pass is repeated, see stuck_frame_calls(). + */ + bool made_calls: 1; /* scratch of bpf_pads_note_causes(): its insns are searched for causes of the error */ bool below_conflict: 1; /* @@ -1560,6 +1579,8 @@ struct bpf_subprog_info { * references the arguments of the call had, see bpf_pad_states_meet() */ bool arg_refs_differ: 1; + /* where it is cancelled or unwinds, callees included: bits by enum bpf_site_kind */ + u8 left_at; /* in this pass it cannot have hidden slots for these groups, bits by enum bpf_pad_group */ u8 no_slots: 4; /* the groups that it has hidden slots for. Each bpf_pads_settle() decides again. */ @@ -2262,6 +2283,7 @@ void bpf_flow_new_pass(struct bpf_verifier_env *env); void bpf_flow_drop_guards(struct bpf_verifier_env *env); bool bpf_flow_guard_is_guess(struct bpf_verifier_env *env, int idx); int bpf_flow_place_guards(struct bpf_verifier_env *env); +void bpf_mark_may_goto_nops(struct bpf_verifier_env *env); /* verifier.c, for flow.c */ int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge_loop, bool *starts_leftover); @@ -2326,6 +2348,8 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan, struct bpf_insn *buf, struct bpf_insn_aux_data *aux); void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pad_plan *plan); void bpf_pad_log_handed_over(struct bpf_verifier_env *env, int subprog, u8 args); +void bpf_pad_note_left(struct bpf_verifier_env *env, struct bpf_subprog_info *sub, + const struct bpf_pad_plan *plan, enum bpf_site_kind kind); bool bpf_pad_must_unwind(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan); void bpf_pads_must_unwind(struct bpf_verifier_env *env); void bpf_pads_mark_used(struct bpf_verifier_env *env); diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c index 97e147cc73ab..f36e99814ab0 100644 --- a/kernel/bpf/fixups.c +++ b/kernel/bpf/fixups.c @@ -655,6 +655,8 @@ bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_ return false; case BPF_SITE_FAULT: return !env->insn_aux_data[i].fault_skips; + case BPF_SITE_MAY_GOTO: + return plan->visited && !bpf_find_containing_subprog(env, i)->stuck; } return false; } @@ -817,6 +819,38 @@ static int insert_unwind_gotos(struct bpf_verifier_env *env, const int *added) return bpf_patch_list_commit(env); } +/* + * Make each may_goto of the program that is a site jump to its landing pad, see + * check_may_goto_site(). This has to run before dead code is hard wired. No state takes the jump + * of such a may_goto, so its old target can be dead code, and the insn would become 'goto +0', + * which stops no loop. @added is the number of insns that were appended to each subprog. + */ +static int retarget_may_gotos(struct bpf_verifier_env *env, const int *added) +{ + struct bpf_patch_list *pl = &env->patch_list; + const struct bpf_subprog_info *sub; + const struct bpf_pad_plan *plan; + struct bpf_insn *insn; + int i, s; + + for (s = 0; s < env->subprog_cnt; s++) { + sub = &env->subprog_info[s]; + for (i = sub->start; added[s] && i < sub[1].start - added[s]; i++) { + plan = bpf_pad_plan(&env->insn_aux_data[i], BPF_SITE_MAY_GOTO); + if (!plan || !bpf_site_is_used(env, i, plan)) + continue; + if (bpf_must_abort()) + return -EINTR; + /* queue the insn as its own patch: the list sets the offset, however far */ + insn = __bpf_patch_list_add(pl, env->prog, i, &env->prog->insnsi[i], 1); + if (IS_ERR(insn)) + return PTR_ERR(insn); + bpf_patch_list_jump(pl, insn, sub[1].start - added[s] + plan->pad, 0); + } + } + return bpf_patch_list_commit(env); +} + /* * Add the stores that keep the hidden slots up to date, see kernel/bpf/pads.c. @buf has room for * BPF_PAD_MAX_SLOT_INSNS. @added is the number of insns that were appended to each subprog. @@ -877,10 +911,9 @@ static int insert_slot_stores(struct bpf_verifier_env *env, struct bpf_insn *buf } /* - * Emit what the main pass decided about the sites: may_goto before the insns that it - * marked, see check_loop_guard(), unwind_goto after calls and after accesses to arena, a jump in - * place of a call of bpf_throw(), the landing pads, and the stores to the hidden slots that the pads - * read. What a pad does it did to the states that left the frame at the site, see unwind_frame(). + * Emit the code for the sites that the main pass recorded. The landing pads of a subprog go after + * its last insn. They are not verified: unwind_frame() did to each state that left its frame at a + * site what the pad of the site does. * * may_goto pad before an insn of a loop, see check_loop_guard(). A may_goto * insn of the program that is a site jumps to its pad too. @@ -979,6 +1012,7 @@ int bpf_insert_sites(struct bpf_verifier_env *env) } err = insert_slot_stores(env, new, added); err = err ?: insert_unwind_gotos(env, added); + err = err ?: retarget_may_gotos(env, added); out: kvfree(added); kvfree(new); @@ -1256,6 +1290,39 @@ static bool insn_is_nop(struct bpf_verifier_env *env, int i, int next) !memcmp(&insn, &MAY_GOTO_0, sizeof(MAY_GOTO_0)); } +/* Is @insn an addr_space_cast of a register into itself? bpf_lower_cast_mov() may remove it. */ +static bool cast_may_be_nop(const struct bpf_insn *insn) +{ + return insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && + insn->off == BPF_ADDR_SPACE_CAST && insn->dst_reg == insn->src_reg; +} + +/* + * Mark each may_goto that jumps over nothing, or over nothing but insns like itself. clang emits + * them when it unrolls a loop with can_loop. bpf_opt_remove_nops() removes such an insn, so the + * main pass does not make it a site, see check_may_goto_site(). + * + * A cast that may be removed counts as nothing too. If the cast stays, so does the may_goto that + * jumps over it. It then jumps where the program says, and the main pass has verified that jump. + */ +void bpf_mark_may_goto_nops(struct bpf_verifier_env *env) +{ + struct bpf_insn *insns = env->prog->insnsi, insn; + int i, next; + + for (i = env->prog->len - 1, next = env->prog->len; i >= 0; i--) { + if (cast_may_be_nop(&insns[i])) + continue; + insn = insns[i]; + insn.off = 0; + if (insns[i].off < 0 || i + 1 + insns[i].off > next || + (memcmp(&insn, &NOP, sizeof(NOP)) && memcmp(&insn, &MAY_GOTO_0, sizeof(insn)))) + next = i; + else + env->insn_aux_data[i].may_goto_nop = bpf_is_may_goto_insn(&insn); + } +} + /* addr_space_cast of a pointer that is not in arena is a move, see is_cast_mov() */ void bpf_lower_cast_mov(struct bpf_verifier_env *env) { @@ -3516,6 +3583,14 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env) * The time is up, but the helper would call the function again and * again. End its loop. The verifier has seen that: the loop can end * after each call. + * + * This check is not a site, unlike a may_goto of the program, see + * check_may_goto_site(). When it ends the loop, the helper returns + * the number of calls that it made, and the program continues + * until its next may_goto. The main pass cannot make the check a + * site: no insn of the program stands for it, and only after the + * pass is it known that only loop helpers call the function and + * that the program has a timed may_goto. */ insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_0, count_off); diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c index 57cbeae78edb..36086dc5ee98 100644 --- a/kernel/bpf/pads.c +++ b/kernel/bpf/pads.c @@ -4,7 +4,8 @@ * * The kernel can cancel a BPF program: it ends the program before the program's own code returns. A * SITE is an insn at which that can happen: - * - a may_goto that the verifier adds, when the time of the program is up (BPF_SITE_GUARD) + * - a may_goto of the verifier or of the program, when the time of the program is up + * (BPF_SITE_GUARD, BPF_SITE_MAY_GOTO) * - the stack check at the start of a recursive function (BPF_SITE_RECURSION) * - an access to arena that faults (BPF_SITE_FAULT) * - a call of bpf_throw() (BPF_SITE_THROW) @@ -2397,15 +2398,17 @@ static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan) } /* - * Is the pad the only way out of the site of @plan? An access to arena that faults can be skipped. - * So can all of them below a call, unless a subprog comes back to the call that is left elsewhere. + * Is the pad the only way out of the site of @plan, whatever the subprog turns out to be? An access + * to arena that faults can be skipped. may_goto of the program can jump where the program says, as + * it does in a subprog that cannot unwind. So can all of them below a call, unless a subprog comes + * back to the call that is left elsewhere. */ bool bpf_pad_must_unwind(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan) { int s; if (plan->kind != BPF_SITE_CALL) - return plan->kind != BPF_SITE_FAULT; + return plan->kind != BPF_SITE_FAULT && plan->kind != BPF_SITE_MAY_GOTO; bpf_pad_for_each_callee(plan, s) if (env->subprog_info[s].must_unwind) return true; @@ -2433,6 +2436,100 @@ void bpf_pads_must_unwind(struct bpf_verifier_env *env) } while (changed); } +/* + * At which kinds of site does the program leave each subprog? At its own, and at those of what + * comes back to its calls. Bits by enum bpf_site_kind in 'left_at'. The main pass notes them as + * the states leave, see bpf_pad_note_left(). This is what is left of that when the pass is over. + */ +static void sites_of_subprogs(struct bpf_verifier_env *env) +{ + const struct bpf_insn_aux_data *aux = env->insn_aux_data; + const struct bpf_pad_plan *plan; + struct bpf_subprog_info *sub; + bool changed; + int i, s, c; + u8 kinds; + + for (s = 0; s < env->subprog_cnt; s++) { + sub = &env->subprog_info[s]; + sub->left_at = 0; + } + do { + changed = false; + for (s = 0; s < env->subprog_cnt; s++) { + sub = &env->subprog_info[s]; + kinds = sub->left_at; + for (i = sub->start; i < sub[1].start; i++) { + if (aux[i].loop_guard) + kinds |= BIT(BPF_SITE_GUARD); + if (aux[i].fault_empty && !aux[i].fault_skips) + kinds |= BIT(BPF_SITE_FAULT); + for (plan = aux[i].pad_plans; plan; plan = plan->next) { + if (!plan->used) + continue; + if (plan->kind != BPF_SITE_CALL) { + kinds |= BIT(plan->kind); + continue; + } + bpf_pad_for_each_callee(plan, c) + kinds |= env->subprog_info[c].left_at; + } + } + changed |= kinds != sub->left_at; + sub->left_at = kinds; + } + } while (changed); +} + +/* The kinds of site that the subprogs which come back to the call of @plan are left at */ +static u8 sites_below(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan) +{ + u8 kinds = 0; + int s; + + bpf_pad_for_each_callee(plan, s) + kinds |= env->subprog_info[s].left_at; + return kinds; +} + +/* The frame at the site of @plan cannot be cancelled, so there is no pad to generate */ +static bool plan_is_stuck(const struct bpf_pad_plan *plan) +{ + return plan->conflict == BPF_CONFLICT_CANNOT_UNWIND || + plan->conflict == BPF_CONFLICT_NO_EXIT; +} + +/* + * Does the site of @plan need a pad wherever its frame can unwind? If so a conflict there is an + * error, and hidden slots are worth their stores. All sites do, but for: + * - an access to arena, and a call that has nothing but such accesses below it: they are + * skipped, see skip_faults(). + * may_goto of the program needs one, and so does a call above it: the jump that the program + * has there was not verified. + */ +static bool site_needs_pad(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan) +{ + if (bpf_pad_must_unwind(env, plan)) + return true; + if (plan->kind == BPF_SITE_FAULT) + return false; + return plan->kind != BPF_SITE_CALL || (sites_below(env, plan) & BIT(BPF_SITE_MAY_GOTO)); +} + +/* + * Is the conflict of @plan an error? Not where the frame cannot unwind and the site has another way + * out, see bpf_pad_must_unwind(): what comes back to a call there is made unable to unwind, see + * skip_faults(). + */ +static bool plan_rejects(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan) +{ + if (!plan->conflict) + return false; + if (bpf_pad_must_unwind(env, plan)) + return true; + return !plan_is_stuck(plan) && site_needs_pad(env, plan); +} + /* * Does an insn of @sub acquire an iterator or a dynptr? If none does, a reference of its frame that * has no location is always a pointer, and the hidden slot of the call that returned it holds it. @@ -2462,7 +2559,7 @@ static u8 plan_needs_slots(struct bpf_verifier_env *env, const struct bpf_pad_pl u8 groups = plan->sections_differ; int i, err; - if (!plan->used || plan->conflict || !bpf_pad_must_unwind(env, plan)) + if (!plan->used || plan->conflict || !site_needs_pad(env, plan)) return 0; if (plan->no_place && all_ptrs) groups |= BIT(BPF_PAD_GROUP_REFS); @@ -2670,7 +2767,7 @@ static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group) for (i = sub->start; i < sub[1].start; i++) for (plan = aux[i].pad_plans; plan; plan = plan->next) if (plan->used && plan_has_slots(plan) && - !plan_has_room(plan, group, slots) && bpf_pad_must_unwind(env, plan)) + !plan_has_room(plan, group, slots) && site_needs_pad(env, plan)) return 0; sub->hidden_words += words; err = bpf_hidden_slots_fit(env); @@ -3030,6 +3127,7 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad [BPF_SITE_CALL] = "call", [BPF_SITE_FAULT] = "arena access", [BPF_SITE_THROW] = "bpf_throw", + [BPF_SITE_MAY_GOTO] = "may_goto of the program", }; static const char * const why[] = { [BPF_CONFLICT_SECTIONS_DIFFER] = "the number of sections differs", @@ -3095,12 +3193,23 @@ void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pa print_plan(env, insn_idx, plan); } +/* + * A state leaves a frame of @sub at the site of @plan, which is of @kind. Record the kind in + * 'left_at', for the callers. bpf_pads_settle() computes it again for the sites that are kept. + */ +void bpf_pad_note_left(struct bpf_verifier_env *env, struct bpf_subprog_info *sub, + const struct bpf_pad_plan *plan, enum bpf_site_kind kind) +{ + sub->left_at |= kind == BPF_SITE_CALL ? sites_below(env, plan) : BIT(kind); +} + /* * The site of @plan, at insn @i, has no pad. An access to arena: it is skipped when it faults. * What follows the access was verified, and less unwinds than the main pass looked at. - * Or it is a call, and only accesses to arena unwind below it. They are skipped: what came back to - * the call cannot unwind, nor can what came back to the calls in there. The pass is done again, - * and they cannot from its start, see check_funcs(). + * Or it is a call, and below it only accesses to arena and may_goto of the program unwind. The + * accesses are skipped and may_goto jumps where the program says: what came back to the call cannot + * unwind, nor can what came back to the calls in there. The pass is done again, and they cannot + * from its start, see check_funcs(). */ static int skip_faults(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan) { @@ -3125,6 +3234,7 @@ static int skip_faults(struct bpf_verifier_env *env, int i, const struct bpf_pad if (!sub->bail_unwinds) continue; sub->bail_unwinds = false; + sub->stuck = true; for (i = sub->start; i < sub[1].start; i++) { plan = bpf_pad_plan(&aux[i], BPF_SITE_CALL); if (plan) @@ -3187,6 +3297,7 @@ int bpf_pads_settle(struct bpf_verifier_env *env) int i, s, err; bpf_pads_must_unwind(env); + sites_of_subprogs(env); /* sort the releases first: hidden slots are inserted into that order */ for (i = 0; i < env->prog->len; i++) { for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next) { @@ -3210,7 +3321,7 @@ int bpf_pads_settle(struct bpf_verifier_env *env) if (err < 0) return err; plan->conflict = err; - if (plan->conflict && bpf_pad_must_unwind(env, plan)) { + if (plan_rejects(env, plan)) { print_plan(env, i, plan); return -EINVAL; } @@ -3237,7 +3348,7 @@ bool bpf_pads_conflict(struct bpf_verifier_env *env, const struct bpf_insn_aux_d const struct bpf_pad_plan *plan; for (plan = aux->pad_plans; plan; plan = plan->next) - if (plan->used && plan->conflict && bpf_pad_must_unwind(env, plan)) + if (plan->used && plan_rejects(env, plan)) return true; return false; } @@ -3262,6 +3373,17 @@ static bool jump_leaves_loop(struct bpf_verifier_env *env, int h, int n) !loop_is_in(env, bpf_loop_at_index(env, n + 1), h); } +/* The pass left a frame at the insn of @aux, may_goto of the program */ +static bool left_at_insn(const struct bpf_insn_aux_data *aux) +{ + const struct bpf_pad_plan *plan; + + for (plan = aux->pad_plans; plan; plan = plan->next) + if (plan->visited && plan->kind == BPF_SITE_MAY_GOTO) + return true; + return false; +} + /* * The landing pad of the call of @plan has a conflict, and that is an error: what the call calls * is unwound. Where that is at may_goto that the verifier adds, it depends on the @@ -3279,6 +3401,11 @@ static bool jump_leaves_loop(struct bpf_verifier_env *env, int h, int n) * Kept apart, neither call is cancelled. The calls do not say what to keep apart, because their * arguments are constants, so the causes are recorded in the callee. * + * may_goto of the program leaves a function as well. The dependencies of the next pass know exit, + * unwind_exit and bpf_throw() as the ways out of a function, and none of these stands for such an + * insn. Where only the calls together get to it, the jumps that can skip it are the cause: the insn + * is noted, and they are what controls it. + * * No pass that keeps more apart gives the frame of the call a place for a pointer that it passed * on and kept no copy of, or a way to tell whether the callee has released it. Where that is the * conflict, see conflict_of_ref(), and the callee is one that releases what the call could hand @@ -3364,6 +3491,8 @@ static void note_causes_below(struct bpf_verifier_env *env) for (s = 0; s < cnt; s++) { guards = false; for (i = sub[s].start; sub[s].below_conflict && i < sub[s + 1].start; i++) { + if (left_at_insn(&aux[i])) + bpf_note_controlled_cause(env, i); if (!aux[i].loop_guard || bpf_flow_guard_is_guess(env, i)) continue; h = bpf_loop_at_index(env, i); @@ -3403,8 +3532,7 @@ void bpf_pads_note_causes(struct bpf_verifier_env *env) env->ref_conflict = false; for (i = 0; i < env->prog->len; i++) for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next) - if (plan->failed || (plan->used && plan->conflict && - bpf_pad_must_unwind(env, plan))) + if (plan->failed || (plan->used && plan_rejects(env, plan))) note_causes(env, i, plan); note_causes_below(env); /* The caller checks the limits before the next pass. This is for a load that ends here. */ diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index f5bc401bce87..2141cef41a88 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -225,6 +225,8 @@ static inline bool in_sleepable_context(struct bpf_verifier_env *env); static bool in_rcu_callback(struct bpf_verifier_env *env); static const char *non_sleepable_context_description(struct bpf_verifier_env *env); static int check_arena_site(struct bpf_verifier_env *env, const struct bpf_reg_state *reg); +static int check_may_goto_site(struct bpf_verifier_env *env); +static void stuck_frame_calls(struct bpf_verifier_env *env, int subprog); static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, struct bpf_map *map, @@ -3421,9 +3423,14 @@ static int subprog_cannot_unwind(struct bpf_verifier_env *env, int subprog) env->insn_idx, bpf_subprog_name(env, subprog)); return -EINVAL; } - /* It did at accesses to arena only. They are skipped, and the pass is done again. */ - env->faults_late |= did_unwind; + /* + * It did at accesses to arena, which are skipped, and at may_goto of the program, which + * jumps where the program says, see check_may_goto_site(). The pass is done again. + */ + env->faults_late |= did_unwind || + ((sub->may_goto_unwinds || sub->made_calls) && !sub->stuck); sub->bail_unwinds = false; + sub->stuck = true; return 0; } @@ -3468,6 +3475,51 @@ static void mark_unwind_above(struct bpf_verifier_env *env) } while (changed); } +/* + * A global subprog that has a may_goto of the program, or that calls a subprog which has one, is + * cancelled there when the time is up, see check_may_goto_site(). Its callers are verified before + * it. Mark it before the first pass, so that the pass does not have to start again to tell them. + */ +static int expect_may_goto_unwinds(struct bpf_verifier_env *env) +{ + struct bpf_subprog_info *si = env->subprog_info; + struct bpf_insn *insn = env->prog->insnsi; + int i, k, s, c, cnt = env->subprog_cnt, err = 0; + unsigned long *soft; + bool changed; + + if (!env->prog->jit_requested || !bpf_jit_supports_timed_may_goto() || + bpf_prog_is_offloaded(env->prog->aux)) + return 0; + soft = bitmap_zalloc(cnt, BPF_VERIFIER_GFP); + if (!soft) + return -ENOMEM; + for (i = 0; i < env->prog->len; i++) + if (bpf_is_may_goto_insn(&insn[i]) && !env->insn_aux_data[i].may_goto_nop) + __set_bit(bpf_find_containing_subprog(env, i) - si, soft); + /* Callees come first in the order, so only a cycle of calls needs a second round. */ + do { + changed = false; + err = bpf_add_cost_and_check(env, env->prog->len, BPF_COST_SCAN); + for (k = 0; k < cnt && !err; k++) { + c = env->subprog_topo_order[k]; + for (i = si[c].start; i < si[c + 1].start && !test_bit(c, soft); i++) { + if (!bpf_pseudo_call(&insn[i])) + continue; + s = bpf_find_subprog(env, i + insn[i].imm + 1); + if (s < 0 || !test_bit(s, soft)) + continue; + __set_bit(c, soft); + changed = true; + } + } + } while (changed); + for_each_set_bit(s, soft, cnt) + si[s].did_unwind |= si[s].bail_unwinds && bpf_subprog_is_global(env, s); + bitmap_free(soft); + return err; +} + /* * 'call foo; unwind_goto pad' goes to the pad when foo left with unwind_exit. * JITs don't emit a branch for it. unwind_exit finds the pad by its return @@ -11817,6 +11869,7 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins err = record_callx_edge(env, caller->subprogno, subprog); if (err) return err; + stuck_frame_calls(env, subprog); if (!bpf_pseudo_kfunc_call(insn) && (insn->imm == BPF_FUNC_loop || insn->imm == BPF_FUNC_for_each_map_elem)) @@ -12286,6 +12339,7 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, return err; if (err == -ENODATA) return -EINVAL; + stuck_frame_calls(env, subprog); if (bpf_subprog_is_global(env, subprog)) { struct bpf_func_info_aux *sub_aux = subprog_aux(env, subprog); const char *sub_name = bpf_subprog_name(env, subprog); @@ -12418,6 +12472,7 @@ static int check_func_callx_one(struct bpf_verifier_env *env, int subprog, int * err = record_callx_edge(env, cur_func(env)->subprogno, subprog); if (err) return err; + stuck_frame_calls(env, subprog); env->subprog_info[subprog].via_callx = true; return check_static_func_call(env, subprog, insn_idx); @@ -19850,6 +19905,11 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env, struct bpf_verifier_state *queued_st; int idx = *insn_idx; + /* At a site the frame is cancelled here, and no state takes the jump. */ + err = check_may_goto_site(env); + if (err) + return min(err, 0); + /* branch out 'fallthrough' insn as a new state to explore */ queued_st = push_stack(env, idx + 1, idx, false); if (IS_ERR(queued_st)) @@ -21967,6 +22027,39 @@ static enum bpf_pad_conflict frame_cannot_unwind(struct bpf_verifier_env *env, return BPF_NO_CONFLICT; } +/* + * An insn of the program enters @subprog from the current frame: a call, callx, a helper or a + * kfunc that has a landing pad for its callback. If the frame cannot unwind, or is a frame of a + * subprog whose may_goto stays and that has a caller in the program, then what comes back + * unwound to the call may have nowhere to go. So may_goto of @subprog stays too, see + * check_may_goto_site(): from this call on, before a state gets to its may_goto and makes a + * conflict there, or at another call of @subprog, that is none. That closes the answer over what + * a subprog that cannot unwind calls, call by call as the pass gets to them. If a state has left + * @subprog before, the pass is done again. The same if a frame of @subprog has made a call before: + * what it called was not told, and the function may not be walked again, since the call of a + * function on its own that an instance subsumes waits for the exits of that instance. A state that + * came back unwound from there can have ended in a conflict at the call, which leaves no other + * trace in @subprog. + * @subprog still unwinds where there is no other way out. A state that does so on the way from + * this call is an error at the call, see unwind_frame(). + */ +static void stuck_frame_calls(struct bpf_verifier_env *env, int subprog) +{ + struct bpf_subprog_info *caller = &env->subprog_info[cur_func(env)->subprogno]; + struct bpf_subprog_info *sub = &env->subprog_info[subprog]; + const struct bpf_verifier_state *st = env->cur_state; + + if (sub->stuck) + return; + if (!frame_cannot_unwind(env, st) && (!caller->stuck || frame_is_top(st))) { + caller->made_calls = true; + return; + } + env->faults_late |= sub->may_goto_unwinds || sub->made_calls || + (sub->did_unwind && sub->bail_unwinds); + sub->stuck = true; +} + /* This insn is a site of @kind. Push a copy of the current state that leaves its frame here. */ static int push_unwind_edge(struct bpf_verifier_env *env, enum bpf_site_kind kind) { @@ -22028,6 +22121,37 @@ static int check_loop_guard(struct bpf_verifier_env *env) return err; } +/* + * The insn is a may_goto of the program (can_loop, cond_break). When its time is up, the kernel + * cancels the program here, as at a may_goto that the verifier adds: a copy of the state leaves the + * frame, see unwind_frame(), and no state takes the jump. The jump stays an edge of the control + * flow graph and of liveness, so what the program reads only at the target is live here. + * + * Returns 1 if the frame is cancelled here. Returns 0 if the insn stays a plain jump: it jumps + * over nothing, see bpf_mark_may_goto_nops(), no JIT runs the timed form (BPF_MAX_LOOPS trips are + * a bound of the loop, not a time-out), or its function cannot be cancelled ('stuck'). An insn is + * rewritten in one way, so the mark holds for all frames of the function, and the pass is repeated + * if the mark comes late. + */ +static int check_may_goto_site(struct bpf_verifier_env *env) +{ + struct bpf_subprog_info *sub = &env->subprog_info[cur_func(env)->subprogno]; + int err; + + if (cur_aux(env)->may_goto_nop || !env->prog->jit_requested || + !bpf_jit_supports_timed_may_goto() || bpf_prog_is_offloaded(env->prog->aux)) + return 0; + if (sub->stuck || frame_cannot_unwind(env, env->cur_state)) { + env->faults_late |= (sub->may_goto_unwinds || sub->made_calls) && + !sub->stuck; + sub->stuck = true; + return 0; + } + sub->may_goto_unwinds = true; + err = push_unwind_edge(env, BPF_SITE_MAY_GOTO); + return err ?: 1; +} + /* Is all that the current frame of @st holds a pointer, which is NULL where nothing is held? */ static bool frame_holds_pointers_only(const struct bpf_verifier_state *st) { @@ -22220,9 +22344,11 @@ static bool site_is_certain(struct bpf_verifier_env *env, const struct bpf_pad_p * * With a conflict there is no pad: the site is an unproven insn in @st, which ends here. The pass * goes on, and a pass that keeps more apart may have no such state. - * A frame that cannot unwind is a conflict. At an access to arena check_arena_site() saw to both. + * A frame that cannot unwind is a conflict. At an access to arena check_arena_site() saw to both, + * and at may_goto of the program check_may_goto_site() saw to it: the jump is taken there. * At a call that has only such accesses below it a conflict is no error: @st is dropped, and - * bpf_pads_settle() has the accesses skipped. + * bpf_pads_settle() has the accesses skipped. The same at a call in a frame that cannot unwind, if + * what comes back to it has another way out: the callees are made unable to unwind. * Nor is it one at a site that the program may not have in the end, see site_is_certain(): @st is * dropped, the plan keeps the conflict, and bpf_pads_settle() makes it an error of the pass if the * site is still there. @@ -22235,7 +22361,8 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state struct bpf_verifier_state *cur = env->cur_state; int cur_idx = env->insn_idx, err = 0; struct bpf_pad_plan *plan = NULL; - bool print_state, certain = false; + bool print_state, certain = false, stuck; + enum bpf_pad_conflict conflict; u32 cnt; env->cur_state = st; @@ -22247,14 +22374,25 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state err = PTR_ERR_OR_ZERO(plan); if (err) goto out; - if (!plan->conflict) - plan->conflict = frame_cannot_unwind(env, st); + conflict = frame_cannot_unwind(env, st); + /* + * The frame cannot be cancelled. If the site can be skipped, that replaces any + * other reason: no landing pad runs in this frame, see bpf_pads_settle(). + */ + if (conflict && (!plan->conflict || !bpf_pad_must_unwind(env, plan))) + plan->conflict = conflict; if (!plan->conflict && bpf_site_has_value(env, kind) && frame->regs[bpf_site_value_reg(kind)].type != SCALAR_VALUE) plan->conflict = BPF_CONFLICT_NO_VALUE; certain = site_is_certain(env, plan, insn_idx); - /* there is no other way out */ - if (plan->conflict && bpf_pad_must_unwind(env, plan) && certain) { + stuck = plan->conflict == BPF_CONFLICT_CANNOT_UNWIND || + plan->conflict == BPF_CONFLICT_NO_EXIT; + /* + * There is no other way out. Not for may_goto of the program and a call above it + * either, but in a subprog that cannot unwind, and whether it is one may be found + * later in the pass. Then this error was none, see do_check_all(). + */ + if (plan->conflict && certain && (bpf_pad_must_unwind(env, plan) || !stuck)) { bpf_pad_log(env, insn_idx, plan); /* for bpf_pads_note_causes() */ plan->failed = true; @@ -22291,8 +22429,10 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state env->pads_late = true; } sub->did_unwind |= st->unwound; + if (st->unwound) + bpf_pad_note_left(env, sub, plan, kind); sub->must_unwind |= st->unwound && plan && bpf_pad_must_unwind(env, plan); - sub->unwinds_for_sure |= st->unwound && plan && bpf_pad_must_unwind(env, plan) && certain; + sub->unwinds_for_sure |= st->unwound && plan && certain; if (env->log.level & BPF_LOG_LEVEL2) verbose(env, "from %d to %s of func#%d\n", insn_idx, st->unwound ? "unwind_exit" : "exit", frame->subprogno); @@ -24487,7 +24627,7 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia if (bpf_subprog_is_global(env, i)) initial->subprogs[i].did_unwind |= env->subprog_info[i].did_unwind; /* - * The accesses to arena in it are skipped and the pass is done again, see + * The accesses to arena in it are skipped, and the pass is done again, see * subprog_cannot_unwind() and skip_faults(). The second run has to know from its * start that the subprog cannot unwind, or it finds out late once more. * No other run knows: like all else about a subprog that is what one pass finds. A @@ -24500,6 +24640,14 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia initial->subprogs[i].bail_unwinds_at_first; else if (env->faults_late) initial->subprogs[i].bail_unwinds &= env->subprog_info[i].bail_unwinds; + /* + * Its may_goto jumps where the program says, see check_may_goto_site() and + * stuck_frame_calls(). That is what it did before the verifier unwound programs + * there, so it is safe to keep in every run that follows: a run that had to find + * it again could end at an error which is none before it gets to the call that + * tells. + */ + initial->subprogs[i].stuck |= env->subprog_info[i].stuck; /* releases_args adds up. asks_args is that of the last pass with an error. */ initial->subprogs[i].releases_args |= env->subprog_info[i].releases_args; initial->subprogs[i].asks_args = env->subprog_info[i].asks_args; @@ -24794,6 +24942,20 @@ static int do_check_all(struct bpf_verifier_env *env) err = ret; break; } + /* + * The run has an error, and it found late what a run has to know from its start, + * see check_arena_site(). Mostly that a subprog cannot unwind: its may_goto jumps + * where the program says, and the states that left it there went where no run of + * the program goes. A conflict at such a site or at a call above it was none, and + * neither was what such a state ran into on its way. The run that follows knows + * from its start. + */ + if (ret && env->faults_late && !env->over_limit) { + /* Drop the log of that error. */ + restart_log(env, &log); + env->pass_again = true; + continue; + } more = bpf_undo_precision(env); if (more > 0) continue; @@ -26963,6 +27125,11 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, if (ret < 0) goto skip_full_check; + bpf_mark_may_goto_nops(env); + ret = expect_may_goto_unwinds(env); + if (ret < 0) + goto skip_full_check; + ret = bpf_compute_live_registers(env); if (ret < 0) goto skip_full_check; diff --git a/tools/testing/selftests/bpf/prog_tests/may_goto_far.c b/tools/testing/selftests/bpf/prog_tests/may_goto_far.c index b6d262911a3e..201cda7cf34b 100644 --- a/tools/testing/selftests/bpf/prog_tests/may_goto_far.c +++ b/tools/testing/selftests/bpf/prog_tests/may_goto_far.c @@ -18,7 +18,7 @@ static struct bpf_insn *fill(struct bpf_insn *insn, int cnt, int reg) * away: * * r6 = r7 = 0, but not a constant for the verifier - * r8 = 2 + * r8 = 3 * r9 = 0 * r0 = r8 x FILL_CNT or 1 * 1: if r6 == r9 goto +1 @@ -31,16 +31,21 @@ static struct bpf_insn *fill(struct bpf_insn *insn, int cnt, int reg) * 3: r0 = r8 x N when off is positive * 4: exit * - * The prog returns 0 when may_goto jumps to its target and 2 when - * it lands in one of 'r0 = r8' areas. There are no constants between - * may_goto and its target to keep the distance when constants are blinded. + * When may_goto expires the prog is unwound: the insn does not go to the + * target that the program gives it, but to a landing pad behind the last + * insn, which is far too. It is a tc prog: it returns 2, TC_ACT_SHOT, when + * may_goto jumps to the pad, 3 when it lands in one of the 'r0 = r8' areas, + * and 0, which r0 has in the loop, when it lands on an exit: the last one + * is one insn short of the pad. There are no constants between may_goto + * and its target to keep the distance when constants are blinded. * * With 'subprog' all of that is a subprog. */ static void test_far(int off, bool subprog) { - LIBBPF_OPTS(bpf_prog_load_opts, opts, .prog_flags = BPF_F_SLEEPABLE); - LIBBPF_OPTS(bpf_test_run_opts, topts); + LIBBPF_OPTS(bpf_prog_load_opts, opts); + char pkt[64] = {}; + LIBBPF_OPTS(bpf_test_run_opts, topts, .data_in = pkt, .data_size_in = sizeof(pkt)); int front = off < 0 ? 1 : FILL_CNT; int mid = off < 0 ? -off - 5 : 1; int back = off < 0 ? FILL_CNT : off - 1; @@ -61,7 +66,7 @@ static void test_far(int off, bool subprog) *insn++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_6, 63); *insn++ = BPF_MOV64_REG(BPF_REG_7, BPF_REG_0); *insn++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_7, 63); - *insn++ = BPF_MOV64_IMM(BPF_REG_8, 2); + *insn++ = BPF_MOV64_IMM(BPF_REG_8, 3); *insn++ = BPF_MOV64_IMM(BPF_REG_9, 0); insn = fill(insn, front, BPF_REG_8); *insn++ = BPF_JMP_REG(BPF_JEQ, BPF_REG_6, BPF_REG_9, 1); @@ -74,14 +79,14 @@ static void test_far(int off, bool subprog) insn = fill(insn, back, BPF_REG_8); *insn++ = BPF_EXIT_INSN(); - fd = bpf_prog_load(BPF_PROG_TYPE_SYSCALL, NULL, "GPL", insns, insn - insns, &opts); + fd = bpf_prog_load(BPF_PROG_TYPE_SCHED_CLS, NULL, "GPL", insns, insn - insns, &opts); free(insns); if (!ASSERT_GE(fd, 0, "prog_load")) return; err = bpf_prog_test_run_opts(fd, &topts); ASSERT_OK(err, "test_run"); - ASSERT_EQ(topts.retval, 0, "retval"); + ASSERT_EQ(topts.retval, 2, "retval"); close(fd); } diff --git a/tools/testing/selftests/bpf/prog_tests/timed_may_goto.c b/tools/testing/selftests/bpf/prog_tests/timed_may_goto.c index 3da3f33a2898..8f46e6a096ec 100644 --- a/tools/testing/selftests/bpf/prog_tests/timed_may_goto.c +++ b/tools/testing/selftests/bpf/prog_tests/timed_may_goto.c @@ -42,7 +42,7 @@ static void wait_for(int *val, int expected, const char *name) static void test_async(struct timed_may_goto_user *skel) { - ASSERT_EQ(run_syscall(skel->progs.async_after_timeout), 0, "async_after_timeout"); + ASSERT_EQ(run_syscall(skel->progs.async_after_timeout), -ECANCELED, "async_after_timeout"); wait_for(&skel->bss->timer_cnt, 1000, "timer_cnt"); wait_for(&skel->bss->wq_cnt, 1000, "wq_cnt"); wait_for(&skel->bss->tw_cnt, 1000, "tw_cnt"); @@ -50,10 +50,23 @@ static void test_async(struct timed_may_goto_user *skel) wait_for(&skel->bss->rcu_trace_cnt, 1000, "rcu_trace_cnt"); } +static long now_ms(void) +{ + struct timespec ts; + + clock_gettime(CLOCK_MONOTONIC, &ts); + return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; +} + static void test_timer_on_top(struct timed_may_goto_user *skel) { - int ms = run_syscall(skel->progs.spin_under_timer); - int ticks = skel->bss->ticks; + long ms = now_ms(); + int ticks; + + /* the prog is unwound */ + ASSERT_EQ(run_syscall(skel->progs.spin_under_timer), -ECANCELED, "spin_under_timer"); + ms = now_ms() - ms; + ticks = skel->bss->ticks; /* stop the timer */ skel->bss->ticks = 100; @@ -68,21 +81,37 @@ static void test_freplace(struct timed_may_goto_user *skel) { struct timed_may_goto_ext *ext; - ASSERT_EQ(run_tc(skel->progs.freplace_target), 1, "not replaced"); + /* replaced_global() is unwound, and the prog with it */ + ASSERT_EQ(run_tc(skel->progs.freplace_target), 2, "not replaced"); + /* so it cannot be replaced */ ext = timed_may_goto_ext__open(); if (!ASSERT_OK_PTR(ext, "ext_open")) return; bpf_program__set_attach_target(ext->progs.replacement, bpf_program__fd(skel->progs.freplace_target), "replaced_global"); + ASSERT_ERR(timed_may_goto_ext__load(ext), "ext_load of what can unwind"); + timed_may_goto_ext__destroy(ext); + + ASSERT_EQ(run_tc(skel->progs.freplace_plain_target), 10, "not replaced"); + ext = timed_may_goto_ext__open(); + if (!ASSERT_OK_PTR(ext, "ext_open")) + return; + bpf_program__set_attach_target(ext->progs.replacement, + bpf_program__fd(skel->progs.freplace_plain_target), + "plain_global"); if (!ASSERT_OK(timed_may_goto_ext__load(ext), "ext_load") || !ASSERT_OK(timed_may_goto_ext__attach(ext), "ext_attach")) goto out; - ASSERT_EQ(run_tc(skel->progs.freplace_target), TRIES, "replaced"); + /* Each call of the extension spins, is unwound and returns 2 into the prog, which goes on */ + ASSERT_EQ(run_tc(skel->progs.freplace_plain_target), 10 + TRIES * 2, "replaced"); + /* and each call had its time: a short loop came to its end before the call used it up */ + ASSERT_EQ(ext->bss->calls, TRIES, "calls of the extension"); + ASSERT_EQ(ext->bss->counted_to_1000, TRIES, "a slice per call"); out: timed_may_goto_ext__destroy(ext); - ASSERT_EQ(run_tc(skel->progs.freplace_target), 1, "not replaced"); + ASSERT_EQ(run_tc(skel->progs.freplace_plain_target), 10, "not replaced"); } /* What a prog leaves behind when its time is up doesn't matter for the next one on the cpu. */ @@ -94,14 +123,29 @@ static void test_tail_call_and_throw(struct timed_may_goto_user *skel) if (!ASSERT_OK(bpf_map_update_elem(map_fd, &key, &fd, 0), "update")) return; - ASSERT_EQ(run_tc(skel->progs.normal_prog), 1, "normal_prog"); - ASSERT_EQ(run_tc(skel->progs.normal_prog), 1, "normal_prog"); - - ASSERT_EQ(run_tc(skel->progs.tail_call_in_subprog), 1, "tail_call_in_subprog"); - ASSERT_EQ(skel->bss->tail_callee_spun, 1, "tail_callee_spun"); - - ASSERT_EQ(run_tc(skel->progs.tail_call_after_timeout), 0, "tail_call_after_timeout"); - ASSERT_EQ(skel->bss->tail_callee_spun, 1, "tail_callee_spun"); + /* + * Each run has its time: the loop counts to 1000, then the prog is unwound. With the count + * that the run before left behind the prog would be unwound in the short loop, which 2 + * does not tell: the prog stores what it counted. + */ + skel->bss->normal_cnt = -1; + ASSERT_EQ(run_tc(skel->progs.normal_prog), 2, "normal_prog"); + ASSERT_EQ(skel->bss->normal_cnt, 1000, "normal_cnt"); + skel->bss->normal_cnt = -1; + ASSERT_EQ(run_tc(skel->progs.normal_prog), 2, "normal_prog"); + ASSERT_EQ(skel->bss->normal_cnt, 1000, "normal_cnt, second run"); + + /* the callee is unwound and returns 2 into the subprog of its caller, which goes on */ + skel->bss->tail_callee_cnt = -1; + ASSERT_EQ(run_tc(skel->progs.tail_call_in_subprog), 12, "tail_call_in_subprog"); + ASSERT_EQ(skel->bss->tail_callee_runs, 1, "tail_callee_runs"); + ASSERT_EQ(skel->bss->tail_callee_cnt, 1000, "tail_callee_cnt"); + + /* the callee has its time when its caller has none left: it counts, then it is unwound */ + skel->bss->tail_callee_cnt = -1; + ASSERT_EQ(run_tc(skel->progs.tail_call_after_timeout), 2, "tail_call_after_timeout"); + ASSERT_EQ(skel->bss->tail_callee_runs, 2, "tail_callee_runs"); + ASSERT_EQ(skel->bss->tail_callee_cnt, 1000, "tail_callee_cnt, caller out of time"); ASSERT_EQ(run_tc(skel->progs.throw_after_timeout), 7, "throw_after_timeout"); ASSERT_EQ(run_tc(skel->progs.throw_after_timeout), 7, "throw_after_timeout"); @@ -122,8 +166,13 @@ static void test_user_ringbuf(struct timed_may_goto_user *skel) goto out; user_ring_buffer__submit(rb, sample); } - /* The helper takes a sample out of the buffer for each call: all calls have to run. */ - ASSERT_EQ(run_syscall(skel->progs.drain), TRIES * 10 + 1, "drain"); + /* + * The helper takes a sample out of the buffer for each call. The callback is unwound in + * each run, and its sample is gone like one of a callback that returns. + */ + for (i = 0; i < TRIES; i++) + ASSERT_EQ(run_syscall(skel->progs.drain), -ECANCELED, "drain"); + ASSERT_EQ(run_syscall(skel->progs.drain), 100, "drain of no samples"); out: user_ring_buffer__free(rb); } @@ -137,9 +186,13 @@ static void test_priv_stack(struct timed_may_goto_user *skel) link = bpf_program__attach(skel->progs.priv_stack); if (!ASSERT_OK_PTR(link, "attach")) return; + skel->bss->priv_stack_spun = skel->bss->priv_stack_cb_spun = -1; + /* unwound in the first call: the prog does not get to what follows its loop */ + ASSERT_OK(bpf_prog_test_run_opts(fd, &opts), "test_run"); ASSERT_OK(bpf_prog_test_run_opts(fd, &opts), "test_run"); - ASSERT_EQ(skel->bss->priv_stack_spun, 1, "priv_stack_spun"); - ASSERT_EQ(skel->bss->priv_stack_cb_spun, 0, "priv_stack_cb_spun"); + ASSERT_EQ(skel->bss->priv_stack_runs, 2, "priv_stack_runs"); + ASSERT_EQ(skel->bss->priv_stack_spun, -1, "priv_stack_spun"); + ASSERT_EQ(skel->bss->priv_stack_cb_spun, -1, "priv_stack_cb_spun"); bpf_link__destroy(link); } diff --git a/tools/testing/selftests/bpf/progs/may_goto_priv_stack.c b/tools/testing/selftests/bpf/progs/may_goto_priv_stack.c index 5c2aa0aa5055..d842cf5c966d 100644 --- a/tools/testing/selftests/bpf/progs/may_goto_priv_stack.c +++ b/tools/testing/selftests/bpf/progs/may_goto_priv_stack.c @@ -5,13 +5,15 @@ #include "../../../include/linux/filter.h" #include "bpf_misc.h" -/* r0-r5 after the loop and the number of iterations */ +/* r0-r5 in the last trip of the loop and the number of iterations */ __u64 regs_64[7]; __u64 regs_128[7]; /* * fentry prog with 64 or more bytes of stack uses private stack. * Loop until may_goto expires. r0-r5 should stay zero. + * When may_goto expires the prog is unwound: what follows the loop does not run, so each trip + * stores the registers. */ #define TIMED_MAY_GOTO_PRIV_STACK(size, func) \ SEC("fentry/" #func) \ @@ -30,7 +32,6 @@ __naked void priv_stack_##size(void) \ "1:" \ ".8byte %[may_goto];" \ "r6 += 1;" \ - "goto 1b;" \ "*(u64 *)(r7 + 0) = r0;" \ "*(u64 *)(r7 + 8) = r1;" \ "*(u64 *)(r7 + 16) = r2;" \ @@ -38,11 +39,12 @@ __naked void priv_stack_##size(void) \ "*(u64 *)(r7 + 32) = r4;" \ "*(u64 *)(r7 + 40) = r5;" \ "*(u64 *)(r7 + 48) = r6;" \ + "goto 1b;" \ "r0 = 0;" \ "exit;" \ : \ : [regs]"i"(®s_##size), \ - __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 2, 0)) \ + __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 9, 0)) \ : __clobber_all); \ } diff --git a/tools/testing/selftests/bpf/progs/stream.c b/tools/testing/selftests/bpf/progs/stream.c index 949c1b2fa6c0..68c2c80d7edf 100644 --- a/tools/testing/selftests/bpf/progs/stream.c +++ b/tools/testing/selftests/bpf/progs/stream.c @@ -74,7 +74,7 @@ __arch_arm64 __arch_s390x __arch_riscv64 __arch_loongarch -__success __retval(0) +__success __retval(-ECANCELED) __stderr("ERROR: Timeout detected for may_goto instruction") __stderr("CPU: {{[0-9]+}} UID: 0 PID: {{[0-9]+}} Comm: {{.*}}") __stderr("Call trace:\n" diff --git a/tools/testing/selftests/bpf/progs/timed_may_goto.c b/tools/testing/selftests/bpf/progs/timed_may_goto.c index c1c48af808a9..e01b7e727707 100644 --- a/tools/testing/selftests/bpf/progs/timed_may_goto.c +++ b/tools/testing/selftests/bpf/progs/timed_may_goto.c @@ -3,8 +3,14 @@ * There is one time slice of may_goto for an invocation of a prog: one call from the kernel into * the main prog, with the subprogs and sync callbacks that it reaches. * - * Most tests call a function that spins until may_goto stops it, four times, each in a different - * way. Only the first call can spin. With a time slice for each call all four do. + * When it is up may_goto ends the invocation: the prog is unwound, and returns what an unwound + * prog of its type returns. That is 2, TC_ACT_SHOT, for tc and 0 for a socket filter or a + * tracing prog. Most tests call a function that spins until may_goto stops it, four times, each + * in a different way. The first call ends the prog. With a time slice for each call the prog would + * go on for a second, or for ever. + * + * Where a subprog cannot unwind may_goto jumps where the program says and the prog goes on, see + * time_is_up(). The tests of what follows then use it. */ #include #include @@ -44,36 +50,124 @@ static __noinline int counts_to_1000(void) return cnt; } +/* The prog is unwound in the first call. If it went on it would return 11, or 14. */ SEC("tc") __description("timed may_goto: call") -__success __retval(1) +__success __retval(2) int call_subprog(void *ctx) { - int i, n = 0; + int i, n = 10; for (i = 0; i < TRIES; i++) n += spins(); return n; } +/* + * A subprog that cannot unwind: the comparator of bpf_rbtree_add() for a node that takes a lock + * when it is freed, and what the comparator calls. There may_goto jumps where the program says. + */ +struct item { + struct bpf_list_node link; +}; + +struct stuck_node { + struct bpf_rb_node rb; + struct bpf_spin_lock lock; + struct bpf_list_head items __contains(item, link); +}; + +#define private(name) SEC(".data." #name) __hidden __attribute__((aligned(8))) +private(S) struct bpf_spin_lock stuck_lock; +private(S) struct bpf_rb_root stuck_root __contains(stuck_node, rb); + +/* No code has an item: this puts it in BTF, for __contains() above */ +void __item_btf_root(struct item *i) +{ +} + +long stuck_ret; + +/* Add two nodes, so that @less runs one time, and take them out again. Returns 0. */ +static __always_inline int run_stuck(bool (less)(struct bpf_rb_node *a, + const struct bpf_rb_node *b)) +{ + struct bpf_rb_node *rb; + struct stuck_node *n; + int i; + + for (i = 0; i < 2; i++) { + n = bpf_obj_new(typeof(*n)); + if (!n) + return 100; + bpf_spin_lock(&stuck_lock); + bpf_rbtree_add(&stuck_root, &n->rb, less); + bpf_spin_unlock(&stuck_lock); + } + for (i = 0; i < 2; i++) { + bpf_spin_lock(&stuck_lock); + rb = bpf_rbtree_first(&stuck_root); + rb = rb ? bpf_rbtree_remove(&stuck_root, rb) : NULL; + bpf_spin_unlock(&stuck_lock); + if (!rb) + return 101; + bpf_obj_drop(container_of(rb, struct stuck_node, rb)); + } + return 0; +} + +/* no helpers under the lock: the loop counts its trips, a million of them take no 250 ms */ +static __always_inline int spin_stuck(void) +{ + long n = zero; + + while (can_loop) + n++; + return n > 1000 * 1000; +} + +static bool less_uses_up_time(struct bpf_rb_node *a, const struct bpf_rb_node *b) +{ + stuck_ret = spin_stuck(); + return false; +} + +/* + * Use up the time of the invocation where the prog is not unwound for it. The prog goes on, until + * the next may_goto in a subprog that can unwind. Returns 0. + */ +static __always_inline int time_is_up(void) +{ + return run_stuck(less_uses_up_time) ?: !stuck_ret; +} + +static bool less_counts_after_timeout(struct bpf_rb_node *a, const struct bpf_rb_node *b) +{ + spin_stuck(); + stuck_ret = counts_to_1000(); + return false; +} + +/* Both loops are in a subprog that cannot unwind */ SEC("tc") __description("timed may_goto: a call after the time is up makes no iteration") -__success __retval(0) +__success __retval(10) int short_loop_after_timeout(void *ctx) { - spins(); - return counts_to_1000(); + stuck_ret = -1; + return run_stuck(less_counts_after_timeout) ?: 10 + stuck_ret; } +/* The loop of the main prog can unwind: it does, in the trip after the time was used up */ SEC("tc") -__description("timed may_goto: the loop of the main prog stops when the time is up in a subprog") -__success __retval(1) +__description("timed may_goto: the loop of the main prog ends the prog when the time is up in a subprog that cannot unwind") +__success __retval(2) int main_loop_after_timeout(void *ctx) { - int n = 0; + int n = 10; - while (can_loop && n < 2 * TRIES) - n += spins(); + while (can_loop && n < 10 + 2 * TRIES) + n += time_is_up() + 1; return n; } @@ -84,10 +178,10 @@ static __noinline int passes(int i) SEC("tc") __description("timed may_goto: call through a function without a loop") -__success __retval(1) +__success __retval(2) int call_through(void *ctx) { - int i, n = 0; + int i, n = 10; for (i = 0; i < TRIES; i++) n += passes(zero); @@ -101,10 +195,10 @@ __noinline int global_spins(void) SEC("tc") __description("timed may_goto: call of a global function") -__success __retval(1) +__success __retval(2) int call_global(void *ctx) { - int i, n = 0; + int i, n = 10; for (i = 0; i < TRIES; i++) n += global_spins(); @@ -113,11 +207,11 @@ int call_global(void *ctx) SEC("tc") __description("timed may_goto: callx") -__success __retval(1) +__success __retval(2) __naked void callx_subprog(void) { asm volatile ( - "r6 = 0;" + "r6 = 10;" "r7 = 0;" "1:" "r3 = %[spins] ll;" @@ -139,12 +233,13 @@ static int loop_cb(__u64 i, int *spun) return *spun > 2 * TRIES; } +/* The callback is unwound, and the helper and the prog with it */ SEC("tc") __description("timed may_goto: bpf_loop() inlined") -__success __retval(1) +__success __retval(2) int loop_inlined(void *ctx) { - int spun = 0; + int spun = 10; bpf_loop(1 << 20, loop_cb, &spun, 0); return spun; @@ -152,10 +247,10 @@ int loop_inlined(void *ctx) SEC("tc") __description("timed may_goto: bpf_loop() not inlined") -__success __retval(1) +__success __retval(2) int loop_not_inlined(void *ctx) { - int spun = 0; + int spun = 10; bpf_loop(1 << 20, loop_cb, &spun, zero); return spun; @@ -167,7 +262,10 @@ static int count_cb(__u64 i, int *calls) return 0; } -/* The time is up: the helper calls the callback one more time. It returns 1 in its first insns. */ +/* + * The time is up: the helper calls the callback one more time. It returns 1 in its first insns. + * The callback has no may_goto and the prog has none after the time is up: nothing is unwound. + */ #define LOOP_ENDS(name, flags) \ SEC("tc") \ __description("timed may_goto: bpf_loop() " #name " ends when the time is up") \ @@ -176,7 +274,8 @@ int loop_ends_##name(void *ctx) \ { \ int calls = 0; \ \ - spins(); \ + if (time_is_up()) \ + return 100; \ return bpf_loop(1000, count_cb, &calls, flags) * 10 + calls; \ } @@ -202,15 +301,16 @@ static int outer_cb(__u64 i, struct nested *n) return bpf_ktime_get_ns() - n->t0 > 1000 * 1000 * 1000; } +/* The inner callback is unwound through both helpers */ SEC("tc") __description("timed may_goto: bpf_loop() in bpf_loop() ends when the time is up") -__success __retval(1) +__success __retval(2) int loop_in_loop(void *ctx) { struct nested n = { .t0 = bpf_ktime_get_ns() }; bpf_loop(1 << 23, outer_cb, &n, 0); - return n.spun && bpf_ktime_get_ns() - n.t0 < 500 * 1000 * 1000; + return 10 + (n.spun && bpf_ktime_get_ns() - n.t0 < 500 * 1000 * 1000); } static __noinline int called_cb(__u64 i, int *calls) @@ -227,7 +327,8 @@ int loop_and_call(void *ctx) { int calls = 0; - spins(); + if (time_is_up()) + return 101; if (called_cb(zero, &calls)) return 100; return bpf_loop(TRIES, called_cb, &calls, 0) * 10 + calls; @@ -244,38 +345,39 @@ static int short_cb(__u64 i, __u64 *t0) /* * The main prog has no may_goto. Each call of the callback ends before it reads the clock. The - * iterations of all calls add up. + * iterations of all calls add up: a call finds that the time is up, and the next one is unwound. + * With a time slice for each call the callback gives up after a second, and the prog returns 10. */ SEC("tc") __description("timed may_goto: bpf_loop() the callback makes 60000 iterations") -__success __retval(1) +__success __retval(2) int loop_short_cb(void *ctx) { __u64 t0 = bpf_ktime_get_ns(); bpf_loop(1 << 20, short_cb, &t0, 0); - return bpf_ktime_get_ns() - t0 < 1000 * 1000 * 1000; + return 10 + (bpf_ktime_get_ns() - t0 < 1000 * 1000 * 1000); } -/* spins() uses up the time. The loop that calls it ends at its next may_goto. */ -static __noinline int loops_around_spins(void) +/* The comparator uses up the time. The loop that got there ends the prog at its next may_goto. */ +static __noinline int loops_around_time_is_up(void) { int n = zero; while (can_loop && n < 20000) { - if (n < 2 * TRIES) - spins(); + if (n < 2 * TRIES && time_is_up()) + return 100; n++; } - return n; + return 10 + n; } SEC("tc") -__description("timed may_goto: a loop that is on the stack ends when the time is up") -__success __retval(1) +__description("timed may_goto: a loop that is on the stack ends the prog when the time is up") +__success __retval(2) int rest_of_batch(void *ctx) { - return loops_around_spins(); + return loops_around_time_is_up(); } static __noinline int one_iteration(void) @@ -308,7 +410,8 @@ static int call_many(__u64 i, __u64 *t0) /* * The iterations of all calls count: the prog reads the clock in each 65535th call. The call that - * finds out that the time is up makes its iteration. + * finds out that the time is up makes its iteration. No may_goto runs after it: the helpers call + * their callbacks one more time, which return 1 in their first insns, and the prog goes on. */ SEC("tc") __description("timed may_goto: 65535 calls that make one iteration read the clock") @@ -334,7 +437,7 @@ struct { \ MAP(array, BPF_MAP_TYPE_ARRAY, 0); MAP(hash, BPF_MAP_TYPE_HASH, 0); -/* The first call uses up the time. The second call ends the loop of the helper. */ +/* The first call uses up the time, and is unwound through the helper */ static int elem_cb(void *map, int *key, int *val, int *spun) { *spun += spin(); @@ -344,10 +447,10 @@ static int elem_cb(void *map, int *key, int *val, int *spun) #define FOR_EACH(name) \ SEC("tc") \ __description("timed may_goto: bpf_for_each_map_elem() " #name) \ -__success __retval(21) \ +__success __retval(2) \ int for_each_##name(void *ctx) \ { \ - int i, key, spun = 0; \ + int i, key, spun = 100; \ \ for (i = 0; i < TRIES; i++) { \ key = i; \ @@ -365,14 +468,15 @@ static long vma_cb(struct task_struct *task, struct vm_area_struct *vma, int *sp return 0; } +/* An unwound tracing prog returns 0 */ SEC("raw_tp") __description("timed may_goto: bpf_find_vma()") -__success __retval(1) +__success __retval(0) int find_vma(void *ctx) { struct task_struct *task = bpf_get_current_task_btf(); __u64 addr = task->mm->arg_start; - int i, spun = 0; + int i, spun = 10; for (i = 0; i < TRIES; i++) if (bpf_find_vma(task, addr, vma_cb, &spun, 0)) @@ -385,7 +489,6 @@ struct tree_node { int key; }; -#define private(name) SEC(".data." #name) __hidden __attribute__((aligned(8))) private(A) struct bpf_spin_lock lock; private(A) struct bpf_rb_root root __contains(tree_node, rb); @@ -404,9 +507,13 @@ static bool less(struct bpf_rb_node *a, const struct bpf_rb_node *b) container_of(b, struct tree_node, rb)->key; } +/* + * The comparator is unwound: the kfunc drops the node, and the pad of the prog releases the lock. + * The node of the first trip stays in the tree. + */ SEC("tc") __description("timed may_goto: bpf_rbtree_add()") -__success __retval(1) +__success __retval(2) int rbtree_add(void *ctx) { struct bpf_rb_node *rb; @@ -435,7 +542,7 @@ int rbtree_add(void *ctx) } if (less_calls < TRIES - 1) return 102; - return less_spun; + return 10 + less_spun; } /* @@ -619,7 +726,6 @@ static long live_fall_through(void) #define CALL_AND_ADD(f) "call " #f ";" "r6 += r0;" #define CALL_ALL_LIVE \ - "r6 = 0;" \ CALL_AND_ADD(live_r0_r0) \ CALL_AND_ADD(live_r0_r1) \ CALL_AND_ADD(live_r0_r2) \ @@ -645,25 +751,15 @@ __success __retval(840180) __naked void dead_reg(void) { asm volatile ( - CALL_ALL_LIVE - ::: __clobber_all); -} - -/* No iteration: 165, then 6, 6 (the may_goto jumps) and 4 (R2 isn't stored). */ -SEC("tc") -__description("timed may_goto: may_goto takes a register that is dead, the time is up") -__success __retval(181) -__naked void dead_reg_time_is_up(void) -{ - asm volatile ( - "call spins_on_may_goto;" + "r6 = 0;" CALL_ALL_LIVE ::: __clobber_all); } /* - * The subprog uses up the time of the prog and returns. With a time slice for each call the caller - * calls it 65535 times before it reads the clock. + * The subprog uses up the time of the prog. Where it can unwind that ends the prog. Where it + * cannot it returns: with a time slice for each call its caller would call it 65535 times before + * it reads the clock. */ __naked __noinline __used static unsigned long spins_on_may_goto(void) @@ -678,11 +774,37 @@ static unsigned long spins_on_may_goto(void) ::: __clobber_all); } -/* The first may_goto of the function finds that the time is up */ +/* The time is up: each may_goto of these functions jumps in its first trip */ +__naked __noinline __used +static long all_live_time_is_up(void) +{ + asm volatile ( + "call spins_on_may_goto;" + "r6 = r0;" + CALL_ALL_LIVE + ::: __clobber_all); +} + +static bool less_all_live(struct bpf_rb_node *a, const struct bpf_rb_node *b) +{ + stuck_ret = all_live_time_is_up(); + return false; +} + +/* + * In a subprog that cannot unwind, where may_goto jumps. No iteration: 165, then 6, 6 (the + * may_goto jumps) and 4 (R2 isn't stored). + */ SEC("tc") -__description("timed may_goto: registers across may_goto when the time is up") -__success __retval(46) -__naked void regs_when_time_is_up(void) +__description("timed may_goto: may_goto takes a register that is dead, the time is up") +__success __retval(181) +int dead_reg_time_is_up(void *ctx) +{ + return run_stuck(less_all_live) ?: stuck_ret; +} + +__naked __noinline __used +static long regs_time_is_up(void) { asm volatile ( "call spins_on_may_goto;" @@ -696,15 +818,33 @@ __naked void regs_when_time_is_up(void) ::: __clobber_all); } -/* The first insn of the main prog is the target of a jump. It must not set the count again. */ +static bool less_regs(struct bpf_rb_node *a, const struct bpf_rb_node *b) +{ + stuck_ret = regs_time_is_up(); + return false; +} + +/* The same: the first may_goto of the function finds that the time is up */ +SEC("tc") +__description("timed may_goto: registers across may_goto when the time is up") +__success __retval(46) +int regs_when_time_is_up(void *ctx) +{ + return run_stuck(less_regs) ?: stuck_ret; +} + +/* + * The first insn of the main prog is the target of a jump. It must not set the count again: the + * subprog makes 60000 iterations in a call and would never read the clock. + */ SEC("socket") __description("timed may_goto: 9 insns") -__success __retval(1) +__success __retval(0) __naked void loop_calls_subprog_with_may_goto(void) { asm volatile ( "1:" - "call spins_on_may_goto;" + "call loops_60000;" "may_goto 2f;" "goto 1b;" "2:" @@ -716,7 +856,7 @@ __naked void loop_calls_subprog_with_may_goto(void) /* * These subprogs make 60000 iterations in each call. With a read of the clock after 65535 * iterations of a call none of them reads it, and their caller does it after - * 65535 * 60000 * 60000 iterations. + * 65535 * 60000 * 60000 iterations. The prog ends unwound, a socket filter returns 0 then. */ __naked __noinline __used static unsigned long loops_60000(void) @@ -751,7 +891,7 @@ static unsigned long calls_60000_times(void) SEC("socket") __description("timed may_goto: three levels of loops that end before they read the clock") -__success __retval(1) +__success __retval(0) __naked void three_levels_of_short_loops(void) { asm volatile ( @@ -781,41 +921,57 @@ static unsigned long loops_65534(void) ::: __clobber_all); } +/* + * The iterations of the callee count for the prog: it reads the clock in each 65535th of them, and + * is unwound when the time is up. With a count for each frame only the calls would count, the + * time would be up after 2^32 iterations, and the prog gives up after a second: 3. + * It gives up at the third round that finds the second over. Each round has one read of the clock + * by may_goto, so the round after a stall of the guest, however long, is one that unwinds the prog. + */ SEC("socket") __description("timed may_goto: the subprog makes 65534 iterations") -__success __retval(1) +__success __retval(0) __naked void loop_calls_subprog_with_65534_iterations(void) { asm volatile ( "call %[bpf_ktime_get_ns];" "r6 = r0;" + "r7 = 0;" "1:" "call loops_65534;" + "call %[bpf_ktime_get_ns];" + "r0 -= r6;" + "if r0 <= 1000000000 goto +2;" + "r7 += 1;" + "if r7 > 2 goto 3f;" "may_goto 2f;" "goto 1b;" "2:" - "call %[bpf_ktime_get_ns];" - "r0 -= r6;" - "r1 = r0;" "r0 = 1;" - "if r1 < 1000000000 goto +1;" - "r0 = 0;" + "exit;" + "3:" + "r0 = 3;" "exit;" : : __imm(bpf_ktime_get_ns) : __clobber_all); } -/* The subprog returns 16 bytes in R0 and R2. may_goto must not change them. */ +/* + * The subprog returns 16 bytes in R0 and R2. may_goto must not change them: the loop reads the + * clock one time and ends. + */ __naked __noinline __used static unsigned __int128 returns_pair_after_may_goto(void) { asm volatile ( "r0 = 1;" "r2 = 2;" + "r1 = 70000;" "1:" "may_goto 2f;" - "goto 1b;" + "r1 += -1;" + "if r1 != 0 goto 1b;" "2:" "exit;" ::: __clobber_all); @@ -863,26 +1019,32 @@ __naked void dead_may_goto(void) ::: __clobber_all); } -static __noinline int throws_after_spin(void) +static __noinline int throws_after_time_is_up(void) { - spin(); + if (time_is_up()) + return 100; bpf_throw(0); return 0; } __noinline int exception_cb_loops(u64 cookie) { - return counts_to_1000(); + return 20 + counts_to_1000(); } -/* The exception callback belongs to the invocation that throws. */ +/* + * The exception callback belongs to the invocation that throws. The time is up before the prog + * throws, in a subprog that cannot unwind, so the prog does get to bpf_throw(). The loop of the + * callback has no time of its own: it ends the prog in its first trip. With a new slice the + * callback would count to 1000 and return 1020. + */ SEC("tc") __description("timed may_goto: bpf_throw() the exception callback has a loop") __exception_cb(exception_cb_loops) -__success __retval(0) +__success __retval(2) int throw_after_timeout(void *ctx) { - return throws_after_spin(); + return throws_after_time_is_up(); } #else diff --git a/tools/testing/selftests/bpf/progs/timed_may_goto_ext.c b/tools/testing/selftests/bpf/progs/timed_may_goto_ext.c index 969ca58b6eed..d6cd5f370fd8 100644 --- a/tools/testing/selftests/bpf/progs/timed_may_goto_ext.c +++ b/tools/testing/selftests/bpf/progs/timed_may_goto_ext.c @@ -15,9 +15,27 @@ static __noinline int spins(void) return bpf_ktime_get_ns() - t0 > 100 * 1000 * 1000; } -/* Each call of an extension prog is an invocation: one of its two calls spins. */ +/* + * Each call of an extension prog is an invocation, with its own time. When that is up the + * extension is unwound, to its own exit: the function that it replaces returns the value of an + * unwound prog of the type that it extends, and the caller goes on. + */ +static __noinline int counts_to_1000(void) +{ + int i, cnt = 0; + + for (i = 0; i < 1000 && can_loop; i++) + cnt++; + return cnt; +} + +/* The calls that had the time for a short loop before they used it up */ +int calls, counted_to_1000; + SEC("freplace") int replacement(int i) { - return spins() + spins() + i; + calls++; + counted_to_1000 += counts_to_1000() == 1000; + return 10 + spins() + spins() + i; } diff --git a/tools/testing/selftests/bpf/progs/timed_may_goto_user.c b/tools/testing/selftests/bpf/progs/timed_may_goto_user.c index 8b85815d45d2..aed7a2354c41 100644 --- a/tools/testing/selftests/bpf/progs/timed_may_goto_user.c +++ b/tools/testing/selftests/bpf/progs/timed_may_goto_user.c @@ -1,5 +1,8 @@ // SPDX-License-Identifier: GPL-2.0 -/* The tests of timed_may_goto.c that need help from user space. */ +/* + * The tests of timed_may_goto.c that need help from user space. A prog whose time is up is + * unwound: tc returns 2, TC_ACT_SHOT, then, and a syscall prog -ECANCELED. + */ #include #include #include @@ -37,19 +40,88 @@ static __noinline int counts_to_1000(void) return cnt; } -/* Nothing special: the loops go on, then the time is up one time. */ +/* What a short loop counts before the time is up: user space sees that it got to its end */ +int normal_cnt, tail_callee_cnt; + +/* Nothing special: the loops go on, then the time is up and the prog is unwound. */ SEC("tc") int normal_prog(void *ctx) { - int i, n = 0; + int i, n = 10; - if (counts_to_1000() != 1000) + normal_cnt = counts_to_1000(); + if (normal_cnt != 1000) return 100; for (i = 0; i < TRIES; i++) n += spins(); return n; } +/* + * A subprog that cannot unwind: the comparator of bpf_rbtree_add() for a node that takes a lock + * when it is freed. There may_goto jumps where the program says when the time is up, and the prog + * goes on, see timed_may_goto.c. + */ +struct item { + struct bpf_list_node link; +}; + +struct stuck_node { + struct bpf_rb_node rb; + struct bpf_spin_lock lock; + struct bpf_list_head items __contains(item, link); +}; + +#define private(name) SEC(".data." #name) __hidden __attribute__((aligned(8))) +private(S) struct bpf_spin_lock stuck_lock; +private(S) struct bpf_rb_root stuck_root __contains(stuck_node, rb); + +/* No code has an item: this puts it in BTF, for __contains() above */ +void __item_btf_root(struct item *i) +{ +} + +long stuck_spun; + +static bool less_uses_up_time(struct bpf_rb_node *a, const struct bpf_rb_node *b) +{ + long n = zero; + + /* no helpers under the lock */ + while (can_loop) + n++; + stuck_spun = n > 1000 * 1000; + return false; +} + +/* Use up the time of the invocation, the prog goes on. Returns 0. */ +static __always_inline int time_is_up(void) +{ + struct bpf_rb_node *rb; + struct stuck_node *n; + int i; + + stuck_spun = 0; + for (i = 0; i < 2; i++) { + n = bpf_obj_new(typeof(*n)); + if (!n) + return 100; + bpf_spin_lock(&stuck_lock); + bpf_rbtree_add(&stuck_root, &n->rb, less_uses_up_time); + bpf_spin_unlock(&stuck_lock); + } + for (i = 0; i < 2; i++) { + bpf_spin_lock(&stuck_lock); + rb = bpf_rbtree_first(&stuck_root); + rb = rb ? bpf_rbtree_remove(&stuck_root, rb) : NULL; + bpf_spin_unlock(&stuck_lock); + if (!rb) + return 101; + bpf_obj_drop(container_of(rb, struct stuck_node, rb)); + } + return !stuck_spun; +} + /* * Async callbacks */ @@ -100,8 +172,9 @@ static int rcu_trace_cb(struct bpf_map *map, void *key, void *val) } /* - * The time of this prog is up when it starts the callbacks. User space keeps the task on the cpu, - * so the callbacks find what it has left. Each call of a callback is an invocation of its own. + * The time of this prog is up when it starts the callbacks: a comparator has used it. User space + * keeps the task on the cpu, so the callbacks find what it has left. Each call of a callback is an + * invocation of its own. */ SEC("syscall") int async_after_timeout(void *ctx) @@ -119,11 +192,8 @@ int async_after_timeout(void *ctx) return 101; if (bpf_wq_init(&e->wq, &async, 0) || bpf_wq_set_callback(&e->wq, wq_cb, 0)) return 102; - if (!spins()) + if (time_is_up()) return 103; - /* control: the time is up */ - if (counts_to_1000()) - return 109; if (bpf_timer_start(&e->timer, 0, BPF_F_TIMER_CPU_PIN)) return 104; if (bpf_wq_start(&e->wq, 0)) @@ -134,7 +204,8 @@ int async_after_timeout(void *ctx) return 107; if (bpf_call_rcu_tasks_trace(&e1->rcu, &async, rcu_trace_cb)) return 108; - return 0; + /* control: the time is up, the prog is unwound here and returns -ECANCELED */ + return 109 + counts_to_1000(); } int ticks; @@ -150,30 +221,30 @@ static int tick_cb(void *map, int *key, struct elem *e) /* * A callback of the prog interrupts it, on the same cpu, each 20 ms. It has its own time. That - * doesn't give more time to the prog. Return how long the loop went on, in ms. + * doesn't give more time to the prog: it is unwound when its own time is up. User space sees how + * long that took. */ SEC("syscall") int spin_under_timer(void *ctx) { struct elem *e; int key = 1; - __u64 t0; e = bpf_map_lookup_elem(&async, &key); if (!e) - return 0; + return 100; if (bpf_timer_init(&e->timer, &async, CLOCK_MONOTONIC) || bpf_timer_set_callback(&e->timer, tick_cb) || bpf_timer_start(&e->timer, 20 * 1000 * 1000, BPF_F_TIMER_CPU_PIN)) - return 0; - t0 = bpf_ktime_get_ns(); + return 101; while (can_loop) ; - return (bpf_ktime_get_ns() - t0) / 1000000; + return 102; } /* - * Extension prog + * Extension prog. A function that can unwind cannot be replaced: an extension ends in its main + * prog. With a loop that may_goto stops that is replaced_global(). plain_global() cannot unwind. */ __noinline int replaced_global(int i) { @@ -183,13 +254,32 @@ __noinline int replaced_global(int i) SEC("tc") int freplace_target(void *ctx) { - int i, n = 0; + int i, n = 10; for (i = 0; i < TRIES; i++) n += replaced_global(zero); return n; } +int plain_global_calls; + +/* It counts its calls: the compiler must not make one call of the calls in a loop */ +__noinline int plain_global(int i) +{ + plain_global_calls++; + return i + zero; +} + +SEC("tc") +int freplace_plain_target(void *ctx) +{ + int i, n = 10; + + for (i = 0; i < TRIES; i++) + n += plain_global(zero); + return n; +} + /* * Tail calls */ @@ -200,17 +290,21 @@ struct { __uint(value_size, sizeof(int)); } jmp_table SEC(".maps"); -int tail_callee_spun; +int tail_callee_runs; +/* It has its own time: the prog that makes the tail call may have none left */ SEC("tc") int tail_callee(struct __sk_buff *skb) { - int i; + int i, n = 10; - tail_callee_spun = 0; + tail_callee_runs++; + tail_callee_cnt = counts_to_1000(); + if (tail_callee_cnt != 1000) + return 100; for (i = 0; i < TRIES; i++) - tail_callee_spun += spins(); - return 0; + n += spins(); + return n; } static __noinline int tail_calls(struct __sk_buff *skb) @@ -219,31 +313,32 @@ static __noinline int tail_calls(struct __sk_buff *skb) return zero + 100; } -/* The target of the tail call is another prog. It returns to this function. */ +/* + * The target of the tail call is another prog. It is unwound when its time is up, and that ends + * at its own exit: it returns 2 to this function, which goes on with the time that it has. + */ SEC("tc") int tail_call_in_subprog(struct __sk_buff *skb) { - int i, n; + int n; n = tail_calls(skb); if (counts_to_1000() != 1000) return 101; - for (i = 0; i < TRIES; i++) - n += spins(); - return n; + return 10 + n; } SEC("tc") int tail_call_after_timeout(struct __sk_buff *skb) { - spins(); + if (time_is_up()) + return 101; bpf_tail_call(skb, &jmp_table, 0); return 100; } static __noinline int throws(void) { - spin(); bpf_throw(7); return 0; } @@ -251,6 +346,8 @@ static __noinline int throws(void) SEC("tc") int throw_after_timeout(void *ctx) { + if (time_is_up()) + return 101; return throws(); } @@ -268,18 +365,22 @@ static long drain_cb(struct bpf_dynptr *dynptr, int *spun) return 0; } +/* + * The callback is unwound, and the helper and the prog with it: -ECANCELED. The helper has taken + * the sample of that call out of the buffer. With no sample left the prog returns 100. + */ SEC("syscall") int drain(void *ctx) { int spun = 0; - return bpf_user_ringbuf_drain(&user_ringbuf, drain_cb, &spun, 0) * 10 + spun; + return 100 + bpf_user_ringbuf_drain(&user_ringbuf, drain_cb, &spun, 0) * 10 + spun; } /* * A tracing prog with large frames: they are in a private stack. */ -int priv_stack_spun, priv_stack_cb_spun; +int priv_stack_runs, priv_stack_spun, priv_stack_cb_spun; static __noinline int spins_with_stack(void) { @@ -302,6 +403,8 @@ int BPF_PROG(priv_stack) volatile char buf[128] = {}; int i, n = buf[zero & 127], spun = 0; + /* the first call is unwound in each run: the frames in the private stack are left */ + priv_stack_runs++; for (i = 0; i < TRIES; i++) n += spins_with_stack(); bpf_loop(TRIES, priv_stack_cb, &spun, zero); diff --git a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c index ca7bdbd7e1ce..5d22dfc6fdcb 100644 --- a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c +++ b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c @@ -1032,7 +1032,11 @@ __naked void may_goto_keeps_r12(void) : __clobber_all); } -/* counts the calls and spins until the time of may_goto is up */ +/* + * Counts the calls, takes its time in a loop that has a trip count, and gets to one may_goto. The + * one that finds the time up is the last insn of its kind in the call: the callback returns, and + * nothing is unwound. + */ static __naked __noinline __used long spin_cb(void) { asm volatile ( @@ -1040,9 +1044,12 @@ static __naked __noinline __used long spin_cb(void) "r3 = *(u64 *)(r2 + 0);" "r3 += 1;" "*(u64 *)(r2 + 0) = r3;" + "r4 = 1000;" "1:" + "r4 += -1;" + "if r4 != 0 goto 1b;" ".8byte %[may_goto];" - "goto 1b;" + "r4 = 1;" "r0 = 0;" "exit;" : @@ -1051,10 +1058,16 @@ static __naked __noinline __used long spin_cb(void) : __clobber_all); } +/* + * The call after the one that found the time up returns 1 in its first insns, before it takes a + * frame in the stack in arena: bpf_loop() ends, and the prog, which has no may_goto, goes on. + * The helper counts one call more than the callback, some calls ran, and the slot of the prog in + * the stack in arena is as it was: 20 + 1 + 100. + */ SEC("syscall") __description("arena stack: bpf_loop() ends when the time of may_goto is up") __success __retval(121) -/* the second call of the callback returns 1 before it takes a stack */ +/* a call of the callback when the time is up returns 1 before it takes a stack */ __xlated("if r0 != 0x0 goto pc+2") __xlated("r0 = 1") __xlated("exit") @@ -1075,10 +1088,12 @@ __naked void loop_ends_early(void) "r3 += -8;" "r4 = 0;" "call %[bpf_loop];" - /* 2 calls, 1 of them ran */ - "r0 *= 10;" + /* the last call did not run */ "r1 = *(u64 *)(r10 - 8);" - "r0 += r1;" + "r0 -= r1;" + "r0 *= 20;" + "if r1 == 0 goto +1;" + "r0 += 1;" ".8byte %[ldx];" /* r1 = *(u64 *)(r12 - 8) */ "r0 += r1;" "exit;" diff --git a/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c b/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c index 2120f4e71fb8..8a69d6b7874f 100644 --- a/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c +++ b/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c @@ -949,7 +949,8 @@ __xlated("...") __xlated("10: r2 = ") __xlated("12: r2 = &(void __percpu *)(r2)") __xlated("13: r13 = *(u64 *)(r2 +0)") -__xlated("14: if r13 == 0x0 goto pc+6") +/* when the time is up may_goto goes to the landing pad of the prog */ +__xlated("14: if r13 == 0x0 goto pc+7") __xlated("15: r13 -= 1") __xlated("16: if r13 != 0x0 goto pc+2") __xlated("17: r13 = r2") @@ -958,6 +959,9 @@ __xlated("19: *(u64 *)(r2 +0) = r13") /* may_goto expansion ends */ __xlated("20: *(u64 *)(r10 -8) = r1") __xlated("21: exit") +/* the landing pad */ +__xlated("22: r0 = 0") +__xlated("23: exit") __success __naked void may_goto_interaction_x86_64(void) { @@ -992,7 +996,8 @@ __xlated("7: call bpf_get_smp_processor_id") __xlated("8: r2 = ") __xlated("10: r2 = &(void __percpu *)(r2)") __xlated("11: r13 = *(u64 *)(r2 +0)") -__xlated("12: if r13 == 0x0 goto pc+6") +/* when the time is up may_goto goes to the landing pad of the prog */ +__xlated("12: if r13 == 0x0 goto pc+7") __xlated("13: r13 -= 1") __xlated("14: if r13 != 0x0 goto pc+2") __xlated("15: r13 = r2") @@ -1001,6 +1006,9 @@ __xlated("17: *(u64 *)(r2 +0) = r13") /* may_goto expansion ends */ __xlated("18: *(u64 *)(r10 -8) = r1") __xlated("19: exit") +/* the landing pad */ +__xlated("20: r0 = 0") +__xlated("21: exit") __success __naked void may_goto_interaction(void) { diff --git a/tools/testing/selftests/bpf/progs/verifier_equations.c b/tools/testing/selftests/bpf/progs/verifier_equations.c index 66786aae3664..21a30e6c9b3f 100644 --- a/tools/testing/selftests/bpf/progs/verifier_equations.c +++ b/tools/testing/selftests/bpf/progs/verifier_equations.c @@ -821,12 +821,17 @@ ONE_TEST(cond_of_low_half_bad, BAD_WRITE, 8, COND_OF_LOW_HALF(-1)) ONE_TEST(and_of_two_values, __success, 8, TWO_ANDS(7)) ONE_TEST(and_of_two_values_bad, BAD_WRITE, 8, TWO_ANDS(255)) -/* The jump compares a number with itself. It gives no trip count. */ +/* + * The jump compares a number with itself. It gives no trip count. The loop is left when the clock + * says 0: the jump of may_goto ends the prog. + */ ONE_TEST(jump_that_does_not_count, __failure __msg("invalid write to stack R8 off=0 size=1"), 8, "r7 = 0; r8 = r10; r8 += -24; r9 = r10; r9 += -256;" "1:" "r0 = 0;" -"2:" MAY_GOTO(2) +"2:" "call %[bpf_ktime_get_ns];" + "if r0 == 0 goto +3;" + MAY_GOTO(2) "r9 += 1;" "if r9 == r9 goto 2b;" "*(u8 *)(r8 + 0) = r7;" diff --git a/tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c b/tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c index 1dfeb13b4382..c4a0c3f303b4 100644 --- a/tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c +++ b/tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c @@ -590,19 +590,24 @@ int cond_break3(const void *ctx) return loop(); } +/* + * A socket filter that is unwound returns 0. Where may_goto jumps, without a JIT, the prog goes + * on and returns 1. + */ SEC("socket") -__success __retval(1) +__load_if_JITed() +__success __retval(0) int cond_break4(const void *ctx) { int cnt = zero; for (;;) { - /* should eventually break out of the loop */ + /* should eventually end the prog, and not break out of the loop */ cond_break; cnt++; } - /* if we looped a bit, it's a success */ - return cnt > 1 ? 1 : 0; + /* if we looped a bit, it's 1 */ + return cnt > 1 ? 1 : 2; } static __noinline int static_subprog(void) @@ -618,24 +623,22 @@ static __noinline int static_subprog(void) } SEC("socket") -__success __retval(1) +__load_if_JITed() +__success __retval(0) int cond_break5(const void *ctx) { int cnt1 = zero, cnt2; - /* - * There is one time slice for all may_goto of the prog. When it's used up a function that - * is called after that makes no iteration. So this loop has an end. - */ + /* This loop has an end: it does not use up the time slice of the prog. */ for (; cnt1 < 100;) { cond_break; cnt1++; } + /* The loop of the subprog does. The prog is unwound from there. */ cnt2 = static_subprog(); - /* main and subprog have to loop a bit */ - return cnt1 > 1 && cnt2 > 1 ? 1 : 0; + return cnt1 > 1 && cnt2 > 1 ? 1 : 2; } #define ARR2_SZ 1000 diff --git a/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c b/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c index f61a07424834..4995b3116691 100644 --- a/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c +++ b/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c @@ -812,7 +812,10 @@ LINK_TEST(and_cuts_in_the_middle, TOO_FAR, LINK_TEST(and_rounds_down_far, TOO_FAR, "r6 &= 0xff; r7 = r6; r7 &= 0xf0; if r7 > 7 goto 1f;") -/* r7 is 4 * trip + 8, r8 is 8 * trip. The loop has no trip count, so the products wrap. */ +/* + * r7 is 4 * trip + 8, r8 is 8 * trip. The loop has no trip count, so the products wrap. It is + * left when the random number is 0: the jump of may_goto ends the prog. + */ #define STRIDE_TEST(name, verdict, body) \ SEC("raw_tp") \ verdict \ @@ -823,6 +826,8 @@ __naked void name(void) \ "r8 = 0;" \ "*(u64 *)(r10 - 8) = r8;" \ "2:" \ + "call %[bpf_get_prandom_u32];" \ + "if r0 == 0 goto +4;" \ ".8byte %[may_goto];" \ "r7 += 4;" \ "r8 += 8;" \ diff --git a/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c b/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c index 8d231fb2a317..f8861ad046ce 100644 --- a/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c +++ b/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c @@ -94,11 +94,11 @@ __xlated("2: r0 = &(void __percpu *)(r0)") __xlated("3: *(u64 *)(r0 +0) = 65535") __xlated("4: *(u64 *)(r0 +8) = 0") __xlated("5: *(u64 *)(r0 +16) = 0") -/* may_goto, r0 is dead */ +/* may_goto, r0 is dead. When the time is up it goes to the landing pad of the prog. */ __xlated("6: r0 = ") __xlated("8: r0 = &(void __percpu *)(r0)") __xlated("9: r13 = *(u64 *)(r0 +0)") -__xlated("10: if r13 == 0x0 goto pc+6") +__xlated("10: if r13 == 0x0 goto pc+8") __xlated("11: r13 -= 1") __xlated("12: if r13 != 0x0 goto pc+2") __xlated("13: r13 = r0") @@ -107,6 +107,9 @@ __xlated("15: *(u64 *)(r0 +0) = r13") __xlated("16: r0 = 1") __xlated("17: r0 = 2") __xlated("18: exit") +/* the landing pad */ +__xlated("19: r0 = 0") +__xlated("20: exit") __success __naked void may_goto_batch_2(void) { @@ -125,6 +128,8 @@ __naked void may_goto_batch_2(void) /* * Use bpf_get_prandom_u32() to prevent DCE from removing the checks. * retval: 0=all ok, 1-6=R0-R5 clobbered. + * The loop makes more trips than may_goto counts before it reads the clock, and ends by its own + * count: a loop that waits for its time to be up ends the prog, and the checks never run. */ SEC("syscall") __description("timed may_goto preserves R0-R5") @@ -152,8 +157,11 @@ __naked void timed_may_goto_preserves_regs(void) "r4 += r6;" "r5 = 0x6666;" "r5 += r6;" + "r7 = 70000;" +"7:" ".8byte %[may_goto];" - ".8byte %[loop];" + "r7 -= 1;" + "if r7 != 0 goto 7b;" "r0 -= r6;" "r1 -= r6;" "r2 -= r6;" @@ -176,8 +184,7 @@ __naked void timed_may_goto_preserves_regs(void) "6: r0 = 6; exit;" : : __imm(bpf_get_prandom_u32), - __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 1, 0)), - __imm_insn(loop, BPF_RAW_INSN(BPF_JMP | BPF_JA, 0, 0, -2, 0)) + __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 2, 0)) : __clobber_all); } diff --git a/tools/testing/selftests/bpf/progs/verifier_passes.c b/tools/testing/selftests/bpf/progs/verifier_passes.c index d17254990744..48c59e7935e2 100644 --- a/tools/testing/selftests/bpf/progs/verifier_passes.c +++ b/tools/testing/selftests/bpf/progs/verifier_passes.c @@ -823,8 +823,10 @@ __naked void thresholds_over_budget(void) "r0 = *(u8 *)(r1 + 0);" ".rept 500;" "r6 = 0;" -"3:" MAY_GOTO(10) +"3:" MAY_GOTO(11) "call %[bpf_get_prandom_u32];" + /* the way to what follows the loop: the jump of may_goto ends the prog */ + "if r0 == 2 goto 5f;" "if r0 & 1 goto 4f;" "if r6 >= 60000 goto 4f;" "r6 += 1;" @@ -834,7 +836,7 @@ __naked void thresholds_over_budget(void) "r1 = 0;" "call long_dead_code;" "goto 3b;" - "r6 >>= 10;" +"5: r6 >>= 10;" "r1 = r9;" "r1 += r6;" "r0 = *(u8 *)(r1 + 0);" @@ -2577,13 +2579,21 @@ int leak_made_up_in_loop(struct __sk_buff *skb) return 0; } +/* + * The time of may_goto that is up ends the prog, and no state takes its jump. These loops have + * another way out, so that what follows them is verified. + */ +#define OR_BREAK if (bpf_get_prandom_u32() & 1) break + SEC("tc") __description("held: a loop acquires and does not release") __failure __msg("BPF_EXIT instruction in main prog cannot be used inside bpf_preempt_disable") int loop_only_acquires(void *unused) { - while (can_loop) + while (can_loop) { + OR_BREAK; bpf_preempt_disable(); + } return 0; } @@ -2591,6 +2601,7 @@ int loop_only_acquires(void *unused) void *prev = NULL, *cur = NULL; \ \ while (can_loop) { \ + OR_BREAK; \ if (prev) \ bpf_ringbuf_discard(prev, 0); \ prev = cur; \ @@ -2625,8 +2636,10 @@ int loop_drops_the_pointer(void *unused) { void *cur = NULL; - while (can_loop) + while (can_loop) { + OR_BREAK; cur = bpf_ringbuf_reserve(&rb, 8, 0); + } if (cur) bpf_ringbuf_discard(cur, 0); return 0; @@ -3120,7 +3133,10 @@ __naked void peel_does_not_starve(void) { ASM(VALUE_IN_R9 "r6 = 0;" -"1:" MAY_GOTO(2) + /* the way to what follows the loop: the jump of may_goto ends the prog */ +"1: call %[bpf_get_prandom_u32];" + "if r0 == 0 goto +3;" + MAY_GOTO(2) "r6 += 1;" "goto 1b;" "call %[bpf_get_prandom_u32];" diff --git a/tools/testing/selftests/bpf/progs/verifier_patch_list.c b/tools/testing/selftests/bpf/progs/verifier_patch_list.c index 80d08d93b625..5516100dd2b0 100644 --- a/tools/testing/selftests/bpf/progs/verifier_patch_list.c +++ b/tools/testing/selftests/bpf/progs/verifier_patch_list.c @@ -85,7 +85,10 @@ __naked void patch_list_backward(void) : __clobber_all); } -/* The jump of may_goto leaves its own patch and crosses another one. */ +/* + * The jump of may_goto leaves its own patch and crosses another one, on the way to the landing pad + * that follows the prog. + */ SEC("raw_tp") __description("patch list: may_goto between patched insns") __arch_x86_64 @@ -104,13 +107,15 @@ __xlated("11: r0 /= r1") __xlated("12: r2 = ") __xlated("14: r2 = &(void __percpu *)(r2)") __xlated("15: r13 = *(u64 *)(r2 +0)") -__xlated("16: if r13 == 0x0 goto pc+9") +__xlated("16: if r13 == 0x0 goto pc+10") __xlated("...") __xlated("22: if r1 != 0x0 goto pc+2") __xlated("23: w0 ^= w0") __xlated("24: goto pc+1") __xlated("25: r0 /= r1") __xlated("26: exit") +__xlated("27: r0 = 0") +__xlated("28: exit") __naked void patch_list_may_goto(void) { asm volatile ( @@ -311,42 +316,38 @@ int patch_list_indirect(void) #endif /* - * may_goto jumps back by 8195 insns, by 32768 once each of the 8191 - * divisions is guarded by a patch of 4 insns. That still fits the 16 bits of - * may_goto, but not the jump it expands to, which has to become gotol. Once - * the budget runs out, may_goto jumps back with r6 set and the program exits. + * When the time is up may_goto goes to the landing pad, which follows the prog: over 8191 + * divisions, 32764 insns once each of them is guarded by a patch of 4 insns. That does not fit + * the 16 bits of the jump that may_goto expands to, which has to become gotol. */ SEC("raw_tp") -__description("patch list: backward may_goto expanded to gotol") +__description("patch list: far may_goto expanded to gotol") __arch_x86_64 __arch_arm64 __success -__xlated("12: if r6 != 0x0 goto pc-3") +__xlated("12: r13 = *(u64 *)(r2 +0)") +__xlated("13: if r13 == 0x0 goto pc+1") +__xlated("14: goto pc+1") +__xlated("15: gotol pc+32771") __xlated("...") -__xlated("32783: if r13 == 0x0 goto pc+1") -__xlated("32784: goto pc+1") -__xlated("32785: gotol pc-32774") +__xlated("32786: exit") +__xlated("32787: r0 = 0") +__xlated("32788: exit") __naked void patch_list_may_goto_gotol(void) { asm volatile (" \ call %[bpf_get_prandom_u32]; \ r1 = r0; \ r6 = 0; \ - goto 0f; \ -1: r0 = 0; \ - exit; \ -0: if r6 != 0 goto 1b; \ + .8byte %[may_goto]; \ .rept 8191; \ r0 /= r1; \ .endr; \ - r2 = 0; \ - r6 = 1; \ - .8byte %[may_goto]; \ r0 = 0; \ exit; \ " : : __imm(bpf_get_prandom_u32), - __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, -8195 /* offset */, 0)) + __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 8191 /* offset */, 0)) : __clobber_all); } @@ -388,17 +389,60 @@ static unsigned long patch_list_loop_at_start(void) : __clobber_all); } +#define INSERT_IN_FRONT \ + asm volatile ( \ + "r1 = 3;" \ + "r2 = %[patch_list_loop_at_start] ll;" \ + "r3 = 0;" \ + "r4 = 0;" \ + "call %[bpf_loop];" \ + "exit;" \ + : \ + : __imm_addr(patch_list_loop_at_start), \ + __imm(bpf_loop) \ + : __clobber_all) + /* * The check of the may_goto count goes in front of the callback of bpf_loop(). * The call of the inlined bpf_loop() lands on the check, the jump to the first * insn of the callback behind it. - * This is the code for the JITs that support the timed may_goto. + * This is the code for the JITs that support the timed may_goto and unwind programs: the callback + * can unwind at its may_goto, so the inlined bpf_loop() has a landing pad, and the callback has + * one after its last insn. */ SEC("raw_tp") __description("patch list: call of and jump to an insn with insns inserted in front") __arch_x86_64 -__arch_s390x __arch_arm64 +__success +__xlated("27: call pc+10") +__xlated("28: unwind_goto pc-15") +__xlated("...") +__xlated("37: exit") +__xlated("38: r0 = ") +__xlated("40: r0 = &(void __percpu *)(r0)") +__xlated("41: r0 = *(u64 *)(r0 +0)") +__xlated("42: if r0 != 0x0 goto pc+2") +__xlated("43: r0 = 1") +__xlated("44: exit") +__xlated("45: r1 += -1") +__xlated("...") +__xlated("50: if r13 == 0x0 goto pc+8") +__xlated("...") +__xlated("56: if r1 != 0x0 goto pc-12") +__xlated("57: r0 = 0") +__xlated("58: exit") +__xlated("59: r0 = 0") +__xlated("60: unwind_exit") +__naked void patch_list_insert_in_front(void) +{ + INSERT_IN_FRONT; +} + +/* The JITs that do not unwind programs: the callback cannot unwind, and its may_goto jumps */ +SEC("raw_tp") +__description("patch list: call of and jump to an insn with insns inserted in front, no pads") +__arch_s390x __arch_riscv64 __arch_loongarch __success @@ -416,19 +460,9 @@ __xlated("...") __xlated("49: if r1 != 0x0 goto pc-12") __xlated("50: r0 = 0") __xlated("51: exit") -__naked void patch_list_insert_in_front(void) +__naked void patch_list_insert_in_front_no_pads(void) { - asm volatile ( - "r1 = 3;" - "r2 = %[patch_list_loop_at_start] ll;" - "r3 = 0;" - "r4 = 0;" - "call %[bpf_loop];" - "exit;" - : - : __imm_addr(patch_list_loop_at_start), - __imm(bpf_loop) - : __clobber_all); + INSERT_IN_FRONT; } __naked __noinline __used diff --git a/tools/testing/selftests/bpf/progs/verifier_stack_arg.c b/tools/testing/selftests/bpf/progs/verifier_stack_arg.c index 16afc69af947..91357043fdf4 100644 --- a/tools/testing/selftests/bpf/progs/verifier_stack_arg.c +++ b/tools/testing/selftests/bpf/progs/verifier_stack_arg.c @@ -982,9 +982,13 @@ static long spins_then_reads_8args(long a, long b, long c, long d, long e, long ); } +/* + * The callee is unwound when the time is up: it does not get to the loads of its args, which + * are behind the jump of may_goto, and tc drops the packet. + */ SEC("tc") -__description("stack_arg: the time of may_goto is up, then the callee reads its args") -__success __retval(876) +__description("stack_arg: the time of may_goto is up, the callee with args in the stack is unwound") +__success __retval(2) __naked void stack_arg_may_goto_timeout_in_callee(void) { asm volatile ( -- 2.53.1-Meta