+static int32_t *patch_checked_location(int32_t *p, int32_t val)
+{
+ assert(*p == 0);
+ // verify that it's aligned
+ assert((((uintptr_t) p) & (4-1)) == 0);
+ *p = val;
+ return p;
+}
+
+static void checked_icache_flush(int32_t *addr, int nbytes, int32_t *check_loc)
+{
+ assert((int8_t*) addr + nbytes - sizeof(int32_t) >= (int8_t*) check_loc);
+ md_icacheflush(addr, nbytes);
+}
+
+/**
+ * Check if the trap instruction at the given PC is valid.
+ *
+ * @param pc Program counter.
+ *
+ * @return true if valid, false otherwise.
+ */
+bool patcher_is_valid_trap_instruction_at(void* pc)
+{
+ uint16_t mcode = *((uint16_t*) pc);
+
+ // Check for the undefined instruction we use.
+ return (mcode == 0x0b0f);
+}
+
+/**
+ * Overwrites the MFENCE instruction at the indicated address with a 3-byte
+ * NOP. The MFENCE instruction is not allowed to cross a (4-byte) word
+ * boundary.
+ *
+ * @param pc Program counter.
+ */
+static void patch_out_mfence(void *pc)
+{
+ uint32_t *p = (uint32_t*) (((uintptr_t) pc) & ~3);
+
+ assert((((uintptr_t) pc) & 3) < 2);
+ if (((uintptr_t) pc) & 1)
+ *p = (*p & 0x000000ff) | 0x001f0f00;
+ else
+ *p = (*p & 0xff000000) | 0x00001f0f;
+
+ md_icacheflush(p, 4);
+}