arch/riscv/kernel/patch.c

Source file repositories/reference/linux-study-clean/arch/riscv/kernel/patch.c

File Facts

System
Linux kernel
Corpus path
arch/riscv/kernel/patch.c
Extension
.c
Size
7274 bytes
Lines
303
Domain
Architecture Layer
Bucket
arch/riscv
Inferred role
Architecture Layer: implementation source
Status
source implementation candidate

Why This File Exists

CPU and platform-specific kernel glue: boot entry, traps, syscall entry, interrupts, page tables, context switch, and low-level barriers.

Dependency Surface

Detected Declarations

Annotated Snippet

struct patch_insn {
	void *addr;
	u32 *insns;
	size_t len;
	atomic_t cpu_count;
};

int riscv_patch_in_stop_machine = false;

#ifdef CONFIG_MMU

static inline bool is_kernel_exittext(uintptr_t addr)
{
	return system_state < SYSTEM_RUNNING &&
		addr >= (uintptr_t)__exittext_begin &&
		addr < (uintptr_t)__exittext_end;
}

/*
 * The fix_to_virt(, idx) needs a const value (not a dynamic variable of
 * reg-a0) or BUILD_BUG_ON failed with "idx >= __end_of_fixed_addresses".
 * So use '__always_inline' and 'const unsigned int fixmap' here.
 */
static __always_inline void *patch_map(void *addr, const unsigned int fixmap)
{
	uintptr_t uintaddr = (uintptr_t) addr;
	phys_addr_t phys;

	if (core_kernel_text(uintaddr) || is_kernel_exittext(uintaddr)) {
		phys = __pa_symbol(addr);
	} else if (IS_ENABLED(CONFIG_STRICT_MODULE_RWX)) {
		struct page *page = vmalloc_to_page(addr);

		BUG_ON(!page);
		phys = page_to_phys(page) + offset_in_page(addr);
	} else {
		return addr;
	}

	return (void *)set_fixmap_offset(fixmap, phys);
}

static void patch_unmap(int fixmap)
{
	clear_fixmap(fixmap);
}
NOKPROBE_SYMBOL(patch_unmap);

static int __patch_insn_set(void *addr, u8 c, size_t len)
{
	bool across_pages = (offset_in_page(addr) + len) > PAGE_SIZE;
	void *waddr = addr;

	/*
	 * Only two pages can be mapped at a time for writing.
	 */
	if (len + offset_in_page(addr) > 2 * PAGE_SIZE)
		return -EINVAL;
	/*
	 * Before reaching here, it was expected to lock the text_mutex
	 * already, so we don't need to give another lock here and could
	 * ensure that it was safe between each cores.
	 */
	lockdep_assert_held(&text_mutex);

	preempt_disable();

	if (across_pages)
		patch_map(addr + PAGE_SIZE, FIX_TEXT_POKE1);

	waddr = patch_map(addr, FIX_TEXT_POKE0);

	memset(waddr, c, len);

	/*
	 * We could have just patched a function that is about to be
	 * called so make sure we don't execute partially patched
	 * instructions by flushing the icache as soon as possible.
	 */
	local_flush_icache_range((unsigned long)waddr,
				 (unsigned long)waddr + len);

	patch_unmap(FIX_TEXT_POKE0);

	if (across_pages)
		patch_unmap(FIX_TEXT_POKE1);

	preempt_enable();

	return 0;

Annotation

Implementation Notes