transition.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  20. #include <linux/cpu.h>
  21. #include <linux/stacktrace.h>
  22. #include "core.h"
  23. #include "patch.h"
  24. #include "transition.h"
  25. #include "../sched/sched.h"
  26. #define MAX_STACK_ENTRIES 100
  27. #define STACK_ERR_BUF_SIZE 128
  28. struct klp_patch *klp_transition_patch;
  29. static int klp_target_state = KLP_UNDEFINED;
  30. /*
  31. * This work can be performed periodically to finish patching or unpatching any
  32. * "straggler" tasks which failed to transition in the first attempt.
  33. */
  34. static void klp_transition_work_fn(struct work_struct *work)
  35. {
  36. mutex_lock(&klp_mutex);
  37. if (klp_transition_patch)
  38. klp_try_complete_transition();
  39. mutex_unlock(&klp_mutex);
  40. }
  41. static DECLARE_DELAYED_WORK(klp_transition_work, klp_transition_work_fn);
  42. /*
  43. * This function is just a stub to implement a hard force
  44. * of synchronize_sched(). This requires synchronizing
  45. * tasks even in userspace and idle.
  46. */
  47. static void klp_sync(struct work_struct *work)
  48. {
  49. }
  50. /*
  51. * We allow to patch also functions where RCU is not watching,
  52. * e.g. before user_exit(). We can not rely on the RCU infrastructure
  53. * to do the synchronization. Instead hard force the sched synchronization.
  54. *
  55. * This approach allows to use RCU functions for manipulating func_stack
  56. * safely.
  57. */
  58. static void klp_synchronize_transition(void)
  59. {
  60. schedule_on_each_cpu(klp_sync);
  61. }
  62. /*
  63. * The transition to the target patch state is complete. Clean up the data
  64. * structures.
  65. */
  66. static void klp_complete_transition(void)
  67. {
  68. struct klp_object *obj;
  69. struct klp_func *func;
  70. struct task_struct *g, *task;
  71. unsigned int cpu;
  72. bool immediate_func = false;
  73. pr_debug("'%s': completing %s transition\n",
  74. klp_transition_patch->mod->name,
  75. klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
  76. if (klp_target_state == KLP_UNPATCHED) {
  77. /*
  78. * All tasks have transitioned to KLP_UNPATCHED so we can now
  79. * remove the new functions from the func_stack.
  80. */
  81. klp_unpatch_objects(klp_transition_patch);
  82. /*
  83. * Make sure klp_ftrace_handler() can no longer see functions
  84. * from this patch on the ops->func_stack. Otherwise, after
  85. * func->transition gets cleared, the handler may choose a
  86. * removed function.
  87. */
  88. klp_synchronize_transition();
  89. }
  90. if (klp_transition_patch->immediate)
  91. goto done;
  92. klp_for_each_object(klp_transition_patch, obj) {
  93. klp_for_each_func(obj, func) {
  94. func->transition = false;
  95. if (func->immediate)
  96. immediate_func = true;
  97. }
  98. }
  99. /* Prevent klp_ftrace_handler() from seeing KLP_UNDEFINED state */
  100. if (klp_target_state == KLP_PATCHED)
  101. klp_synchronize_transition();
  102. read_lock(&tasklist_lock);
  103. for_each_process_thread(g, task) {
  104. WARN_ON_ONCE(test_tsk_thread_flag(task, TIF_PATCH_PENDING));
  105. task->patch_state = KLP_UNDEFINED;
  106. }
  107. read_unlock(&tasklist_lock);
  108. for_each_possible_cpu(cpu) {
  109. task = idle_task(cpu);
  110. WARN_ON_ONCE(test_tsk_thread_flag(task, TIF_PATCH_PENDING));
  111. task->patch_state = KLP_UNDEFINED;
  112. }
  113. done:
  114. klp_for_each_object(klp_transition_patch, obj) {
  115. if (!klp_is_object_loaded(obj))
  116. continue;
  117. if (klp_target_state == KLP_PATCHED)
  118. klp_post_patch_callback(obj);
  119. else if (klp_target_state == KLP_UNPATCHED)
  120. klp_post_unpatch_callback(obj);
  121. }
  122. pr_notice("'%s': %s complete\n", klp_transition_patch->mod->name,
  123. klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
  124. /*
  125. * See complementary comment in __klp_enable_patch() for why we
  126. * keep the module reference for immediate patches.
  127. */
  128. if (!klp_transition_patch->immediate && !immediate_func &&
  129. klp_target_state == KLP_UNPATCHED) {
  130. module_put(klp_transition_patch->mod);
  131. }
  132. klp_target_state = KLP_UNDEFINED;
  133. klp_transition_patch = NULL;
  134. }
  135. /*
  136. * This is called in the error path, to cancel a transition before it has
  137. * started, i.e. klp_init_transition() has been called but
  138. * klp_start_transition() hasn't. If the transition *has* been started,
  139. * klp_reverse_transition() should be used instead.
  140. */
  141. void klp_cancel_transition(void)
  142. {
  143. if (WARN_ON_ONCE(klp_target_state != KLP_PATCHED))
  144. return;
  145. pr_debug("'%s': canceling patching transition, going to unpatch\n",
  146. klp_transition_patch->mod->name);
  147. klp_target_state = KLP_UNPATCHED;
  148. klp_complete_transition();
  149. }
  150. /*
  151. * Switch the patched state of the task to the set of functions in the target
  152. * patch state.
  153. *
  154. * NOTE: If task is not 'current', the caller must ensure the task is inactive.
  155. * Otherwise klp_ftrace_handler() might read the wrong 'patch_state' value.
  156. */
  157. void klp_update_patch_state(struct task_struct *task)
  158. {
  159. /*
  160. * A variant of synchronize_sched() is used to allow patching functions
  161. * where RCU is not watching, see klp_synchronize_transition().
  162. */
  163. preempt_disable_notrace();
  164. /*
  165. * This test_and_clear_tsk_thread_flag() call also serves as a read
  166. * barrier (smp_rmb) for two cases:
  167. *
  168. * 1) Enforce the order of the TIF_PATCH_PENDING read and the
  169. * klp_target_state read. The corresponding write barrier is in
  170. * klp_init_transition().
  171. *
  172. * 2) Enforce the order of the TIF_PATCH_PENDING read and a future read
  173. * of func->transition, if klp_ftrace_handler() is called later on
  174. * the same CPU. See __klp_disable_patch().
  175. */
  176. if (test_and_clear_tsk_thread_flag(task, TIF_PATCH_PENDING))
  177. task->patch_state = READ_ONCE(klp_target_state);
  178. preempt_enable_notrace();
  179. }
  180. /*
  181. * Determine whether the given stack trace includes any references to a
  182. * to-be-patched or to-be-unpatched function.
  183. */
  184. static int klp_check_stack_func(struct klp_func *func,
  185. struct stack_trace *trace)
  186. {
  187. unsigned long func_addr, func_size, address;
  188. struct klp_ops *ops;
  189. int i;
  190. if (func->immediate)
  191. return 0;
  192. for (i = 0; i < trace->nr_entries; i++) {
  193. address = trace->entries[i];
  194. if (klp_target_state == KLP_UNPATCHED) {
  195. /*
  196. * Check for the to-be-unpatched function
  197. * (the func itself).
  198. */
  199. func_addr = (unsigned long)func->new_func;
  200. func_size = func->new_size;
  201. } else {
  202. /*
  203. * Check for the to-be-patched function
  204. * (the previous func).
  205. */
  206. ops = klp_find_ops(func->old_addr);
  207. if (list_is_singular(&ops->func_stack)) {
  208. /* original function */
  209. func_addr = func->old_addr;
  210. func_size = func->old_size;
  211. } else {
  212. /* previously patched function */
  213. struct klp_func *prev;
  214. prev = list_next_entry(func, stack_node);
  215. func_addr = (unsigned long)prev->new_func;
  216. func_size = prev->new_size;
  217. }
  218. }
  219. if (address >= func_addr && address < func_addr + func_size)
  220. return -EAGAIN;
  221. }
  222. return 0;
  223. }
  224. /*
  225. * Determine whether it's safe to transition the task to the target patch state
  226. * by looking for any to-be-patched or to-be-unpatched functions on its stack.
  227. */
  228. static int klp_check_stack(struct task_struct *task, char *err_buf)
  229. {
  230. static unsigned long entries[MAX_STACK_ENTRIES];
  231. struct stack_trace trace;
  232. struct klp_object *obj;
  233. struct klp_func *func;
  234. int ret;
  235. trace.skip = 0;
  236. trace.nr_entries = 0;
  237. trace.max_entries = MAX_STACK_ENTRIES;
  238. trace.entries = entries;
  239. ret = save_stack_trace_tsk_reliable(task, &trace);
  240. WARN_ON_ONCE(ret == -ENOSYS);
  241. if (ret) {
  242. snprintf(err_buf, STACK_ERR_BUF_SIZE,
  243. "%s: %s:%d has an unreliable stack\n",
  244. __func__, task->comm, task->pid);
  245. return ret;
  246. }
  247. klp_for_each_object(klp_transition_patch, obj) {
  248. if (!obj->patched)
  249. continue;
  250. klp_for_each_func(obj, func) {
  251. ret = klp_check_stack_func(func, &trace);
  252. if (ret) {
  253. snprintf(err_buf, STACK_ERR_BUF_SIZE,
  254. "%s: %s:%d is sleeping on function %s\n",
  255. __func__, task->comm, task->pid,
  256. func->old_name);
  257. return ret;
  258. }
  259. }
  260. }
  261. return 0;
  262. }
  263. /*
  264. * Try to safely switch a task to the target patch state. If it's currently
  265. * running, or it's sleeping on a to-be-patched or to-be-unpatched function, or
  266. * if the stack is unreliable, return false.
  267. */
  268. static bool klp_try_switch_task(struct task_struct *task)
  269. {
  270. struct rq *rq;
  271. struct rq_flags flags;
  272. int ret;
  273. bool success = false;
  274. char err_buf[STACK_ERR_BUF_SIZE];
  275. err_buf[0] = '\0';
  276. /* check if this task has already switched over */
  277. if (task->patch_state == klp_target_state)
  278. return true;
  279. /*
  280. * For arches which don't have reliable stack traces, we have to rely
  281. * on other methods (e.g., switching tasks at kernel exit).
  282. */
  283. if (!klp_have_reliable_stack())
  284. return false;
  285. /*
  286. * Now try to check the stack for any to-be-patched or to-be-unpatched
  287. * functions. If all goes well, switch the task to the target patch
  288. * state.
  289. */
  290. rq = task_rq_lock(task, &flags);
  291. if (task_running(rq, task) && task != current) {
  292. snprintf(err_buf, STACK_ERR_BUF_SIZE,
  293. "%s: %s:%d is running\n", __func__, task->comm,
  294. task->pid);
  295. goto done;
  296. }
  297. ret = klp_check_stack(task, err_buf);
  298. if (ret)
  299. goto done;
  300. success = true;
  301. clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
  302. task->patch_state = klp_target_state;
  303. done:
  304. task_rq_unlock(rq, task, &flags);
  305. /*
  306. * Due to console deadlock issues, pr_debug() can't be used while
  307. * holding the task rq lock. Instead we have to use a temporary buffer
  308. * and print the debug message after releasing the lock.
  309. */
  310. if (err_buf[0] != '\0')
  311. pr_debug("%s", err_buf);
  312. return success;
  313. }
  314. /*
  315. * Try to switch all remaining tasks to the target patch state by walking the
  316. * stacks of sleeping tasks and looking for any to-be-patched or
  317. * to-be-unpatched functions. If such functions are found, the task can't be
  318. * switched yet.
  319. *
  320. * If any tasks are still stuck in the initial patch state, schedule a retry.
  321. */
  322. void klp_try_complete_transition(void)
  323. {
  324. unsigned int cpu;
  325. struct task_struct *g, *task;
  326. bool complete = true;
  327. WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
  328. /*
  329. * If the patch can be applied or reverted immediately, skip the
  330. * per-task transitions.
  331. */
  332. if (klp_transition_patch->immediate)
  333. goto success;
  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. get_online_cpus();
  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. } else if (task->patch_state != klp_target_state) {
  358. /* offline idle tasks can be switched immediately */
  359. clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
  360. task->patch_state = klp_target_state;
  361. }
  362. }
  363. put_online_cpus();
  364. if (!complete) {
  365. /*
  366. * Some tasks weren't able to be switched over. Try again
  367. * later and/or wait for other methods like kernel exit
  368. * switching.
  369. */
  370. schedule_delayed_work(&klp_transition_work,
  371. round_jiffies_relative(HZ));
  372. return;
  373. }
  374. success:
  375. /* we're done, now cleanup the data structures */
  376. klp_complete_transition();
  377. }
  378. /*
  379. * Start the transition to the specified target patch state so tasks can begin
  380. * switching to it.
  381. */
  382. void klp_start_transition(void)
  383. {
  384. struct task_struct *g, *task;
  385. unsigned int cpu;
  386. WARN_ON_ONCE(klp_target_state == KLP_UNDEFINED);
  387. pr_notice("'%s': starting %s transition\n",
  388. klp_transition_patch->mod->name,
  389. klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
  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. return;
  396. /*
  397. * Mark all normal tasks as needing a patch state update. They'll
  398. * switch either in klp_try_complete_transition() or as they exit the
  399. * kernel.
  400. */
  401. read_lock(&tasklist_lock);
  402. for_each_process_thread(g, task)
  403. if (task->patch_state != klp_target_state)
  404. set_tsk_thread_flag(task, TIF_PATCH_PENDING);
  405. read_unlock(&tasklist_lock);
  406. /*
  407. * Mark all idle tasks as needing a patch state update. They'll switch
  408. * either in klp_try_complete_transition() or at the idle loop switch
  409. * point.
  410. */
  411. for_each_possible_cpu(cpu) {
  412. task = idle_task(cpu);
  413. if (task->patch_state != klp_target_state)
  414. set_tsk_thread_flag(task, TIF_PATCH_PENDING);
  415. }
  416. }
  417. /*
  418. * Initialize the global target patch state and all tasks to the initial patch
  419. * state, and initialize all function transition states to true in preparation
  420. * for patching or unpatching.
  421. */
  422. void klp_init_transition(struct klp_patch *patch, int state)
  423. {
  424. struct task_struct *g, *task;
  425. unsigned int cpu;
  426. struct klp_object *obj;
  427. struct klp_func *func;
  428. int initial_state = !state;
  429. WARN_ON_ONCE(klp_target_state != KLP_UNDEFINED);
  430. klp_transition_patch = patch;
  431. /*
  432. * Set the global target patch state which tasks will switch to. This
  433. * has no effect until the TIF_PATCH_PENDING flags get set later.
  434. */
  435. klp_target_state = state;
  436. pr_debug("'%s': initializing %s transition\n", patch->mod->name,
  437. klp_target_state == KLP_PATCHED ? "patching" : "unpatching");
  438. /*
  439. * If the patch can be applied or reverted immediately, skip the
  440. * per-task transitions.
  441. */
  442. if (patch->immediate)
  443. return;
  444. /*
  445. * Initialize all tasks to the initial patch state to prepare them for
  446. * switching to the target state.
  447. */
  448. read_lock(&tasklist_lock);
  449. for_each_process_thread(g, task) {
  450. WARN_ON_ONCE(task->patch_state != KLP_UNDEFINED);
  451. task->patch_state = initial_state;
  452. }
  453. read_unlock(&tasklist_lock);
  454. /*
  455. * Ditto for the idle "swapper" tasks.
  456. */
  457. for_each_possible_cpu(cpu) {
  458. task = idle_task(cpu);
  459. WARN_ON_ONCE(task->patch_state != KLP_UNDEFINED);
  460. task->patch_state = initial_state;
  461. }
  462. /*
  463. * Enforce the order of the task->patch_state initializations and the
  464. * func->transition updates to ensure that klp_ftrace_handler() doesn't
  465. * see a func in transition with a task->patch_state of KLP_UNDEFINED.
  466. *
  467. * Also enforce the order of the klp_target_state write and future
  468. * TIF_PATCH_PENDING writes to ensure klp_update_patch_state() doesn't
  469. * set a task->patch_state to KLP_UNDEFINED.
  470. */
  471. smp_wmb();
  472. /*
  473. * Set the func transition states so klp_ftrace_handler() will know to
  474. * switch to the transition logic.
  475. *
  476. * When patching, the funcs aren't yet in the func_stack and will be
  477. * made visible to the ftrace handler shortly by the calls to
  478. * klp_patch_object().
  479. *
  480. * When unpatching, the funcs are already in the func_stack and so are
  481. * already visible to the ftrace handler.
  482. */
  483. klp_for_each_object(patch, obj)
  484. klp_for_each_func(obj, func)
  485. func->transition = true;
  486. }
  487. /*
  488. * This function can be called in the middle of an existing transition to
  489. * reverse the direction of the target patch state. This can be done to
  490. * effectively cancel an existing enable or disable operation if there are any
  491. * tasks which are stuck in the initial patch state.
  492. */
  493. void klp_reverse_transition(void)
  494. {
  495. unsigned int cpu;
  496. struct task_struct *g, *task;
  497. pr_debug("'%s': reversing transition from %s\n",
  498. klp_transition_patch->mod->name,
  499. klp_target_state == KLP_PATCHED ? "patching to unpatching" :
  500. "unpatching to patching");
  501. klp_transition_patch->enabled = !klp_transition_patch->enabled;
  502. klp_target_state = !klp_target_state;
  503. /*
  504. * Clear all TIF_PATCH_PENDING flags to prevent races caused by
  505. * klp_update_patch_state() running in parallel with
  506. * klp_start_transition().
  507. */
  508. read_lock(&tasklist_lock);
  509. for_each_process_thread(g, task)
  510. clear_tsk_thread_flag(task, TIF_PATCH_PENDING);
  511. read_unlock(&tasklist_lock);
  512. for_each_possible_cpu(cpu)
  513. clear_tsk_thread_flag(idle_task(cpu), TIF_PATCH_PENDING);
  514. /* Let any remaining calls to klp_update_patch_state() complete */
  515. klp_synchronize_transition();
  516. klp_start_transition();
  517. }
  518. /* Called from copy_process() during fork */
  519. void klp_copy_process(struct task_struct *child)
  520. {
  521. child->patch_state = current->patch_state;
  522. /* TIF_PATCH_PENDING gets copied in setup_thread_stack() */
  523. }