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