Skip to contentSkip to conversation

ftrace: host klp and bpf trampoline together

PATCH Superseded Song Liu 4 participants 14 messages Jul 18, 2022

Subsystems (7)
x86 BPF Tracing BPF core +3 more subsystems

v3 of 5 Superseded Latest is v5 →

lore
Share & tools
lore

Song Liu

author maintainer
#0 lore raw

v3 cover ftrace: host klp and bpf trampoline together

Changes v2 => v3:
1. Major rewrite after discussions with Steven Rostedt. [1]
2. Remove SHARE_IPMODIFY flag from ftrace code. Instead use the callback function to communicate this information. (Steven)
3. Add cleanup_direct_functions_after_ipmodify() to clear SHARE_IPMODIFY on the DIRECT ops when the IPMODIFY ops is removed.

Changes v1 => v2:
1. Fix build errors for different config. (kernel test robot)

Kernel Live Patch (livepatch, or klp) and bpf trampoline are important features for modern systems. This set allows the two to work on the same kernel function as the same time.

live patch uses ftrace with IPMODIFY, while bpf trampoline use direct ftrace. Existing policy does not allow the two to attach to the same kernel function. This is changed by fine tuning ftrace IPMODIFY policy, and allows one IPMODIFY ftrace_ops and one DIRECT ftrace_ops on the same kernel function at the same time. Please see patch 2 and 4 for more details.

Note that, one of the constraint here is to let bpf trampoline use direct call when it is not working on the same function as live patch. This is achieved by allowing ftrace code to ask bpf trampoline to make changes.

[1] https://lore.kernel.org/all/[email protected]/

Jiri Olsa (1):
bpf, x64: Allow to use caller address from stack

Song Liu (3):
ftrace: add modify_ftrace_direct_multi_nolock
ftrace: allow IPMODIFY and DIRECT ops on the same function
bpf: support bpf_trampoline on functions with IPMODIFY (e.g.
livepatch)

 arch/x86/net/bpf_jit_comp.c |  13 +-
 include/linux/bpf.h         |  13 ++
 include/linux/ftrace.h      |  43 ++++++
 kernel/bpf/trampoline.c     | 158 +++++++++++++++++---
 kernel/trace/ftrace.c       | 288 +++++++++++++++++++++++++++++++-----
 5 files changed, 455 insertions(+), 60 deletions(-)

--
2.30.2

author maintainer
#1 lore raw

PATCH v3 1/4 ftrace: add modify_ftrace_direct_multi_nolock

This is similar to modify_ftrace_direct_multi, but does not acquire direct_mutex. This is useful when direct_mutex is already locked by the user.

---
 include/linux/ftrace.h |  5 +++
 kernel/trace/ftrace.c  | 85 ++++++++++++++++++++++++++++++------------
 2 files changed, 67 insertions(+), 23 deletions(-)
include/linux/ftrace.h +5 -0
index 979f6bfa2c25..acb35243ce5d 100644
@@ -340,6 +340,7 @@ unsigned long ftrace_find_rec_direct(unsigned long ip);
 int register_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr);
 int unregister_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr);
 int modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr);
+int modify_ftrace_direct_multi_nolock(struct ftrace_ops *ops, unsigned long addr);
 
 #else
 struct ftrace_ops;
@@ -384,6 +385,10 @@ static inline int modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned lo
 {
 	return -ENODEV;
 }
+static inline int modify_ftrace_direct_multi_nolock(struct ftrace_ops *ops, unsigned long addr)
+{
+	return -ENODEV;
+}
 #endif /* CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS */
 
 #ifndef CONFIG_HAVE_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
kernel/trace/ftrace.c +62 -23

110 lines not on this page · raw message

Signature · 1 line
2.30.2
author maintainer
#4 lore raw

PATCH v3 2/4 ftrace: allow IPMODIFY and DIRECT ops on the same function

In reply to Song Liu

IPMODIFY (livepatch) and DIRECT (bpf trampoline) ops are both important users of ftrace. It is necessary to allow them work on the same function at the same time.

First, DIRECT ops no longer specify IPMODIFY flag. Instead, DIRECT flag is handled together with IPMODIFY flag in __ftrace_hash_update_ipmodify().

The, a callback function, ops_func, is added to ftrace_ops. This is used by ftrace core code to understand whether the DIRECT ops can share with an IPMODIFY ops. To share with IPMODIFY ops, the DIRECT ops need to implement the callback function and adjust the direct trampoline accordingly.

If DIRECT ops is attached before the IPMODIFY ops, ftrace core code calls ENABLE_SHARE_IPMODIFY_PEER on the DIRECT ops before registering the IPMODIFY ops.

If IPMODIFY ops is attached before the DIRECT ops, ftrace core code calls ENABLE_SHARE_IPMODIFY_SELF in __ftrace_hash_update_ipmodify. Owner of the DIRECT ops may return 0 if the DIRECT trampoline can share with IPMODIFY, so error code otherwise. The error code is propagated to register_ftrace_direct_multi so that onwer of the DIRECT trampoline can handle it properly.

For more details, please refer to comment before enum ftrace_ops_cmd.

---
 include/linux/ftrace.h |  38 ++++++++
 kernel/trace/ftrace.c  | 205 +++++++++++++++++++++++++++++++++++++----
 2 files changed, 227 insertions(+), 16 deletions(-)
include/linux/ftrace.h +38 -0
index acb35243ce5d..306bf08acda6 100644
@@ -208,6 +208,43 @@ enum {
 	FTRACE_OPS_FL_DIRECT			= BIT(17),
 };
 
