transition.c 16 KB

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