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