+/*
+ * FTRACE_OPS_CMD_* commands allow the ftrace core logic to request changes
+ * to a ftrace_ops. Note, the requests may fail.
+ *
+ * ENABLE_SHARE_IPMODIFY_SELF - enable a DIRECT ops to work on the same
+ *                              function as an ops with IPMODIFY. Called
+ *                              when the DIRECT ops is being registered.
+ *                              This is called with both direct_mutex and
+ *                              ftrace_lock are locked.
+ *
+ * ENABLE_SHARE_IPMODIFY_PEER - enable a DIRECT ops to work on the same
+ *                              function as an ops with IPMODIFY. Called
+ *                              when the other ops (the one with IPMODIFY)
+ *                              is being registered.
+ *                              This is called with direct_mutex locked.
+ *
+ * DISABLE_SHARE_IPMODIFY_PEER - disable a DIRECT ops to work on the same
+ *                               function as an ops with IPMODIFY. Called
+ *                               when the other ops (the one with IPMODIFY)
+ *                               is being unregistered.
+ *                               This is called with direct_mutex locked.
+ */
+enum ftrace_ops_cmd {
+	FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_SELF,
+	FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER,
+	FTRACE_OPS_CMD_DISABLE_SHARE_IPMODIFY_PEER,
+};
+
+/*
+ * For most ftrace_ops_cmd,
+ * Returns:
+ *        0 - Success.
+ *        -EBUSY - The operation cannot process
+ *        -EAGAIN - The operation cannot process tempoorarily.
+ */
+typedef int (*ftrace_ops_func_t)(struct ftrace_ops *op, enum ftrace_ops_cmd cmd);
+
 #ifdef CONFIG_DYNAMIC_FTRACE
 /* The hash used to know what functions callbacks trace */
 struct ftrace_ops_hash {
@@ -250,6 +287,7 @@ struct ftrace_ops {
 	unsigned long			trampoline;
 	unsigned long			trampoline_size;
 	struct list_head		list;
+	ftrace_ops_func_t		ops_func;
 #endif
 };
 
kernel/trace/ftrace.c +189 -16

308 lines not on this page · raw message

Signature · 1 line
2.30.2
author maintainer
#10 lore raw

PATCH v3 4/4 bpf: support bpf_trampoline on functions with IPMODIFY (e.g. livepatch)

In reply to Song Liu

When tracing a function with IPMODIFY ftrace_ops (livepatch), the bpf trampoline must follow the instruction pointer saved on stack. This needs extra handling for bpf trampolines with BPF_TRAMP_F_CALL_ORIG flag.

Implement bpf_tramp_ftrace_ops_func and use it for the ftrace_ops used by BPF trampoline. This enables tracing functions with livepatch.

This also requires moving bpf trampoline to *_ftrace_direct_mult APIs.

---
 include/linux/bpf.h     |   8 ++
 kernel/bpf/trampoline.c | 158 +++++++++++++++++++++++++++++++++++-----
 2 files changed, 149 insertions(+), 17 deletions(-)
include/linux/bpf.h +8 -0
index 7496842a4671..f35c59e0b742 100644
@@ -47,6 +47,7 @@ struct kobject;
 struct mem_cgroup;
 struct module;
 struct bpf_func_state;
+struct ftrace_ops;
 
 extern struct idr btf_idr;
 extern spinlock_t btf_idr_lock;
@@ -756,6 +757,11 @@ struct btf_func_model {
  */
 #define BPF_TRAMP_F_ORIG_STACK		BIT(5)
 
+/* This trampoline is on a function with another ftrace_ops with IPMODIFY,
+ * e.g., a live patch. This flag is set and cleared by ftrace call backs,
+ */
+#define BPF_TRAMP_F_SHARE_IPMODIFY	BIT(6)
+
 /* Each call __bpf_prog_enter + call bpf_func + call __bpf_prog_exit is ~50
  * bytes on x86.
  */
@@ -838,9 +844,11 @@ struct bpf_tramp_image {
 struct bpf_trampoline {
 	/* hlist for trampoline_table */
 	struct hlist_node hlist;
+	struct ftrace_ops *fops;
 	/* serializes access to fields of this trampoline */
 	struct mutex mutex;
 	refcount_t refcnt;
+	u32 flags;
 	u64 key;
 	struct {
 		struct btf_func_model model;
kernel/bpf/trampoline.c +141 -17

257 lines not on this page · raw message

Signature · 1 line
2.30.2
author maintainer
#9 lore raw

PATCH v3 3/4 bpf, x64: Allow to use caller address from stack

In reply to Song Liu

From: Jiri Olsa <[email protected]>

Currently we call the original function by using the absolute address given at the JIT generation. That's not usable when having trampoline attached to multiple functions, or the target address changes dynamically (in case of live patch). In such cases we need to take the return address from the stack.

Adding support to retrieve the original function address from the stack by adding new BPF_TRAMP_F_ORIG_STACK flag for arch_prepare_bpf_trampoline function.

Basically we take the return address of the 'fentry' call:

function + 0: call fentry # stores 'function + 5' address on stack
function + 5: ...

The 'function + 5' address will be used as the address for the original function to call.

---
 arch/x86/net/bpf_jit_comp.c | 13 +++++++++----
 include/linux/bpf.h         |  5 +++++
 2 files changed, 14 insertions(+), 4 deletions(-)
arch/x86/net/bpf_jit_comp.c +9 -4
index 54c7f46c453f..e1b0c5ed0b7c 100644
@@ -2119,10 +2119,15 @@ int arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *image, void *i
 	if (flags & BPF_TRAMP_F_CALL_ORIG) {
 		restore_regs(m, &prog, nr_args, regs_off);
 
-		/* call original function */
-		if (emit_call(&prog, orig_call, prog)) {
-			ret = -EINVAL;
-			goto cleanup;
+		if (flags & BPF_TRAMP_F_ORIG_STACK) {
+			emit_ldx(&prog, BPF_DW, BPF_REG_0, BPF_REG_FP, 8);
+			EMIT2(0xff, 0xd0); /* call *rax */
+		} else {
+			/* call original function */
+			if (emit_call(&prog, orig_call, prog)) {
+				ret = -EINVAL;
+				goto cleanup;
+			}
 		}
 		/* remember return value in a stack for bpf prog to access */
 		emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -8);
include/linux/bpf.h +5 -0
index a5bf00649995..7496842a4671 100644
@@ -751,6 +751,11 @@ struct btf_func_model {
 /* Return the return value of fentry prog. Only used by bpf_struct_ops. */
 #define BPF_TRAMP_F_RET_FENTRY_RET	BIT(4)
 
+/* Get original function from stack instead of from provided direct address.
+ * Makes sense for trampolines with fexit or fmod_ret programs.
+ */
+#define BPF_TRAMP_F_ORIG_STACK		BIT(5)
+
 /* Each call __bpf_prog_enter + call bpf_func + call __bpf_prog_exit is ~50
  * bytes on x86.
  */
Signature · 1 line
2.30.2
#5 lore raw

Re: [PATCH v3 bpf-next 2/4] ftrace: allow IPMODIFY and DIRECT ops on the same function

In reply to Song Liu
I love your patch! Yet something to improve:

Hi Song,

I love your patch! Yet something to improve:

[auto build test ERROR on bpf-next/master]

url:    https://github.com/intel-lab-lkp/linux/commits/Song-Liu/ftrace-host-klp-and-bpf-trampoline-together/20220718-081533
base:   https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git master
config: x86_64-randconfig-a006 (https://download.01.org/0day-ci/archive/20220718/[email protected]/config)
compiler: gcc-11 (Debian 11.3.0-3) 11.3.0
reproduce (this is a W=1 build):
        # https://github.com/intel-lab-lkp/linux/commit/1535f287d288f9b7540ec50f56da1fe437ac6512
        git remote add linux-review https://github.com/intel-lab-lkp/linux
        git fetch --no-tags linux-review Song-Liu/ftrace-host-klp-and-bpf-trampoline-together/20220718-081533
        git checkout 1535f287d288f9b7540ec50f56da1fe437ac6512
        # save the config file
        mkdir build_dir && cp config build_dir/.config
        make W=1 O=build_dir ARCH=x86_64 SHELL=/bin/bash

If you fix the issue, kindly add following tag where applicable

All errors (new ones prefixed by >>):

In file included from include/linux/rhashtable-types.h:14,
from include/linux/ipc.h:7,
from include/uapi/linux/sem.h:5,
from include/linux/sem.h:5,
from include/linux/sched.h:15,
from include/linux/ratelimit.h:6,
from include/linux/dev_printk.h:16,
from include/linux/device.h:15,
from include/linux/node.h:18,
from include/linux/cpu.h:17,
from include/linux/stop_machine.h:5,
from kernel/trace/ftrace.c:17:
kernel/trace/ftrace.c: In function 'prepare_direct_functions_for_ipmodify':

>> kernel/trace/ftrace.c:8082:21: error: 'direct_mutex' undeclared (first use in this function); did you mean 'event_mutex'?
    8082 |         mutex_lock(&direct_mutex);
         |                     ^~~~~~~~~~~~
   include/linux/mutex.h:187:44: note: in definition of macro 'mutex_lock'
     187 | #define mutex_lock(lock) mutex_lock_nested(lock, 0)
         |                                            ^~~~
   kernel/trace/ftrace.c:8082:21: note: each undeclared identifier is reported only once for each function it appears in
    8082 |         mutex_lock(&direct_mutex);
         |                     ^~~~~~~~~~~~
   include/linux/mutex.h:187:44: note: in definition of macro 'mutex_lock'
     187 | #define mutex_lock(lock) mutex_lock_nested(lock, 0)
         |                                            ^~~~
>> kernel/trace/ftrace.c:8084:19: error: 'struct ftrace_ops' has no member named 'func_hash'
    8084 |         hash = ops->func_hash->filter_hash;
         |                   ^~
>> kernel/trace/ftrace.c:8095:37: error: implicit declaration of function 'ops_references_ip' [-Werror=implicit-function-declaration]
    8095 |                                 if (ops_references_ip(op, ip)) {
         |                                     ^~~~~~~~~~~~~~~~~
>> kernel/trace/ftrace.c:8103:40: error: 'struct ftrace_ops' has no member named 'ops_func'
    8103 |                                 if (!op->ops_func) {
         |                                        ^~
   kernel/trace/ftrace.c:8107:41: error: 'struct ftrace_ops' has no member named 'ops_func'
    8107 |                                 ret = op->ops_func(op, FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER);
         |                                         ^~
   kernel/trace/ftrace.c: In function 'register_ftrace_function':
   kernel/trace/ftrace.c:8158:31: error: 'direct_mutex' undeclared (first use in this function); did you mean 'event_mutex'?
    8158 |                 mutex_unlock(&direct_mutex);
         |                               ^~~~~~~~~~~~
         |                               event_mutex
   In file included from include/linux/rhashtable-types.h:14,
                    from include/linux/ipc.h:7,
                    from include/uapi/linux/sem.h:5,
                    from include/linux/sem.h:5,
                    from include/linux/sched.h:15,
                    from include/linux/ratelimit.h:6,
                    from include/linux/dev_printk.h:16,
                    from include/linux/device.h:15,
                    from include/linux/node.h:18,
                    from include/linux/cpu.h:17,
                    from include/linux/stop_machine.h:5,
                    from kernel/trace/ftrace.c:17:
   kernel/trace/ftrace.c: In function 'cleanup_direct_functions_after_ipmodify':
   kernel/trace/ftrace.c:8178:21: error: 'direct_mutex' undeclared (first use in this function); did you mean 'event_mutex'?
    8178 |         mutex_lock(&direct_mutex);
         |                     ^~~~~~~~~~~~
   include/linux/mutex.h:187:44: note: in definition of macro 'mutex_lock'
     187 | #define mutex_lock(lock) mutex_lock_nested(lock, 0)
         |                                            ^~~~
   kernel/trace/ftrace.c:8180:19: error: 'struct ftrace_ops' has no member named 'func_hash'
    8180 |         hash = ops->func_hash->filter_hash;
         |                   ^~
   kernel/trace/ftrace.c:8199:43: error: 'struct ftrace_ops' has no member named 'ops_func'
    8199 |                         if (found_op && op->ops_func)
         |                                           ^~
   kernel/trace/ftrace.c:8200:35: error: 'struct ftrace_ops' has no member named 'ops_func'
    8200 |                                 op->ops_func(op, FTRACE_OPS_CMD_DISABLE_SHARE_IPMODIFY_PEER);
         |                                   ^~

cc1: some warnings being treated as errors

vim +8082 kernel/trace/ftrace.c

8051
8052 /*
8053 * When registering ftrace_ops with IPMODIFY, it is necessary to make sure
8054 * it doesn't conflict with any direct ftrace_ops. If there is existing
8055 * direct ftrace_ops on a kernel function being patched, call
8056 * FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER on it to enable sharing.
8057 *
8058 * @ops: ftrace_ops being registered.
8059 *
8060 * Returns:
8061 * 0 - @ops does not have IPMODIFY or @ops itself is DIRECT, no
8062 * change needed;
8063 * 1 - @ops has IPMODIFY, hold direct_mutex;
8064 * -EBUSY - currently registered DIRECT ftrace_ops cannot share the
8065 * same function with IPMODIFY, abort the register.
8066 * -EAGAIN - cannot make changes to currently registered DIRECT

  8067	 *                   ftrace_ops due to rare race conditions. Should retry
  8068	 *                   later. This is needed to avoid potential deadlocks
  8069	 *                   on the DIRECT ftrace_ops side.
  8070	 */
  8071	static int prepare_direct_functions_for_ipmodify(struct ftrace_ops *ops)
  8072		__acquires(&direct_mutex)
  8073	{
  8074		struct ftrace_func_entry *entry;
  8075		struct ftrace_hash *hash;
  8076		struct ftrace_ops *op;
  8077		int size, i, ret;
  8078	
  8079		if (!(ops->flags & FTRACE_OPS_FL_IPMODIFY))
  8080			return 0;
  8081	
> 8082		mutex_lock(&direct_mutex);
  8083	
> 8084		hash = ops->func_hash->filter_hash;
  8085		size = 1 << hash->size_bits;
  8086		for (i = 0; i < size; i++) {
  8087			hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
  8088				unsigned long ip = entry->ip;
  8089				bool found_op = false;
  8090	
  8091				mutex_lock(&ftrace_lock);
  8092				do_for_each_ftrace_op(op, ftrace_ops_list) {
  8093					if (!(op->flags & FTRACE_OPS_FL_DIRECT))
  8094						continue;
> 8095					if (ops_references_ip(op, ip)) {
  8096						found_op = true;
  8097						break;
  8098					}
  8099				} while_for_each_ftrace_op(op);
  8100				mutex_unlock(&ftrace_lock);
  8101	
  8102				if (found_op) {
> 8103					if (!op->ops_func) {

8104 ret = -EBUSY;
8105 goto err_out;
8106 }
8107 ret = op->ops_func(op, FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER);
8108 if (ret)
8109 goto err_out;
8110 }
8111 }
8112 }
8113
8114 /*
8115 * Didn't find any overlap with direct ftrace_ops, or the direct
8116 * function can share with ipmodify. Hold direct_mutex to make sure
8117 * this doesn't change until we are done.
8118 */
8119 return 1;
8120
8121 err_out:
8122 mutex_unlock(&direct_mutex);
8123 return ret;
8124 }
8125

Signature · 2 lines
0-DAY CI Kernel Test Service
https://01.org/lkp
#6 lore raw

Re: [PATCH v3 bpf-next 2/4] ftrace: allow IPMODIFY and DIRECT ops on the same function

In reply to Song Liu
I love your patch! Yet something to improve:

Hi Song,

I love your patch! Yet something to improve:

[auto build test ERROR on bpf-next/master]

url:    https://github.com/intel-lab-lkp/linux/commits/Song-Liu/ftrace-host-klp-and-bpf-trampoline-together/20220718-081533
base:   https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git master
config: powerpc-randconfig-r023-20220717 (https://download.01.org/0day-ci/archive/20220718/[email protected]/config)
compiler: clang version 15.0.0 (https://github.com/llvm/llvm-project d74b88c69dc2644bd0dc5d64e2d7413a0d4040e5)

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# install powerpc cross compiling tool for clang build
# apt-get install binutils-powerpc-linux-gnu
# https://github.com/intel-lab-lkp/linux/commit/1535f287d288f9b7540ec50f56da1fe437ac6512
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Song-Liu/ftrace-host-klp-and-bpf-trampoline-together/20220718-081533 git checkout 1535f287d288f9b7540ec50f56da1fe437ac6512
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=clang make.cross W=1 O=build_dir ARCH=powerpc SHELL=/bin/bash kernel/trace/

If you fix the issue, kindly add following tag where applicable

All errors (new ones prefixed by >>):

kernel/trace/ftrace.c:299:5: warning: no previous prototype for function '__register_ftrace_function' [-Wmissing-prototypes] int __register_ftrace_function(struct ftrace_ops *ops)

       ^
   kernel/trace/ftrace.c:299:1: note: declare 'static' if the function is not intended to be used outside of this translation unit
   int __register_ftrace_function(struct ftrace_ops *ops)
   ^
   static 
   kernel/trace/ftrace.c:342:5: warning: no previous prototype for function '__unregister_ftrace_function' [-Wmissing-prototypes]
   int __unregister_ftrace_function(struct ftrace_ops *ops)
       ^
   kernel/trace/ftrace.c:342:1: note: declare 'static' if the function is not intended to be used outside of this translation unit
   int __unregister_ftrace_function(struct ftrace_ops *ops)
   ^
   static 
   kernel/trace/ftrace.c:4030:15: warning: no previous prototype for function 'arch_ftrace_match_adjust' [-Wmissing-prototypes]
   char * __weak arch_ftrace_match_adjust(char *str, const char *search)
                 ^
   kernel/trace/ftrace.c:4030:1: note: declare 'static' if the function is not intended to be used outside of this translation unit
   char * __weak arch_ftrace_match_adjust(char *str, const char *search)
   ^
   static 
>> kernel/trace/ftrace.c:8082:14: error: use of undeclared identifier 'direct_mutex'; did you mean 'event_mutex'?
           mutex_lock(&direct_mutex);
                       ^~~~~~~~~~~~
                       event_mutex
   include/linux/mutex.h:187:44: note: expanded from macro 'mutex_lock'
   #define mutex_lock(lock) mutex_lock_nested(lock, 0)
                                              ^
   kernel/trace/trace.h:1523:21: note: 'event_mutex' declared here
   extern struct mutex event_mutex;
                       ^
   kernel/trace/ftrace.c:8122:16: error: use of undeclared identifier 'direct_mutex'; did you mean 'event_mutex'?
           mutex_unlock(&direct_mutex);
                         ^~~~~~~~~~~~
                         event_mutex
   kernel/trace/trace.h:1523:21: note: 'event_mutex' declared here
   extern struct mutex event_mutex;
                       ^
   kernel/trace/ftrace.c:8158:17: error: use of undeclared identifier 'direct_mutex'; did you mean 'event_mutex'?
                   mutex_unlock(&direct_mutex);
                                 ^~~~~~~~~~~~
                                 event_mutex
   kernel/trace/trace.h:1523:21: note: 'event_mutex' declared here
   extern struct mutex event_mutex;
                       ^
   kernel/trace/ftrace.c:8178:14: error: use of undeclared identifier 'direct_mutex'; did you mean 'event_mutex'?
           mutex_lock(&direct_mutex);
                       ^~~~~~~~~~~~
                       event_mutex
   include/linux/mutex.h:187:44: note: expanded from macro 'mutex_lock'
   #define mutex_lock(lock) mutex_lock_nested(lock, 0)
                                              ^
   kernel/trace/trace.h:1523:21: note: 'event_mutex' declared here
   extern struct mutex event_mutex;
                       ^
   kernel/trace/ftrace.c:8203:16: error: use of undeclared identifier 'direct_mutex'; did you mean 'event_mutex'?
           mutex_unlock(&direct_mutex);
                         ^~~~~~~~~~~~
                         event_mutex
   kernel/trace/trace.h:1523:21: note: 'event_mutex' declared here
   extern struct mutex event_mutex;
                       ^

3 warnings and 5 errors generated.

vim +8082 kernel/trace/ftrace.c

8051
8052 /*
8053 * When registering ftrace_ops with IPMODIFY, it is necessary to make sure
8054 * it doesn't conflict with any direct ftrace_ops. If there is existing
8055 * direct ftrace_ops on a kernel function being patched, call
8056 * FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER on it to enable sharing.
8057 *
8058 * @ops: ftrace_ops being registered.
8059 *
8060 * Returns:
8061 * 0 - @ops does not have IPMODIFY or @ops itself is DIRECT, no
8062 * change needed;
8063 * 1 - @ops has IPMODIFY, hold direct_mutex;
8064 * -EBUSY - currently registered DIRECT ftrace_ops cannot share the
8065 * same function with IPMODIFY, abort the register.
8066 * -EAGAIN - cannot make changes to currently registered DIRECT

  8067	 *                   ftrace_ops due to rare race conditions. Should retry
  8068	 *                   later. This is needed to avoid potential deadlocks
  8069	 *                   on the DIRECT ftrace_ops side.
  8070	 */
  8071	static int prepare_direct_functions_for_ipmodify(struct ftrace_ops *ops)
  8072		__acquires(&direct_mutex)
  8073	{
  8074		struct ftrace_func_entry *entry;
  8075		struct ftrace_hash *hash;
  8076		struct ftrace_ops *op;
  8077		int size, i, ret;
  8078	
  8079		if (!(ops->flags & FTRACE_OPS_FL_IPMODIFY))
  8080			return 0;
  8081	
> 8082		mutex_lock(&direct_mutex);

8083
8084 hash = ops->func_hash->filter_hash;
8085 size = 1 << hash->size_bits;
8086 for (i = 0; i < size; i++) {
8087 hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
8088 unsigned long ip = entry->ip;
8089 bool found_op = false;
8090
8091 mutex_lock(&ftrace_lock);
8092 do_for_each_ftrace_op(op, ftrace_ops_list) {
8093 if (!(op->flags & FTRACE_OPS_FL_DIRECT))
8094 continue;
8095 if (ops_references_ip(op, ip)) {
8096 found_op = true;
8097 break;
8098 }
8099 } while_for_each_ftrace_op(op);
8100 mutex_unlock(&ftrace_lock);
8101
8102 if (found_op) {
8103 if (!op->ops_func) {
8104 ret = -EBUSY;
8105 goto err_out;
8106 }
8107 ret = op->ops_func(op, FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER);
8108 if (ret)
8109 goto err_out;
8110 }
8111 }
8112 }
8113
8114 /*
8115 * Didn't find any overlap with direct ftrace_ops, or the direct
8116 * function can share with ipmodify. Hold direct_mutex to make sure
8117 * this doesn't change until we are done.
8118 */
8119 return 1;
8120
8121 err_out:
8122 mutex_unlock(&direct_mutex);
8123 return ret;
8124 }
8125

Signature · 2 lines
0-DAY CI Kernel Test Service
https://01.org/lkp
#7 lore raw

Re: [PATCH v3 bpf-next 2/4] ftrace: allow IPMODIFY and DIRECT ops on the same function

In reply to Song Liu
I love your patch! Yet something to improve:

Hi Song,

I love your patch! Yet something to improve:

[auto build test ERROR on bpf-next/master]

url:    https://github.com/intel-lab-lkp/linux/commits/Song-Liu/ftrace-host-klp-and-bpf-trampoline-together/20220718-081533
base:   https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git master
config: x86_64-randconfig-a001 (https://download.01.org/0day-ci/archive/20220718/[email protected]/config)
compiler: clang version 15.0.0 (https://github.com/llvm/llvm-project d74b88c69dc2644bd0dc5d64e2d7413a0d4040e5)

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# https://github.com/intel-lab-lkp/linux/commit/1535f287d288f9b7540ec50f56da1fe437ac6512
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Song-Liu/ftrace-host-klp-and-bpf-trampoline-together/20220718-081533 git checkout 1535f287d288f9b7540ec50f56da1fe437ac6512
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=clang make.cross W=1 O=build_dir ARCH=x86_64 SHELL=/bin/bash

If you fix the issue, kindly add following tag where applicable

All errors (new ones prefixed by >>):

>> kernel/trace/ftrace.c:8082:14: error: use of undeclared identifier 'direct_mutex'; did you mean 'event_mutex'?
           mutex_lock(&direct_mutex);
                       ^~~~~~~~~~~~
                       event_mutex
   include/linux/mutex.h:187:44: note: expanded from macro 'mutex_lock'
   #define mutex_lock(lock) mutex_lock_nested(lock, 0)
                                              ^
   kernel/trace/trace.h:1523:21: note: 'event_mutex' declared here
   extern struct mutex event_mutex;
                       ^
>> kernel/trace/ftrace.c:8084:14: error: no member named 'func_hash' in 'struct ftrace_ops'
           hash = ops->func_hash->filter_hash;
                  ~~~  ^
>> kernel/trace/ftrace.c:8095:9: error: call to undeclared function 'ops_references_ip'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
                                   if (ops_references_ip(op, ip)) {
                                       ^
>> kernel/trace/ftrace.c:8103:14: error: no member named 'ops_func' in 'struct ftrace_ops'
                                   if (!op->ops_func) {
                                        ~~  ^
   kernel/trace/ftrace.c:8107:15: error: no member named 'ops_func' in 'struct ftrace_ops'
                                   ret = op->ops_func(op, FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER);
                                         ~~  ^
   kernel/trace/ftrace.c:8122:16: error: use of undeclared identifier 'direct_mutex'; did you mean 'event_mutex'?
           mutex_unlock(&direct_mutex);
                         ^~~~~~~~~~~~
                         event_mutex
   kernel/trace/trace.h:1523:21: note: 'event_mutex' declared here
   extern struct mutex event_mutex;
                       ^
   kernel/trace/ftrace.c:8158:17: error: use of undeclared identifier 'direct_mutex'; did you mean 'event_mutex'?
                   mutex_unlock(&direct_mutex);
                                 ^~~~~~~~~~~~
                                 event_mutex
   kernel/trace/trace.h:1523:21: note: 'event_mutex' declared here
   extern struct mutex event_mutex;
                       ^
   kernel/trace/ftrace.c:8178:14: error: use of undeclared identifier 'direct_mutex'; did you mean 'event_mutex'?
           mutex_lock(&direct_mutex);
                       ^~~~~~~~~~~~
                       event_mutex
   include/linux/mutex.h:187:44: note: expanded from macro 'mutex_lock'
   #define mutex_lock(lock) mutex_lock_nested(lock, 0)
                                              ^
   kernel/trace/trace.h:1523:21: note: 'event_mutex' declared here
   extern struct mutex event_mutex;
                       ^
   kernel/trace/ftrace.c:8180:14: error: no member named 'func_hash' in 'struct ftrace_ops'
           hash = ops->func_hash->filter_hash;
                  ~~~  ^
   kernel/trace/ftrace.c:8191:9: error: call to undeclared function 'ops_references_ip'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
                                   if (ops_references_ip(op, ip)) {
                                       ^
   kernel/trace/ftrace.c:8199:24: error: no member named 'ops_func' in 'struct ftrace_ops'
                           if (found_op && op->ops_func)
                                           ~~  ^
   kernel/trace/ftrace.c:8200:9: error: no member named 'ops_func' in 'struct ftrace_ops'
                                   op->ops_func(op, FTRACE_OPS_CMD_DISABLE_SHARE_IPMODIFY_PEER);
                                   ~~  ^
   kernel/trace/ftrace.c:8203:16: error: use of undeclared identifier 'direct_mutex'; did you mean 'event_mutex'?
           mutex_unlock(&direct_mutex);
                         ^~~~~~~~~~~~
                         event_mutex
   kernel/trace/trace.h:1523:21: note: 'event_mutex' declared here
   extern struct mutex event_mutex;
                       ^

13 errors generated.

vim +8082 kernel/trace/ftrace.c

8051
8052 /*
8053 * When registering ftrace_ops with IPMODIFY, it is necessary to make sure
8054 * it doesn't conflict with any direct ftrace_ops. If there is existing
8055 * direct ftrace_ops on a kernel function being patched, call
8056 * FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER on it to enable sharing.
8057 *
8058 * @ops: ftrace_ops being registered.
8059 *
8060 * Returns:
8061 * 0 - @ops does not have IPMODIFY or @ops itself is DIRECT, no
8062 * change needed;
8063 * 1 - @ops has IPMODIFY, hold direct_mutex;
8064 * -EBUSY - currently registered DIRECT ftrace_ops cannot share the
8065 * same function with IPMODIFY, abort the register.
8066 * -EAGAIN - cannot make changes to currently registered DIRECT

  8067	 *                   ftrace_ops due to rare race conditions. Should retry
  8068	 *                   later. This is needed to avoid potential deadlocks
  8069	 *                   on the DIRECT ftrace_ops side.
  8070	 */
  8071	static int prepare_direct_functions_for_ipmodify(struct ftrace_ops *ops)
  8072		__acquires(&direct_mutex)
  8073	{
  8074		struct ftrace_func_entry *entry;
  8075		struct ftrace_hash *hash;
  8076		struct ftrace_ops *op;
  8077		int size, i, ret;
  8078	
  8079		if (!(ops->flags & FTRACE_OPS_FL_IPMODIFY))
  8080			return 0;
  8081	
> 8082		mutex_lock(&direct_mutex);
  8083	
> 8084		hash = ops->func_hash->filter_hash;
  8085		size = 1 << hash->size_bits;
  8086		for (i = 0; i < size; i++) {
  8087			hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
  8088				unsigned long ip = entry->ip;
  8089				bool found_op = false;
  8090	
  8091				mutex_lock(&ftrace_lock);
  8092				do_for_each_ftrace_op(op, ftrace_ops_list) {
  8093					if (!(op->flags & FTRACE_OPS_FL_DIRECT))
  8094						continue;
> 8095					if (ops_references_ip(op, ip)) {
  8096						found_op = true;
  8097						break;
  8098					}
  8099				} while_for_each_ftrace_op(op);
  8100				mutex_unlock(&ftrace_lock);
  8101	
  8102				if (found_op) {
> 8103					if (!op->ops_func) {

8104 ret = -EBUSY;
8105 goto err_out;
8106 }
8107 ret = op->ops_func(op, FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER);
8108 if (ret)
8109 goto err_out;
8110 }
8111 }
8112 }
8113
8114 /*
8115 * Didn't find any overlap with direct ftrace_ops, or the direct
8116 * function can share with ipmodify. Hold direct_mutex to make sure
8117 * this doesn't change until we are done.
8118 */
8119 return 1;
8120
8121 err_out:
8122 mutex_unlock(&direct_mutex);
8123 return ret;
8124 }
8125

Signature · 2 lines
0-DAY CI Kernel Test Service
https://01.org/lkp
#8 lore raw

Re: [PATCH v3 bpf-next 2/4] ftrace: allow IPMODIFY and DIRECT ops on the same function

Quoted 26 lines · kernel test robot

Hi Song,

I love your patch! Yet something to improve:

[auto build test ERROR on bpf-next/master]

url:    https://github.com/intel-lab-lkp/linux/commits/Song-Liu/ftrace-host-klp-and-bpf-trampoline-together/20220718-081533
base:   https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git master
config: x86_64-randconfig-a001 (https://download.01.org/0day-ci/archive/20220718/202207181140.tqIgD0Jp-lkp(a)intel.com/config )
compiler: clang version 15.0.0 (https://github.com/llvm/llvm-project d74b88c69dc2644bd0dc5d64e2d7413a0d4040e5)

reproduce (this is a W=1 build):
wget https://raw.githubusercontent.com/intel/lkp-tests/master/sbin/make.cross -O ~/bin/make.cross chmod +x ~/bin/make.cross
# https://github.com/intel-lab-lkp/linux/commit/1535f287d288f9b7540ec50f56da1fe437ac6512
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Song-Liu/ftrace-host-klp-and-bpf-trampoline-together/20220718-081533 git checkout 1535f287d288f9b7540ec50f56da1fe437ac6512
# save the config file
mkdir build_dir && cp config build_dir/.config
COMPILER_INSTALL_PATH=$HOME/0day COMPILER=clang make.cross W=1 O=build_dir ARCH=x86_64 SHELL=/bin/bash

If you fix the issue, kindly add following tag where applicable

Quoted 8 lines

All errors (new ones prefixed by >>):

Quoted 1 line
Quoted 1 line

kernel/trace/ftrace.c:8082:14: error: use of undeclared identifier 'direct_mutex'; did you mean 'event_mutex'?

          mutex_lock(&direct_mutex);
                      ^~~~~~~~~~~~
                      event_mutex

Folded the the fix in. I guess this should also fail on v2, but the kernel test robot didn't seem to find it.

Song

Quoted 145 lines

include/linux/mutex.h:187:44: note: expanded from macro 'mutex_lock'

  #define mutex_lock(lock) mutex_lock_nested(lock, 0)
                                             ^
  kernel/trace/trace.h:1523:21: note: 'event_mutex' declared here
  extern struct mutex event_mutex;
                      ^
Quoted 1 line
Quoted 1 line

kernel/trace/ftrace.c:8084:14: error: no member named 'func_hash' in 'struct ftrace_ops'

          hash = ops->func_hash->filter_hash;
                 ~~~  ^
Quoted 1 line
Quoted 1 line

kernel/trace/ftrace.c:8095:9: error: call to undeclared function 'ops_references_ip'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]

                                  if (ops_references_ip(op, ip)) {
                                      ^
Quoted 1 line
Quoted 1 line

kernel/trace/ftrace.c:8103:14: error: no member named 'ops_func' in 'struct ftrace_ops'

                                  if (!op->ops_func) {
                                       ~~  ^
  kernel/trace/ftrace.c:8107:15: error: no member named 'ops_func' in 'struct ftrace_ops'
                                  ret = op->ops_func(op, FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER);
                                        ~~  ^
  kernel/trace/ftrace.c:8122:16: error: use of undeclared identifier 'direct_mutex'; did you mean 'event_mutex'?
          mutex_unlock(&direct_mutex);
                        ^~~~~~~~~~~~
                        event_mutex
  kernel/trace/trace.h:1523:21: note: 'event_mutex' declared here
  extern struct mutex event_mutex;
                      ^
  kernel/trace/ftrace.c:8158:17: error: use of undeclared identifier 'direct_mutex'; did you mean 'event_mutex'?
                  mutex_unlock(&direct_mutex);
                                ^~~~~~~~~~~~
                                event_mutex
  kernel/trace/trace.h:1523:21: note: 'event_mutex' declared here
  extern struct mutex event_mutex;
                      ^
  kernel/trace/ftrace.c:8178:14: error: use of undeclared identifier 'direct_mutex'; did you mean 'event_mutex'?
          mutex_lock(&direct_mutex);
                      ^~~~~~~~~~~~
                      event_mutex
  include/linux/mutex.h:187:44: note: expanded from macro 'mutex_lock'
  #define mutex_lock(lock) mutex_lock_nested(lock, 0)
                                             ^
  kernel/trace/trace.h:1523:21: note: 'event_mutex' declared here
  extern struct mutex event_mutex;
                      ^
  kernel/trace/ftrace.c:8180:14: error: no member named 'func_hash' in 'struct ftrace_ops'
          hash = ops->func_hash->filter_hash;
                 ~~~  ^
  kernel/trace/ftrace.c:8191:9: error: call to undeclared function 'ops_references_ip'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
                                  if (ops_references_ip(op, ip)) {
                                      ^
  kernel/trace/ftrace.c:8199:24: error: no member named 'ops_func' in 'struct ftrace_ops'
                          if (found_op && op->ops_func)
                                          ~~  ^
  kernel/trace/ftrace.c:8200:9: error: no member named 'ops_func' in 'struct ftrace_ops'
                                  op->ops_func(op, FTRACE_OPS_CMD_DISABLE_SHARE_IPMODIFY_PEER);
                                  ~~  ^
  kernel/trace/ftrace.c:8203:16: error: use of undeclared identifier 'direct_mutex'; did you mean 'event_mutex'?
          mutex_unlock(&direct_mutex);
                        ^~~~~~~~~~~~
                        event_mutex
  kernel/trace/trace.h:1523:21: note: 'event_mutex' declared here
  extern struct mutex event_mutex;
                      ^

13 errors generated.

vim +8082 kernel/trace/ftrace.c

8051
8052 /*
8053 * When registering ftrace_ops with IPMODIFY, it is necessary to make sure
8054 * it doesn't conflict with any direct ftrace_ops. If there is existing
8055 * direct ftrace_ops on a kernel function being patched, call
8056 * FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER on it to enable sharing.
8057 *
8058 * @ops: ftrace_ops being registered.
8059 *
8060 * Returns:
8061 * 0 - @ops does not have IPMODIFY or @ops itself is DIRECT, no
8062 * change needed;
8063 * 1 - @ops has IPMODIFY, hold direct_mutex;
8064 * -EBUSY - currently registered DIRECT ftrace_ops cannot share the
8065 * same function with IPMODIFY, abort the register.
8066 * -EAGAIN - cannot make changes to currently registered DIRECT

 8067	 *                   ftrace_ops due to rare race conditions. Should retry
 8068	 *                   later. This is needed to avoid potential deadlocks
 8069	 *                   on the DIRECT ftrace_ops side.

8070 */
8071 static int prepare_direct_functions_for_ipmodify(struct ftrace_ops *ops)
8072 __acquires(&direct_mutex)
8073 {
8074 struct ftrace_func_entry *entry;
8075 struct ftrace_hash *hash;
8076 struct ftrace_ops *op;
8077 int size, i, ret;
8078
8079 if (!(ops->flags & FTRACE_OPS_FL_IPMODIFY))
8080 return 0;
8081

Quoted 1 line

8082 mutex_lock(&direct_mutex);

8083

Quoted 1 line

8084 hash = ops->func_hash->filter_hash;

8085 size = 1 << hash->size_bits;
8086 for (i = 0; i < size; i++) {
8087 hlist_for_each_entry(entry, &hash->buckets[i], hlist) {
8088 unsigned long ip = entry->ip;
8089 bool found_op = false;
8090
8091 mutex_lock(&ftrace_lock);
8092 do_for_each_ftrace_op(op, ftrace_ops_list) {
8093 if (!(op->flags & FTRACE_OPS_FL_DIRECT))
8094 continue;

Quoted 1 line

8095 if (ops_references_ip(op, ip)) {

8096 found_op = true;
8097 break;
8098 }
8099 } while_for_each_ftrace_op(op);
8100 mutex_unlock(&ftrace_lock);
8101
8102 if (found_op) {

Quoted 1 line

8103 if (!op->ops_func) {

8104 ret = -EBUSY;
8105 goto err_out;
8106 }
8107 ret = op->ops_func(op, FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER);
8108 if (ret)
8109 goto err_out;
8110 }
8111 }
8112 }
8113
8114 /*
8115 * Didn't find any overlap with direct ftrace_ops, or the direct
8116 * function can share with ipmodify. Hold direct_mutex to make sure
8117 * this doesn't change until we are done.
8118 */
8119 return 1;
8120
8121 err_out:
8122 mutex_unlock(&direct_mutex);
8123 return ret;
8124 }
8125

Signature · 2 lines
0-DAY CI Kernel Test Service
https://01.org/lkp 
maintainer
#2 lore raw

Re: [PATCH v3 bpf-next 1/4] ftrace: add modify_ftrace_direct_multi_nolock

In reply to Song Liu
Quoted 8 lines · Song Liu

This is similar to modify_ftrace_direct_multi, but does not acquire direct_mutex. This is useful when direct_mutex is already locked by the user.

kernel/trace/ftrace.c +0 -0
@@ -5691,22 +5691,8 @@ int unregister_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr)

kernel/trace/ftrace.c int modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr) · line 5707

Quoted 6 lines
kernel/trace/ftrace.c +1 -1
@@ -5717,12 +5703,8 @@ int modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr)
 	int i, size;
 	int err;
 
-	if (check_direct_multi(ops))
+	if (WARN_ON_ONCE(!mutex_is_locked(&direct_mutex)))
 		return -EINVAL;

IMHO, it is better to use:

	lockdep_assert_held_once(&direct_mutex);

It will always catch the problem when called without the lock and lockdep is enabled.

Quoted 72 lines
kernel/trace/ftrace.c +52 -6
-	if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
-		return -EINVAL;
-
-	mutex_lock(&direct_mutex);
 
 	/* Enable the tmp_ops to have the same functions as the direct ops */
 	ftrace_ops_init(&tmp_ops);
@@ -5730,7 +5712,7 @@ int modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr)
 
 	err = register_ftrace_function(&tmp_ops);
 	if (err)
-		goto out_direct;
+		return err;
 
 	/*
 	 * Now the ftrace_ops_list_func() is called to do the direct callers.
@@ -5754,7 +5736,64 @@ int modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr)
 	/* Removing the tmp_ops will add the updated direct callers to the functions */
 	unregister_ftrace_function(&tmp_ops);
 
- out_direct:
+	return err;
+}
+
+/**
+ * modify_ftrace_direct_multi_nolock - Modify an existing direct 'multi' call
+ * to call something else
+ * @ops: The address of the struct ftrace_ops object
+ * @addr: The address of the new trampoline to call at @ops functions
+ *
+ * This is used to unregister currently registered direct caller and
+ * register new one @addr on functions registered in @ops object.
+ *
+ * Note there's window between ftrace_shutdown and ftrace_startup calls
+ * where there will be no callbacks called.
+ *
+ * Caller should already have direct_mutex locked, so we don't lock
+ * direct_mutex here.
+ *
+ * Returns: zero on success. Non zero on error, which includes:
+ *  -EINVAL - The @ops object was not properly registered.
+ */
+int modify_ftrace_direct_multi_nolock(struct ftrace_ops *ops, unsigned long addr)
+{
+	if (check_direct_multi(ops))
+		return -EINVAL;
+	if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
+		return -EINVAL;
+
+	return __modify_ftrace_direct_multi(ops, addr);
+}
+EXPORT_SYMBOL_GPL(modify_ftrace_direct_multi_nolock);
+
+/**
+ * modify_ftrace_direct_multi - Modify an existing direct 'multi' call
+ * to call something else
+ * @ops: The address of the struct ftrace_ops object
+ * @addr: The address of the new trampoline to call at @ops functions
+ *
+ * This is used to unregister currently registered direct caller and
+ * register new one @addr on functions registered in @ops object.
+ *
+ * Note there's window between ftrace_shutdown and ftrace_startup calls
+ * where there will be no callbacks called.
+ *
+ * Returns: zero on success. Non zero on error, which includes:
+ *  -EINVAL - The @ops object was not properly registered.
+ */
+int modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr)
+{
+	int err;
+

kernel/trace/ftrace.c int modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr) · line 5799

Quoted 10 lines
kernel/trace/ftrace.c +7 -0
+	if (check_direct_multi(ops))
+		return -EINVAL;
+	if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
+		return -EINVAL;
+
+	mutex_lock(&direct_mutex);
+	err = __modify_ftrace_direct_multi(ops, addr);
 	mutex_unlock(&direct_mutex);
 	return err;
 }

I would personally do:

int __modify_ftrace_direct_multi(struct ftrace_ops *ops,
unsigned long addr, bool lock)

{
	int err;

	if (check_direct_multi(ops))
		return -EINVAL;
	if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
		return -EINVAL;

	if (lock)
		mutex_lock(&direct_mutex);

	err = __modify_ftrace_direct_multi(ops, addr);

	if (lock)
		mutex_unlock(&direct_mutex);

	return err;
}

int modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr)

{
	__modify_ftrace_direct_multi(ops, addr, true);
}

int modify_ftrace_direct_multi_nolock(struct ftrace_ops *ops, unsigned long addr)

{
	__modify_ftrace_direct_multi(ops, addr, false);
}

To avoid duplication of the checks. But it is a matter of taste.

Best Regards,
Petr

maintainer
#11 lore raw

Re: [PATCH v3 bpf-next 4/4] bpf: support bpf_trampoline on functions with IPMODIFY (e.g. livepatch)

In reply to Song Liu
Quoted 26 lines · Song Liu

When tracing a function with IPMODIFY ftrace_ops (livepatch), the bpf trampoline must follow the instruction pointer saved on stack. This needs extra handling for bpf trampolines with BPF_TRAMP_F_CALL_ORIG flag.

Implement bpf_tramp_ftrace_ops_func and use it for the ftrace_ops used by BPF trampoline. This enables tracing functions with livepatch.

This also requires moving bpf trampoline to *_ftrace_direct_mult APIs.

kernel/bpf/trampoline.c +4 -0
@@ -13,6 +13,7 @@
 #include <linux/static_call.h>
 #include <linux/bpf_verifier.h>
 #include <linux/bpf_lsm.h>
+#include <linux/delay.h>
 
 /* dummy _ops. The verifier will operate on target program's ops. */
 const struct bpf_verifier_ops bpf_extension_verifier_ops = {
@@ -29,6 +30,81 @@ static struct hlist_head trampoline_table[TRAMPOLINE_TABLE_SIZE];
 /* serializes access to trampoline_table */
 static DEFINE_MUTEX(trampoline_mutex);
 
+#ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
+static int bpf_trampoline_update(struct bpf_trampoline *tr, bool lock_direct_mutex);
+

kernel/bpf/trampoline.c static struct hlist_head trampoline_table[TRAMPOLINE_TABLE_SIZE]; · line 45

Quoted 10 lines
kernel/bpf/trampoline.c +10 -0
+static int bpf_tramp_ftrace_ops_func(struct ftrace_ops *ops, enum ftrace_ops_cmd cmd)
+{
+	struct bpf_trampoline *tr = ops->private;
+	int ret = 0;
+
+	if (cmd == FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_SELF) {
+		/* This is called inside register_ftrace_direct_multi(), so
+		 * tr->mutex is already locked.
+		 */
+		WARN_ON_ONCE(!mutex_is_locked(&tr->mutex));

Again, better is:

		lockdep_assert_held_once(&tr->mutex);
Quoted 27 lines
kernel/bpf/trampoline.c +27 -0
+
+		/* Instead of updating the trampoline here, we propagate
+		 * -EAGAIN to register_ftrace_direct_multi(). Then we can
+		 * retry register_ftrace_direct_multi() after updating the
+		 * trampoline.
+		 */
+		if ((tr->flags & BPF_TRAMP_F_CALL_ORIG) &&
+		    !(tr->flags & BPF_TRAMP_F_ORIG_STACK)) {
+			if (WARN_ON_ONCE(tr->flags & BPF_TRAMP_F_SHARE_IPMODIFY))
+				return -EBUSY;
+
+			tr->flags |= BPF_TRAMP_F_SHARE_IPMODIFY;
+			return -EAGAIN;
+		}
+
+		return 0;
+	}
+
+	/* The normal locking order is
+	 *    tr->mutex => direct_mutex (ftrace.c) => ftrace_lock (ftrace.c)
+	 *
+	 * The following two commands are called from
+	 *
+	 *   prepare_direct_functions_for_ipmodify
+	 *   cleanup_direct_functions_after_ipmodify
+	 *
+	 * In both cases, direct_mutex is already locked. Use

kernel/bpf/trampoline.c static struct hlist_head trampoline_table[TRAMPOLINE_TABLE_SIZE]; · line 82

Quoted 10 lines
kernel/bpf/trampoline.c +10 -0
+	 * mutex_trylock(&tr->mutex) to avoid deadlock in race condition
+	 * (something else is making changes to this same trampoline).
+	 */
+	if (!mutex_trylock(&tr->mutex)) {
+		/* sleep 1 ms to make sure whatever holding tr->mutex makes
+		 * some progress.
+		 */
+		msleep(1);
+		return -EAGAIN;
+	}

Huh, this looks horrible. And I do not get it. The above block prints a warning when the mutex is not taken. Why it is already taken when cmd == FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_SELF
and why it has to be explicitly taken otherwise?

Would it be possible to call prepare_direct_functions_for_ipmodify(), cleanup_direct_functions_after_ipmodify() with rt->mutex already taken so that the ordering is correct even in this case.

That said, this is the first version when I am in Cc. I am not sure if it has already been discussed.

Quoted 17 lines
kernel/bpf/trampoline.c +17 -0
+	switch (cmd) {
+	case FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER:
+		tr->flags |= BPF_TRAMP_F_SHARE_IPMODIFY;
+
+		if ((tr->flags & BPF_TRAMP_F_CALL_ORIG) &&
+		    !(tr->flags & BPF_TRAMP_F_ORIG_STACK))
+			ret = bpf_trampoline_update(tr, false /* lock_direct_mutex */);
+		break;
+	case FTRACE_OPS_CMD_DISABLE_SHARE_IPMODIFY_PEER:
+		tr->flags &= ~BPF_TRAMP_F_SHARE_IPMODIFY;
+
+		if (tr->flags & BPF_TRAMP_F_ORIG_STACK)
+			ret = bpf_trampoline_update(tr, false /* lock_direct_mutex */);
+		break;
+	default:
+		ret = -EINVAL;
+		break;

kernel/bpf/trampoline.c static struct hlist_head trampoline_table[TRAMPOLINE_TABLE_SIZE]; · line 110

Quoted 10 lines
kernel/bpf/trampoline.c +7 -0
+	};
+
+	mutex_unlock(&tr->mutex);
+	return ret;
+}
+#endif
+
 bool bpf_prog_has_trampoline(const struct bpf_prog *prog)
 {
 	enum bpf_attach_type eatype = prog->expected_attach_type;

Note that I did not do proper review. I not much familiar with the ftrace code. I just wanted to check how much this patchset affects livepatching and noticed the commented things.

Best Regards,
Petr

#3 lore raw

Re: [PATCH v3 bpf-next 1/4] ftrace: add modify_ftrace_direct_multi_nolock

In reply to Petr Mladek

Hi Petr,

Thanks for your quick review!

Quoted 20 lines · Petr Mladek
Quoted 8 lines · Song Liu

This is similar to modify_ftrace_direct_multi, but does not acquire direct_mutex. This is useful when direct_mutex is already locked by the user.

kernel/trace/ftrace.c +0 -0
@@ -5691,22 +5691,8 @@ int unregister_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr)

kernel/trace/ftrace.c int modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr) · line 5707

Quoted 6 lines
kernel/trace/ftrace.c +1 -1
@@ -5717,12 +5703,8 @@ int modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr)
 	int i, size;
 	int err;
 
-	if (check_direct_multi(ops))
+	if (WARN_ON_ONCE(!mutex_is_locked(&direct_mutex)))
 		return -EINVAL;

IMHO, it is better to use:

Quoted 4 lines
	lockdep_assert_held_once(&direct_mutex);

It will always catch the problem when called without the lock and lockdep is enabled.

Will fix.

Quoted 88 lines
Quoted 73 lines
kernel/trace/ftrace.c +52 -6
-	if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
-		return -EINVAL;
-
-	mutex_lock(&direct_mutex);
 
 	/* Enable the tmp_ops to have the same functions as the direct ops */
 	ftrace_ops_init(&tmp_ops);
@@ -5730,7 +5712,7 @@ int modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr)
 
 	err = register_ftrace_function(&tmp_ops);
 	if (err)
-		goto out_direct;
+		return err;
 
 	/*
 	 * Now the ftrace_ops_list_func() is called to do the direct callers.
@@ -5754,7 +5736,64 @@ int modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr)
 	/* Removing the tmp_ops will add the updated direct callers to the functions */
 	unregister_ftrace_function(&tmp_ops);
 
- out_direct:
+	return err;
+}
+
+/**
+ * modify_ftrace_direct_multi_nolock - Modify an existing direct 'multi' call
+ * to call something else
+ * @ops: The address of the struct ftrace_ops object
+ * @addr: The address of the new trampoline to call at @ops functions
+ *
+ * This is used to unregister currently registered direct caller and
+ * register new one @addr on functions registered in @ops object.
+ *
+ * Note there's window between ftrace_shutdown and ftrace_startup calls
+ * where there will be no callbacks called.
+ *
+ * Caller should already have direct_mutex locked, so we don't lock
+ * direct_mutex here.
+ *
+ * Returns: zero on success. Non zero on error, which includes:
+ *  -EINVAL - The @ops object was not properly registered.
+ */
+int modify_ftrace_direct_multi_nolock(struct ftrace_ops *ops, unsigned long addr)
+{
+	if (check_direct_multi(ops))
+		return -EINVAL;
+	if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
+		return -EINVAL;
+
+	return __modify_ftrace_direct_multi(ops, addr);
+}
+EXPORT_SYMBOL_GPL(modify_ftrace_direct_multi_nolock);
+
+/**
+ * modify_ftrace_direct_multi - Modify an existing direct 'multi' call
+ * to call something else
+ * @ops: The address of the struct ftrace_ops object
+ * @addr: The address of the new trampoline to call at @ops functions
+ *
+ * This is used to unregister currently registered direct caller and
+ * register new one @addr on functions registered in @ops object.
+ *
+ * Note there's window between ftrace_shutdown and ftrace_startup calls
+ * where there will be no callbacks called.
+ *
+ * Returns: zero on success. Non zero on error, which includes:
+ *  -EINVAL - The @ops object was not properly registered.
+ */
+int modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr)
+{
+	int err;
+

kernel/trace/ftrace.c int modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr) · line 5799

Quoted 10 lines
kernel/trace/ftrace.c +7 -0
+	if (check_direct_multi(ops))
+		return -EINVAL;
+	if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
+		return -EINVAL;
+
+	mutex_lock(&direct_mutex);
+	err = __modify_ftrace_direct_multi(ops, addr);
 	mutex_unlock(&direct_mutex);
 	return err;
 }

I would personally do:

int __modify_ftrace_direct_multi(struct ftrace_ops *ops,
unsigned long addr, bool lock)

Quoted 15 lines
{
	int err;

	if (check_direct_multi(ops))
		return -EINVAL;
	if (!(ops->flags & FTRACE_OPS_FL_ENABLED))
		return -EINVAL;

	if (lock)
		mutex_lock(&direct_mutex);

	err = __modify_ftrace_direct_multi(ops, addr);

	if (lock)
		mutex_unlock(&direct_mutex);

The "if (lock) lock" pattern bothers me a little. But I agrees this is a matter of taste. If other folks prefers this way, I will make the change.

Thanks,
Song

Quoted 18 lines
	return err;
}

int modify_ftrace_direct_multi(struct ftrace_ops *ops, unsigned long addr)

{
	__modify_ftrace_direct_multi(ops, addr, true);
}

int modify_ftrace_direct_multi_nolock(struct ftrace_ops *ops, unsigned long addr)

{
	__modify_ftrace_direct_multi(ops, addr, false);
}

To avoid duplication of the checks. But it is a matter of taste.

Best Regards,
Petr

#12 lore raw

Re: [PATCH v3 bpf-next 4/4] bpf: support bpf_trampoline on functions with IPMODIFY (e.g. livepatch)

In reply to Petr Mladek
Quoted 44 lines · Petr Mladek
Quoted 26 lines · Song Liu

When tracing a function with IPMODIFY ftrace_ops (livepatch), the bpf trampoline must follow the instruction pointer saved on stack. This needs extra handling for bpf trampolines with BPF_TRAMP_F_CALL_ORIG flag.

Implement bpf_tramp_ftrace_ops_func and use it for the ftrace_ops used by BPF trampoline. This enables tracing functions with livepatch.

This also requires moving bpf trampoline to *_ftrace_direct_mult APIs.

kernel/bpf/trampoline.c +4 -0
@@ -13,6 +13,7 @@
 #include <linux/static_call.h>
 #include <linux/bpf_verifier.h>
 #include <linux/bpf_lsm.h>
+#include <linux/delay.h>
 
 /* dummy _ops. The verifier will operate on target program's ops. */
 const struct bpf_verifier_ops bpf_extension_verifier_ops = {
@@ -29,6 +30,81 @@ static struct hlist_head trampoline_table[TRAMPOLINE_TABLE_SIZE];
 /* serializes access to trampoline_table */
 static DEFINE_MUTEX(trampoline_mutex);
 
+#ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
+static int bpf_trampoline_update(struct bpf_trampoline *tr, bool lock_direct_mutex);
+

kernel/bpf/trampoline.c static struct hlist_head trampoline_table[TRAMPOLINE_TABLE_SIZE]; · line 45

Quoted 10 lines
kernel/bpf/trampoline.c +10 -0
+static int bpf_tramp_ftrace_ops_func(struct ftrace_ops *ops, enum ftrace_ops_cmd cmd)
+{
+	struct bpf_trampoline *tr = ops->private;
+	int ret = 0;
+
+	if (cmd == FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_SELF) {
+		/* This is called inside register_ftrace_direct_multi(), so
+		 * tr->mutex is already locked.
+		 */
+		WARN_ON_ONCE(!mutex_is_locked(&tr->mutex));

Again, better is:

Quoted 1 line
		lockdep_assert_held_once(&tr->mutex);

Will fix.

Quoted 35 lines
Quoted 35 lines
kernel/bpf/trampoline.c +34 -0
+
+		/* Instead of updating the trampoline here, we propagate
+		 * -EAGAIN to register_ftrace_direct_multi(). Then we can
+		 * retry register_ftrace_direct_multi() after updating the
+		 * trampoline.
+		 */
+		if ((tr->flags & BPF_TRAMP_F_CALL_ORIG) &&
+		    !(tr->flags & BPF_TRAMP_F_ORIG_STACK)) {
+			if (WARN_ON_ONCE(tr->flags & BPF_TRAMP_F_SHARE_IPMODIFY))
+				return -EBUSY;
+
+			tr->flags |= BPF_TRAMP_F_SHARE_IPMODIFY;
+			return -EAGAIN;
+		}
+
+		return 0;
+	}
+
+	/* The normal locking order is
+	 *    tr->mutex => direct_mutex (ftrace.c) => ftrace_lock (ftrace.c)
+	 *
+	 * The following two commands are called from
+	 *
+	 *   prepare_direct_functions_for_ipmodify
+	 *   cleanup_direct_functions_after_ipmodify
+	 *
+	 * In both cases, direct_mutex is already locked. Use
+	 * mutex_trylock(&tr->mutex) to avoid deadlock in race condition
+	 * (something else is making changes to this same trampoline).
+	 */
+	if (!mutex_trylock(&tr->mutex)) {
+		/* sleep 1 ms to make sure whatever holding tr->mutex makes
+		 * some progress.
+		 */
Quoted 8 lines

kernel/bpf/trampoline.c static struct hlist_head trampoline_table[TRAMPOLINE_TABLE_SIZE]; · line 82

Quoted 3 lines
kernel/bpf/trampoline.c +3 -0
+		msleep(1);
+		return -EAGAIN;
+	}

Huh, this looks horrible. And I do not get it. The above block prints a warning when the mutex is not taken. Why it is already taken when cmd == FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_SELF
and why it has to be explicitly taken otherwise?

There are two different scenarios:

1. livepatch applied first, then bpf trampoline is registered.

In this case, we call ops_func(FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_SELF). _SELF means we are making change to the DIRECT ops (bpf trampoline) itself. In this case, tr->mutex is already taken.

2. bpf_trampoline registered first, then livepatch is applied.

In this case, ftrace cannot take tr->mutex first. Instead, ftrace has to lock direct_mutex, find any conflict DIRECT ops, and call ops_func(FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER). _PEER means this is called by a peer ftrace ops (livepatch).

Quoted 32 lines

Would it be possible to call prepare_direct_functions_for_ipmodify(), cleanup_direct_functions_after_ipmodify() with rt->mutex already taken so that the ordering is correct even in this case.

That said, this is the first version when I am in Cc. I am not sure if it has already been discussed.

Quoted 23 lines
kernel/bpf/trampoline.c +23 -0
+	switch (cmd) {
+	case FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER:
+		tr->flags |= BPF_TRAMP_F_SHARE_IPMODIFY;
+
+		if ((tr->flags & BPF_TRAMP_F_CALL_ORIG) &&
+		    !(tr->flags & BPF_TRAMP_F_ORIG_STACK))
+			ret = bpf_trampoline_update(tr, false /* lock_direct_mutex */);
+		break;
+	case FTRACE_OPS_CMD_DISABLE_SHARE_IPMODIFY_PEER:
+		tr->flags &= ~BPF_TRAMP_F_SHARE_IPMODIFY;
+
+		if (tr->flags & BPF_TRAMP_F_ORIG_STACK)
+			ret = bpf_trampoline_update(tr, false /* lock_direct_mutex */);
+		break;
+	default:
+		ret = -EINVAL;
+		break;
+	};
+
+	mutex_unlock(&tr->mutex);
+	return ret;
+}
+#endif
Quoted 8 lines

kernel/bpf/trampoline.c static struct hlist_head trampoline_table[TRAMPOLINE_TABLE_SIZE]; · line 110

Quoted 4 lines
kernel/bpf/trampoline.c +1 -0
+
 bool bpf_prog_has_trampoline(const struct bpf_prog *prog)
 {
 	enum bpf_attach_type eatype = prog->expected_attach_type;

Note that I did not do proper review. I not much familiar with the ftrace code. I just wanted to check how much this patchset affects livepatching and noticed the commented things.

Before this set, livepatch and bpf trampoline cannot work on the same function. Whichever applied latter will fail. After this, the two will work almost perfectly together. By "almost" I mean the race condition protected by the mutex_trylock:

	if (!mutex_trylock(&tr->mutex)) {
		/* sleep 1 ms to make sure whatever holding tr->mutex makes
		 * some progress.
		 */
		msleep(1);
		return -EAGAIN;
	}

If livepatch is applied while something is making changes to the bpf trampoline at the same time, livepatch code will get -EAGAIN from register_ftrace_function(). Then we need to retry from livepatch side. AFAICT, kpatch user space already does the retry, so it gonna work as-is. I am not sure about other user space though.

The msleep(1) is suggested by Steven to avoid deadlock in RT case [1].

Does this make sense?

Thanks,
Song

[1] https://lore.kernel.org/bpf/[email protected]/

#13 lore raw

Re: [PATCH v3 bpf-next 4/4] bpf: support bpf_trampoline on functions with IPMODIFY (e.g. livepatch)

In reply to Petr Mladek
Quoted 44 lines · Petr Mladek
Quoted 26 lines · Song Liu

When tracing a function with IPMODIFY ftrace_ops (livepatch), the bpf trampoline must follow the instruction pointer saved on stack. This needs extra handling for bpf trampolines with BPF_TRAMP_F_CALL_ORIG flag.

Implement bpf_tramp_ftrace_ops_func and use it for the ftrace_ops used by BPF trampoline. This enables tracing functions with livepatch.

This also requires moving bpf trampoline to *_ftrace_direct_mult APIs.

kernel/bpf/trampoline.c +4 -0
@@ -13,6 +13,7 @@
 #include <linux/static_call.h>
 #include <linux/bpf_verifier.h>
 #include <linux/bpf_lsm.h>
+#include <linux/delay.h>
 
 /* dummy _ops. The verifier will operate on target program's ops. */
 const struct bpf_verifier_ops bpf_extension_verifier_ops = {
@@ -29,6 +30,81 @@ static struct hlist_head trampoline_table[TRAMPOLINE_TABLE_SIZE];
 /* serializes access to trampoline_table */
 static DEFINE_MUTEX(trampoline_mutex);
 
+#ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
+static int bpf_trampoline_update(struct bpf_trampoline *tr, bool lock_direct_mutex);
+

kernel/bpf/trampoline.c static struct hlist_head trampoline_table[TRAMPOLINE_TABLE_SIZE]; · line 45

Quoted 10 lines
kernel/bpf/trampoline.c +10 -0
+static int bpf_tramp_ftrace_ops_func(struct ftrace_ops *ops, enum ftrace_ops_cmd cmd)
+{
+	struct bpf_trampoline *tr = ops->private;
+	int ret = 0;
+
+	if (cmd == FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_SELF) {
+		/* This is called inside register_ftrace_direct_multi(), so
+		 * tr->mutex is already locked.
+		 */
+		WARN_ON_ONCE(!mutex_is_locked(&tr->mutex));

Again, better is:

Quoted 1 line
		lockdep_assert_held_once(&tr->mutex);

Will fix.

Quoted 35 lines
Quoted 35 lines
kernel/bpf/trampoline.c +34 -0
+
+		/* Instead of updating the trampoline here, we propagate
+		 * -EAGAIN to register_ftrace_direct_multi(). Then we can
+		 * retry register_ftrace_direct_multi() after updating the
+		 * trampoline.
+		 */
+		if ((tr->flags & BPF_TRAMP_F_CALL_ORIG) &&
+		    !(tr->flags & BPF_TRAMP_F_ORIG_STACK)) {
+			if (WARN_ON_ONCE(tr->flags & BPF_TRAMP_F_SHARE_IPMODIFY))
+				return -EBUSY;
+
+			tr->flags |= BPF_TRAMP_F_SHARE_IPMODIFY;
+			return -EAGAIN;
+		}
+
+		return 0;
+	}
+
+	/* The normal locking order is
+	 *    tr->mutex => direct_mutex (ftrace.c) => ftrace_lock (ftrace.c)
+	 *
+	 * The following two commands are called from
+	 *
+	 *   prepare_direct_functions_for_ipmodify
+	 *   cleanup_direct_functions_after_ipmodify
+	 *
+	 * In both cases, direct_mutex is already locked. Use
+	 * mutex_trylock(&tr->mutex) to avoid deadlock in race condition
+	 * (something else is making changes to this same trampoline).
+	 */
+	if (!mutex_trylock(&tr->mutex)) {
+		/* sleep 1 ms to make sure whatever holding tr->mutex makes
+		 * some progress.
+		 */
Quoted 8 lines

kernel/bpf/trampoline.c static struct hlist_head trampoline_table[TRAMPOLINE_TABLE_SIZE]; · line 82

Quoted 3 lines
kernel/bpf/trampoline.c +3 -0
+		msleep(1);
+		return -EAGAIN;
+	}

Huh, this looks horrible. And I do not get it. The above block prints a warning when the mutex is not taken. Why it is already taken when cmd == FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_SELF
and why it has to be explicitly taken otherwise?

There are two different scenarios:

1. livepatch applied first, then bpf trampoline is registered.

In this case, we call ops_func(FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_SELF). _SELF means we are making change to the DIRECT ops (bpf trampoline) itself. In this case, tr->mutex is already taken.

2. bpf_trampoline registered first, then livepatch is applied.

In this case, ftrace cannot take tr->mutex first. Instead, ftrace has to lock direct_mutex, find any conflict DIRECT ops, and call ops_func(FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER). _PEER means this is called by a peer ftrace ops (livepatch).

Quoted 32 lines

Would it be possible to call prepare_direct_functions_for_ipmodify(), cleanup_direct_functions_after_ipmodify() with rt->mutex already taken so that the ordering is correct even in this case.

That said, this is the first version when I am in Cc. I am not sure if it has already been discussed.

Quoted 23 lines
kernel/bpf/trampoline.c +23 -0
+	switch (cmd) {
+	case FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER:
+		tr->flags |= BPF_TRAMP_F_SHARE_IPMODIFY;
+
+		if ((tr->flags & BPF_TRAMP_F_CALL_ORIG) &&
+		    !(tr->flags & BPF_TRAMP_F_ORIG_STACK))
+			ret = bpf_trampoline_update(tr, false /* lock_direct_mutex */);
+		break;
+	case FTRACE_OPS_CMD_DISABLE_SHARE_IPMODIFY_PEER:
+		tr->flags &= ~BPF_TRAMP_F_SHARE_IPMODIFY;
+
+		if (tr->flags & BPF_TRAMP_F_ORIG_STACK)
+			ret = bpf_trampoline_update(tr, false /* lock_direct_mutex */);
+		break;
+	default:
+		ret = -EINVAL;
+		break;
+	};
+
+	mutex_unlock(&tr->mutex);
+	return ret;
+}
+#endif
Quoted 8 lines

kernel/bpf/trampoline.c static struct hlist_head trampoline_table[TRAMPOLINE_TABLE_SIZE]; · line 110

Quoted 4 lines
kernel/bpf/trampoline.c +1 -0
+
 bool bpf_prog_has_trampoline(const struct bpf_prog *prog)
 {
 	enum bpf_attach_type eatype = prog->expected_attach_type;

Note that I did not do proper review. I not much familiar with the ftrace code. I just wanted to check how much this patchset affects livepatching and noticed the commented things.

Before this set, livepatch and bpf trampoline cannot work on the same function. Whichever applied latter will fail. After this, the two will work almost perfectly together. By "almost" I mean the race condition protected by the mutex_trylock:

	if (!mutex_trylock(&tr->mutex)) {
		/* sleep 1 ms to make sure whatever holding tr->mutex makes
		 * some progress.
		 */
		msleep(1);
		return -EAGAIN;
	}

If livepatch is applied while something is making changes to the bpf trampoline at the same time, livepatch code will get -EAGAIN from register_ftrace_function(). Then we need to retry from livepatch side. AFAICT, kpatch user space already does the retry, so it gonna work as-is. I am not sure about other user space though.

The msleep(1) is suggested by Steven to avoid deadlock in RT case [1].

Does this make sense?

Thanks,
Song

[1] https://lore.kernel.org/bpf/[email protected]/