blob: 53887f0bca1021e3c4f5ab20eb42b7da45264f88 [file] [log] [blame]
Josh Poimboeufd83a7cb2017-02-13 19:42:40 -06001/*
2 * transition.c - Kernel Live Patching transition functions
3 *
4 * Copyright (C) 2015-2016 Josh Poimboeuf <jpoimboe@redhat.com>
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>
Jiri Kosina10517422017-03-08 14:27:05 +010024#include "core.h"
Josh Poimboeufd83a7cb2017-02-13 19:42:40 -060025#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
Josh Poimboeufd83a7cb2017-02-13 19:42:40 -060032struct klp_patch *klp_transition_patch;
33
34static 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 */
40static 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}
49static DECLARE_DELAYED_WORK(klp_transition_work, klp_transition_work_fn);
50
51/*
Petr Mladek842c0882017-06-14 10:54:52 +020052 * This function is just a stub to implement a hard force
53 * of synchronize_sched(). This requires synchronizing
54 * tasks even in userspace and idle.
55 */
56static 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 */
68static void klp_synchronize_transition(void)
69{
70 schedule_on_each_cpu(klp_sync);
71}
72
73/*
Josh Poimboeufd83a7cb2017-02-13 19:42:40 -060074 * The transition to the target patch state is complete. Clean up the data
75 * structures.
76 */
77static 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;
Josh Poimboeuf3ec24772017-03-06 11:20:29 -060083 bool immediate_func = false;
Josh Poimboeufd83a7cb2017-02-13 19:42:40 -060084
85 if (klp_target_state == KLP_UNPATCHED) {
86 /*
87 * All tasks have transitioned to KLP_UNPATCHED so we can now
88 * remove the new functions from the func_stack.
89 */
90 klp_unpatch_objects(klp_transition_patch);
91
92 /*
93 * Make sure klp_ftrace_handler() can no longer see functions
94 * from this patch on the ops->func_stack. Otherwise, after
95 * func->transition gets cleared, the handler may choose a
96 * removed function.
97 */
Petr Mladek842c0882017-06-14 10:54:52 +020098 klp_synchronize_transition();
Josh Poimboeufd83a7cb2017-02-13 19:42:40 -060099 }
100
101 if (klp_transition_patch->immediate)
102 goto done;
103
Josh Poimboeuf3ec24772017-03-06 11:20:29 -0600104 klp_for_each_object(klp_transition_patch, obj) {
105 klp_for_each_func(obj, func) {
Josh Poimboeufd83a7cb2017-02-13 19:42:40 -0600106 func->transition = false;
Josh Poimboeuf3ec24772017-03-06 11:20:29 -0600107 if (func->immediate)
108 immediate_func = true;
109 }
110 }
111
Josh Poimboeufd83a7cb2017-02-13 19:42:40 -0600112 /* Prevent klp_ftrace_handler() from seeing KLP_UNDEFINED state */
113 if (klp_target_state == KLP_PATCHED)
Petr Mladek842c0882017-06-14 10:54:52 +0200114 klp_synchronize_transition();
Josh Poimboeufd83a7cb2017-02-13 19:42:40 -0600115
116 read_lock(&tasklist_lock);
117 for_each_process_thread(g, task) {
118 WARN_ON_ONCE(test_tsk_thread_flag(task, TIF_PATCH_PENDING));
119 task->patch_state = KLP_UNDEFINED;
120 }
121 read_unlock(&tasklist_lock);
122
123 for_each_possible_cpu(cpu) {
124 task = idle_task(cpu);
125 WARN_ON_ONCE(test_tsk_thread_flag(task, TIF_PATCH_PENDING));
126 task->patch_state = KLP_UNDEFINED;
127 }
128
129done:
Joe Lawrence93862e32017-10-13 15:08:41 -0400130 klp_for_each_object(klp_transition_patch, obj) {
131 if (!klp_is_object_loaded(obj))
132 continue;
133 if (klp_target_state == KLP_PATCHED)
134 klp_post_patch_callback(obj);
135 else if (klp_target_state == KLP_UNPATCHED)
136 klp_post_unpatch_callback(obj);
137 }
138
Joe Lawrence6116c302017-10-13 15:08:42 -0400139 pr_notice("'%s': %s complete\n", klp_transition_patch->mod->name,
140 klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
141
Joe Lawrence93862e32017-10-13 15:08:41 -0400142 /*
143 * See complementary comment in __klp_enable_patch() for why we
144 * keep the module reference for immediate patches.
145 */
146 if (!klp_transition_patch->immediate && !immediate_func &&
147 klp_target_state == KLP_UNPATCHED) {
148 module_put(klp_transition_patch->mod);
149 }
150
Josh Poimboeufd83a7cb2017-02-13 19:42:40 -0600151 klp_target_state = KLP_UNDEFINED;
152 klp_transition_patch = NULL;
153}
154
155/*
156 * This is called in the error path, to cancel a transition before it has
157 * started, i.e. klp_init_transition() has been called but
158 * klp_start_transition() hasn't. If the transition *has* been started,
159 * klp_reverse_transition() should be used instead.
160 */
161void klp_cancel_transition(void)
162{
Josh Poimboeuf3ec24772017-03-06 11:20:29 -0600163 if (WARN_ON_ONCE(klp_target_state != KLP_PATCHED))
164 return;
165
166 klp_target_state = KLP_UNPATCHED;
Josh Poimboeufd83a7cb2017-02-13 19:42:40 -0600167 klp_complete_transition();
Josh Poimboeufd83a7cb2017-02-13 19:42:40 -0600168}
169
170/*
171 * Switch the patched state of the task to the set of functions in the target
172 * patch state.
173 *
174 * NOTE: If task is not 'current', the caller must ensure the task is inactive.
175 * Otherwise klp_ftrace_handler() might read the wrong 'patch_state' value.
176 */
177void klp_update_patch_state(struct task_struct *task)
178{
Petr Mladek842c0882017-06-14 10:54:52 +0200179 /*
180 * A variant of synchronize_sched() is used to allow patching functions
181 * where RCU is not watching, see klp_synchronize_transition().
182 */
183 preempt_disable_notrace();
Josh Poimboeufd83a7cb2017-02-13 19:42:40 -0600184
185 /*
186 * This test_and_clear_tsk_thread_flag() call also serves as a read
187 * barrier (smp_rmb) for two cases:
188 *
189 * 1) Enforce the order of the TIF_PATCH_PENDING read and the
190 * klp_target_state read. The corresponding write barrier is in
191 * klp_init_transition().
192 *
193 * 2) Enforce the order of the TIF_PATCH_PENDING read and a future read
194 * of func->transition, if klp_ftrace_handler() is called later on
195 * the same CPU. See __klp_disable_patch().
196 */
197 if (test_and_clear_tsk_thread_flag(task, TIF_PATCH_PENDING))
198 task->patch_state = READ_ONCE(klp_target_state);
199
Petr Mladek842c0882017-06-14 10:54:52 +0200200 preempt_enable_notrace();
Josh Poimboeufd83a7cb2017-02-13 19:42:40 -0600201}
202
203/*
204 * Determine whether the given stack trace includes any references to a
205 * to-be-patched or to-be-unpatched function.
206 */
207static int klp_check_stack_func(struct klp_func *func,
208 struct stack_trace *trace)
209{
210 unsigned long func_addr, func_size, address;
211 struct klp_ops *ops;
212 int i;
213
214 if (func->immediate)
215 return 0;
216
217 for (i = 0; i < trace->nr_entries; i++) {
218 address = trace->entries[i];
219
220 if (klp_target_state == KLP_UNPATCHED) {
221 /*
222 * Check for the to-be-unpatched function
223 * (the func itself).
224 */
225 func_addr = (unsigned long)func->new_func;
226 func_size = func->new_size;
227 } else {
228 /*
229 * Check for the to-be-patched function
230 * (the previous func).
231 */
232 ops = klp_find_ops(func->old_addr);
233
234 if (list_is_singular(&ops->func_stack)) {
235 /* original function */
236 func_addr = func->old_addr;
237 func_size = func->old_size;
238 } else {
239 /* previously patched function */
240 struct klp_func *prev;
241
242 prev = list_next_entry(func, stack_node);
243 func_addr = (unsigned long)prev->new_func;
244 func_size = prev->new_size;
245 }
246 }
247
248 if (address >= func_addr && address < func_addr + func_size)
249 return -EAGAIN;
250 }
251
252 return 0;
253}
254
255/*
256 * Determine whether it's safe to transition the task to the target patch state
257 * by looking for any to-be-patched or to-be-unpatched functions on its stack.
258 */
259static int klp_check_stack(struct task_struct *task, char *err_buf)
260{
261 static unsigned long entries[MAX_STACK_ENTRIES];
262 struct stack_trace trace;
263 struct klp_object *obj;
264 struct klp_func *func;
265 int ret;
266
267 trace.skip = 0;
268 trace.nr_entries = 0;
269 trace.max_entries = MAX_STACK_ENTRIES;
270 trace.entries = entries;
271 ret = save_stack_trace_tsk_reliable(task, &trace);
272 WARN_ON_ONCE(ret == -ENOSYS);
273 if (ret) {
274 snprintf(err_buf, STACK_ERR_BUF_SIZE,
275 "%s: %s:%d has an unreliable stack\n",
276 __func__, task->comm, task->pid);
277 return ret;
278 }
279
280 klp_for_each_object(klp_transition_patch, obj) {
281 if (!obj->patched)
282 continue;
283 klp_for_each_func(obj, func) {
284 ret = klp_check_stack_func(func, &trace);
285 if (ret) {
286 snprintf(err_buf, STACK_ERR_BUF_SIZE,
287 "%s: %s:%d is sleeping on function %s\n",
288 __func__, task->comm, task->pid,
289 func->old_name);
290 return ret;
291 }
292 }
293 }
294
295 return 0;
296}
297
298/*
299 * Try to safely switch a task to the target patch state. If it's currently
300 * running, or it's sleeping on a to-be-patched or to-be-unpatched function, or
301 * if the stack is unreliable, return false.
302 */
303static bool klp_try_switch_task(struct task_struct *task)
304{
305 struct rq *rq;
306 struct rq_flags flags;
307 int ret;
308 bool success = false;
309 char err_buf[STACK_ERR_BUF_SIZE];
310
311 err_buf[0] = '\0';
312
313 /* check if this task has already switched over */
314 if (task->patch_state == klp_target_state)
315 return true;
316
317 /*
318 * For arches which don't have reliable stack traces, we have to rely
319 * on other methods (e.g., switching tasks at kernel exit).
320 */
321 if (!klp_have_reliable_stack())
322 return false;
323
324 /*
325 * Now try to check the stack for any to-be-patched or to-be-unpatched
326 * functions. If all goes well, switch the task to the target patch
327 * state.
328 */
329 rq = task_rq_lock(task, &flags);
330
331 if (task_running(rq, task) && task != current) {
332 snprintf(err_buf, STACK_ERR_BUF_SIZE,
333 "%s: %s:%d is running\n", __func__, task->comm,
334 task->pid);
335 goto done;
336 }
337
338 ret = klp_check_stack(task, err_buf);
339 if (ret)
340 goto done;
341
342 success = true;
343
344 clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
345 task->patch_state = klp_target_state;
346
347done:
348 task_rq_unlock(rq, task, &flags);
349
350 /*
351 * Due to console deadlock issues, pr_debug() can't be used while
352 * holding the task rq lock. Instead we have to use a temporary buffer
353 * and print the debug message after releasing the lock.
354 */
355 if (err_buf[0] != '\0')
356 pr_debug("%s", err_buf);
357
358 return success;
359
360}
361
362/*
363 * Try to switch all remaining tasks to the target patch state by walking the
364 * stacks of sleeping tasks and looking for any to-be-patched or
365 * to-be-unpatched functions. If such functions are found, the task can't be
366 * switched yet.
367 *
368 * If any tasks are still stuck in the initial patch state, schedule a retry.
369 */
370void klp_try_complete_transition(void)
371{
372 unsigned int cpu;
373 struct task_struct *g, *task;
374 bool complete = true;
375
376 WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
377
378 /*
379 * If the patch can be applied or reverted immediately, skip the
380 * per-task transitions.
381 */
382 if (klp_transition_patch->immediate)
383 goto success;
384
385 /*
386 * Try to switch the tasks to the target patch state by walking their
387 * stacks and looking for any to-be-patched or to-be-unpatched
388 * functions. If such functions are found on a stack, or if the stack
389 * is deemed unreliable, the task can't be switched yet.
390 *
391 * Usually this will transition most (or all) of the tasks on a system
392 * unless the patch includes changes to a very common function.
393 */
394 read_lock(&tasklist_lock);
395 for_each_process_thread(g, task)
396 if (!klp_try_switch_task(task))
397 complete = false;
398 read_unlock(&tasklist_lock);
399
400 /*
401 * Ditto for the idle "swapper" tasks.
402 */
403 get_online_cpus();
404 for_each_possible_cpu(cpu) {
405 task = idle_task(cpu);
406 if (cpu_online(cpu)) {
407 if (!klp_try_switch_task(task))
408 complete = false;
409 } else if (task->patch_state != klp_target_state) {
410 /* offline idle tasks can be switched immediately */
411 clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
412 task->patch_state = klp_target_state;
413 }
414 }
415 put_online_cpus();
416
417 if (!complete) {
418 /*
419 * Some tasks weren't able to be switched over. Try again
420 * later and/or wait for other methods like kernel exit
421 * switching.
422 */
423 schedule_delayed_work(&klp_transition_work,
424 round_jiffies_relative(HZ));
425 return;
426 }
427
428success:
Josh Poimboeufd83a7cb2017-02-13 19:42:40 -0600429 /* we're done, now cleanup the data structures */
430 klp_complete_transition();
431}
432
433/*
434 * Start the transition to the specified target patch state so tasks can begin
435 * switching to it.
436 */
437void klp_start_transition(void)
438{
439 struct task_struct *g, *task;
440 unsigned int cpu;
441
442 WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
443
444 pr_notice("'%s': %s...\n", klp_transition_patch->mod->name,
445 klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
446
447 /*
448 * If the patch can be applied or reverted immediately, skip the
449 * per-task transitions.
450 */
451 if (klp_transition_patch->immediate)
452 return;
453
454 /*
455 * Mark all normal tasks as needing a patch state update. They'll
456 * switch either in klp_try_complete_transition() or as they exit the
457 * kernel.
458 */
459 read_lock(&tasklist_lock);
460 for_each_process_thread(g, task)
461 if (task->patch_state != klp_target_state)
462 set_tsk_thread_flag(task, TIF_PATCH_PENDING);
463 read_unlock(&tasklist_lock);
464
465 /*
466 * Mark all idle tasks as needing a patch state update. They'll switch
467 * either in klp_try_complete_transition() or at the idle loop switch
468 * point.
469 */
470 for_each_possible_cpu(cpu) {
471 task = idle_task(cpu);
472 if (task->patch_state != klp_target_state)
473 set_tsk_thread_flag(task, TIF_PATCH_PENDING);
474 }
475}
476
477/*
478 * Initialize the global target patch state and all tasks to the initial patch
479 * state, and initialize all function transition states to true in preparation
480 * for patching or unpatching.
481 */
482void klp_init_transition(struct klp_patch *patch, int state)
483{
484 struct task_struct *g, *task;
485 unsigned int cpu;
486 struct klp_object *obj;
487 struct klp_func *func;
488 int initial_state = !state;
489
490 WARN_ON_ONCE(klp_target_state != KLP_UNDEFINED);
491
492 klp_transition_patch = patch;
493
494 /*
495 * Set the global target patch state which tasks will switch to. This
496 * has no effect until the TIF_PATCH_PENDING flags get set later.
497 */
498 klp_target_state = state;
499
500 /*
501 * If the patch can be applied or reverted immediately, skip the
502 * per-task transitions.
503 */
504 if (patch->immediate)
505 return;
506
507 /*
508 * Initialize all tasks to the initial patch state to prepare them for
509 * switching to the target state.
510 */
511 read_lock(&tasklist_lock);
512 for_each_process_thread(g, task) {
513 WARN_ON_ONCE(task->patch_state != KLP_UNDEFINED);
514 task->patch_state = initial_state;
515 }
516 read_unlock(&tasklist_lock);
517
518 /*
519 * Ditto for the idle "swapper" tasks.
520 */
521 for_each_possible_cpu(cpu) {
522 task = idle_task(cpu);
523 WARN_ON_ONCE(task->patch_state != KLP_UNDEFINED);
524 task->patch_state = initial_state;
525 }
526
527 /*
528 * Enforce the order of the task->patch_state initializations and the
529 * func->transition updates to ensure that klp_ftrace_handler() doesn't
530 * see a func in transition with a task->patch_state of KLP_UNDEFINED.
531 *
532 * Also enforce the order of the klp_target_state write and future
533 * TIF_PATCH_PENDING writes to ensure klp_update_patch_state() doesn't
534 * set a task->patch_state to KLP_UNDEFINED.
535 */
536 smp_wmb();
537
538 /*
539 * Set the func transition states so klp_ftrace_handler() will know to
540 * switch to the transition logic.
541 *
542 * When patching, the funcs aren't yet in the func_stack and will be
543 * made visible to the ftrace handler shortly by the calls to
544 * klp_patch_object().
545 *
546 * When unpatching, the funcs are already in the func_stack and so are
547 * already visible to the ftrace handler.
548 */
549 klp_for_each_object(patch, obj)
550 klp_for_each_func(obj, func)
551 func->transition = true;
552}
553
554/*
555 * This function can be called in the middle of an existing transition to
556 * reverse the direction of the target patch state. This can be done to
557 * effectively cancel an existing enable or disable operation if there are any
558 * tasks which are stuck in the initial patch state.
559 */
560void klp_reverse_transition(void)
561{
562 unsigned int cpu;
563 struct task_struct *g, *task;
564
565 klp_transition_patch->enabled = !klp_transition_patch->enabled;
566
567 klp_target_state = !klp_target_state;
568
569 /*
570 * Clear all TIF_PATCH_PENDING flags to prevent races caused by
571 * klp_update_patch_state() running in parallel with
572 * klp_start_transition().
573 */
574 read_lock(&tasklist_lock);
575 for_each_process_thread(g, task)
576 clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
577 read_unlock(&tasklist_lock);
578
579 for_each_possible_cpu(cpu)
580 clear_tsk_thread_flag(idle_task(cpu), TIF_PATCH_PENDING);
581
582 /* Let any remaining calls to klp_update_patch_state() complete */
Petr Mladek842c0882017-06-14 10:54:52 +0200583 klp_synchronize_transition();
Josh Poimboeufd83a7cb2017-02-13 19:42:40 -0600584
585 klp_start_transition();
586}
587
588/* Called from copy_process() during fork */
589void klp_copy_process(struct task_struct *child)
590{
591 child->patch_state = current->patch_state;
592
593 /* TIF_PATCH_PENDING gets copied in setup_thread_stack() */
594}