alternative.c 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. #define pr_fmt(fmt) "SMP alternatives: " fmt
  3. #include <linux/module.h>
  4. #include <linux/sched.h>
  5. #include <linux/perf_event.h>
  6. #include <linux/mutex.h>
  7. #include <linux/list.h>
  8. #include <linux/stringify.h>
  9. #include <linux/highmem.h>
  10. #include <linux/mm.h>
  11. #include <linux/vmalloc.h>
  12. #include <linux/memory.h>
  13. #include <linux/stop_machine.h>
  14. #include <linux/slab.h>
  15. #include <linux/kdebug.h>
  16. #include <linux/kprobes.h>
  17. #include <linux/mmu_context.h>
  18. #include <linux/bsearch.h>
  19. #include <linux/sync_core.h>
  20. #include <linux/execmem.h>
  21. #include <asm/text-patching.h>
  22. #include <asm/alternative.h>
  23. #include <asm/sections.h>
  24. #include <asm/mce.h>
  25. #include <asm/nmi.h>
  26. #include <asm/cacheflush.h>
  27. #include <asm/tlbflush.h>
  28. #include <asm/insn.h>
  29. #include <asm/io.h>
  30. #include <asm/fixmap.h>
  31. #include <asm/paravirt.h>
  32. #include <asm/asm-prototypes.h>
  33. #include <asm/cfi.h>
  34. #include <asm/ibt.h>
  35. #include <asm/set_memory.h>
  36. int __read_mostly alternatives_patched;
  37. EXPORT_SYMBOL_GPL(alternatives_patched);
  38. #define MAX_PATCH_LEN (255-1)
  39. #define DA_ALL (~0)
  40. #define DA_ALT 0x01
  41. #define DA_RET 0x02
  42. #define DA_RETPOLINE 0x04
  43. #define DA_ENDBR 0x08
  44. #define DA_SMP 0x10
  45. static unsigned int debug_alternative;
  46. static int __init debug_alt(char *str)
  47. {
  48. if (str && *str == '=')
  49. str++;
  50. if (!str || kstrtouint(str, 0, &debug_alternative))
  51. debug_alternative = DA_ALL;
  52. return 1;
  53. }
  54. __setup("debug-alternative", debug_alt);
  55. static int noreplace_smp;
  56. static int __init setup_noreplace_smp(char *str)
  57. {
  58. noreplace_smp = 1;
  59. return 1;
  60. }
  61. __setup("noreplace-smp", setup_noreplace_smp);
  62. #define DPRINTK(type, fmt, args...) \
  63. do { \
  64. if (debug_alternative & DA_##type) \
  65. printk(KERN_DEBUG pr_fmt(fmt) "\n", ##args); \
  66. } while (0)
  67. #define DUMP_BYTES(type, buf, len, fmt, args...) \
  68. do { \
  69. if (unlikely(debug_alternative & DA_##type)) { \
  70. int j; \
  71. \
  72. if (!(len)) \
  73. break; \
  74. \
  75. printk(KERN_DEBUG pr_fmt(fmt), ##args); \
  76. for (j = 0; j < (len) - 1; j++) \
  77. printk(KERN_CONT "%02hhx ", buf[j]); \
  78. printk(KERN_CONT "%02hhx\n", buf[j]); \
  79. } \
  80. } while (0)
  81. static const unsigned char x86nops[] =
  82. {
  83. BYTES_NOP1,
  84. BYTES_NOP2,
  85. BYTES_NOP3,
  86. BYTES_NOP4,
  87. BYTES_NOP5,
  88. BYTES_NOP6,
  89. BYTES_NOP7,
  90. BYTES_NOP8,
  91. #ifdef CONFIG_64BIT
  92. BYTES_NOP9,
  93. BYTES_NOP10,
  94. BYTES_NOP11,
  95. #endif
  96. };
  97. const unsigned char * const x86_nops[ASM_NOP_MAX+1] =
  98. {
  99. NULL,
  100. x86nops,
  101. x86nops + 1,
  102. x86nops + 1 + 2,
  103. x86nops + 1 + 2 + 3,
  104. x86nops + 1 + 2 + 3 + 4,
  105. x86nops + 1 + 2 + 3 + 4 + 5,
  106. x86nops + 1 + 2 + 3 + 4 + 5 + 6,
  107. x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
  108. #ifdef CONFIG_64BIT
  109. x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
  110. x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9,
  111. x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10,
  112. #endif
  113. };
  114. #ifdef CONFIG_MITIGATION_ITS
  115. #ifdef CONFIG_MODULES
  116. static struct module *its_mod;
  117. #endif
  118. static void *its_page;
  119. static unsigned int its_offset;
  120. /* Initialize a thunk with the "jmp *reg; int3" instructions. */
  121. static void *its_init_thunk(void *thunk, int reg)
  122. {
  123. u8 *bytes = thunk;
  124. int i = 0;
  125. if (reg >= 8) {
  126. bytes[i++] = 0x41; /* REX.B prefix */
  127. reg -= 8;
  128. }
  129. bytes[i++] = 0xff;
  130. bytes[i++] = 0xe0 + reg; /* jmp *reg */
  131. bytes[i++] = 0xcc;
  132. return thunk;
  133. }
  134. #ifdef CONFIG_MODULES
  135. void its_init_mod(struct module *mod)
  136. {
  137. if (!cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS))
  138. return;
  139. mutex_lock(&text_mutex);
  140. its_mod = mod;
  141. its_page = NULL;
  142. }
  143. void its_fini_mod(struct module *mod)
  144. {
  145. if (!cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS))
  146. return;
  147. WARN_ON_ONCE(its_mod != mod);
  148. its_mod = NULL;
  149. its_page = NULL;
  150. mutex_unlock(&text_mutex);
  151. for (int i = 0; i < mod->its_num_pages; i++) {
  152. void *page = mod->its_page_array[i];
  153. set_memory_rox((unsigned long)page, 1);
  154. }
  155. }
  156. void its_free_mod(struct module *mod)
  157. {
  158. if (!cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS))
  159. return;
  160. for (int i = 0; i < mod->its_num_pages; i++) {
  161. void *page = mod->its_page_array[i];
  162. execmem_free(page);
  163. }
  164. kfree(mod->its_page_array);
  165. }
  166. #endif /* CONFIG_MODULES */
  167. static void *its_alloc(void)
  168. {
  169. void *page __free(execmem) = execmem_alloc(EXECMEM_MODULE_TEXT, PAGE_SIZE);
  170. if (!page)
  171. return NULL;
  172. #ifdef CONFIG_MODULES
  173. if (its_mod) {
  174. void *tmp = krealloc(its_mod->its_page_array,
  175. (its_mod->its_num_pages+1) * sizeof(void *),
  176. GFP_KERNEL);
  177. if (!tmp)
  178. return NULL;
  179. its_mod->its_page_array = tmp;
  180. its_mod->its_page_array[its_mod->its_num_pages++] = page;
  181. }
  182. #endif /* CONFIG_MODULES */
  183. return no_free_ptr(page);
  184. }
  185. static void *its_allocate_thunk(int reg)
  186. {
  187. int size = 3 + (reg / 8);
  188. void *thunk;
  189. if (!its_page || (its_offset + size - 1) >= PAGE_SIZE) {
  190. its_page = its_alloc();
  191. if (!its_page) {
  192. pr_err("ITS page allocation failed\n");
  193. return NULL;
  194. }
  195. memset(its_page, INT3_INSN_OPCODE, PAGE_SIZE);
  196. its_offset = 32;
  197. }
  198. /*
  199. * If the indirect branch instruction will be in the lower half
  200. * of a cacheline, then update the offset to reach the upper half.
  201. */
  202. if ((its_offset + size - 1) % 64 < 32)
  203. its_offset = ((its_offset - 1) | 0x3F) + 33;
  204. thunk = its_page + its_offset;
  205. its_offset += size;
  206. set_memory_rw((unsigned long)its_page, 1);
  207. thunk = its_init_thunk(thunk, reg);
  208. set_memory_rox((unsigned long)its_page, 1);
  209. return thunk;
  210. }
  211. u8 *its_static_thunk(int reg)
  212. {
  213. u8 *thunk = __x86_indirect_its_thunk_array[reg];
  214. return thunk;
  215. }
  216. #endif
  217. /*
  218. * Nomenclature for variable names to simplify and clarify this code and ease
  219. * any potential staring at it:
  220. *
  221. * @instr: source address of the original instructions in the kernel text as
  222. * generated by the compiler.
  223. *
  224. * @buf: temporary buffer on which the patching operates. This buffer is
  225. * eventually text-poked into the kernel image.
  226. *
  227. * @replacement/@repl: pointer to the opcodes which are replacing @instr, located
  228. * in the .altinstr_replacement section.
  229. */
  230. /*
  231. * Fill the buffer with a single effective instruction of size @len.
  232. *
  233. * In order not to issue an ORC stack depth tracking CFI entry (Call Frame Info)
  234. * for every single-byte NOP, try to generate the maximally available NOP of
  235. * size <= ASM_NOP_MAX such that only a single CFI entry is generated (vs one for
  236. * each single-byte NOPs). If @len to fill out is > ASM_NOP_MAX, pad with INT3 and
  237. * *jump* over instead of executing long and daft NOPs.
  238. */
  239. static void add_nop(u8 *buf, unsigned int len)
  240. {
  241. u8 *target = buf + len;
  242. if (!len)
  243. return;
  244. if (len <= ASM_NOP_MAX) {
  245. memcpy(buf, x86_nops[len], len);
  246. return;
  247. }
  248. if (len < 128) {
  249. __text_gen_insn(buf, JMP8_INSN_OPCODE, buf, target, JMP8_INSN_SIZE);
  250. buf += JMP8_INSN_SIZE;
  251. } else {
  252. __text_gen_insn(buf, JMP32_INSN_OPCODE, buf, target, JMP32_INSN_SIZE);
  253. buf += JMP32_INSN_SIZE;
  254. }
  255. for (;buf < target; buf++)
  256. *buf = INT3_INSN_OPCODE;
  257. }
  258. extern s32 __retpoline_sites[], __retpoline_sites_end[];
  259. extern s32 __return_sites[], __return_sites_end[];
  260. extern s32 __cfi_sites[], __cfi_sites_end[];
  261. extern s32 __ibt_endbr_seal[], __ibt_endbr_seal_end[];
  262. extern s32 __smp_locks[], __smp_locks_end[];
  263. void text_poke_early(void *addr, const void *opcode, size_t len);
  264. /*
  265. * Matches NOP and NOPL, not any of the other possible NOPs.
  266. */
  267. static bool insn_is_nop(struct insn *insn)
  268. {
  269. /* Anything NOP, but no REP NOP */
  270. if (insn->opcode.bytes[0] == 0x90 &&
  271. (!insn->prefixes.nbytes || insn->prefixes.bytes[0] != 0xF3))
  272. return true;
  273. /* NOPL */
  274. if (insn->opcode.bytes[0] == 0x0F && insn->opcode.bytes[1] == 0x1F)
  275. return true;
  276. /* TODO: more nops */
  277. return false;
  278. }
  279. /*
  280. * Find the offset of the first non-NOP instruction starting at @offset
  281. * but no further than @len.
  282. */
  283. static int skip_nops(u8 *buf, int offset, int len)
  284. {
  285. struct insn insn;
  286. for (; offset < len; offset += insn.length) {
  287. if (insn_decode_kernel(&insn, &buf[offset]))
  288. break;
  289. if (!insn_is_nop(&insn))
  290. break;
  291. }
  292. return offset;
  293. }
  294. /*
  295. * "noinline" to cause control flow change and thus invalidate I$ and
  296. * cause refetch after modification.
  297. */
  298. static void noinline optimize_nops(const u8 * const instr, u8 *buf, size_t len)
  299. {
  300. for (int next, i = 0; i < len; i = next) {
  301. struct insn insn;
  302. if (insn_decode_kernel(&insn, &buf[i]))
  303. return;
  304. next = i + insn.length;
  305. if (insn_is_nop(&insn)) {
  306. int nop = i;
  307. /* Has the NOP already been optimized? */
  308. if (i + insn.length == len)
  309. return;
  310. next = skip_nops(buf, next, len);
  311. add_nop(buf + nop, next - nop);
  312. DUMP_BYTES(ALT, buf, len, "%px: [%d:%d) optimized NOPs: ", instr, nop, next);
  313. }
  314. }
  315. }
  316. /*
  317. * In this context, "source" is where the instructions are placed in the
  318. * section .altinstr_replacement, for example during kernel build by the
  319. * toolchain.
  320. * "Destination" is where the instructions are being patched in by this
  321. * machinery.
  322. *
  323. * The source offset is:
  324. *
  325. * src_imm = target - src_next_ip (1)
  326. *
  327. * and the target offset is:
  328. *
  329. * dst_imm = target - dst_next_ip (2)
  330. *
  331. * so rework (1) as an expression for target like:
  332. *
  333. * target = src_imm + src_next_ip (1a)
  334. *
  335. * and substitute in (2) to get:
  336. *
  337. * dst_imm = (src_imm + src_next_ip) - dst_next_ip (3)
  338. *
  339. * Now, since the instruction stream is 'identical' at src and dst (it
  340. * is being copied after all) it can be stated that:
  341. *
  342. * src_next_ip = src + ip_offset
  343. * dst_next_ip = dst + ip_offset (4)
  344. *
  345. * Substitute (4) in (3) and observe ip_offset being cancelled out to
  346. * obtain:
  347. *
  348. * dst_imm = src_imm + (src + ip_offset) - (dst + ip_offset)
  349. * = src_imm + src - dst + ip_offset - ip_offset
  350. * = src_imm + src - dst (5)
  351. *
  352. * IOW, only the relative displacement of the code block matters.
  353. */
  354. #define apply_reloc_n(n_, p_, d_) \
  355. do { \
  356. s32 v = *(s##n_ *)(p_); \
  357. v += (d_); \
  358. BUG_ON((v >> 31) != (v >> (n_-1))); \
  359. *(s##n_ *)(p_) = (s##n_)v; \
  360. } while (0)
  361. static __always_inline
  362. void apply_reloc(int n, void *ptr, uintptr_t diff)
  363. {
  364. switch (n) {
  365. case 1: apply_reloc_n(8, ptr, diff); break;
  366. case 2: apply_reloc_n(16, ptr, diff); break;
  367. case 4: apply_reloc_n(32, ptr, diff); break;
  368. default: BUG();
  369. }
  370. }
  371. static __always_inline
  372. bool need_reloc(unsigned long offset, u8 *src, size_t src_len)
  373. {
  374. u8 *target = src + offset;
  375. /*
  376. * If the target is inside the patched block, it's relative to the
  377. * block itself and does not need relocation.
  378. */
  379. return (target < src || target > src + src_len);
  380. }
  381. static void __apply_relocation(u8 *buf, const u8 * const instr, size_t instrlen, u8 *repl, size_t repl_len)
  382. {
  383. for (int next, i = 0; i < instrlen; i = next) {
  384. struct insn insn;
  385. if (WARN_ON_ONCE(insn_decode_kernel(&insn, &buf[i])))
  386. return;
  387. next = i + insn.length;
  388. switch (insn.opcode.bytes[0]) {
  389. case 0x0f:
  390. if (insn.opcode.bytes[1] < 0x80 ||
  391. insn.opcode.bytes[1] > 0x8f)
  392. break;
  393. fallthrough; /* Jcc.d32 */
  394. case 0x70 ... 0x7f: /* Jcc.d8 */
  395. case JMP8_INSN_OPCODE:
  396. case JMP32_INSN_OPCODE:
  397. case CALL_INSN_OPCODE:
  398. if (need_reloc(next + insn.immediate.value, repl, repl_len)) {
  399. apply_reloc(insn.immediate.nbytes,
  400. buf + i + insn_offset_immediate(&insn),
  401. repl - instr);
  402. }
  403. /*
  404. * Where possible, convert JMP.d32 into JMP.d8.
  405. */
  406. if (insn.opcode.bytes[0] == JMP32_INSN_OPCODE) {
  407. s32 imm = insn.immediate.value;
  408. imm += repl - instr;
  409. imm += JMP32_INSN_SIZE - JMP8_INSN_SIZE;
  410. if ((imm >> 31) == (imm >> 7)) {
  411. buf[i+0] = JMP8_INSN_OPCODE;
  412. buf[i+1] = (s8)imm;
  413. memset(&buf[i+2], INT3_INSN_OPCODE, insn.length - 2);
  414. }
  415. }
  416. break;
  417. }
  418. if (insn_rip_relative(&insn)) {
  419. if (need_reloc(next + insn.displacement.value, repl, repl_len)) {
  420. apply_reloc(insn.displacement.nbytes,
  421. buf + i + insn_offset_displacement(&insn),
  422. repl - instr);
  423. }
  424. }
  425. }
  426. }
  427. void apply_relocation(u8 *buf, const u8 * const instr, size_t instrlen, u8 *repl, size_t repl_len)
  428. {
  429. __apply_relocation(buf, instr, instrlen, repl, repl_len);
  430. optimize_nops(instr, buf, instrlen);
  431. }
  432. /* Low-level backend functions usable from alternative code replacements. */
  433. DEFINE_ASM_FUNC(nop_func, "", .entry.text);
  434. EXPORT_SYMBOL_GPL(nop_func);
  435. noinstr void BUG_func(void)
  436. {
  437. BUG();
  438. }
  439. EXPORT_SYMBOL(BUG_func);
  440. #define CALL_RIP_REL_OPCODE 0xff
  441. #define CALL_RIP_REL_MODRM 0x15
  442. /*
  443. * Rewrite the "call BUG_func" replacement to point to the target of the
  444. * indirect pv_ops call "call *disp(%ip)".
  445. */
  446. static int alt_replace_call(u8 *instr, u8 *insn_buff, struct alt_instr *a)
  447. {
  448. void *target, *bug = &BUG_func;
  449. s32 disp;
  450. if (a->replacementlen != 5 || insn_buff[0] != CALL_INSN_OPCODE) {
  451. pr_err("ALT_FLAG_DIRECT_CALL set for a non-call replacement instruction\n");
  452. BUG();
  453. }
  454. if (a->instrlen != 6 ||
  455. instr[0] != CALL_RIP_REL_OPCODE ||
  456. instr[1] != CALL_RIP_REL_MODRM) {
  457. pr_err("ALT_FLAG_DIRECT_CALL set for unrecognized indirect call\n");
  458. BUG();
  459. }
  460. /* Skip CALL_RIP_REL_OPCODE and CALL_RIP_REL_MODRM */
  461. disp = *(s32 *)(instr + 2);
  462. #ifdef CONFIG_X86_64
  463. /* ff 15 00 00 00 00 call *0x0(%rip) */
  464. /* target address is stored at "next instruction + disp". */
  465. target = *(void **)(instr + a->instrlen + disp);
  466. #else
  467. /* ff 15 00 00 00 00 call *0x0 */
  468. /* target address is stored at disp. */
  469. target = *(void **)disp;
  470. #endif
  471. if (!target)
  472. target = bug;
  473. /* (BUG_func - .) + (target - BUG_func) := target - . */
  474. *(s32 *)(insn_buff + 1) += target - bug;
  475. if (target == &nop_func)
  476. return 0;
  477. return 5;
  478. }
  479. static inline u8 * instr_va(struct alt_instr *i)
  480. {
  481. return (u8 *)&i->instr_offset + i->instr_offset;
  482. }
  483. /*
  484. * Replace instructions with better alternatives for this CPU type. This runs
  485. * before SMP is initialized to avoid SMP problems with self modifying code.
  486. * This implies that asymmetric systems where APs have less capabilities than
  487. * the boot processor are not handled. Tough. Make sure you disable such
  488. * features by hand.
  489. *
  490. * Marked "noinline" to cause control flow change and thus insn cache
  491. * to refetch changed I$ lines.
  492. */
  493. void __init_or_module noinline apply_alternatives(struct alt_instr *start,
  494. struct alt_instr *end)
  495. {
  496. u8 insn_buff[MAX_PATCH_LEN];
  497. u8 *instr, *replacement;
  498. struct alt_instr *a, *b;
  499. DPRINTK(ALT, "alt table %px, -> %px", start, end);
  500. /*
  501. * In the case CONFIG_X86_5LEVEL=y, KASAN_SHADOW_START is defined using
  502. * cpu_feature_enabled(X86_FEATURE_LA57) and is therefore patched here.
  503. * During the process, KASAN becomes confused seeing partial LA57
  504. * conversion and triggers a false-positive out-of-bound report.
  505. *
  506. * Disable KASAN until the patching is complete.
  507. */
  508. kasan_disable_current();
  509. /*
  510. * The scan order should be from start to end. A later scanned
  511. * alternative code can overwrite previously scanned alternative code.
  512. * Some kernel functions (e.g. memcpy, memset, etc) use this order to
  513. * patch code.
  514. *
  515. * So be careful if you want to change the scan order to any other
  516. * order.
  517. */
  518. for (a = start; a < end; a++) {
  519. int insn_buff_sz = 0;
  520. /*
  521. * In case of nested ALTERNATIVE()s the outer alternative might
  522. * add more padding. To ensure consistent patching find the max
  523. * padding for all alt_instr entries for this site (nested
  524. * alternatives result in consecutive entries).
  525. */
  526. for (b = a+1; b < end && instr_va(b) == instr_va(a); b++) {
  527. u8 len = max(a->instrlen, b->instrlen);
  528. a->instrlen = b->instrlen = len;
  529. }
  530. instr = instr_va(a);
  531. replacement = (u8 *)&a->repl_offset + a->repl_offset;
  532. BUG_ON(a->instrlen > sizeof(insn_buff));
  533. BUG_ON(a->cpuid >= (NCAPINTS + NBUGINTS) * 32);
  534. /*
  535. * Patch if either:
  536. * - feature is present
  537. * - feature not present but ALT_FLAG_NOT is set to mean,
  538. * patch if feature is *NOT* present.
  539. */
  540. if (!boot_cpu_has(a->cpuid) == !(a->flags & ALT_FLAG_NOT)) {
  541. memcpy(insn_buff, instr, a->instrlen);
  542. optimize_nops(instr, insn_buff, a->instrlen);
  543. text_poke_early(instr, insn_buff, a->instrlen);
  544. continue;
  545. }
  546. DPRINTK(ALT, "feat: %d*32+%d, old: (%pS (%px) len: %d), repl: (%px, len: %d) flags: 0x%x",
  547. a->cpuid >> 5,
  548. a->cpuid & 0x1f,
  549. instr, instr, a->instrlen,
  550. replacement, a->replacementlen, a->flags);
  551. memcpy(insn_buff, replacement, a->replacementlen);
  552. insn_buff_sz = a->replacementlen;
  553. if (a->flags & ALT_FLAG_DIRECT_CALL) {
  554. insn_buff_sz = alt_replace_call(instr, insn_buff, a);
  555. if (insn_buff_sz < 0)
  556. continue;
  557. }
  558. for (; insn_buff_sz < a->instrlen; insn_buff_sz++)
  559. insn_buff[insn_buff_sz] = 0x90;
  560. apply_relocation(insn_buff, instr, a->instrlen, replacement, a->replacementlen);
  561. DUMP_BYTES(ALT, instr, a->instrlen, "%px: old_insn: ", instr);
  562. DUMP_BYTES(ALT, replacement, a->replacementlen, "%px: rpl_insn: ", replacement);
  563. DUMP_BYTES(ALT, insn_buff, insn_buff_sz, "%px: final_insn: ", instr);
  564. text_poke_early(instr, insn_buff, insn_buff_sz);
  565. }
  566. kasan_enable_current();
  567. }
  568. static inline bool is_jcc32(struct insn *insn)
  569. {
  570. /* Jcc.d32 second opcode byte is in the range: 0x80-0x8f */
  571. return insn->opcode.bytes[0] == 0x0f && (insn->opcode.bytes[1] & 0xf0) == 0x80;
  572. }
  573. #if defined(CONFIG_MITIGATION_RETPOLINE) && defined(CONFIG_OBJTOOL)
  574. /*
  575. * CALL/JMP *%\reg
  576. */
  577. static int emit_indirect(int op, int reg, u8 *bytes)
  578. {
  579. int i = 0;
  580. u8 modrm;
  581. switch (op) {
  582. case CALL_INSN_OPCODE:
  583. modrm = 0x10; /* Reg = 2; CALL r/m */
  584. break;
  585. case JMP32_INSN_OPCODE:
  586. modrm = 0x20; /* Reg = 4; JMP r/m */
  587. break;
  588. default:
  589. WARN_ON_ONCE(1);
  590. return -1;
  591. }
  592. if (reg >= 8) {
  593. bytes[i++] = 0x41; /* REX.B prefix */
  594. reg -= 8;
  595. }
  596. modrm |= 0xc0; /* Mod = 3 */
  597. modrm += reg;
  598. bytes[i++] = 0xff; /* opcode */
  599. bytes[i++] = modrm;
  600. return i;
  601. }
  602. static int __emit_trampoline(void *addr, struct insn *insn, u8 *bytes,
  603. void *call_dest, void *jmp_dest)
  604. {
  605. u8 op = insn->opcode.bytes[0];
  606. int i = 0;
  607. /*
  608. * Clang does 'weird' Jcc __x86_indirect_thunk_r11 conditional
  609. * tail-calls. Deal with them.
  610. */
  611. if (is_jcc32(insn)) {
  612. bytes[i++] = op;
  613. op = insn->opcode.bytes[1];
  614. goto clang_jcc;
  615. }
  616. if (insn->length == 6)
  617. bytes[i++] = 0x2e; /* CS-prefix */
  618. switch (op) {
  619. case CALL_INSN_OPCODE:
  620. __text_gen_insn(bytes+i, op, addr+i,
  621. call_dest,
  622. CALL_INSN_SIZE);
  623. i += CALL_INSN_SIZE;
  624. break;
  625. case JMP32_INSN_OPCODE:
  626. clang_jcc:
  627. __text_gen_insn(bytes+i, op, addr+i,
  628. jmp_dest,
  629. JMP32_INSN_SIZE);
  630. i += JMP32_INSN_SIZE;
  631. break;
  632. default:
  633. WARN(1, "%pS %px %*ph\n", addr, addr, 6, addr);
  634. return -1;
  635. }
  636. WARN_ON_ONCE(i != insn->length);
  637. return i;
  638. }
  639. static int emit_call_track_retpoline(void *addr, struct insn *insn, int reg, u8 *bytes)
  640. {
  641. return __emit_trampoline(addr, insn, bytes,
  642. __x86_indirect_call_thunk_array[reg],
  643. __x86_indirect_jump_thunk_array[reg]);
  644. }
  645. #ifdef CONFIG_MITIGATION_ITS
  646. static int emit_its_trampoline(void *addr, struct insn *insn, int reg, u8 *bytes)
  647. {
  648. u8 *thunk = __x86_indirect_its_thunk_array[reg];
  649. u8 *tmp = its_allocate_thunk(reg);
  650. if (tmp)
  651. thunk = tmp;
  652. return __emit_trampoline(addr, insn, bytes, thunk, thunk);
  653. }
  654. /* Check if an indirect branch is at ITS-unsafe address */
  655. static bool cpu_wants_indirect_its_thunk_at(unsigned long addr, int reg)
  656. {
  657. if (!cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS))
  658. return false;
  659. /* Indirect branch opcode is 2 or 3 bytes depending on reg */
  660. addr += 1 + reg / 8;
  661. /* Lower-half of the cacheline? */
  662. return !(addr & 0x20);
  663. }
  664. #endif
  665. /*
  666. * Rewrite the compiler generated retpoline thunk calls.
  667. *
  668. * For spectre_v2=off (!X86_FEATURE_RETPOLINE), rewrite them into immediate
  669. * indirect instructions, avoiding the extra indirection.
  670. *
  671. * For example, convert:
  672. *
  673. * CALL __x86_indirect_thunk_\reg
  674. *
  675. * into:
  676. *
  677. * CALL *%\reg
  678. *
  679. * It also tries to inline spectre_v2=retpoline,lfence when size permits.
  680. */
  681. static int patch_retpoline(void *addr, struct insn *insn, u8 *bytes)
  682. {
  683. retpoline_thunk_t *target;
  684. int reg, ret, i = 0;
  685. u8 op, cc;
  686. target = addr + insn->length + insn->immediate.value;
  687. reg = target - __x86_indirect_thunk_array;
  688. if (WARN_ON_ONCE(reg & ~0xf))
  689. return -1;
  690. /* If anyone ever does: CALL/JMP *%rsp, we're in deep trouble. */
  691. BUG_ON(reg == 4);
  692. if (cpu_feature_enabled(X86_FEATURE_RETPOLINE) &&
  693. !cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
  694. if (cpu_feature_enabled(X86_FEATURE_CALL_DEPTH))
  695. return emit_call_track_retpoline(addr, insn, reg, bytes);
  696. return -1;
  697. }
  698. op = insn->opcode.bytes[0];
  699. /*
  700. * Convert:
  701. *
  702. * Jcc.d32 __x86_indirect_thunk_\reg
  703. *
  704. * into:
  705. *
  706. * Jncc.d8 1f
  707. * [ LFENCE ]
  708. * JMP *%\reg
  709. * [ NOP ]
  710. * 1:
  711. */
  712. if (is_jcc32(insn)) {
  713. cc = insn->opcode.bytes[1] & 0xf;
  714. cc ^= 1; /* invert condition */
  715. bytes[i++] = 0x70 + cc; /* Jcc.d8 */
  716. bytes[i++] = insn->length - 2; /* sizeof(Jcc.d8) == 2 */
  717. /* Continue as if: JMP.d32 __x86_indirect_thunk_\reg */
  718. op = JMP32_INSN_OPCODE;
  719. }
  720. /*
  721. * For RETPOLINE_LFENCE: prepend the indirect CALL/JMP with an LFENCE.
  722. */
  723. if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
  724. bytes[i++] = 0x0f;
  725. bytes[i++] = 0xae;
  726. bytes[i++] = 0xe8; /* LFENCE */
  727. }
  728. #ifdef CONFIG_MITIGATION_ITS
  729. /*
  730. * Check if the address of last byte of emitted-indirect is in
  731. * lower-half of the cacheline. Such branches need ITS mitigation.
  732. */
  733. if (cpu_wants_indirect_its_thunk_at((unsigned long)addr + i, reg))
  734. return emit_its_trampoline(addr, insn, reg, bytes);
  735. #endif
  736. ret = emit_indirect(op, reg, bytes + i);
  737. if (ret < 0)
  738. return ret;
  739. i += ret;
  740. /*
  741. * The compiler is supposed to EMIT an INT3 after every unconditional
  742. * JMP instruction due to AMD BTC. However, if the compiler is too old
  743. * or MITIGATION_SLS isn't enabled, we still need an INT3 after
  744. * indirect JMPs even on Intel.
  745. */
  746. if (op == JMP32_INSN_OPCODE && i < insn->length)
  747. bytes[i++] = INT3_INSN_OPCODE;
  748. for (; i < insn->length;)
  749. bytes[i++] = BYTES_NOP1;
  750. return i;
  751. }
  752. /*
  753. * Generated by 'objtool --retpoline'.
  754. */
  755. void __init_or_module noinline apply_retpolines(s32 *start, s32 *end)
  756. {
  757. s32 *s;
  758. for (s = start; s < end; s++) {
  759. void *addr = (void *)s + *s;
  760. struct insn insn;
  761. int len, ret;
  762. u8 bytes[16];
  763. u8 op1, op2;
  764. ret = insn_decode_kernel(&insn, addr);
  765. if (WARN_ON_ONCE(ret < 0))
  766. continue;
  767. op1 = insn.opcode.bytes[0];
  768. op2 = insn.opcode.bytes[1];
  769. switch (op1) {
  770. case CALL_INSN_OPCODE:
  771. case JMP32_INSN_OPCODE:
  772. break;
  773. case 0x0f: /* escape */
  774. if (op2 >= 0x80 && op2 <= 0x8f)
  775. break;
  776. fallthrough;
  777. default:
  778. WARN_ON_ONCE(1);
  779. continue;
  780. }
  781. DPRINTK(RETPOLINE, "retpoline at: %pS (%px) len: %d to: %pS",
  782. addr, addr, insn.length,
  783. addr + insn.length + insn.immediate.value);
  784. len = patch_retpoline(addr, &insn, bytes);
  785. if (len == insn.length) {
  786. optimize_nops(addr, bytes, len);
  787. DUMP_BYTES(RETPOLINE, ((u8*)addr), len, "%px: orig: ", addr);
  788. DUMP_BYTES(RETPOLINE, ((u8*)bytes), len, "%px: repl: ", addr);
  789. text_poke_early(addr, bytes, len);
  790. }
  791. }
  792. }
  793. #ifdef CONFIG_MITIGATION_RETHUNK
  794. bool cpu_wants_rethunk(void)
  795. {
  796. return cpu_feature_enabled(X86_FEATURE_RETHUNK);
  797. }
  798. bool cpu_wants_rethunk_at(void *addr)
  799. {
  800. if (!cpu_feature_enabled(X86_FEATURE_RETHUNK))
  801. return false;
  802. if (x86_return_thunk != its_return_thunk)
  803. return true;
  804. return !((unsigned long)addr & 0x20);
  805. }
  806. /*
  807. * Rewrite the compiler generated return thunk tail-calls.
  808. *
  809. * For example, convert:
  810. *
  811. * JMP __x86_return_thunk
  812. *
  813. * into:
  814. *
  815. * RET
  816. */
  817. static int patch_return(void *addr, struct insn *insn, u8 *bytes)
  818. {
  819. int i = 0;
  820. /* Patch the custom return thunks... */
  821. if (cpu_wants_rethunk_at(addr)) {
  822. i = JMP32_INSN_SIZE;
  823. __text_gen_insn(bytes, JMP32_INSN_OPCODE, addr, x86_return_thunk, i);
  824. } else {
  825. /* ... or patch them out if not needed. */
  826. bytes[i++] = RET_INSN_OPCODE;
  827. }
  828. for (; i < insn->length;)
  829. bytes[i++] = INT3_INSN_OPCODE;
  830. return i;
  831. }
  832. void __init_or_module noinline apply_returns(s32 *start, s32 *end)
  833. {
  834. s32 *s;
  835. if (cpu_wants_rethunk())
  836. static_call_force_reinit();
  837. for (s = start; s < end; s++) {
  838. void *dest = NULL, *addr = (void *)s + *s;
  839. struct insn insn;
  840. int len, ret;
  841. u8 bytes[16];
  842. u8 op;
  843. ret = insn_decode_kernel(&insn, addr);
  844. if (WARN_ON_ONCE(ret < 0))
  845. continue;
  846. op = insn.opcode.bytes[0];
  847. if (op == JMP32_INSN_OPCODE)
  848. dest = addr + insn.length + insn.immediate.value;
  849. if (__static_call_fixup(addr, op, dest) ||
  850. WARN_ONCE(dest != &__x86_return_thunk,
  851. "missing return thunk: %pS-%pS: %*ph",
  852. addr, dest, 5, addr))
  853. continue;
  854. DPRINTK(RET, "return thunk at: %pS (%px) len: %d to: %pS",
  855. addr, addr, insn.length,
  856. addr + insn.length + insn.immediate.value);
  857. len = patch_return(addr, &insn, bytes);
  858. if (len == insn.length) {
  859. DUMP_BYTES(RET, ((u8*)addr), len, "%px: orig: ", addr);
  860. DUMP_BYTES(RET, ((u8*)bytes), len, "%px: repl: ", addr);
  861. text_poke_early(addr, bytes, len);
  862. }
  863. }
  864. }
  865. #else
  866. void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
  867. #endif /* CONFIG_MITIGATION_RETHUNK */
  868. #else /* !CONFIG_MITIGATION_RETPOLINE || !CONFIG_OBJTOOL */
  869. void __init_or_module noinline apply_retpolines(s32 *start, s32 *end) { }
  870. void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
  871. #endif /* CONFIG_MITIGATION_RETPOLINE && CONFIG_OBJTOOL */
  872. #ifdef CONFIG_X86_KERNEL_IBT
  873. static void poison_cfi(void *addr);
  874. static void __init_or_module poison_endbr(void *addr, bool warn)
  875. {
  876. u32 endbr, poison = gen_endbr_poison();
  877. if (WARN_ON_ONCE(get_kernel_nofault(endbr, addr)))
  878. return;
  879. if (!is_endbr(endbr)) {
  880. WARN_ON_ONCE(warn);
  881. return;
  882. }
  883. DPRINTK(ENDBR, "ENDBR at: %pS (%px)", addr, addr);
  884. /*
  885. * When we have IBT, the lack of ENDBR will trigger #CP
  886. */
  887. DUMP_BYTES(ENDBR, ((u8*)addr), 4, "%px: orig: ", addr);
  888. DUMP_BYTES(ENDBR, ((u8*)&poison), 4, "%px: repl: ", addr);
  889. text_poke_early(addr, &poison, 4);
  890. }
  891. /*
  892. * Generated by: objtool --ibt
  893. *
  894. * Seal the functions for indirect calls by clobbering the ENDBR instructions
  895. * and the kCFI hash value.
  896. */
  897. void __init_or_module noinline apply_seal_endbr(s32 *start, s32 *end)
  898. {
  899. s32 *s;
  900. for (s = start; s < end; s++) {
  901. void *addr = (void *)s + *s;
  902. poison_endbr(addr, true);
  903. if (IS_ENABLED(CONFIG_FINEIBT))
  904. poison_cfi(addr - 16);
  905. }
  906. }
  907. #else
  908. void __init_or_module apply_seal_endbr(s32 *start, s32 *end) { }
  909. #endif /* CONFIG_X86_KERNEL_IBT */
  910. #ifdef CONFIG_CFI_AUTO_DEFAULT
  911. #define __CFI_DEFAULT CFI_AUTO
  912. #elif defined(CONFIG_CFI_CLANG)
  913. #define __CFI_DEFAULT CFI_KCFI
  914. #else
  915. #define __CFI_DEFAULT CFI_OFF
  916. #endif
  917. enum cfi_mode cfi_mode __ro_after_init = __CFI_DEFAULT;
  918. #ifdef CONFIG_CFI_CLANG
  919. struct bpf_insn;
  920. /* Must match bpf_func_t / DEFINE_BPF_PROG_RUN() */
  921. extern unsigned int __bpf_prog_runX(const void *ctx,
  922. const struct bpf_insn *insn);
  923. /*
  924. * Force a reference to the external symbol so the compiler generates
  925. * __kcfi_typid.
  926. */
  927. __ADDRESSABLE(__bpf_prog_runX);
  928. /* u32 __ro_after_init cfi_bpf_hash = __kcfi_typeid___bpf_prog_runX; */
  929. asm (
  930. " .pushsection .data..ro_after_init,\"aw\",@progbits \n"
  931. " .type cfi_bpf_hash,@object \n"
  932. " .globl cfi_bpf_hash \n"
  933. " .p2align 2, 0x0 \n"
  934. "cfi_bpf_hash: \n"
  935. " .long __kcfi_typeid___bpf_prog_runX \n"
  936. " .size cfi_bpf_hash, 4 \n"
  937. " .popsection \n"
  938. );
  939. /* Must match bpf_callback_t */
  940. extern u64 __bpf_callback_fn(u64, u64, u64, u64, u64);
  941. __ADDRESSABLE(__bpf_callback_fn);
  942. /* u32 __ro_after_init cfi_bpf_subprog_hash = __kcfi_typeid___bpf_callback_fn; */
  943. asm (
  944. " .pushsection .data..ro_after_init,\"aw\",@progbits \n"
  945. " .type cfi_bpf_subprog_hash,@object \n"
  946. " .globl cfi_bpf_subprog_hash \n"
  947. " .p2align 2, 0x0 \n"
  948. "cfi_bpf_subprog_hash: \n"
  949. " .long __kcfi_typeid___bpf_callback_fn \n"
  950. " .size cfi_bpf_subprog_hash, 4 \n"
  951. " .popsection \n"
  952. );
  953. u32 cfi_get_func_hash(void *func)
  954. {
  955. u32 hash;
  956. func -= cfi_get_offset();
  957. switch (cfi_mode) {
  958. case CFI_FINEIBT:
  959. func += 7;
  960. break;
  961. case CFI_KCFI:
  962. func += 1;
  963. break;
  964. default:
  965. return 0;
  966. }
  967. if (get_kernel_nofault(hash, func))
  968. return 0;
  969. return hash;
  970. }
  971. #endif
  972. #ifdef CONFIG_FINEIBT
  973. static bool cfi_rand __ro_after_init = true;
  974. static u32 cfi_seed __ro_after_init;
  975. /*
  976. * Re-hash the CFI hash with a boot-time seed while making sure the result is
  977. * not a valid ENDBR instruction.
  978. */
  979. static u32 cfi_rehash(u32 hash)
  980. {
  981. hash ^= cfi_seed;
  982. while (unlikely(is_endbr(hash) || is_endbr(-hash))) {
  983. bool lsb = hash & 1;
  984. hash >>= 1;
  985. if (lsb)
  986. hash ^= 0x80200003;
  987. }
  988. return hash;
  989. }
  990. static __init int cfi_parse_cmdline(char *str)
  991. {
  992. if (!str)
  993. return -EINVAL;
  994. while (str) {
  995. char *next = strchr(str, ',');
  996. if (next) {
  997. *next = 0;
  998. next++;
  999. }
  1000. if (!strcmp(str, "auto")) {
  1001. cfi_mode = CFI_AUTO;
  1002. } else if (!strcmp(str, "off")) {
  1003. cfi_mode = CFI_OFF;
  1004. cfi_rand = false;
  1005. } else if (!strcmp(str, "kcfi")) {
  1006. cfi_mode = CFI_KCFI;
  1007. } else if (!strcmp(str, "fineibt")) {
  1008. cfi_mode = CFI_FINEIBT;
  1009. } else if (!strcmp(str, "norand")) {
  1010. cfi_rand = false;
  1011. } else {
  1012. pr_err("Ignoring unknown cfi option (%s).", str);
  1013. }
  1014. str = next;
  1015. }
  1016. return 0;
  1017. }
  1018. early_param("cfi", cfi_parse_cmdline);
  1019. /*
  1020. * kCFI FineIBT
  1021. *
  1022. * __cfi_\func: __cfi_\func:
  1023. * movl $0x12345678,%eax // 5 endbr64 // 4
  1024. * nop subl $0x12345678,%r10d // 7
  1025. * nop jz 1f // 2
  1026. * nop ud2 // 2
  1027. * nop 1: nop // 1
  1028. * nop
  1029. * nop
  1030. * nop
  1031. * nop
  1032. * nop
  1033. * nop
  1034. * nop
  1035. *
  1036. *
  1037. * caller: caller:
  1038. * movl $(-0x12345678),%r10d // 6 movl $0x12345678,%r10d // 6
  1039. * addl $-15(%r11),%r10d // 4 sub $16,%r11 // 4
  1040. * je 1f // 2 nop4 // 4
  1041. * ud2 // 2
  1042. * 1: call __x86_indirect_thunk_r11 // 5 call *%r11; nop2; // 5
  1043. *
  1044. */
  1045. asm( ".pushsection .rodata \n"
  1046. "fineibt_preamble_start: \n"
  1047. " endbr64 \n"
  1048. " subl $0x12345678, %r10d \n"
  1049. " je fineibt_preamble_end \n"
  1050. "fineibt_preamble_ud2: \n"
  1051. " ud2 \n"
  1052. " nop \n"
  1053. "fineibt_preamble_end: \n"
  1054. ".popsection\n"
  1055. );
  1056. extern u8 fineibt_preamble_start[];
  1057. extern u8 fineibt_preamble_ud2[];
  1058. extern u8 fineibt_preamble_end[];
  1059. #define fineibt_preamble_size (fineibt_preamble_end - fineibt_preamble_start)
  1060. #define fineibt_preamble_ud2 (fineibt_preamble_ud2 - fineibt_preamble_start)
  1061. #define fineibt_preamble_hash 7
  1062. asm( ".pushsection .rodata \n"
  1063. "fineibt_caller_start: \n"
  1064. " movl $0x12345678, %r10d \n"
  1065. " sub $16, %r11 \n"
  1066. ASM_NOP4
  1067. "fineibt_caller_end: \n"
  1068. ".popsection \n"
  1069. );
  1070. extern u8 fineibt_caller_start[];
  1071. extern u8 fineibt_caller_end[];
  1072. #define fineibt_caller_size (fineibt_caller_end - fineibt_caller_start)
  1073. #define fineibt_caller_hash 2
  1074. #define fineibt_caller_jmp (fineibt_caller_size - 2)
  1075. static u32 decode_preamble_hash(void *addr)
  1076. {
  1077. u8 *p = addr;
  1078. /* b8 78 56 34 12 mov $0x12345678,%eax */
  1079. if (p[0] == 0xb8)
  1080. return *(u32 *)(addr + 1);
  1081. return 0; /* invalid hash value */
  1082. }
  1083. static u32 decode_caller_hash(void *addr)
  1084. {
  1085. u8 *p = addr;
  1086. /* 41 ba 78 56 34 12 mov $0x12345678,%r10d */
  1087. if (p[0] == 0x41 && p[1] == 0xba)
  1088. return -*(u32 *)(addr + 2);
  1089. /* e8 0c 78 56 34 12 jmp.d8 +12 */
  1090. if (p[0] == JMP8_INSN_OPCODE && p[1] == fineibt_caller_jmp)
  1091. return -*(u32 *)(addr + 2);
  1092. return 0; /* invalid hash value */
  1093. }
  1094. /* .retpoline_sites */
  1095. static int cfi_disable_callers(s32 *start, s32 *end)
  1096. {
  1097. /*
  1098. * Disable kCFI by patching in a JMP.d8, this leaves the hash immediate
  1099. * in tact for later usage. Also see decode_caller_hash() and
  1100. * cfi_rewrite_callers().
  1101. */
  1102. const u8 jmp[] = { JMP8_INSN_OPCODE, fineibt_caller_jmp };
  1103. s32 *s;
  1104. for (s = start; s < end; s++) {
  1105. void *addr = (void *)s + *s;
  1106. u32 hash;
  1107. addr -= fineibt_caller_size;
  1108. hash = decode_caller_hash(addr);
  1109. if (!hash) /* nocfi callers */
  1110. continue;
  1111. text_poke_early(addr, jmp, 2);
  1112. }
  1113. return 0;
  1114. }
  1115. static int cfi_enable_callers(s32 *start, s32 *end)
  1116. {
  1117. /*
  1118. * Re-enable kCFI, undo what cfi_disable_callers() did.
  1119. */
  1120. const u8 mov[] = { 0x41, 0xba };
  1121. s32 *s;
  1122. for (s = start; s < end; s++) {
  1123. void *addr = (void *)s + *s;
  1124. u32 hash;
  1125. addr -= fineibt_caller_size;
  1126. hash = decode_caller_hash(addr);
  1127. if (!hash) /* nocfi callers */
  1128. continue;
  1129. text_poke_early(addr, mov, 2);
  1130. }
  1131. return 0;
  1132. }
  1133. /* .cfi_sites */
  1134. static int cfi_rand_preamble(s32 *start, s32 *end)
  1135. {
  1136. s32 *s;
  1137. for (s = start; s < end; s++) {
  1138. void *addr = (void *)s + *s;
  1139. u32 hash;
  1140. hash = decode_preamble_hash(addr);
  1141. if (WARN(!hash, "no CFI hash found at: %pS %px %*ph\n",
  1142. addr, addr, 5, addr))
  1143. return -EINVAL;
  1144. hash = cfi_rehash(hash);
  1145. text_poke_early(addr + 1, &hash, 4);
  1146. }
  1147. return 0;
  1148. }
  1149. static int cfi_rewrite_preamble(s32 *start, s32 *end)
  1150. {
  1151. s32 *s;
  1152. for (s = start; s < end; s++) {
  1153. void *addr = (void *)s + *s;
  1154. u32 hash;
  1155. hash = decode_preamble_hash(addr);
  1156. if (WARN(!hash, "no CFI hash found at: %pS %px %*ph\n",
  1157. addr, addr, 5, addr))
  1158. return -EINVAL;
  1159. text_poke_early(addr, fineibt_preamble_start, fineibt_preamble_size);
  1160. WARN_ON(*(u32 *)(addr + fineibt_preamble_hash) != 0x12345678);
  1161. text_poke_early(addr + fineibt_preamble_hash, &hash, 4);
  1162. }
  1163. return 0;
  1164. }
  1165. static void cfi_rewrite_endbr(s32 *start, s32 *end)
  1166. {
  1167. s32 *s;
  1168. for (s = start; s < end; s++) {
  1169. void *addr = (void *)s + *s;
  1170. poison_endbr(addr+16, false);
  1171. }
  1172. }
  1173. /* .retpoline_sites */
  1174. static int cfi_rand_callers(s32 *start, s32 *end)
  1175. {
  1176. s32 *s;
  1177. for (s = start; s < end; s++) {
  1178. void *addr = (void *)s + *s;
  1179. u32 hash;
  1180. addr -= fineibt_caller_size;
  1181. hash = decode_caller_hash(addr);
  1182. if (hash) {
  1183. hash = -cfi_rehash(hash);
  1184. text_poke_early(addr + 2, &hash, 4);
  1185. }
  1186. }
  1187. return 0;
  1188. }
  1189. static int cfi_rewrite_callers(s32 *start, s32 *end)
  1190. {
  1191. s32 *s;
  1192. for (s = start; s < end; s++) {
  1193. void *addr = (void *)s + *s;
  1194. u32 hash;
  1195. addr -= fineibt_caller_size;
  1196. hash = decode_caller_hash(addr);
  1197. if (hash) {
  1198. text_poke_early(addr, fineibt_caller_start, fineibt_caller_size);
  1199. WARN_ON(*(u32 *)(addr + fineibt_caller_hash) != 0x12345678);
  1200. text_poke_early(addr + fineibt_caller_hash, &hash, 4);
  1201. }
  1202. /* rely on apply_retpolines() */
  1203. }
  1204. return 0;
  1205. }
  1206. static void __apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
  1207. s32 *start_cfi, s32 *end_cfi, bool builtin)
  1208. {
  1209. int ret;
  1210. if (WARN_ONCE(fineibt_preamble_size != 16,
  1211. "FineIBT preamble wrong size: %ld", fineibt_preamble_size))
  1212. return;
  1213. if (cfi_mode == CFI_AUTO) {
  1214. cfi_mode = CFI_KCFI;
  1215. if (HAS_KERNEL_IBT && cpu_feature_enabled(X86_FEATURE_IBT))
  1216. cfi_mode = CFI_FINEIBT;
  1217. }
  1218. /*
  1219. * Rewrite the callers to not use the __cfi_ stubs, such that we might
  1220. * rewrite them. This disables all CFI. If this succeeds but any of the
  1221. * later stages fails, we're without CFI.
  1222. */
  1223. ret = cfi_disable_callers(start_retpoline, end_retpoline);
  1224. if (ret)
  1225. goto err;
  1226. if (cfi_rand) {
  1227. if (builtin) {
  1228. cfi_seed = get_random_u32();
  1229. cfi_bpf_hash = cfi_rehash(cfi_bpf_hash);
  1230. cfi_bpf_subprog_hash = cfi_rehash(cfi_bpf_subprog_hash);
  1231. }
  1232. ret = cfi_rand_preamble(start_cfi, end_cfi);
  1233. if (ret)
  1234. goto err;
  1235. ret = cfi_rand_callers(start_retpoline, end_retpoline);
  1236. if (ret)
  1237. goto err;
  1238. }
  1239. switch (cfi_mode) {
  1240. case CFI_OFF:
  1241. if (builtin)
  1242. pr_info("Disabling CFI\n");
  1243. return;
  1244. case CFI_KCFI:
  1245. ret = cfi_enable_callers(start_retpoline, end_retpoline);
  1246. if (ret)
  1247. goto err;
  1248. if (builtin)
  1249. pr_info("Using kCFI\n");
  1250. return;
  1251. case CFI_FINEIBT:
  1252. /* place the FineIBT preamble at func()-16 */
  1253. ret = cfi_rewrite_preamble(start_cfi, end_cfi);
  1254. if (ret)
  1255. goto err;
  1256. /* rewrite the callers to target func()-16 */
  1257. ret = cfi_rewrite_callers(start_retpoline, end_retpoline);
  1258. if (ret)
  1259. goto err;
  1260. /* now that nobody targets func()+0, remove ENDBR there */
  1261. cfi_rewrite_endbr(start_cfi, end_cfi);
  1262. if (builtin)
  1263. pr_info("Using FineIBT CFI\n");
  1264. return;
  1265. default:
  1266. break;
  1267. }
  1268. err:
  1269. pr_err("Something went horribly wrong trying to rewrite the CFI implementation.\n");
  1270. }
  1271. static inline void poison_hash(void *addr)
  1272. {
  1273. *(u32 *)addr = 0;
  1274. }
  1275. static void poison_cfi(void *addr)
  1276. {
  1277. switch (cfi_mode) {
  1278. case CFI_FINEIBT:
  1279. /*
  1280. * __cfi_\func:
  1281. * osp nopl (%rax)
  1282. * subl $0, %r10d
  1283. * jz 1f
  1284. * ud2
  1285. * 1: nop
  1286. */
  1287. poison_endbr(addr, false);
  1288. poison_hash(addr + fineibt_preamble_hash);
  1289. break;
  1290. case CFI_KCFI:
  1291. /*
  1292. * __cfi_\func:
  1293. * movl $0, %eax
  1294. * .skip 11, 0x90
  1295. */
  1296. poison_hash(addr + 1);
  1297. break;
  1298. default:
  1299. break;
  1300. }
  1301. }
  1302. /*
  1303. * regs->ip points to a UD2 instruction, return true and fill out target and
  1304. * type when this UD2 is from a FineIBT preamble.
  1305. *
  1306. * We check the preamble by checking for the ENDBR instruction relative to the
  1307. * UD2 instruction.
  1308. */
  1309. bool decode_fineibt_insn(struct pt_regs *regs, unsigned long *target, u32 *type)
  1310. {
  1311. unsigned long addr = regs->ip - fineibt_preamble_ud2;
  1312. u32 endbr, hash;
  1313. __get_kernel_nofault(&endbr, addr, u32, Efault);
  1314. if (endbr != gen_endbr())
  1315. return false;
  1316. *target = addr + fineibt_preamble_size;
  1317. __get_kernel_nofault(&hash, addr + fineibt_preamble_hash, u32, Efault);
  1318. *type = (u32)regs->r10 + hash;
  1319. return true;
  1320. Efault:
  1321. return false;
  1322. }
  1323. #else
  1324. static void __apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
  1325. s32 *start_cfi, s32 *end_cfi, bool builtin)
  1326. {
  1327. }
  1328. #ifdef CONFIG_X86_KERNEL_IBT
  1329. static void poison_cfi(void *addr) { }
  1330. #endif
  1331. #endif
  1332. void apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
  1333. s32 *start_cfi, s32 *end_cfi)
  1334. {
  1335. return __apply_fineibt(start_retpoline, end_retpoline,
  1336. start_cfi, end_cfi,
  1337. /* .builtin = */ false);
  1338. }
  1339. #ifdef CONFIG_SMP
  1340. static void alternatives_smp_lock(const s32 *start, const s32 *end,
  1341. u8 *text, u8 *text_end)
  1342. {
  1343. const s32 *poff;
  1344. for (poff = start; poff < end; poff++) {
  1345. u8 *ptr = (u8 *)poff + *poff;
  1346. if (!*poff || ptr < text || ptr >= text_end)
  1347. continue;
  1348. /* turn DS segment override prefix into lock prefix */
  1349. if (*ptr == 0x3e)
  1350. text_poke(ptr, ((unsigned char []){0xf0}), 1);
  1351. }
  1352. }
  1353. static void alternatives_smp_unlock(const s32 *start, const s32 *end,
  1354. u8 *text, u8 *text_end)
  1355. {
  1356. const s32 *poff;
  1357. for (poff = start; poff < end; poff++) {
  1358. u8 *ptr = (u8 *)poff + *poff;
  1359. if (!*poff || ptr < text || ptr >= text_end)
  1360. continue;
  1361. /* turn lock prefix into DS segment override prefix */
  1362. if (*ptr == 0xf0)
  1363. text_poke(ptr, ((unsigned char []){0x3E}), 1);
  1364. }
  1365. }
  1366. struct smp_alt_module {
  1367. /* what is this ??? */
  1368. struct module *mod;
  1369. char *name;
  1370. /* ptrs to lock prefixes */
  1371. const s32 *locks;
  1372. const s32 *locks_end;
  1373. /* .text segment, needed to avoid patching init code ;) */
  1374. u8 *text;
  1375. u8 *text_end;
  1376. struct list_head next;
  1377. };
  1378. static LIST_HEAD(smp_alt_modules);
  1379. static bool uniproc_patched = false; /* protected by text_mutex */
  1380. void __init_or_module alternatives_smp_module_add(struct module *mod,
  1381. char *name,
  1382. void *locks, void *locks_end,
  1383. void *text, void *text_end)
  1384. {
  1385. struct smp_alt_module *smp;
  1386. mutex_lock(&text_mutex);
  1387. if (!uniproc_patched)
  1388. goto unlock;
  1389. if (num_possible_cpus() == 1)
  1390. /* Don't bother remembering, we'll never have to undo it. */
  1391. goto smp_unlock;
  1392. smp = kzalloc(sizeof(*smp), GFP_KERNEL);
  1393. if (NULL == smp)
  1394. /* we'll run the (safe but slow) SMP code then ... */
  1395. goto unlock;
  1396. smp->mod = mod;
  1397. smp->name = name;
  1398. smp->locks = locks;
  1399. smp->locks_end = locks_end;
  1400. smp->text = text;
  1401. smp->text_end = text_end;
  1402. DPRINTK(SMP, "locks %p -> %p, text %p -> %p, name %s\n",
  1403. smp->locks, smp->locks_end,
  1404. smp->text, smp->text_end, smp->name);
  1405. list_add_tail(&smp->next, &smp_alt_modules);
  1406. smp_unlock:
  1407. alternatives_smp_unlock(locks, locks_end, text, text_end);
  1408. unlock:
  1409. mutex_unlock(&text_mutex);
  1410. }
  1411. void __init_or_module alternatives_smp_module_del(struct module *mod)
  1412. {
  1413. struct smp_alt_module *item;
  1414. mutex_lock(&text_mutex);
  1415. list_for_each_entry(item, &smp_alt_modules, next) {
  1416. if (mod != item->mod)
  1417. continue;
  1418. list_del(&item->next);
  1419. kfree(item);
  1420. break;
  1421. }
  1422. mutex_unlock(&text_mutex);
  1423. }
  1424. void alternatives_enable_smp(void)
  1425. {
  1426. struct smp_alt_module *mod;
  1427. /* Why bother if there are no other CPUs? */
  1428. BUG_ON(num_possible_cpus() == 1);
  1429. mutex_lock(&text_mutex);
  1430. if (uniproc_patched) {
  1431. pr_info("switching to SMP code\n");
  1432. BUG_ON(num_online_cpus() != 1);
  1433. clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
  1434. clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
  1435. list_for_each_entry(mod, &smp_alt_modules, next)
  1436. alternatives_smp_lock(mod->locks, mod->locks_end,
  1437. mod->text, mod->text_end);
  1438. uniproc_patched = false;
  1439. }
  1440. mutex_unlock(&text_mutex);
  1441. }
  1442. /*
  1443. * Return 1 if the address range is reserved for SMP-alternatives.
  1444. * Must hold text_mutex.
  1445. */
  1446. int alternatives_text_reserved(void *start, void *end)
  1447. {
  1448. struct smp_alt_module *mod;
  1449. const s32 *poff;
  1450. u8 *text_start = start;
  1451. u8 *text_end = end;
  1452. lockdep_assert_held(&text_mutex);
  1453. list_for_each_entry(mod, &smp_alt_modules, next) {
  1454. if (mod->text > text_end || mod->text_end < text_start)
  1455. continue;
  1456. for (poff = mod->locks; poff < mod->locks_end; poff++) {
  1457. const u8 *ptr = (const u8 *)poff + *poff;
  1458. if (text_start <= ptr && text_end > ptr)
  1459. return 1;
  1460. }
  1461. }
  1462. return 0;
  1463. }
  1464. #endif /* CONFIG_SMP */
  1465. /*
  1466. * Self-test for the INT3 based CALL emulation code.
  1467. *
  1468. * This exercises int3_emulate_call() to make sure INT3 pt_regs are set up
  1469. * properly and that there is a stack gap between the INT3 frame and the
  1470. * previous context. Without this gap doing a virtual PUSH on the interrupted
  1471. * stack would corrupt the INT3 IRET frame.
  1472. *
  1473. * See entry_{32,64}.S for more details.
  1474. */
  1475. /*
  1476. * We define the int3_magic() function in assembly to control the calling
  1477. * convention such that we can 'call' it from assembly.
  1478. */
  1479. extern void int3_magic(unsigned int *ptr); /* defined in asm */
  1480. asm (
  1481. " .pushsection .init.text, \"ax\", @progbits\n"
  1482. " .type int3_magic, @function\n"
  1483. "int3_magic:\n"
  1484. ANNOTATE_NOENDBR
  1485. " movl $1, (%" _ASM_ARG1 ")\n"
  1486. ASM_RET
  1487. " .size int3_magic, .-int3_magic\n"
  1488. " .popsection\n"
  1489. );
  1490. extern void int3_selftest_ip(void); /* defined in asm below */
  1491. static int __init
  1492. int3_exception_notify(struct notifier_block *self, unsigned long val, void *data)
  1493. {
  1494. unsigned long selftest = (unsigned long)&int3_selftest_ip;
  1495. struct die_args *args = data;
  1496. struct pt_regs *regs = args->regs;
  1497. OPTIMIZER_HIDE_VAR(selftest);
  1498. if (!regs || user_mode(regs))
  1499. return NOTIFY_DONE;
  1500. if (val != DIE_INT3)
  1501. return NOTIFY_DONE;
  1502. if (regs->ip - INT3_INSN_SIZE != selftest)
  1503. return NOTIFY_DONE;
  1504. int3_emulate_call(regs, (unsigned long)&int3_magic);
  1505. return NOTIFY_STOP;
  1506. }
  1507. /* Must be noinline to ensure uniqueness of int3_selftest_ip. */
  1508. static noinline void __init int3_selftest(void)
  1509. {
  1510. static __initdata struct notifier_block int3_exception_nb = {
  1511. .notifier_call = int3_exception_notify,
  1512. .priority = INT_MAX-1, /* last */
  1513. };
  1514. unsigned int val = 0;
  1515. BUG_ON(register_die_notifier(&int3_exception_nb));
  1516. /*
  1517. * Basically: int3_magic(&val); but really complicated :-)
  1518. *
  1519. * INT3 padded with NOP to CALL_INSN_SIZE. The int3_exception_nb
  1520. * notifier above will emulate CALL for us.
  1521. */
  1522. asm volatile ("int3_selftest_ip:\n\t"
  1523. ANNOTATE_NOENDBR
  1524. " int3; nop; nop; nop; nop\n\t"
  1525. : ASM_CALL_CONSTRAINT
  1526. : __ASM_SEL_RAW(a, D) (&val)
  1527. : "memory");
  1528. BUG_ON(val != 1);
  1529. unregister_die_notifier(&int3_exception_nb);
  1530. }
  1531. static __initdata int __alt_reloc_selftest_addr;
  1532. extern void __init __alt_reloc_selftest(void *arg);
  1533. __visible noinline void __init __alt_reloc_selftest(void *arg)
  1534. {
  1535. WARN_ON(arg != &__alt_reloc_selftest_addr);
  1536. }
  1537. static noinline void __init alt_reloc_selftest(void)
  1538. {
  1539. /*
  1540. * Tests apply_relocation().
  1541. *
  1542. * This has a relative immediate (CALL) in a place other than the first
  1543. * instruction and additionally on x86_64 we get a RIP-relative LEA:
  1544. *
  1545. * lea 0x0(%rip),%rdi # 5d0: R_X86_64_PC32 .init.data+0x5566c
  1546. * call +0 # 5d5: R_X86_64_PLT32 __alt_reloc_selftest-0x4
  1547. *
  1548. * Getting this wrong will either crash and burn or tickle the WARN
  1549. * above.
  1550. */
  1551. asm_inline volatile (
  1552. ALTERNATIVE("", "lea %[mem], %%" _ASM_ARG1 "; call __alt_reloc_selftest;", X86_FEATURE_ALWAYS)
  1553. : ASM_CALL_CONSTRAINT
  1554. : [mem] "m" (__alt_reloc_selftest_addr)
  1555. : _ASM_ARG1
  1556. );
  1557. }
  1558. void __init alternative_instructions(void)
  1559. {
  1560. u64 ibt;
  1561. int3_selftest();
  1562. /*
  1563. * The patching is not fully atomic, so try to avoid local
  1564. * interruptions that might execute the to be patched code.
  1565. * Other CPUs are not running.
  1566. */
  1567. stop_nmi();
  1568. /*
  1569. * Don't stop machine check exceptions while patching.
  1570. * MCEs only happen when something got corrupted and in this
  1571. * case we must do something about the corruption.
  1572. * Ignoring it is worse than an unlikely patching race.
  1573. * Also machine checks tend to be broadcast and if one CPU
  1574. * goes into machine check the others follow quickly, so we don't
  1575. * expect a machine check to cause undue problems during to code
  1576. * patching.
  1577. */
  1578. /*
  1579. * Make sure to set (artificial) features depending on used paravirt
  1580. * functions which can later influence alternative patching.
  1581. */
  1582. paravirt_set_cap();
  1583. /* Keep CET-IBT disabled until caller/callee are patched */
  1584. ibt = ibt_save(/*disable*/ true);
  1585. __apply_fineibt(__retpoline_sites, __retpoline_sites_end,
  1586. __cfi_sites, __cfi_sites_end, true);
  1587. /*
  1588. * Rewrite the retpolines, must be done before alternatives since
  1589. * those can rewrite the retpoline thunks.
  1590. */
  1591. apply_retpolines(__retpoline_sites, __retpoline_sites_end);
  1592. apply_returns(__return_sites, __return_sites_end);
  1593. apply_alternatives(__alt_instructions, __alt_instructions_end);
  1594. /*
  1595. * Now all calls are established. Apply the call thunks if
  1596. * required.
  1597. */
  1598. callthunks_patch_builtin_calls();
  1599. /*
  1600. * Seal all functions that do not have their address taken.
  1601. */
  1602. apply_seal_endbr(__ibt_endbr_seal, __ibt_endbr_seal_end);
  1603. ibt_restore(ibt);
  1604. #ifdef CONFIG_SMP
  1605. /* Patch to UP if other cpus not imminent. */
  1606. if (!noreplace_smp && (num_present_cpus() == 1 || setup_max_cpus <= 1)) {
  1607. uniproc_patched = true;
  1608. alternatives_smp_module_add(NULL, "core kernel",
  1609. __smp_locks, __smp_locks_end,
  1610. _text, _etext);
  1611. }
  1612. if (!uniproc_patched || num_possible_cpus() == 1) {
  1613. free_init_pages("SMP alternatives",
  1614. (unsigned long)__smp_locks,
  1615. (unsigned long)__smp_locks_end);
  1616. }
  1617. #endif
  1618. restart_nmi();
  1619. alternatives_patched = 1;
  1620. alt_reloc_selftest();
  1621. }
  1622. /**
  1623. * text_poke_early - Update instructions on a live kernel at boot time
  1624. * @addr: address to modify
  1625. * @opcode: source of the copy
  1626. * @len: length to copy
  1627. *
  1628. * When you use this code to patch more than one byte of an instruction
  1629. * you need to make sure that other CPUs cannot execute this code in parallel.
  1630. * Also no thread must be currently preempted in the middle of these
  1631. * instructions. And on the local CPU you need to be protected against NMI or
  1632. * MCE handlers seeing an inconsistent instruction while you patch.
  1633. */
  1634. void __init_or_module text_poke_early(void *addr, const void *opcode,
  1635. size_t len)
  1636. {
  1637. unsigned long flags;
  1638. if (boot_cpu_has(X86_FEATURE_NX) &&
  1639. is_module_text_address((unsigned long)addr)) {
  1640. /*
  1641. * Modules text is marked initially as non-executable, so the
  1642. * code cannot be running and speculative code-fetches are
  1643. * prevented. Just change the code.
  1644. */
  1645. memcpy(addr, opcode, len);
  1646. } else {
  1647. local_irq_save(flags);
  1648. memcpy(addr, opcode, len);
  1649. sync_core();
  1650. local_irq_restore(flags);
  1651. /*
  1652. * Could also do a CLFLUSH here to speed up CPU recovery; but
  1653. * that causes hangs on some VIA CPUs.
  1654. */
  1655. }
  1656. }
  1657. typedef struct {
  1658. struct mm_struct *mm;
  1659. } temp_mm_state_t;
  1660. /*
  1661. * Using a temporary mm allows to set temporary mappings that are not accessible
  1662. * by other CPUs. Such mappings are needed to perform sensitive memory writes
  1663. * that override the kernel memory protections (e.g., W^X), without exposing the
  1664. * temporary page-table mappings that are required for these write operations to
  1665. * other CPUs. Using a temporary mm also allows to avoid TLB shootdowns when the
  1666. * mapping is torn down.
  1667. *
  1668. * Context: The temporary mm needs to be used exclusively by a single core. To
  1669. * harden security IRQs must be disabled while the temporary mm is
  1670. * loaded, thereby preventing interrupt handler bugs from overriding
  1671. * the kernel memory protection.
  1672. */
  1673. static inline temp_mm_state_t use_temporary_mm(struct mm_struct *mm)
  1674. {
  1675. temp_mm_state_t temp_state;
  1676. lockdep_assert_irqs_disabled();
  1677. /*
  1678. * Make sure not to be in TLB lazy mode, as otherwise we'll end up
  1679. * with a stale address space WITHOUT being in lazy mode after
  1680. * restoring the previous mm.
  1681. */
  1682. if (this_cpu_read(cpu_tlbstate_shared.is_lazy))
  1683. leave_mm();
  1684. temp_state.mm = this_cpu_read(cpu_tlbstate.loaded_mm);
  1685. switch_mm_irqs_off(NULL, mm, current);
  1686. /*
  1687. * If breakpoints are enabled, disable them while the temporary mm is
  1688. * used. Userspace might set up watchpoints on addresses that are used
  1689. * in the temporary mm, which would lead to wrong signals being sent or
  1690. * crashes.
  1691. *
  1692. * Note that breakpoints are not disabled selectively, which also causes
  1693. * kernel breakpoints (e.g., perf's) to be disabled. This might be
  1694. * undesirable, but still seems reasonable as the code that runs in the
  1695. * temporary mm should be short.
  1696. */
  1697. if (hw_breakpoint_active())
  1698. hw_breakpoint_disable();
  1699. return temp_state;
  1700. }
  1701. static inline void unuse_temporary_mm(temp_mm_state_t prev_state)
  1702. {
  1703. lockdep_assert_irqs_disabled();
  1704. switch_mm_irqs_off(NULL, prev_state.mm, current);
  1705. /*
  1706. * Restore the breakpoints if they were disabled before the temporary mm
  1707. * was loaded.
  1708. */
  1709. if (hw_breakpoint_active())
  1710. hw_breakpoint_restore();
  1711. }
  1712. __ro_after_init struct mm_struct *poking_mm;
  1713. __ro_after_init unsigned long poking_addr;
  1714. static void text_poke_memcpy(void *dst, const void *src, size_t len)
  1715. {
  1716. memcpy(dst, src, len);
  1717. }
  1718. static void text_poke_memset(void *dst, const void *src, size_t len)
  1719. {
  1720. int c = *(const int *)src;
  1721. memset(dst, c, len);
  1722. }
  1723. typedef void text_poke_f(void *dst, const void *src, size_t len);
  1724. static void *__text_poke(text_poke_f func, void *addr, const void *src, size_t len)
  1725. {
  1726. bool cross_page_boundary = offset_in_page(addr) + len > PAGE_SIZE;
  1727. struct page *pages[2] = {NULL};
  1728. temp_mm_state_t prev;
  1729. unsigned long flags;
  1730. pte_t pte, *ptep;
  1731. spinlock_t *ptl;
  1732. pgprot_t pgprot;
  1733. /*
  1734. * While boot memory allocator is running we cannot use struct pages as
  1735. * they are not yet initialized. There is no way to recover.
  1736. */
  1737. BUG_ON(!after_bootmem);
  1738. if (!core_kernel_text((unsigned long)addr)) {
  1739. pages[0] = vmalloc_to_page(addr);
  1740. if (cross_page_boundary)
  1741. pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
  1742. } else {
  1743. pages[0] = virt_to_page(addr);
  1744. WARN_ON(!PageReserved(pages[0]));
  1745. if (cross_page_boundary)
  1746. pages[1] = virt_to_page(addr + PAGE_SIZE);
  1747. }
  1748. /*
  1749. * If something went wrong, crash and burn since recovery paths are not
  1750. * implemented.
  1751. */
  1752. BUG_ON(!pages[0] || (cross_page_boundary && !pages[1]));
  1753. /*
  1754. * Map the page without the global bit, as TLB flushing is done with
  1755. * flush_tlb_mm_range(), which is intended for non-global PTEs.
  1756. */
  1757. pgprot = __pgprot(pgprot_val(PAGE_KERNEL) & ~_PAGE_GLOBAL);
  1758. /*
  1759. * The lock is not really needed, but this allows to avoid open-coding.
  1760. */
  1761. ptep = get_locked_pte(poking_mm, poking_addr, &ptl);
  1762. /*
  1763. * This must not fail; preallocated in poking_init().
  1764. */
  1765. VM_BUG_ON(!ptep);
  1766. local_irq_save(flags);
  1767. pte = mk_pte(pages[0], pgprot);
  1768. set_pte_at(poking_mm, poking_addr, ptep, pte);
  1769. if (cross_page_boundary) {
  1770. pte = mk_pte(pages[1], pgprot);
  1771. set_pte_at(poking_mm, poking_addr + PAGE_SIZE, ptep + 1, pte);
  1772. }
  1773. /*
  1774. * Loading the temporary mm behaves as a compiler barrier, which
  1775. * guarantees that the PTE will be set at the time memcpy() is done.
  1776. */
  1777. prev = use_temporary_mm(poking_mm);
  1778. kasan_disable_current();
  1779. func((u8 *)poking_addr + offset_in_page(addr), src, len);
  1780. kasan_enable_current();
  1781. /*
  1782. * Ensure that the PTE is only cleared after the instructions of memcpy
  1783. * were issued by using a compiler barrier.
  1784. */
  1785. barrier();
  1786. pte_clear(poking_mm, poking_addr, ptep);
  1787. if (cross_page_boundary)
  1788. pte_clear(poking_mm, poking_addr + PAGE_SIZE, ptep + 1);
  1789. /*
  1790. * Loading the previous page-table hierarchy requires a serializing
  1791. * instruction that already allows the core to see the updated version.
  1792. * Xen-PV is assumed to serialize execution in a similar manner.
  1793. */
  1794. unuse_temporary_mm(prev);
  1795. /*
  1796. * Flushing the TLB might involve IPIs, which would require enabled
  1797. * IRQs, but not if the mm is not used, as it is in this point.
  1798. */
  1799. flush_tlb_mm_range(poking_mm, poking_addr, poking_addr +
  1800. (cross_page_boundary ? 2 : 1) * PAGE_SIZE,
  1801. PAGE_SHIFT, false);
  1802. if (func == text_poke_memcpy) {
  1803. /*
  1804. * If the text does not match what we just wrote then something is
  1805. * fundamentally screwy; there's nothing we can really do about that.
  1806. */
  1807. BUG_ON(memcmp(addr, src, len));
  1808. }
  1809. local_irq_restore(flags);
  1810. pte_unmap_unlock(ptep, ptl);
  1811. return addr;
  1812. }
  1813. /**
  1814. * text_poke - Update instructions on a live kernel
  1815. * @addr: address to modify
  1816. * @opcode: source of the copy
  1817. * @len: length to copy
  1818. *
  1819. * Only atomic text poke/set should be allowed when not doing early patching.
  1820. * It means the size must be writable atomically and the address must be aligned
  1821. * in a way that permits an atomic write. It also makes sure we fit on a single
  1822. * page.
  1823. *
  1824. * Note that the caller must ensure that if the modified code is part of a
  1825. * module, the module would not be removed during poking. This can be achieved
  1826. * by registering a module notifier, and ordering module removal and patching
  1827. * through a mutex.
  1828. */
  1829. void *text_poke(void *addr, const void *opcode, size_t len)
  1830. {
  1831. lockdep_assert_held(&text_mutex);
  1832. return __text_poke(text_poke_memcpy, addr, opcode, len);
  1833. }
  1834. /**
  1835. * text_poke_kgdb - Update instructions on a live kernel by kgdb
  1836. * @addr: address to modify
  1837. * @opcode: source of the copy
  1838. * @len: length to copy
  1839. *
  1840. * Only atomic text poke/set should be allowed when not doing early patching.
  1841. * It means the size must be writable atomically and the address must be aligned
  1842. * in a way that permits an atomic write. It also makes sure we fit on a single
  1843. * page.
  1844. *
  1845. * Context: should only be used by kgdb, which ensures no other core is running,
  1846. * despite the fact it does not hold the text_mutex.
  1847. */
  1848. void *text_poke_kgdb(void *addr, const void *opcode, size_t len)
  1849. {
  1850. return __text_poke(text_poke_memcpy, addr, opcode, len);
  1851. }
  1852. void *text_poke_copy_locked(void *addr, const void *opcode, size_t len,
  1853. bool core_ok)
  1854. {
  1855. unsigned long start = (unsigned long)addr;
  1856. size_t patched = 0;
  1857. if (WARN_ON_ONCE(!core_ok && core_kernel_text(start)))
  1858. return NULL;
  1859. while (patched < len) {
  1860. unsigned long ptr = start + patched;
  1861. size_t s;
  1862. s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched);
  1863. __text_poke(text_poke_memcpy, (void *)ptr, opcode + patched, s);
  1864. patched += s;
  1865. }
  1866. return addr;
  1867. }
  1868. /**
  1869. * text_poke_copy - Copy instructions into (an unused part of) RX memory
  1870. * @addr: address to modify
  1871. * @opcode: source of the copy
  1872. * @len: length to copy, could be more than 2x PAGE_SIZE
  1873. *
  1874. * Not safe against concurrent execution; useful for JITs to dump
  1875. * new code blocks into unused regions of RX memory. Can be used in
  1876. * conjunction with synchronize_rcu_tasks() to wait for existing
  1877. * execution to quiesce after having made sure no existing functions
  1878. * pointers are live.
  1879. */
  1880. void *text_poke_copy(void *addr, const void *opcode, size_t len)
  1881. {
  1882. mutex_lock(&text_mutex);
  1883. addr = text_poke_copy_locked(addr, opcode, len, false);
  1884. mutex_unlock(&text_mutex);
  1885. return addr;
  1886. }
  1887. /**
  1888. * text_poke_set - memset into (an unused part of) RX memory
  1889. * @addr: address to modify
  1890. * @c: the byte to fill the area with
  1891. * @len: length to copy, could be more than 2x PAGE_SIZE
  1892. *
  1893. * This is useful to overwrite unused regions of RX memory with illegal
  1894. * instructions.
  1895. */
  1896. void *text_poke_set(void *addr, int c, size_t len)
  1897. {
  1898. unsigned long start = (unsigned long)addr;
  1899. size_t patched = 0;
  1900. if (WARN_ON_ONCE(core_kernel_text(start)))
  1901. return NULL;
  1902. mutex_lock(&text_mutex);
  1903. while (patched < len) {
  1904. unsigned long ptr = start + patched;
  1905. size_t s;
  1906. s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched);
  1907. __text_poke(text_poke_memset, (void *)ptr, (void *)&c, s);
  1908. patched += s;
  1909. }
  1910. mutex_unlock(&text_mutex);
  1911. return addr;
  1912. }
  1913. static void do_sync_core(void *info)
  1914. {
  1915. sync_core();
  1916. }
  1917. void text_poke_sync(void)
  1918. {
  1919. on_each_cpu(do_sync_core, NULL, 1);
  1920. }
  1921. /*
  1922. * NOTE: crazy scheme to allow patching Jcc.d32 but not increase the size of
  1923. * this thing. When len == 6 everything is prefixed with 0x0f and we map
  1924. * opcode to Jcc.d8, using len to distinguish.
  1925. */
  1926. struct text_poke_loc {
  1927. /* addr := _stext + rel_addr */
  1928. s32 rel_addr;
  1929. s32 disp;
  1930. u8 len;
  1931. u8 opcode;
  1932. const u8 text[POKE_MAX_OPCODE_SIZE];
  1933. /* see text_poke_bp_batch() */
  1934. u8 old;
  1935. };
  1936. struct bp_patching_desc {
  1937. struct text_poke_loc *vec;
  1938. int nr_entries;
  1939. atomic_t refs;
  1940. };
  1941. static struct bp_patching_desc bp_desc;
  1942. static __always_inline
  1943. struct bp_patching_desc *try_get_desc(void)
  1944. {
  1945. struct bp_patching_desc *desc = &bp_desc;
  1946. if (!raw_atomic_inc_not_zero(&desc->refs))
  1947. return NULL;
  1948. return desc;
  1949. }
  1950. static __always_inline void put_desc(void)
  1951. {
  1952. struct bp_patching_desc *desc = &bp_desc;
  1953. smp_mb__before_atomic();
  1954. raw_atomic_dec(&desc->refs);
  1955. }
  1956. static __always_inline void *text_poke_addr(struct text_poke_loc *tp)
  1957. {
  1958. return _stext + tp->rel_addr;
  1959. }
  1960. static __always_inline int patch_cmp(const void *key, const void *elt)
  1961. {
  1962. struct text_poke_loc *tp = (struct text_poke_loc *) elt;
  1963. if (key < text_poke_addr(tp))
  1964. return -1;
  1965. if (key > text_poke_addr(tp))
  1966. return 1;
  1967. return 0;
  1968. }
  1969. noinstr int poke_int3_handler(struct pt_regs *regs)
  1970. {
  1971. struct bp_patching_desc *desc;
  1972. struct text_poke_loc *tp;
  1973. int ret = 0;
  1974. void *ip;
  1975. if (user_mode(regs))
  1976. return 0;
  1977. /*
  1978. * Having observed our INT3 instruction, we now must observe
  1979. * bp_desc with non-zero refcount:
  1980. *
  1981. * bp_desc.refs = 1 INT3
  1982. * WMB RMB
  1983. * write INT3 if (bp_desc.refs != 0)
  1984. */
  1985. smp_rmb();
  1986. desc = try_get_desc();
  1987. if (!desc)
  1988. return 0;
  1989. /*
  1990. * Discount the INT3. See text_poke_bp_batch().
  1991. */
  1992. ip = (void *) regs->ip - INT3_INSN_SIZE;
  1993. /*
  1994. * Skip the binary search if there is a single member in the vector.
  1995. */
  1996. if (unlikely(desc->nr_entries > 1)) {
  1997. tp = __inline_bsearch(ip, desc->vec, desc->nr_entries,
  1998. sizeof(struct text_poke_loc),
  1999. patch_cmp);
  2000. if (!tp)
  2001. goto out_put;
  2002. } else {
  2003. tp = desc->vec;
  2004. if (text_poke_addr(tp) != ip)
  2005. goto out_put;
  2006. }
  2007. ip += tp->len;
  2008. switch (tp->opcode) {
  2009. case INT3_INSN_OPCODE:
  2010. /*
  2011. * Someone poked an explicit INT3, they'll want to handle it,
  2012. * do not consume.
  2013. */
  2014. goto out_put;
  2015. case RET_INSN_OPCODE:
  2016. int3_emulate_ret(regs);
  2017. break;
  2018. case CALL_INSN_OPCODE:
  2019. int3_emulate_call(regs, (long)ip + tp->disp);
  2020. break;
  2021. case JMP32_INSN_OPCODE:
  2022. case JMP8_INSN_OPCODE:
  2023. int3_emulate_jmp(regs, (long)ip + tp->disp);
  2024. break;
  2025. case 0x70 ... 0x7f: /* Jcc */
  2026. int3_emulate_jcc(regs, tp->opcode & 0xf, (long)ip, tp->disp);
  2027. break;
  2028. default:
  2029. BUG();
  2030. }
  2031. ret = 1;
  2032. out_put:
  2033. put_desc();
  2034. return ret;
  2035. }
  2036. #define TP_VEC_MAX (PAGE_SIZE / sizeof(struct text_poke_loc))
  2037. static struct text_poke_loc tp_vec[TP_VEC_MAX];
  2038. static int tp_vec_nr;
  2039. /**
  2040. * text_poke_bp_batch() -- update instructions on live kernel on SMP
  2041. * @tp: vector of instructions to patch
  2042. * @nr_entries: number of entries in the vector
  2043. *
  2044. * Modify multi-byte instruction by using int3 breakpoint on SMP.
  2045. * We completely avoid stop_machine() here, and achieve the
  2046. * synchronization using int3 breakpoint.
  2047. *
  2048. * The way it is done:
  2049. * - For each entry in the vector:
  2050. * - add a int3 trap to the address that will be patched
  2051. * - sync cores
  2052. * - For each entry in the vector:
  2053. * - update all but the first byte of the patched range
  2054. * - sync cores
  2055. * - For each entry in the vector:
  2056. * - replace the first byte (int3) by the first byte of
  2057. * replacing opcode
  2058. * - sync cores
  2059. */
  2060. static void text_poke_bp_batch(struct text_poke_loc *tp, unsigned int nr_entries)
  2061. {
  2062. unsigned char int3 = INT3_INSN_OPCODE;
  2063. unsigned int i;
  2064. int do_sync;
  2065. lockdep_assert_held(&text_mutex);
  2066. bp_desc.vec = tp;
  2067. bp_desc.nr_entries = nr_entries;
  2068. /*
  2069. * Corresponds to the implicit memory barrier in try_get_desc() to
  2070. * ensure reading a non-zero refcount provides up to date bp_desc data.
  2071. */
  2072. atomic_set_release(&bp_desc.refs, 1);
  2073. /*
  2074. * Function tracing can enable thousands of places that need to be
  2075. * updated. This can take quite some time, and with full kernel debugging
  2076. * enabled, this could cause the softlockup watchdog to trigger.
  2077. * This function gets called every 256 entries added to be patched.
  2078. * Call cond_resched() here to make sure that other tasks can get scheduled
  2079. * while processing all the functions being patched.
  2080. */
  2081. cond_resched();
  2082. /*
  2083. * Corresponding read barrier in int3 notifier for making sure the
  2084. * nr_entries and handler are correctly ordered wrt. patching.
  2085. */
  2086. smp_wmb();
  2087. /*
  2088. * First step: add a int3 trap to the address that will be patched.
  2089. */
  2090. for (i = 0; i < nr_entries; i++) {
  2091. tp[i].old = *(u8 *)text_poke_addr(&tp[i]);
  2092. text_poke(text_poke_addr(&tp[i]), &int3, INT3_INSN_SIZE);
  2093. }
  2094. text_poke_sync();
  2095. /*
  2096. * Second step: update all but the first byte of the patched range.
  2097. */
  2098. for (do_sync = 0, i = 0; i < nr_entries; i++) {
  2099. u8 old[POKE_MAX_OPCODE_SIZE+1] = { tp[i].old, };
  2100. u8 _new[POKE_MAX_OPCODE_SIZE+1];
  2101. const u8 *new = tp[i].text;
  2102. int len = tp[i].len;
  2103. if (len - INT3_INSN_SIZE > 0) {
  2104. memcpy(old + INT3_INSN_SIZE,
  2105. text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
  2106. len - INT3_INSN_SIZE);
  2107. if (len == 6) {
  2108. _new[0] = 0x0f;
  2109. memcpy(_new + 1, new, 5);
  2110. new = _new;
  2111. }
  2112. text_poke(text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
  2113. new + INT3_INSN_SIZE,
  2114. len - INT3_INSN_SIZE);
  2115. do_sync++;
  2116. }
  2117. /*
  2118. * Emit a perf event to record the text poke, primarily to
  2119. * support Intel PT decoding which must walk the executable code
  2120. * to reconstruct the trace. The flow up to here is:
  2121. * - write INT3 byte
  2122. * - IPI-SYNC
  2123. * - write instruction tail
  2124. * At this point the actual control flow will be through the
  2125. * INT3 and handler and not hit the old or new instruction.
  2126. * Intel PT outputs FUP/TIP packets for the INT3, so the flow
  2127. * can still be decoded. Subsequently:
  2128. * - emit RECORD_TEXT_POKE with the new instruction
  2129. * - IPI-SYNC
  2130. * - write first byte
  2131. * - IPI-SYNC
  2132. * So before the text poke event timestamp, the decoder will see
  2133. * either the old instruction flow or FUP/TIP of INT3. After the
  2134. * text poke event timestamp, the decoder will see either the
  2135. * new instruction flow or FUP/TIP of INT3. Thus decoders can
  2136. * use the timestamp as the point at which to modify the
  2137. * executable code.
  2138. * The old instruction is recorded so that the event can be
  2139. * processed forwards or backwards.
  2140. */
  2141. perf_event_text_poke(text_poke_addr(&tp[i]), old, len, new, len);
  2142. }
  2143. if (do_sync) {
  2144. /*
  2145. * According to Intel, this core syncing is very likely
  2146. * not necessary and we'd be safe even without it. But
  2147. * better safe than sorry (plus there's not only Intel).
  2148. */
  2149. text_poke_sync();
  2150. }
  2151. /*
  2152. * Third step: replace the first byte (int3) by the first byte of
  2153. * replacing opcode.
  2154. */
  2155. for (do_sync = 0, i = 0; i < nr_entries; i++) {
  2156. u8 byte = tp[i].text[0];
  2157. if (tp[i].len == 6)
  2158. byte = 0x0f;
  2159. if (byte == INT3_INSN_OPCODE)
  2160. continue;
  2161. text_poke(text_poke_addr(&tp[i]), &byte, INT3_INSN_SIZE);
  2162. do_sync++;
  2163. }
  2164. if (do_sync)
  2165. text_poke_sync();
  2166. /*
  2167. * Remove and wait for refs to be zero.
  2168. */
  2169. if (!atomic_dec_and_test(&bp_desc.refs))
  2170. atomic_cond_read_acquire(&bp_desc.refs, !VAL);
  2171. }
  2172. static void text_poke_loc_init(struct text_poke_loc *tp, void *addr,
  2173. const void *opcode, size_t len, const void *emulate)
  2174. {
  2175. struct insn insn;
  2176. int ret, i = 0;
  2177. if (len == 6)
  2178. i = 1;
  2179. memcpy((void *)tp->text, opcode+i, len-i);
  2180. if (!emulate)
  2181. emulate = opcode;
  2182. ret = insn_decode_kernel(&insn, emulate);
  2183. BUG_ON(ret < 0);
  2184. tp->rel_addr = addr - (void *)_stext;
  2185. tp->len = len;
  2186. tp->opcode = insn.opcode.bytes[0];
  2187. if (is_jcc32(&insn)) {
  2188. /*
  2189. * Map Jcc.d32 onto Jcc.d8 and use len to distinguish.
  2190. */
  2191. tp->opcode = insn.opcode.bytes[1] - 0x10;
  2192. }
  2193. switch (tp->opcode) {
  2194. case RET_INSN_OPCODE:
  2195. case JMP32_INSN_OPCODE:
  2196. case JMP8_INSN_OPCODE:
  2197. /*
  2198. * Control flow instructions without implied execution of the
  2199. * next instruction can be padded with INT3.
  2200. */
  2201. for (i = insn.length; i < len; i++)
  2202. BUG_ON(tp->text[i] != INT3_INSN_OPCODE);
  2203. break;
  2204. default:
  2205. BUG_ON(len != insn.length);
  2206. }
  2207. switch (tp->opcode) {
  2208. case INT3_INSN_OPCODE:
  2209. case RET_INSN_OPCODE:
  2210. break;
  2211. case CALL_INSN_OPCODE:
  2212. case JMP32_INSN_OPCODE:
  2213. case JMP8_INSN_OPCODE:
  2214. case 0x70 ... 0x7f: /* Jcc */
  2215. tp->disp = insn.immediate.value;
  2216. break;
  2217. default: /* assume NOP */
  2218. switch (len) {
  2219. case 2: /* NOP2 -- emulate as JMP8+0 */
  2220. BUG_ON(memcmp(emulate, x86_nops[len], len));
  2221. tp->opcode = JMP8_INSN_OPCODE;
  2222. tp->disp = 0;
  2223. break;
  2224. case 5: /* NOP5 -- emulate as JMP32+0 */
  2225. BUG_ON(memcmp(emulate, x86_nops[len], len));
  2226. tp->opcode = JMP32_INSN_OPCODE;
  2227. tp->disp = 0;
  2228. break;
  2229. default: /* unknown instruction */
  2230. BUG();
  2231. }
  2232. break;
  2233. }
  2234. }
  2235. /*
  2236. * We hard rely on the tp_vec being ordered; ensure this is so by flushing
  2237. * early if needed.
  2238. */
  2239. static bool tp_order_fail(void *addr)
  2240. {
  2241. struct text_poke_loc *tp;
  2242. if (!tp_vec_nr)
  2243. return false;
  2244. if (!addr) /* force */
  2245. return true;
  2246. tp = &tp_vec[tp_vec_nr - 1];
  2247. if ((unsigned long)text_poke_addr(tp) > (unsigned long)addr)
  2248. return true;
  2249. return false;
  2250. }
  2251. static void text_poke_flush(void *addr)
  2252. {
  2253. if (tp_vec_nr == TP_VEC_MAX || tp_order_fail(addr)) {
  2254. text_poke_bp_batch(tp_vec, tp_vec_nr);
  2255. tp_vec_nr = 0;
  2256. }
  2257. }
  2258. void text_poke_finish(void)
  2259. {
  2260. text_poke_flush(NULL);
  2261. }
  2262. void __ref text_poke_queue(void *addr, const void *opcode, size_t len, const void *emulate)
  2263. {
  2264. struct text_poke_loc *tp;
  2265. text_poke_flush(addr);
  2266. tp = &tp_vec[tp_vec_nr++];
  2267. text_poke_loc_init(tp, addr, opcode, len, emulate);
  2268. }
  2269. /**
  2270. * text_poke_bp() -- update instructions on live kernel on SMP
  2271. * @addr: address to patch
  2272. * @opcode: opcode of new instruction
  2273. * @len: length to copy
  2274. * @emulate: instruction to be emulated
  2275. *
  2276. * Update a single instruction with the vector in the stack, avoiding
  2277. * dynamically allocated memory. This function should be used when it is
  2278. * not possible to allocate memory.
  2279. */
  2280. void __ref text_poke_bp(void *addr, const void *opcode, size_t len, const void *emulate)
  2281. {
  2282. struct text_poke_loc tp;
  2283. text_poke_loc_init(&tp, addr, opcode, len, emulate);
  2284. text_poke_bp_batch(&tp, 1);
  2285. }