]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/riscv/riscv/machdep.c
zfs: merge openzfs/zfs@41e55b476
[FreeBSD/FreeBSD.git] / sys / riscv / riscv / machdep.c
1 /*-
2  * Copyright (c) 2014 Andrew Turner
3  * Copyright (c) 2015-2017 Ruslan Bukin <br@bsdpad.com>
4  * All rights reserved.
5  *
6  * Portions of this software were developed by SRI International and the
7  * University of Cambridge Computer Laboratory under DARPA/AFRL contract
8  * FA8750-10-C-0237 ("CTSRD"), as part of the DARPA CRASH research programme.
9  *
10  * Portions of this software were developed by the University of Cambridge
11  * Computer Laboratory as part of the CTSRD Project, with support from the
12  * UK Higher Education Innovation Fund (HEIF).
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35
36 #include "opt_kstack_pages.h"
37 #include "opt_platform.h"
38
39 #include <sys/cdefs.h>
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/boot.h>
43 #include <sys/buf.h>
44 #include <sys/bus.h>
45 #include <sys/cons.h>
46 #include <sys/cpu.h>
47 #include <sys/devmap.h>
48 #include <sys/exec.h>
49 #include <sys/imgact.h>
50 #include <sys/kdb.h>
51 #include <sys/kernel.h>
52 #include <sys/ktr.h>
53 #include <sys/limits.h>
54 #include <sys/linker.h>
55 #include <sys/msgbuf.h>
56 #include <sys/pcpu.h>
57 #include <sys/physmem.h>
58 #include <sys/proc.h>
59 #include <sys/ptrace.h>
60 #include <sys/reboot.h>
61 #include <sys/reg.h>
62 #include <sys/rwlock.h>
63 #include <sys/sched.h>
64 #include <sys/signalvar.h>
65 #include <sys/syscallsubr.h>
66 #include <sys/sysent.h>
67 #include <sys/sysproto.h>
68 #include <sys/tslog.h>
69 #include <sys/ucontext.h>
70 #include <sys/vmmeter.h>
71
72 #include <vm/vm.h>
73 #include <vm/vm_param.h>
74 #include <vm/vm_kern.h>
75 #include <vm/vm_object.h>
76 #include <vm/vm_page.h>
77 #include <vm/vm_phys.h>
78 #include <vm/pmap.h>
79 #include <vm/vm_map.h>
80 #include <vm/vm_pager.h>
81
82 #include <machine/cpu.h>
83 #include <machine/fpe.h>
84 #include <machine/intr.h>
85 #include <machine/kdb.h>
86 #include <machine/machdep.h>
87 #include <machine/metadata.h>
88 #include <machine/pcb.h>
89 #include <machine/pte.h>
90 #include <machine/riscvreg.h>
91 #include <machine/sbi.h>
92 #include <machine/trap.h>
93 #include <machine/vmparam.h>
94
95 #ifdef FDT
96 #include <contrib/libfdt/libfdt.h>
97 #include <dev/fdt/fdt_common.h>
98 #include <dev/ofw/openfirm.h>
99 #endif
100
101 struct pcpu __pcpu[MAXCPU];
102
103 static struct trapframe proc0_tf;
104
105 int early_boot = 1;
106 int cold = 1;
107
108 #define DTB_SIZE_MAX    (1024 * 1024)
109
110 struct kva_md_info kmi;
111
112 int64_t dcache_line_size;       /* The minimum D cache line size */
113 int64_t icache_line_size;       /* The minimum I cache line size */
114 int64_t idcache_line_size;      /* The minimum cache line size */
115
116 #define BOOT_HART_INVALID       0xffffffff
117 uint32_t boot_hart = BOOT_HART_INVALID; /* The hart we booted on. */
118
119 cpuset_t all_harts;
120
121 extern int *end;
122
123 static char static_kenv[PAGE_SIZE];
124
125 static void
126 cpu_startup(void *dummy)
127 {
128
129         sbi_print_version();
130         printcpuinfo(0);
131
132         printf("real memory  = %ju (%ju MB)\n", ptoa((uintmax_t)realmem),
133             ptoa((uintmax_t)realmem) / (1024 * 1024));
134
135         /*
136          * Display any holes after the first chunk of extended memory.
137          */
138         if (bootverbose) {
139                 int indx;
140
141                 printf("Physical memory chunk(s):\n");
142                 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
143                         vm_paddr_t size;
144
145                         size = phys_avail[indx + 1] - phys_avail[indx];
146                         printf(
147                             "0x%016jx - 0x%016jx, %ju bytes (%ju pages)\n",
148                             (uintmax_t)phys_avail[indx],
149                             (uintmax_t)phys_avail[indx + 1] - 1,
150                             (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
151                 }
152         }
153
154         vm_ksubmap_init(&kmi);
155
156         printf("avail memory = %ju (%ju MB)\n",
157             ptoa((uintmax_t)vm_free_count()),
158             ptoa((uintmax_t)vm_free_count()) / (1024 * 1024));
159         if (bootverbose)
160                 devmap_print_table();
161
162         bufinit();
163         vm_pager_bufferinit();
164 }
165
166 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
167
168 int
169 cpu_idle_wakeup(int cpu)
170 {
171
172         return (0);
173 }
174
175 void
176 cpu_idle(int busy)
177 {
178
179         spinlock_enter();
180         if (!busy)
181                 cpu_idleclock();
182         if (!sched_runnable())
183                 __asm __volatile(
184                     "fence \n"
185                     "wfi   \n");
186         if (!busy)
187                 cpu_activeclock();
188         spinlock_exit();
189 }
190
191 void
192 cpu_halt(void)
193 {
194
195         /*
196          * Try to power down using the HSM SBI extension and fall back to a
197          * simple wfi loop.
198          */
199         intr_disable();
200         if (sbi_probe_extension(SBI_EXT_ID_HSM) != 0)
201                 sbi_hsm_hart_stop();
202         for (;;)
203                 __asm __volatile("wfi");
204         /* NOTREACHED */
205 }
206
207 /*
208  * Flush the D-cache for non-DMA I/O so that the I-cache can
209  * be made coherent later.
210  */
211 void
212 cpu_flush_dcache(void *ptr, size_t len)
213 {
214
215         /* TBD */
216 }
217
218 /* Get current clock frequency for the given CPU ID. */
219 int
220 cpu_est_clockrate(int cpu_id, uint64_t *rate)
221 {
222
223         panic("cpu_est_clockrate");
224 }
225
226 void
227 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
228 {
229 }
230
231 void
232 spinlock_enter(void)
233 {
234         struct thread *td;
235         register_t reg;
236
237         td = curthread;
238         if (td->td_md.md_spinlock_count == 0) {
239                 reg = intr_disable();
240                 td->td_md.md_spinlock_count = 1;
241                 td->td_md.md_saved_sstatus_ie = reg;
242                 critical_enter();
243         } else
244                 td->td_md.md_spinlock_count++;
245 }
246
247 void
248 spinlock_exit(void)
249 {
250         struct thread *td;
251         register_t sstatus_ie;
252
253         td = curthread;
254         sstatus_ie = td->td_md.md_saved_sstatus_ie;
255         td->td_md.md_spinlock_count--;
256         if (td->td_md.md_spinlock_count == 0) {
257                 critical_exit();
258                 intr_restore(sstatus_ie);
259         }
260 }
261
262 /*
263  * Construct a PCB from a trapframe. This is called from kdb_trap() where
264  * we want to start a backtrace from the function that caused us to enter
265  * the debugger. We have the context in the trapframe, but base the trace
266  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
267  * enough for a backtrace.
268  */
269 void
270 makectx(struct trapframe *tf, struct pcb *pcb)
271 {
272
273         memcpy(pcb->pcb_s, tf->tf_s, sizeof(tf->tf_s));
274
275         pcb->pcb_ra = tf->tf_sepc;
276         pcb->pcb_sp = tf->tf_sp;
277         pcb->pcb_gp = tf->tf_gp;
278         pcb->pcb_tp = tf->tf_tp;
279 }
280
281 static void
282 init_proc0(vm_offset_t kstack)
283 {
284         struct pcpu *pcpup;
285
286         pcpup = &__pcpu[0];
287
288         proc_linkup0(&proc0, &thread0);
289         thread0.td_kstack = kstack;
290         thread0.td_kstack_pages = KSTACK_PAGES;
291         thread0.td_pcb = (struct pcb *)(thread0.td_kstack +
292             thread0.td_kstack_pages * PAGE_SIZE) - 1;
293         thread0.td_pcb->pcb_fpflags = 0;
294         thread0.td_frame = &proc0_tf;
295         pcpup->pc_curpcb = thread0.td_pcb;
296 }
297
298 #ifdef FDT
299 static void
300 try_load_dtb(caddr_t kmdp)
301 {
302         vm_offset_t dtbp;
303
304         dtbp = MD_FETCH(kmdp, MODINFOMD_DTBP, vm_offset_t);
305
306 #if defined(FDT_DTB_STATIC)
307         /*
308          * In case the device tree blob was not retrieved (from metadata) try
309          * to use the statically embedded one.
310          */
311         if (dtbp == (vm_offset_t)NULL)
312                 dtbp = (vm_offset_t)&fdt_static_dtb;
313 #endif
314
315         if (dtbp == (vm_offset_t)NULL) {
316                 printf("ERROR loading DTB\n");
317                 return;
318         }
319
320         if (OF_install(OFW_FDT, 0) == FALSE)
321                 panic("Cannot install FDT");
322
323         if (OF_init((void *)dtbp) != 0)
324                 panic("OF_init failed with the found device tree");
325 }
326 #endif
327
328 static void
329 cache_setup(void)
330 {
331
332         /* TODO */
333
334         dcache_line_size = 0;
335         icache_line_size = 0;
336         idcache_line_size = 0;
337 }
338
339 /*
340  * Fake up a boot descriptor table.
341  */
342 static void
343 fake_preload_metadata(struct riscv_bootparams *rvbp)
344 {
345         static uint32_t fake_preload[48];
346         vm_offset_t lastaddr;
347         size_t fake_size, dtb_size;
348
349 #define PRELOAD_PUSH_VALUE(type, value) do {                    \
350         *(type *)((char *)fake_preload + fake_size) = (value);  \
351         fake_size += sizeof(type);                              \
352 } while (0)
353
354 #define PRELOAD_PUSH_STRING(str) do {                           \
355         uint32_t ssize;                                         \
356         ssize = strlen(str) + 1;                                \
357         PRELOAD_PUSH_VALUE(uint32_t, ssize);                    \
358         strcpy(((char *)fake_preload + fake_size), str);        \
359         fake_size += ssize;                                     \
360         fake_size = roundup(fake_size, sizeof(u_long));         \
361 } while (0)
362
363         fake_size = 0;
364         lastaddr = (vm_offset_t)&end;
365
366         PRELOAD_PUSH_VALUE(uint32_t, MODINFO_NAME);
367         PRELOAD_PUSH_STRING("kernel");
368         PRELOAD_PUSH_VALUE(uint32_t, MODINFO_TYPE);
369         PRELOAD_PUSH_STRING("elf kernel");
370
371         PRELOAD_PUSH_VALUE(uint32_t, MODINFO_ADDR);
372         PRELOAD_PUSH_VALUE(uint32_t, sizeof(vm_offset_t));
373         PRELOAD_PUSH_VALUE(uint64_t, KERNBASE);
374
375         PRELOAD_PUSH_VALUE(uint32_t, MODINFO_SIZE);
376         PRELOAD_PUSH_VALUE(uint32_t, sizeof(size_t));
377         PRELOAD_PUSH_VALUE(uint64_t, (size_t)((vm_offset_t)&end - KERNBASE));
378
379         /* Copy the DTB to KVA space. */
380         lastaddr = roundup(lastaddr, sizeof(int));
381         PRELOAD_PUSH_VALUE(uint32_t, MODINFO_METADATA | MODINFOMD_DTBP);
382         PRELOAD_PUSH_VALUE(uint32_t, sizeof(vm_offset_t));
383         PRELOAD_PUSH_VALUE(vm_offset_t, lastaddr);
384         dtb_size = fdt_totalsize(rvbp->dtbp_virt);
385         memmove((void *)lastaddr, (const void *)rvbp->dtbp_virt, dtb_size);
386         lastaddr = roundup(lastaddr + dtb_size, sizeof(int));
387
388         PRELOAD_PUSH_VALUE(uint32_t, MODINFO_METADATA | MODINFOMD_KERNEND);
389         PRELOAD_PUSH_VALUE(uint32_t, sizeof(vm_offset_t));
390         PRELOAD_PUSH_VALUE(vm_offset_t, lastaddr);
391
392         PRELOAD_PUSH_VALUE(uint32_t, MODINFO_METADATA | MODINFOMD_HOWTO);
393         PRELOAD_PUSH_VALUE(uint32_t, sizeof(int));
394         PRELOAD_PUSH_VALUE(int, RB_VERBOSE);
395
396         /* End marker */
397         PRELOAD_PUSH_VALUE(uint32_t, 0);
398         PRELOAD_PUSH_VALUE(uint32_t, 0);
399         preload_metadata = (caddr_t)fake_preload;
400
401         /* Check if bootloader clobbered part of the kernel with the DTB. */
402         KASSERT(rvbp->dtbp_phys + dtb_size <= rvbp->kern_phys ||
403                 rvbp->dtbp_phys >= rvbp->kern_phys + (lastaddr - KERNBASE),
404             ("FDT (%lx-%lx) and kernel (%lx-%lx) overlap", rvbp->dtbp_phys,
405                 rvbp->dtbp_phys + dtb_size, rvbp->kern_phys,
406                 rvbp->kern_phys + (lastaddr - KERNBASE)));
407         KASSERT(fake_size < sizeof(fake_preload),
408             ("Too many fake_preload items"));
409
410         if (boothowto & RB_VERBOSE)
411                 printf("FDT phys (%lx-%lx), kernel phys (%lx-%lx)\n",
412                     rvbp->dtbp_phys, rvbp->dtbp_phys + dtb_size,
413                     rvbp->kern_phys, rvbp->kern_phys + (lastaddr - KERNBASE));
414 }
415
416 /* Support for FDT configurations only. */
417 CTASSERT(FDT);
418
419 #ifdef FDT
420 static void
421 parse_fdt_bootargs(void)
422 {
423         char bootargs[512];
424
425         bootargs[sizeof(bootargs) - 1] = '\0';
426         if (fdt_get_chosen_bootargs(bootargs, sizeof(bootargs) - 1) == 0) {
427                 boothowto |= boot_parse_cmdline(bootargs);
428         }
429 }
430 #endif
431
432 static vm_offset_t
433 parse_metadata(void)
434 {
435         caddr_t kmdp;
436         vm_offset_t lastaddr;
437 #ifdef DDB
438         vm_offset_t ksym_start, ksym_end;
439 #endif
440         char *kern_envp;
441
442         /* Find the kernel address */
443         kmdp = preload_search_by_type("elf kernel");
444         if (kmdp == NULL)
445                 kmdp = preload_search_by_type("elf64 kernel");
446         KASSERT(kmdp != NULL, ("No preload metadata found!"));
447
448         /* Read the boot metadata */
449         boothowto = MD_FETCH(kmdp, MODINFOMD_HOWTO, int);
450         lastaddr = MD_FETCH(kmdp, MODINFOMD_KERNEND, vm_offset_t);
451         kern_envp = MD_FETCH(kmdp, MODINFOMD_ENVP, char *);
452         if (kern_envp != NULL)
453                 init_static_kenv(kern_envp, 0);
454         else
455                 init_static_kenv(static_kenv, sizeof(static_kenv));
456 #ifdef DDB
457         ksym_start = MD_FETCH(kmdp, MODINFOMD_SSYM, uintptr_t);
458         ksym_end = MD_FETCH(kmdp, MODINFOMD_ESYM, uintptr_t);
459         db_fetch_ksymtab(ksym_start, ksym_end);
460 #endif
461 #ifdef FDT
462         try_load_dtb(kmdp);
463         if (kern_envp == NULL)
464                 parse_fdt_bootargs();
465 #endif
466         return (lastaddr);
467 }
468
469 void
470 initriscv(struct riscv_bootparams *rvbp)
471 {
472         struct mem_region mem_regions[FDT_MEM_REGIONS];
473         struct pcpu *pcpup;
474         int mem_regions_sz;
475         vm_offset_t lastaddr;
476         vm_size_t kernlen;
477 #ifdef FDT
478         phandle_t chosen;
479         uint32_t hart;
480 #endif
481         char *env;
482
483         TSRAW(&thread0, TS_ENTER, __func__, NULL);
484
485         /* Set the pcpu data, this is needed by pmap_bootstrap */
486         pcpup = &__pcpu[0];
487         pcpu_init(pcpup, 0, sizeof(struct pcpu));
488
489         /* Set the pcpu pointer */
490         __asm __volatile("mv tp, %0" :: "r"(pcpup));
491
492         PCPU_SET(curthread, &thread0);
493
494         /* Initialize SBI interface. */
495         sbi_init();
496
497         /* Parse the boot metadata. */
498         if (rvbp->modulep != 0) {
499                 preload_metadata = (caddr_t)rvbp->modulep;
500         } else {
501                 fake_preload_metadata(rvbp);
502         }
503         lastaddr = parse_metadata();
504
505 #ifdef FDT
506         /*
507          * Look for the boot hart ID. This was either passed in directly from
508          * the SBI firmware and handled by locore, or was stored in the device
509          * tree by an earlier boot stage.
510          */
511         chosen = OF_finddevice("/chosen");
512         if (OF_getencprop(chosen, "boot-hartid", &hart, sizeof(hart)) != -1) {
513                 boot_hart = hart;
514         }
515 #endif
516         if (boot_hart == BOOT_HART_INVALID) {
517                 panic("Boot hart ID was not properly set");
518         }
519         pcpup->pc_hart = boot_hart;
520
521 #ifdef FDT
522         /*
523          * Exclude reserved memory specified by the device tree. Typically,
524          * this contains an entry for memory used by the runtime SBI firmware.
525          */
526         if (fdt_get_reserved_mem(mem_regions, &mem_regions_sz) == 0) {
527                 physmem_exclude_regions(mem_regions, mem_regions_sz,
528                     EXFLAG_NODUMP | EXFLAG_NOALLOC);
529         }
530
531         /* Grab physical memory regions information from device tree. */
532         if (fdt_get_mem_regions(mem_regions, &mem_regions_sz, NULL) != 0) {
533                 panic("Cannot get physical memory regions");
534         }
535         physmem_hardware_regions(mem_regions, mem_regions_sz);
536 #endif
537
538         /*
539          * Identify CPU/ISA features.
540          */
541         identify_cpu(0);
542
543         /* Do basic tuning, hz etc */
544         init_param1();
545
546         cache_setup();
547
548         /* Bootstrap enough of pmap to enter the kernel proper */
549         kernlen = (lastaddr - KERNBASE);
550         pmap_bootstrap(rvbp->kern_l1pt, rvbp->kern_phys, kernlen);
551
552 #ifdef FDT
553         /*
554          * XXX: Unconditionally exclude the lowest 2MB of physical memory, as
555          * this area is assumed to contain the SBI firmware. This is a little
556          * fragile, but it is consistent with the platforms we support so far.
557          *
558          * TODO: remove this when the all regular booting methods properly
559          * report their reserved memory in the device tree.
560          */
561         physmem_exclude_region(mem_regions[0].mr_start, L2_SIZE,
562             EXFLAG_NODUMP | EXFLAG_NOALLOC);
563 #endif
564         physmem_init_kernel_globals();
565
566         /* Establish static device mappings */
567         devmap_bootstrap(0, NULL);
568
569         cninit();
570
571         /*
572          * Dump the boot metadata. We have to wait for cninit() since console
573          * output is required. If it's grossly incorrect the kernel will never
574          * make it this far.
575          */
576         if (getenv_is_true("debug.dump_modinfo_at_boot"))
577                 preload_dump();
578
579         init_proc0(rvbp->kern_stack);
580
581         msgbufinit(msgbufp, msgbufsize);
582         mutex_init();
583         init_param2(physmem);
584         kdb_init();
585 #ifdef KDB
586         if ((boothowto & RB_KDB) != 0)
587                 kdb_enter(KDB_WHY_BOOTFLAGS, "Boot flags requested debugger");
588 #endif
589
590         env = kern_getenv("kernelname");
591         if (env != NULL)
592                 strlcpy(kernelname, env, sizeof(kernelname));
593
594         if (boothowto & RB_VERBOSE)
595                 physmem_print_tables();
596
597         early_boot = 0;
598
599         if (bootverbose && kstack_pages != KSTACK_PAGES)
600                 printf("kern.kstack_pages = %d ignored for thread0\n",
601                     kstack_pages);
602
603         TSEXIT();
604 }