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