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