1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * Copyright (C) 2020-2022 Loongson Technology Corporation Limited
4  */
5 #ifndef _ASM_MODULE_H
6 #define _ASM_MODULE_H
7 
8 #include <asm/inst.h>
9 #include <asm-generic/module.h>
10 
11 #define RELA_STACK_DEPTH 16
12 
13 struct mod_section {
14 	Elf_Shdr *shdr;
15 	int num_entries;
16 	int max_entries;
17 };
18 
19 struct mod_arch_specific {
20 	struct mod_section got;
21 	struct mod_section plt;
22 	struct mod_section plt_idx;
23 };
24 
25 struct got_entry {
26 	Elf_Addr symbol_addr;
27 };
28 
29 struct plt_entry {
30 	u32 inst_lu12iw;
31 	u32 inst_lu32id;
32 	u32 inst_lu52id;
33 	u32 inst_jirl;
34 };
35 
36 struct plt_idx_entry {
37 	Elf_Addr symbol_addr;
38 };
39 
40 Elf_Addr module_emit_got_entry(struct module *mod, Elf_Addr val);
41 Elf_Addr module_emit_plt_entry(struct module *mod, Elf_Addr val);
42 
43 static inline struct got_entry emit_got_entry(Elf_Addr val)
44 {
45 	return (struct got_entry) { val };
46 }
47 
48 static inline struct plt_entry emit_plt_entry(unsigned long val)
49 {
50 	u32 lu12iw, lu32id, lu52id, jirl;
51 
52 	lu12iw = (lu12iw_op << 25 | (((val >> 12) & 0xfffff) << 5) | LOONGARCH_GPR_T1);
53 	lu32id = larch_insn_gen_lu32id(LOONGARCH_GPR_T1, ADDR_IMM(val, LU32ID));
54 	lu52id = larch_insn_gen_lu52id(LOONGARCH_GPR_T1, LOONGARCH_GPR_T1, ADDR_IMM(val, LU52ID));
55 	jirl = larch_insn_gen_jirl(0, LOONGARCH_GPR_T1, 0, (val & 0xfff));
56 
57 	return (struct plt_entry) { lu12iw, lu32id, lu52id, jirl };
58 }
59 
60 static inline struct plt_idx_entry emit_plt_idx_entry(unsigned long val)
61 {
62 	return (struct plt_idx_entry) { val };
63 }
64 
65 static inline int get_plt_idx(unsigned long val, const struct mod_section *sec)
66 {
67 	int i;
68 	struct plt_idx_entry *plt_idx = (struct plt_idx_entry *)sec->shdr->sh_addr;
69 
70 	for (i = 0; i < sec->num_entries; i++) {
71 		if (plt_idx[i].symbol_addr == val)
72 			return i;
73 	}
74 
75 	return -1;
76 }
77 
78 static inline struct plt_entry *get_plt_entry(unsigned long val,
79 				      const struct mod_section *sec_plt,
80 				      const struct mod_section *sec_plt_idx)
81 {
82 	int plt_idx = get_plt_idx(val, sec_plt_idx);
83 	struct plt_entry *plt = (struct plt_entry *)sec_plt->shdr->sh_addr;
84 
85 	if (plt_idx < 0)
86 		return NULL;
87 
88 	return plt + plt_idx;
89 }
90 
91 static inline struct got_entry *get_got_entry(Elf_Addr val,
92 					      const struct mod_section *sec)
93 {
94 	struct got_entry *got = (struct got_entry *)sec->shdr->sh_addr;
95 	int i;
96 
97 	for (i = 0; i < sec->num_entries; i++)
98 		if (got[i].symbol_addr == val)
99 			return &got[i];
100 	return NULL;
101 }
102 
103 #endif /* _ASM_MODULE_H */
104