xref: /linux-6.15/kernel/livepatch/transition.c (revision ac59a471)
1 /*
2  * transition.c - Kernel Live Patching transition functions
3  *
4  * Copyright (C) 2015-2016 Josh Poimboeuf <[email protected]>
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
21 
22 #include <linux/cpu.h>
23 #include <linux/stacktrace.h>
24 #include "core.h"
25 #include "patch.h"
26 #include "transition.h"
27 #include "../sched/sched.h"
28 
29 #define MAX_STACK_ENTRIES  100
30 #define STACK_ERR_BUF_SIZE 128
31 
32 #define SIGNALS_TIMEOUT 15
33 
34 struct klp_patch *klp_transition_patch;
35 
36 static int klp_target_state = KLP_UNDEFINED;
37 
38 static unsigned int klp_signals_cnt;
39 
40 /*
41  * This work can be performed periodically to finish patching or unpatching any
42  * "straggler" tasks which failed to transition in the first attempt.
43  */
44 static void klp_transition_work_fn(struct work_struct *work)
45 {
46 	mutex_lock(&klp_mutex);
47 
48 	if (klp_transition_patch)
49 		klp_try_complete_transition();
50 
51 	mutex_unlock(&klp_mutex);
52 }
53 static DECLARE_DELAYED_WORK(klp_transition_work, klp_transition_work_fn);
54 
55 /*
56  * This function is just a stub to implement a hard force
57  * of synchronize_rcu(). This requires synchronizing
58  * tasks even in userspace and idle.
59  */
60 static void klp_sync(struct work_struct *work)
61 {
62 }
63 
64 /*
65  * We allow to patch also functions where RCU is not watching,
66  * e.g. before user_exit(). We can not rely on the RCU infrastructure
67  * to do the synchronization. Instead hard force the sched synchronization.
68  *
69  * This approach allows to use RCU functions for manipulating func_stack
70  * safely.
71  */
72 static void klp_synchronize_transition(void)
73 {
74 	schedule_on_each_cpu(klp_sync);
75 }
76 
77 /*
78  * The transition to the target patch state is complete.  Clean up the data
79  * structures.
80  */
81 static void klp_complete_transition(void)
82 {
83 	struct klp_object *obj;
84 	struct klp_func *func;
85 	struct task_struct *g, *task;
86 	unsigned int cpu;
87 
88 	pr_debug("'%s': completing %s transition\n",
89 		 klp_transition_patch->mod->name,
90 		 klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
91 
92 	if (klp_transition_patch->replace && klp_target_state == KLP_PATCHED) {
93 		klp_discard_replaced_patches(klp_transition_patch);
94 		klp_discard_nops(klp_transition_patch);
95 	}
96 
97 	if (klp_target_state == KLP_UNPATCHED) {
98 		/*
99 		 * All tasks have transitioned to KLP_UNPATCHED so we can now
100 		 * remove the new functions from the func_stack.
101 		 */
102 		klp_unpatch_objects(klp_transition_patch);
103 
104 		/*
105 		 * Make sure klp_ftrace_handler() can no longer see functions
106 		 * from this patch on the ops->func_stack.  Otherwise, after
107 		 * func->transition gets cleared, the handler may choose a
108 		 * removed function.
109 		 */
110 		klp_synchronize_transition();
111 	}
112 
113 	klp_for_each_object(klp_transition_patch, obj)
114 		klp_for_each_func(obj, func)
115 			func->transition = false;
116 
117 	/* Prevent klp_ftrace_handler() from seeing KLP_UNDEFINED state */
118 	if (klp_target_state == KLP_PATCHED)
119 		klp_synchronize_transition();
120 
121 	read_lock(&tasklist_lock);
122 	for_each_process_thread(g, task) {
123 		WARN_ON_ONCE(test_tsk_thread_flag(task, TIF_PATCH_PENDING));
124 		task->patch_state = KLP_UNDEFINED;
125 	}
126 	read_unlock(&tasklist_lock);
127 
128 	for_each_possible_cpu(cpu) {
129 		task = idle_task(cpu);
130 		WARN_ON_ONCE(test_tsk_thread_flag(task, TIF_PATCH_PENDING));
131 		task->patch_state = KLP_UNDEFINED;
132 	}
133 
134 	klp_for_each_object(klp_transition_patch, obj) {
135 		if (!klp_is_object_loaded(obj))
136 			continue;
137 		if (klp_target_state == KLP_PATCHED)
138 			klp_post_patch_callback(obj);
139 		else if (klp_target_state == KLP_UNPATCHED)
140 			klp_post_unpatch_callback(obj);
141 	}
142 
143 	pr_notice("'%s': %s complete\n", klp_transition_patch->mod->name,
144 		  klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
145 
146 	klp_target_state = KLP_UNDEFINED;
147 	klp_transition_patch = NULL;
148 }
149 
150 /*
151  * This is called in the error path, to cancel a transition before it has
152  * started, i.e. klp_init_transition() has been called but
153  * klp_start_transition() hasn't.  If the transition *has* been started,
154  * klp_reverse_transition() should be used instead.
155  */
156 void klp_cancel_transition(void)
157 {
158 	if (WARN_ON_ONCE(klp_target_state != KLP_PATCHED))
159 		return;
160 
161 	pr_debug("'%s': canceling patching transition, going to unpatch\n",
162 		 klp_transition_patch->mod->name);
163 
164 	klp_target_state = KLP_UNPATCHED;
165 	klp_complete_transition();
166 }
167 
168 /*
169  * Switch the patched state of the task to the set of functions in the target
170  * patch state.
171  *
172  * NOTE: If task is not 'current', the caller must ensure the task is inactive.
173  * Otherwise klp_ftrace_handler() might read the wrong 'patch_state' value.
174  */
175 void klp_update_patch_state(struct task_struct *task)
176 {
177 	/*
178 	 * A variant of synchronize_rcu() is used to allow patching functions
179 	 * where RCU is not watching, see klp_synchronize_transition().
180 	 */
181 	preempt_disable_notrace();
182 
183 	/*
184 	 * This test_and_clear_tsk_thread_flag() call also serves as a read
185 	 * barrier (smp_rmb) for two cases:
186 	 *
187 	 * 1) Enforce the order of the TIF_PATCH_PENDING read and the
188 	 *    klp_target_state read.  The corresponding write barrier is in
189 	 *    klp_init_transition().
190 	 *
191 	 * 2) Enforce the order of the TIF_PATCH_PENDING read and a future read
192 	 *    of func->transition, if klp_ftrace_handler() is called later on
193 	 *    the same CPU.  See __klp_disable_patch().
194 	 */
195 	if (test_and_clear_tsk_thread_flag(task, TIF_PATCH_PENDING))
196 		task->patch_state = READ_ONCE(klp_target_state);
197 
198 	preempt_enable_notrace();
199 }
200 
201 /*
202  * Determine whether the given stack trace includes any references to a
203  * to-be-patched or to-be-unpatched function.
204  */
205 static int klp_check_stack_func(struct klp_func *func, unsigned long *entries,
206 				unsigned int nr_entries)
207 {
208 	unsigned long func_addr, func_size, address;
209 	struct klp_ops *ops;
210 	int i;
211 
212 	for (i = 0; i < nr_entries; i++) {
213 		address = entries[i];
214 
215 		if (klp_target_state == KLP_UNPATCHED) {
216 			 /*
217 			  * Check for the to-be-unpatched function
218 			  * (the func itself).
219 			  */
220 			func_addr = (unsigned long)func->new_func;
221 			func_size = func->new_size;
222 		} else {
223 			/*
224 			 * Check for the to-be-patched function
225 			 * (the previous func).
226 			 */
227 			ops = klp_find_ops(func->old_func);
228 
229 			if (list_is_singular(&ops->func_stack)) {
230 				/* original function */
231 				func_addr = (unsigned long)func->old_func;
232 				func_size = func->old_size;
233 			} else {
234 				/* previously patched function */
235 				struct klp_func *prev;
236 
237 				prev = list_next_entry(func, stack_node);
238 				func_addr = (unsigned long)prev->new_func;
239 				func_size = prev->new_size;
240 			}
241 		}
242 
243 		if (address >= func_addr && address < func_addr + func_size)
244 			return -EAGAIN;
245 	}
246 
247 	return 0;
248 }
249 
250 /*
251  * Determine whether it's safe to transition the task to the target patch state
252  * by looking for any to-be-patched or to-be-unpatched functions on its stack.
253  */
254 static int klp_check_stack(struct task_struct *task, char *err_buf)
255 {
256 	static unsigned long entries[MAX_STACK_ENTRIES];
257 	struct klp_object *obj;
258 	struct klp_func *func;
259 	int ret, nr_entries;
260 
261 	ret = stack_trace_save_tsk_reliable(task, entries, ARRAY_SIZE(entries));
262 	if (ret < 0) {
263 		snprintf(err_buf, STACK_ERR_BUF_SIZE,
264 			 "%s: %s:%d has an unreliable stack\n",
265 			 __func__, task->comm, task->pid);
266 		return ret;
267 	}
268 	nr_entries = ret;
269 
270 	klp_for_each_object(klp_transition_patch, obj) {
271 		if (!obj->patched)
272 			continue;
273 		klp_for_each_func(obj, func) {
274 			ret = klp_check_stack_func(func, entries, nr_entries);
275 			if (ret) {
276 				snprintf(err_buf, STACK_ERR_BUF_SIZE,
277 					 "%s: %s:%d is sleeping on function %s\n",
278 					 __func__, task->comm, task->pid,
279 					 func->old_name);
280 				return ret;
281 			}
282 		}
283 	}
284 
285 	return 0;
286 }
287 
288 /*
289  * Try to safely switch a task to the target patch state.  If it's currently
290  * running, or it's sleeping on a to-be-patched or to-be-unpatched function, or
291  * if the stack is unreliable, return false.
292  */
293 static bool klp_try_switch_task(struct task_struct *task)
294 {
295 	static char err_buf[STACK_ERR_BUF_SIZE];
296 	struct rq *rq;
297 	struct rq_flags flags;
298 	int ret;
299 	bool success = false;
300 
301 	err_buf[0] = '\0';
302 
303 	/* check if this task has already switched over */
304 	if (task->patch_state == klp_target_state)
305 		return true;
306 
307 	/*
308 	 * For arches which don't have reliable stack traces, we have to rely
309 	 * on other methods (e.g., switching tasks at kernel exit).
310 	 */
311 	if (!klp_have_reliable_stack())
312 		return false;
313 
314 	/*
315 	 * Now try to check the stack for any to-be-patched or to-be-unpatched
316 	 * functions.  If all goes well, switch the task to the target patch
317 	 * state.
318 	 */
319 	rq = task_rq_lock(task, &flags);
320 
321 	if (task_running(rq, task) && task != current) {
322 		snprintf(err_buf, STACK_ERR_BUF_SIZE,
323 			 "%s: %s:%d is running\n", __func__, task->comm,
324 			 task->pid);
325 		goto done;
326 	}
327 
328 	ret = klp_check_stack(task, err_buf);
329 	if (ret)
330 		goto done;
331 
332 	success = true;
333 
334 	clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
335 	task->patch_state = klp_target_state;
336 
337 done:
338 	task_rq_unlock(rq, task, &flags);
339 
340 	/*
341 	 * Due to console deadlock issues, pr_debug() can't be used while
342 	 * holding the task rq lock.  Instead we have to use a temporary buffer
343 	 * and print the debug message after releasing the lock.
344 	 */
345 	if (err_buf[0] != '\0')
346 		pr_debug("%s", err_buf);
347 
348 	return success;
349 }
350 
351 /*
352  * Sends a fake signal to all non-kthread tasks with TIF_PATCH_PENDING set.
353  * Kthreads with TIF_PATCH_PENDING set are woken up.
354  */
355 static void klp_send_signals(void)
356 {
357 	struct task_struct *g, *task;
358 
359 	if (klp_signals_cnt == SIGNALS_TIMEOUT)
360 		pr_notice("signaling remaining tasks\n");
361 
362 	read_lock(&tasklist_lock);
363 	for_each_process_thread(g, task) {
364 		if (!klp_patch_pending(task))
365 			continue;
366 
367 		/*
368 		 * There is a small race here. We could see TIF_PATCH_PENDING
369 		 * set and decide to wake up a kthread or send a fake signal.
370 		 * Meanwhile the task could migrate itself and the action
371 		 * would be meaningless. It is not serious though.
372 		 */
373 		if (task->flags & PF_KTHREAD) {
374 			/*
375 			 * Wake up a kthread which sleeps interruptedly and
376 			 * still has not been migrated.
377 			 */
378 			wake_up_state(task, TASK_INTERRUPTIBLE);
379 		} else {
380 			/*
381 			 * Send fake signal to all non-kthread tasks which are
382 			 * still not migrated.
383 			 */
384 			spin_lock_irq(&task->sighand->siglock);
385 			signal_wake_up(task, 0);
386 			spin_unlock_irq(&task->sighand->siglock);
387 		}
388 	}
389 	read_unlock(&tasklist_lock);
390 }
391 
392 /*
393  * Try to switch all remaining tasks to the target patch state by walking the
394  * stacks of sleeping tasks and looking for any to-be-patched or
395  * to-be-unpatched functions.  If such functions are found, the task can't be
396  * switched yet.
397  *
398  * If any tasks are still stuck in the initial patch state, schedule a retry.
399  */
400 void klp_try_complete_transition(void)
401 {
402 	unsigned int cpu;
403 	struct task_struct *g, *task;
404 	struct klp_patch *patch;
405 	bool complete = true;
406 
407 	WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
408 
409 	/*
410 	 * Try to switch the tasks to the target patch state by walking their
411 	 * stacks and looking for any to-be-patched or to-be-unpatched
412 	 * functions.  If such functions are found on a stack, or if the stack
413 	 * is deemed unreliable, the task can't be switched yet.
414 	 *
415 	 * Usually this will transition most (or all) of the tasks on a system
416 	 * unless the patch includes changes to a very common function.
417 	 */
418 	read_lock(&tasklist_lock);
419 	for_each_process_thread(g, task)
420 		if (!klp_try_switch_task(task))
421 			complete = false;
422 	read_unlock(&tasklist_lock);
423 
424 	/*
425 	 * Ditto for the idle "swapper" tasks.
426 	 */
427 	get_online_cpus();
428 	for_each_possible_cpu(cpu) {
429 		task = idle_task(cpu);
430 		if (cpu_online(cpu)) {
431 			if (!klp_try_switch_task(task))
432 				complete = false;
433 		} else if (task->patch_state != klp_target_state) {
434 			/* offline idle tasks can be switched immediately */
435 			clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
436 			task->patch_state = klp_target_state;
437 		}
438 	}
439 	put_online_cpus();
440 
441 	if (!complete) {
442 		if (klp_signals_cnt && !(klp_signals_cnt % SIGNALS_TIMEOUT))
443 			klp_send_signals();
444 		klp_signals_cnt++;
445 
446 		/*
447 		 * Some tasks weren't able to be switched over.  Try again
448 		 * later and/or wait for other methods like kernel exit
449 		 * switching.
450 		 */
451 		schedule_delayed_work(&klp_transition_work,
452 				      round_jiffies_relative(HZ));
453 		return;
454 	}
455 
456 	/* we're done, now cleanup the data structures */
457 	patch = klp_transition_patch;
458 	klp_complete_transition();
459 
460 	/*
461 	 * It would make more sense to free the patch in
462 	 * klp_complete_transition() but it is called also
463 	 * from klp_cancel_transition().
464 	 */
465 	if (!patch->enabled) {
466 		klp_free_patch_start(patch);
467 		schedule_work(&patch->free_work);
468 	}
469 }
470 
471 /*
472  * Start the transition to the specified target patch state so tasks can begin
473  * switching to it.
474  */
475 void klp_start_transition(void)
476 {
477 	struct task_struct *g, *task;
478 	unsigned int cpu;
479 
480 	WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
481 
482 	pr_notice("'%s': starting %s transition\n",
483 		  klp_transition_patch->mod->name,
484 		  klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
485 
486 	/*
487 	 * Mark all normal tasks as needing a patch state update.  They'll
488 	 * switch either in klp_try_complete_transition() or as they exit the
489 	 * kernel.
490 	 */
491 	read_lock(&tasklist_lock);
492 	for_each_process_thread(g, task)
493 		if (task->patch_state != klp_target_state)
494 			set_tsk_thread_flag(task, TIF_PATCH_PENDING);
495 	read_unlock(&tasklist_lock);
496 
497 	/*
498 	 * Mark all idle tasks as needing a patch state update.  They'll switch
499 	 * either in klp_try_complete_transition() or at the idle loop switch
500 	 * point.
501 	 */
502 	for_each_possible_cpu(cpu) {
503 		task = idle_task(cpu);
504 		if (task->patch_state != klp_target_state)
505 			set_tsk_thread_flag(task, TIF_PATCH_PENDING);
506 	}
507 
508 	klp_signals_cnt = 0;
509 }
510 
511 /*
512  * Initialize the global target patch state and all tasks to the initial patch
513  * state, and initialize all function transition states to true in preparation
514  * for patching or unpatching.
515  */
516 void klp_init_transition(struct klp_patch *patch, int state)
517 {
518 	struct task_struct *g, *task;
519 	unsigned int cpu;
520 	struct klp_object *obj;
521 	struct klp_func *func;
522 	int initial_state = !state;
523 
524 	WARN_ON_ONCE(klp_target_state != KLP_UNDEFINED);
525 
526 	klp_transition_patch = patch;
527 
528 	/*
529 	 * Set the global target patch state which tasks will switch to.  This
530 	 * has no effect until the TIF_PATCH_PENDING flags get set later.
531 	 */
532 	klp_target_state = state;
533 
534 	pr_debug("'%s': initializing %s transition\n", patch->mod->name,
535 		 klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
536 
537 	/*
538 	 * Initialize all tasks to the initial patch state to prepare them for
539 	 * switching to the target state.
540 	 */
541 	read_lock(&tasklist_lock);
542 	for_each_process_thread(g, task) {
543 		WARN_ON_ONCE(task->patch_state != KLP_UNDEFINED);
544 		task->patch_state = initial_state;
545 	}
546 	read_unlock(&tasklist_lock);
547 
548 	/*
549 	 * Ditto for the idle "swapper" tasks.
550 	 */
551 	for_each_possible_cpu(cpu) {
552 		task = idle_task(cpu);
553 		WARN_ON_ONCE(task->patch_state != KLP_UNDEFINED);
554 		task->patch_state = initial_state;
555 	}
556 
557 	/*
558 	 * Enforce the order of the task->patch_state initializations and the
559 	 * func->transition updates to ensure that klp_ftrace_handler() doesn't
560 	 * see a func in transition with a task->patch_state of KLP_UNDEFINED.
561 	 *
562 	 * Also enforce the order of the klp_target_state write and future
563 	 * TIF_PATCH_PENDING writes to ensure klp_update_patch_state() doesn't
564 	 * set a task->patch_state to KLP_UNDEFINED.
565 	 */
566 	smp_wmb();
567 
568 	/*
569 	 * Set the func transition states so klp_ftrace_handler() will know to
570 	 * switch to the transition logic.
571 	 *
572 	 * When patching, the funcs aren't yet in the func_stack and will be
573 	 * made visible to the ftrace handler shortly by the calls to
574 	 * klp_patch_object().
575 	 *
576 	 * When unpatching, the funcs are already in the func_stack and so are
577 	 * already visible to the ftrace handler.
578 	 */
579 	klp_for_each_object(patch, obj)
580 		klp_for_each_func(obj, func)
581 			func->transition = true;
582 }
583 
584 /*
585  * This function can be called in the middle of an existing transition to
586  * reverse the direction of the target patch state.  This can be done to
587  * effectively cancel an existing enable or disable operation if there are any
588  * tasks which are stuck in the initial patch state.
589  */
590 void klp_reverse_transition(void)
591 {
592 	unsigned int cpu;
593 	struct task_struct *g, *task;
594 
595 	pr_debug("'%s': reversing transition from %s\n",
596 		 klp_transition_patch->mod->name,
597 		 klp_target_state == KLP_PATCHED ? "patching to unpatching" :
598 						   "unpatching to patching");
599 
600 	klp_transition_patch->enabled = !klp_transition_patch->enabled;
601 
602 	klp_target_state = !klp_target_state;
603 
604 	/*
605 	 * Clear all TIF_PATCH_PENDING flags to prevent races caused by
606 	 * klp_update_patch_state() running in parallel with
607 	 * klp_start_transition().
608 	 */
609 	read_lock(&tasklist_lock);
610 	for_each_process_thread(g, task)
611 		clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
612 	read_unlock(&tasklist_lock);
613 
614 	for_each_possible_cpu(cpu)
615 		clear_tsk_thread_flag(idle_task(cpu), TIF_PATCH_PENDING);
616 
617 	/* Let any remaining calls to klp_update_patch_state() complete */
618 	klp_synchronize_transition();
619 
620 	klp_start_transition();
621 }
622 
623 /* Called from copy_process() during fork */
624 void klp_copy_process(struct task_struct *child)
625 {
626 	child->patch_state = current->patch_state;
627 
628 	/* TIF_PATCH_PENDING gets copied in setup_thread_stack() */
629 }
630 
631 /*
632  * Drop TIF_PATCH_PENDING of all tasks on admin's request. This forces an
633  * existing transition to finish.
634  *
635  * NOTE: klp_update_patch_state(task) requires the task to be inactive or
636  * 'current'. This is not the case here and the consistency model could be
637  * broken. Administrator, who is the only one to execute the
638  * klp_force_transitions(), has to be aware of this.
639  */
640 void klp_force_transition(void)
641 {
642 	struct klp_patch *patch;
643 	struct task_struct *g, *task;
644 	unsigned int cpu;
645 
646 	pr_warn("forcing remaining tasks to the patched state\n");
647 
648 	read_lock(&tasklist_lock);
649 	for_each_process_thread(g, task)
650 		klp_update_patch_state(task);
651 	read_unlock(&tasklist_lock);
652 
653 	for_each_possible_cpu(cpu)
654 		klp_update_patch_state(idle_task(cpu));
655 
656 	klp_for_each_patch(patch)
657 		patch->forced = true;
658 }
659