transition.c 18 KB

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