]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/riscv/riscv/machdep.c
Handle load from loader(8)
[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_platform.h"
37
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40
41 #include <sys/param.h>
42 #include <sys/systm.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/rwlock.h>
62 #include <sys/sched.h>
63 #include <sys/signalvar.h>
64 #include <sys/syscallsubr.h>
65 #include <sys/sysent.h>
66 #include <sys/sysproto.h>
67 #include <sys/tslog.h>
68 #include <sys/ucontext.h>
69 #include <sys/vmmeter.h>
70
71 #include <vm/vm.h>
72 #include <vm/vm_param.h>
73 #include <vm/vm_kern.h>
74 #include <vm/vm_object.h>
75 #include <vm/vm_page.h>
76 #include <vm/vm_phys.h>
77 #include <vm/pmap.h>
78 #include <vm/vm_map.h>
79 #include <vm/vm_pager.h>
80
81 #include <machine/cpu.h>
82 #include <machine/intr.h>
83 #include <machine/kdb.h>
84 #include <machine/machdep.h>
85 #include <machine/metadata.h>
86 #include <machine/pcb.h>
87 #include <machine/pte.h>
88 #include <machine/reg.h>
89 #include <machine/riscvreg.h>
90 #include <machine/sbi.h>
91 #include <machine/trap.h>
92 #include <machine/vmparam.h>
93
94 #ifdef FPE
95 #include <machine/fpe.h>
96 #endif
97
98 #ifdef FDT
99 #include <contrib/libfdt/libfdt.h>
100 #include <dev/fdt/fdt_common.h>
101 #include <dev/ofw/openfirm.h>
102 #endif
103
104 static void get_fpcontext(struct thread *td, mcontext_t *mcp);
105 static void set_fpcontext(struct thread *td, mcontext_t *mcp);
106
107 struct pcpu __pcpu[MAXCPU];
108
109 static struct trapframe proc0_tf;
110
111 int early_boot = 1;
112 int cold = 1;
113
114 #define DTB_SIZE_MAX    (1024 * 1024)
115
116 vm_paddr_t physmap[PHYS_AVAIL_ENTRIES];
117 u_int physmap_idx;
118
119 struct kva_md_info kmi;
120
121 int64_t dcache_line_size;       /* The minimum D cache line size */
122 int64_t icache_line_size;       /* The minimum I cache line size */
123 int64_t idcache_line_size;      /* The minimum cache line size */
124
125 #define BOOT_HART_INVALID       0xffffffff
126 uint32_t boot_hart = BOOT_HART_INVALID; /* The hart we booted on. */
127
128 cpuset_t all_harts;
129
130 extern int *end;
131
132 static void
133 cpu_startup(void *dummy)
134 {
135
136         sbi_print_version();
137         identify_cpu();
138
139         printf("real memory  = %ju (%ju MB)\n", ptoa((uintmax_t)realmem),
140             ptoa((uintmax_t)realmem) / (1024 * 1024));
141
142         /*
143          * Display any holes after the first chunk of extended memory.
144          */
145         if (bootverbose) {
146                 int indx;
147
148                 printf("Physical memory chunk(s):\n");
149                 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
150                         vm_paddr_t size;
151
152                         size = phys_avail[indx + 1] - phys_avail[indx];
153                         printf(
154                             "0x%016jx - 0x%016jx, %ju bytes (%ju pages)\n",
155                             (uintmax_t)phys_avail[indx],
156                             (uintmax_t)phys_avail[indx + 1] - 1,
157                             (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
158                 }
159         }
160
161         vm_ksubmap_init(&kmi);
162
163         printf("avail memory = %ju (%ju MB)\n",
164             ptoa((uintmax_t)vm_free_count()),
165             ptoa((uintmax_t)vm_free_count()) / (1024 * 1024));
166         if (bootverbose)
167                 devmap_print_table();
168
169         bufinit();
170         vm_pager_bufferinit();
171 }
172
173 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
174
175 int
176 cpu_idle_wakeup(int cpu)
177 {
178
179         return (0);
180 }
181
182 int
183 fill_regs(struct thread *td, struct reg *regs)
184 {
185         struct trapframe *frame;
186
187         frame = td->td_frame;
188         regs->sepc = frame->tf_sepc;
189         regs->sstatus = frame->tf_sstatus;
190         regs->ra = frame->tf_ra;
191         regs->sp = frame->tf_sp;
192         regs->gp = frame->tf_gp;
193         regs->tp = frame->tf_tp;
194
195         memcpy(regs->t, frame->tf_t, sizeof(regs->t));
196         memcpy(regs->s, frame->tf_s, sizeof(regs->s));
197         memcpy(regs->a, frame->tf_a, sizeof(regs->a));
198
199         return (0);
200 }
201
202 int
203 set_regs(struct thread *td, struct reg *regs)
204 {
205         struct trapframe *frame;
206
207         frame = td->td_frame;
208         frame->tf_sepc = regs->sepc;
209         frame->tf_ra = regs->ra;
210         frame->tf_sp = regs->sp;
211         frame->tf_gp = regs->gp;
212         frame->tf_tp = regs->tp;
213
214         memcpy(frame->tf_t, regs->t, sizeof(frame->tf_t));
215         memcpy(frame->tf_s, regs->s, sizeof(frame->tf_s));
216         memcpy(frame->tf_a, regs->a, sizeof(frame->tf_a));
217
218         return (0);
219 }
220
221 int
222 fill_fpregs(struct thread *td, struct fpreg *regs)
223 {
224 #ifdef FPE
225         struct pcb *pcb;
226
227         pcb = td->td_pcb;
228
229         if ((pcb->pcb_fpflags & PCB_FP_STARTED) != 0) {
230                 /*
231                  * If we have just been running FPE instructions we will
232                  * need to save the state to memcpy it below.
233                  */
234                 if (td == curthread)
235                         fpe_state_save(td);
236
237                 memcpy(regs->fp_x, pcb->pcb_x, sizeof(regs->fp_x));
238                 regs->fp_fcsr = pcb->pcb_fcsr;
239         } else
240 #endif
241                 memset(regs, 0, sizeof(*regs));
242
243         return (0);
244 }
245
246 int
247 set_fpregs(struct thread *td, struct fpreg *regs)
248 {
249 #ifdef FPE
250         struct trapframe *frame;
251         struct pcb *pcb;
252
253         frame = td->td_frame;
254         pcb = td->td_pcb;
255
256         memcpy(pcb->pcb_x, regs->fp_x, sizeof(regs->fp_x));
257         pcb->pcb_fcsr = regs->fp_fcsr;
258         pcb->pcb_fpflags |= PCB_FP_STARTED;
259         frame->tf_sstatus &= ~SSTATUS_FS_MASK;
260         frame->tf_sstatus |= SSTATUS_FS_CLEAN;
261 #endif
262
263         return (0);
264 }
265
266 int
267 fill_dbregs(struct thread *td, struct dbreg *regs)
268 {
269
270         panic("fill_dbregs");
271 }
272
273 int
274 set_dbregs(struct thread *td, struct dbreg *regs)
275 {
276
277         panic("set_dbregs");
278 }
279
280 int
281 ptrace_set_pc(struct thread *td, u_long addr)
282 {
283
284         td->td_frame->tf_sepc = addr;
285         return (0);
286 }
287
288 int
289 ptrace_single_step(struct thread *td)
290 {
291
292         /* TODO; */
293         return (EOPNOTSUPP);
294 }
295
296 int
297 ptrace_clear_single_step(struct thread *td)
298 {
299
300         /* TODO; */
301         return (EOPNOTSUPP);
302 }
303
304 void
305 exec_setregs(struct thread *td, struct image_params *imgp, uintptr_t stack)
306 {
307         struct trapframe *tf;
308         struct pcb *pcb;
309
310         tf = td->td_frame;
311         pcb = td->td_pcb;
312
313         memset(tf, 0, sizeof(struct trapframe));
314
315         tf->tf_a[0] = stack;
316         tf->tf_sp = STACKALIGN(stack);
317         tf->tf_ra = imgp->entry_addr;
318         tf->tf_sepc = imgp->entry_addr;
319
320         pcb->pcb_fpflags &= ~PCB_FP_STARTED;
321 }
322
323 /* Sanity check these are the same size, they will be memcpy'd to and fro */
324 CTASSERT(sizeof(((struct trapframe *)0)->tf_a) ==
325     sizeof((struct gpregs *)0)->gp_a);
326 CTASSERT(sizeof(((struct trapframe *)0)->tf_s) ==
327     sizeof((struct gpregs *)0)->gp_s);
328 CTASSERT(sizeof(((struct trapframe *)0)->tf_t) ==
329     sizeof((struct gpregs *)0)->gp_t);
330 CTASSERT(sizeof(((struct trapframe *)0)->tf_a) ==
331     sizeof((struct reg *)0)->a);
332 CTASSERT(sizeof(((struct trapframe *)0)->tf_s) ==
333     sizeof((struct reg *)0)->s);
334 CTASSERT(sizeof(((struct trapframe *)0)->tf_t) ==
335     sizeof((struct reg *)0)->t);
336
337 /* Support for FDT configurations only. */
338 CTASSERT(FDT);
339
340 int
341 get_mcontext(struct thread *td, mcontext_t *mcp, int clear_ret)
342 {
343         struct trapframe *tf = td->td_frame;
344
345         memcpy(mcp->mc_gpregs.gp_t, tf->tf_t, sizeof(mcp->mc_gpregs.gp_t));
346         memcpy(mcp->mc_gpregs.gp_s, tf->tf_s, sizeof(mcp->mc_gpregs.gp_s));
347         memcpy(mcp->mc_gpregs.gp_a, tf->tf_a, sizeof(mcp->mc_gpregs.gp_a));
348
349         if (clear_ret & GET_MC_CLEAR_RET) {
350                 mcp->mc_gpregs.gp_a[0] = 0;
351                 mcp->mc_gpregs.gp_t[0] = 0; /* clear syscall error */
352         }
353
354         mcp->mc_gpregs.gp_ra = tf->tf_ra;
355         mcp->mc_gpregs.gp_sp = tf->tf_sp;
356         mcp->mc_gpregs.gp_gp = tf->tf_gp;
357         mcp->mc_gpregs.gp_tp = tf->tf_tp;
358         mcp->mc_gpregs.gp_sepc = tf->tf_sepc;
359         mcp->mc_gpregs.gp_sstatus = tf->tf_sstatus;
360         get_fpcontext(td, mcp);
361
362         return (0);
363 }
364
365 int
366 set_mcontext(struct thread *td, mcontext_t *mcp)
367 {
368         struct trapframe *tf;
369
370         tf = td->td_frame;
371
372         /*
373          * Permit changes to the USTATUS bits of SSTATUS.
374          *
375          * Ignore writes to read-only bits (SD, XS).
376          *
377          * Ignore writes to the FS field as set_fpcontext() will set
378          * it explicitly.
379          */
380         if (((mcp->mc_gpregs.gp_sstatus ^ tf->tf_sstatus) &
381             ~(SSTATUS_SD | SSTATUS_XS_MASK | SSTATUS_FS_MASK | SSTATUS_UPIE |
382             SSTATUS_UIE)) != 0)
383                 return (EINVAL);
384
385         memcpy(tf->tf_t, mcp->mc_gpregs.gp_t, sizeof(tf->tf_t));
386         memcpy(tf->tf_s, mcp->mc_gpregs.gp_s, sizeof(tf->tf_s));
387         memcpy(tf->tf_a, mcp->mc_gpregs.gp_a, sizeof(tf->tf_a));
388
389         tf->tf_ra = mcp->mc_gpregs.gp_ra;
390         tf->tf_sp = mcp->mc_gpregs.gp_sp;
391         tf->tf_gp = mcp->mc_gpregs.gp_gp;
392         tf->tf_sepc = mcp->mc_gpregs.gp_sepc;
393         tf->tf_sstatus = mcp->mc_gpregs.gp_sstatus;
394         set_fpcontext(td, mcp);
395
396         return (0);
397 }
398
399 static void
400 get_fpcontext(struct thread *td, mcontext_t *mcp)
401 {
402 #ifdef FPE
403         struct pcb *curpcb;
404
405         critical_enter();
406
407         curpcb = curthread->td_pcb;
408
409         KASSERT(td->td_pcb == curpcb, ("Invalid fpe pcb"));
410
411         if ((curpcb->pcb_fpflags & PCB_FP_STARTED) != 0) {
412                 /*
413                  * If we have just been running FPE instructions we will
414                  * need to save the state to memcpy it below.
415                  */
416                 fpe_state_save(td);
417
418                 KASSERT((curpcb->pcb_fpflags & ~PCB_FP_USERMASK) == 0,
419                     ("Non-userspace FPE flags set in get_fpcontext"));
420                 memcpy(mcp->mc_fpregs.fp_x, curpcb->pcb_x,
421                     sizeof(mcp->mc_fpregs));
422                 mcp->mc_fpregs.fp_fcsr = curpcb->pcb_fcsr;
423                 mcp->mc_fpregs.fp_flags = curpcb->pcb_fpflags;
424                 mcp->mc_flags |= _MC_FP_VALID;
425         }
426
427         critical_exit();
428 #endif
429 }
430
431 static void
432 set_fpcontext(struct thread *td, mcontext_t *mcp)
433 {
434 #ifdef FPE
435         struct pcb *curpcb;
436 #endif
437
438         td->td_frame->tf_sstatus &= ~SSTATUS_FS_MASK;
439         td->td_frame->tf_sstatus |= SSTATUS_FS_OFF;
440
441 #ifdef FPE
442         critical_enter();
443
444         if ((mcp->mc_flags & _MC_FP_VALID) != 0) {
445                 curpcb = curthread->td_pcb;
446                 /* FPE usage is enabled, override registers. */
447                 memcpy(curpcb->pcb_x, mcp->mc_fpregs.fp_x,
448                     sizeof(mcp->mc_fpregs));
449                 curpcb->pcb_fcsr = mcp->mc_fpregs.fp_fcsr;
450                 curpcb->pcb_fpflags = mcp->mc_fpregs.fp_flags & PCB_FP_USERMASK;
451                 td->td_frame->tf_sstatus |= SSTATUS_FS_CLEAN;
452         }
453
454         critical_exit();
455 #endif
456 }
457
458 void
459 cpu_idle(int busy)
460 {
461
462         spinlock_enter();
463         if (!busy)
464                 cpu_idleclock();
465         if (!sched_runnable())
466                 __asm __volatile(
467                     "fence \n"
468                     "wfi   \n");
469         if (!busy)
470                 cpu_activeclock();
471         spinlock_exit();
472 }
473
474 void
475 cpu_halt(void)
476 {
477
478         /*
479          * Try to power down using the HSM SBI extension and fall back to a
480          * simple wfi loop.
481          */
482         intr_disable();
483         if (sbi_probe_extension(SBI_EXT_ID_HSM) != 0)
484                 sbi_hsm_hart_stop();
485         for (;;)
486                 __asm __volatile("wfi");
487         /* NOTREACHED */
488 }
489
490 /*
491  * Flush the D-cache for non-DMA I/O so that the I-cache can
492  * be made coherent later.
493  */
494 void
495 cpu_flush_dcache(void *ptr, size_t len)
496 {
497
498         /* TBD */
499 }
500
501 /* Get current clock frequency for the given CPU ID. */
502 int
503 cpu_est_clockrate(int cpu_id, uint64_t *rate)
504 {
505
506         panic("cpu_est_clockrate");
507 }
508
509 void
510 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
511 {
512 }
513
514 void
515 spinlock_enter(void)
516 {
517         struct thread *td;
518         register_t reg;
519
520         td = curthread;
521         if (td->td_md.md_spinlock_count == 0) {
522                 reg = intr_disable();
523                 td->td_md.md_spinlock_count = 1;
524                 td->td_md.md_saved_sstatus_ie = reg;
525                 critical_enter();
526         } else
527                 td->td_md.md_spinlock_count++;
528 }
529
530 void
531 spinlock_exit(void)
532 {
533         struct thread *td;
534         register_t sstatus_ie;
535
536         td = curthread;
537         sstatus_ie = td->td_md.md_saved_sstatus_ie;
538         td->td_md.md_spinlock_count--;
539         if (td->td_md.md_spinlock_count == 0) {
540                 critical_exit();
541                 intr_restore(sstatus_ie);
542         }
543 }
544
545 #ifndef _SYS_SYSPROTO_H_
546 struct sigreturn_args {
547         ucontext_t *ucp;
548 };
549 #endif
550
551 int
552 sys_sigreturn(struct thread *td, struct sigreturn_args *uap)
553 {
554         ucontext_t uc;
555         int error;
556
557         if (copyin(uap->sigcntxp, &uc, sizeof(uc)))
558                 return (EFAULT);
559
560         error = set_mcontext(td, &uc.uc_mcontext);
561         if (error != 0)
562                 return (error);
563
564         /* Restore signal mask. */
565         kern_sigprocmask(td, SIG_SETMASK, &uc.uc_sigmask, NULL, 0);
566
567         return (EJUSTRETURN);
568 }
569
570 /*
571  * Construct a PCB from a trapframe. This is called from kdb_trap() where
572  * we want to start a backtrace from the function that caused us to enter
573  * the debugger. We have the context in the trapframe, but base the trace
574  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
575  * enough for a backtrace.
576  */
577 void
578 makectx(struct trapframe *tf, struct pcb *pcb)
579 {
580
581         memcpy(pcb->pcb_s, tf->tf_s, sizeof(tf->tf_s));
582
583         pcb->pcb_ra = tf->tf_sepc;
584         pcb->pcb_sp = tf->tf_sp;
585         pcb->pcb_gp = tf->tf_gp;
586         pcb->pcb_tp = tf->tf_tp;
587 }
588
589 void
590 sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
591 {
592         struct sigframe *fp, frame;
593         struct sysentvec *sysent;
594         struct trapframe *tf;
595         struct sigacts *psp;
596         struct thread *td;
597         struct proc *p;
598         int onstack;
599         int sig;
600
601         td = curthread;
602         p = td->td_proc;
603         PROC_LOCK_ASSERT(p, MA_OWNED);
604
605         sig = ksi->ksi_signo;
606         psp = p->p_sigacts;
607         mtx_assert(&psp->ps_mtx, MA_OWNED);
608
609         tf = td->td_frame;
610         onstack = sigonstack(tf->tf_sp);
611
612         CTR4(KTR_SIG, "sendsig: td=%p (%s) catcher=%p sig=%d", td, p->p_comm,
613             catcher, sig);
614
615         /* Allocate and validate space for the signal handler context. */
616         if ((td->td_pflags & TDP_ALTSTACK) != 0 && !onstack &&
617             SIGISMEMBER(psp->ps_sigonstack, sig)) {
618                 fp = (struct sigframe *)((uintptr_t)td->td_sigstk.ss_sp +
619                     td->td_sigstk.ss_size);
620         } else {
621                 fp = (struct sigframe *)td->td_frame->tf_sp;
622         }
623
624         /* Make room, keeping the stack aligned */
625         fp--;
626         fp = (struct sigframe *)STACKALIGN(fp);
627
628         /* Fill in the frame to copy out */
629         bzero(&frame, sizeof(frame));
630         get_mcontext(td, &frame.sf_uc.uc_mcontext, 0);
631         frame.sf_si = ksi->ksi_info;
632         frame.sf_uc.uc_sigmask = *mask;
633         frame.sf_uc.uc_stack = td->td_sigstk;
634         frame.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK) != 0 ?
635             (onstack ? SS_ONSTACK : 0) : SS_DISABLE;
636         mtx_unlock(&psp->ps_mtx);
637         PROC_UNLOCK(td->td_proc);
638
639         /* Copy the sigframe out to the user's stack. */
640         if (copyout(&frame, fp, sizeof(*fp)) != 0) {
641                 /* Process has trashed its stack. Kill it. */
642                 CTR2(KTR_SIG, "sendsig: sigexit td=%p fp=%p", td, fp);
643                 PROC_LOCK(p);
644                 sigexit(td, SIGILL);
645         }
646
647         tf->tf_a[0] = sig;
648         tf->tf_a[1] = (register_t)&fp->sf_si;
649         tf->tf_a[2] = (register_t)&fp->sf_uc;
650
651         tf->tf_sepc = (register_t)catcher;
652         tf->tf_sp = (register_t)fp;
653
654         sysent = p->p_sysent;
655         if (sysent->sv_sigcode_base != 0)
656                 tf->tf_ra = (register_t)sysent->sv_sigcode_base;
657         else
658                 tf->tf_ra = (register_t)(sysent->sv_psstrings -
659                     *(sysent->sv_szsigcode));
660
661         CTR3(KTR_SIG, "sendsig: return td=%p pc=%#x sp=%#x", td, tf->tf_sepc,
662             tf->tf_sp);
663
664         PROC_LOCK(p);
665         mtx_lock(&psp->ps_mtx);
666 }
667
668 static void
669 init_proc0(vm_offset_t kstack)
670 {
671         struct pcpu *pcpup;
672
673         pcpup = &__pcpu[0];
674
675         proc_linkup0(&proc0, &thread0);
676         thread0.td_kstack = kstack;
677         thread0.td_kstack_pages = KSTACK_PAGES;
678         thread0.td_pcb = (struct pcb *)(thread0.td_kstack +
679             thread0.td_kstack_pages * PAGE_SIZE) - 1;
680         thread0.td_pcb->pcb_fpflags = 0;
681         thread0.td_frame = &proc0_tf;
682         pcpup->pc_curpcb = thread0.td_pcb;
683 }
684
685 #ifdef FDT
686 static void
687 try_load_dtb(caddr_t kmdp)
688 {
689         vm_offset_t dtbp;
690
691         dtbp = MD_FETCH(kmdp, MODINFOMD_DTBP, vm_offset_t);
692
693 #if defined(FDT_DTB_STATIC)
694         /*
695          * In case the device tree blob was not retrieved (from metadata) try
696          * to use the statically embedded one.
697          */
698         if (dtbp == (vm_offset_t)NULL)
699                 dtbp = (vm_offset_t)&fdt_static_dtb;
700 #endif
701
702         if (dtbp == (vm_offset_t)NULL) {
703                 printf("ERROR loading DTB\n");
704                 return;
705         }
706
707         if (OF_install(OFW_FDT, 0) == FALSE)
708                 panic("Cannot install FDT");
709
710         if (OF_init((void *)dtbp) != 0)
711                 panic("OF_init failed with the found device tree");
712 }
713 #endif
714
715 static void
716 cache_setup(void)
717 {
718
719         /* TODO */
720
721         dcache_line_size = 0;
722         icache_line_size = 0;
723         idcache_line_size = 0;
724 }
725
726 /*
727  * Fake up a boot descriptor table.
728  */
729 static void
730 fake_preload_metadata(struct riscv_bootparams *rvbp)
731 {
732         static uint32_t fake_preload[48];
733         vm_offset_t lastaddr;
734         size_t fake_size, dtb_size;
735
736 #define PRELOAD_PUSH_VALUE(type, value) do {                    \
737         *(type *)((char *)fake_preload + fake_size) = (value);  \
738         fake_size += sizeof(type);                              \
739 } while (0)
740
741 #define PRELOAD_PUSH_STRING(str) do {                           \
742         uint32_t ssize;                                         \
743         ssize = strlen(str) + 1;                                \
744         PRELOAD_PUSH_VALUE(uint32_t, ssize);                    \
745         strcpy(((char *)fake_preload + fake_size), str);        \
746         fake_size += ssize;                                     \
747         fake_size = roundup(fake_size, sizeof(u_long));         \
748 } while (0)
749
750         fake_size = 0;
751         lastaddr = (vm_offset_t)&end;
752
753         PRELOAD_PUSH_VALUE(uint32_t, MODINFO_NAME);
754         PRELOAD_PUSH_STRING("kernel");
755         PRELOAD_PUSH_VALUE(uint32_t, MODINFO_TYPE);
756         PRELOAD_PUSH_STRING("elf kernel");
757
758         PRELOAD_PUSH_VALUE(uint32_t, MODINFO_ADDR);
759         PRELOAD_PUSH_VALUE(uint32_t, sizeof(vm_offset_t));
760         PRELOAD_PUSH_VALUE(uint64_t, KERNBASE);
761
762         PRELOAD_PUSH_VALUE(uint32_t, MODINFO_SIZE);
763         PRELOAD_PUSH_VALUE(uint32_t, sizeof(size_t));
764         PRELOAD_PUSH_VALUE(uint64_t, (size_t)((vm_offset_t)&end - KERNBASE));
765
766         /* Copy the DTB to KVA space. */
767         lastaddr = roundup(lastaddr, sizeof(int));
768         PRELOAD_PUSH_VALUE(uint32_t, MODINFO_METADATA | MODINFOMD_DTBP);
769         PRELOAD_PUSH_VALUE(uint32_t, sizeof(vm_offset_t));
770         PRELOAD_PUSH_VALUE(vm_offset_t, lastaddr);
771         dtb_size = fdt_totalsize(rvbp->dtbp_virt);
772         memmove((void *)lastaddr, (const void *)rvbp->dtbp_virt, dtb_size);
773         lastaddr = roundup(lastaddr + dtb_size, sizeof(int));
774
775         PRELOAD_PUSH_VALUE(uint32_t, MODINFO_METADATA | MODINFOMD_KERNEND);
776         PRELOAD_PUSH_VALUE(uint32_t, sizeof(vm_offset_t));
777         PRELOAD_PUSH_VALUE(vm_offset_t, lastaddr);
778
779         PRELOAD_PUSH_VALUE(uint32_t, MODINFO_METADATA | MODINFOMD_HOWTO);
780         PRELOAD_PUSH_VALUE(uint32_t, sizeof(int));
781         PRELOAD_PUSH_VALUE(int, RB_VERBOSE);
782
783         /* End marker */
784         PRELOAD_PUSH_VALUE(uint32_t, 0);
785         PRELOAD_PUSH_VALUE(uint32_t, 0);
786         preload_metadata = (caddr_t)fake_preload;
787
788         /* Check if bootloader clobbered part of the kernel with the DTB. */
789         KASSERT(rvbp->dtbp_phys + dtb_size <= rvbp->kern_phys ||
790                 rvbp->dtbp_phys >= rvbp->kern_phys + (lastaddr - KERNBASE),
791             ("FDT (%lx-%lx) and kernel (%lx-%lx) overlap", rvbp->dtbp_phys,
792                 rvbp->dtbp_phys + dtb_size, rvbp->kern_phys,
793                 rvbp->kern_phys + (lastaddr - KERNBASE)));
794         KASSERT(fake_size < sizeof(fake_preload),
795             ("Too many fake_preload items"));
796
797         if (boothowto & RB_VERBOSE)
798                 printf("FDT phys (%lx-%lx), kernel phys (%lx-%lx)\n",
799                     rvbp->dtbp_phys, rvbp->dtbp_phys + dtb_size,
800                     rvbp->kern_phys, rvbp->kern_phys + (lastaddr - KERNBASE));
801 }
802
803 static vm_offset_t
804 parse_metadata(void)
805 {
806         caddr_t kmdp;
807         vm_offset_t lastaddr;
808 #ifdef DDB
809         vm_offset_t ksym_start, ksym_end;
810 #endif
811         char *kern_envp;
812
813         /* Find the kernel address */
814         kmdp = preload_search_by_type("elf kernel");
815         if (kmdp == NULL)
816                 kmdp = preload_search_by_type("elf64 kernel");
817         KASSERT(kmdp != NULL, ("No preload metadata found!"));
818
819         /* Read the boot metadata */
820         boothowto = MD_FETCH(kmdp, MODINFOMD_HOWTO, int);
821         lastaddr = MD_FETCH(kmdp, MODINFOMD_KERNEND, vm_offset_t);
822         kern_envp = MD_FETCH(kmdp, MODINFOMD_ENVP, char *);
823         if (kern_envp != NULL)
824                 init_static_kenv(kern_envp, 0);
825 #ifdef DDB
826         ksym_start = MD_FETCH(kmdp, MODINFOMD_SSYM, uintptr_t);
827         ksym_end = MD_FETCH(kmdp, MODINFOMD_ESYM, uintptr_t);
828         db_fetch_ksymtab(ksym_start, ksym_end);
829 #endif
830 #ifdef FDT
831         try_load_dtb(kmdp);
832 #endif
833         return (lastaddr);
834 }
835
836 void
837 initriscv(struct riscv_bootparams *rvbp)
838 {
839         struct mem_region mem_regions[FDT_MEM_REGIONS];
840         struct pcpu *pcpup;
841         int mem_regions_sz;
842         vm_offset_t lastaddr;
843         vm_size_t kernlen;
844 #ifdef FDT
845         phandle_t chosen;
846         uint32_t hart;
847 #endif
848
849         TSRAW(&thread0, TS_ENTER, __func__, NULL);
850
851         /* Set the pcpu data, this is needed by pmap_bootstrap */
852         pcpup = &__pcpu[0];
853         pcpu_init(pcpup, 0, sizeof(struct pcpu));
854
855         /* Set the pcpu pointer */
856         __asm __volatile("mv tp, %0" :: "r"(pcpup));
857
858         PCPU_SET(curthread, &thread0);
859
860         /* Initialize SBI interface. */
861         sbi_init();
862
863         /* Parse the boot metadata. */
864         if (rvbp->modulep != 0) {
865                 preload_metadata = (caddr_t)rvbp->modulep;
866         } else {
867                 fake_preload_metadata(rvbp);
868         }
869         lastaddr = parse_metadata();
870
871 #ifdef FDT
872         /*
873          * Look for the boot hart ID. This was either passed in directly from
874          * the SBI firmware and handled by locore, or was stored in the device
875          * tree by an earlier boot stage.
876          */
877         chosen = OF_finddevice("/chosen");
878         if (OF_getencprop(chosen, "boot-hartid", &hart, sizeof(hart)) != -1) {
879                 boot_hart = hart;
880         }
881 #endif
882         if (boot_hart == BOOT_HART_INVALID) {
883                 panic("Boot hart ID was not properly set");
884         }
885         pcpup->pc_hart = boot_hart;
886
887 #ifdef FDT
888         /*
889          * Exclude reserved memory specified by the device tree. Typically,
890          * this contains an entry for memory used by the runtime SBI firmware.
891          */
892         if (fdt_get_reserved_mem(mem_regions, &mem_regions_sz) == 0) {
893                 physmem_exclude_regions(mem_regions, mem_regions_sz,
894                     EXFLAG_NODUMP | EXFLAG_NOALLOC);
895         }
896
897         /* Grab physical memory regions information from device tree. */
898         if (fdt_get_mem_regions(mem_regions, &mem_regions_sz, NULL) != 0) {
899                 panic("Cannot get physical memory regions");
900         }
901         physmem_hardware_regions(mem_regions, mem_regions_sz);
902 #endif
903
904         /* Do basic tuning, hz etc */
905         init_param1();
906
907         cache_setup();
908
909         /* Bootstrap enough of pmap to enter the kernel proper */
910         kernlen = (lastaddr - KERNBASE);
911         pmap_bootstrap(rvbp->kern_l1pt, rvbp->kern_phys, kernlen);
912
913 #ifdef FDT
914         /*
915          * XXX: Exclude the lowest 2MB of physical memory, if it hasn't been
916          * already, as this area is assumed to contain the SBI firmware. This
917          * is a little fragile, but it is consistent with the platforms we
918          * support so far.
919          *
920          * TODO: remove this when the all regular booting methods properly
921          * report their reserved memory in the device tree.
922          */
923         if (mem_regions[0].mr_start == physmap[0]) {
924                 physmem_exclude_region(mem_regions[0].mr_start, L2_SIZE,
925                     EXFLAG_NODUMP | EXFLAG_NOALLOC);
926         }
927 #endif
928         physmem_init_kernel_globals();
929
930         /* Establish static device mappings */
931         devmap_bootstrap(0, NULL);
932
933         cninit();
934
935         init_proc0(rvbp->kern_stack);
936
937         msgbufinit(msgbufp, msgbufsize);
938         mutex_init();
939         init_param2(physmem);
940         kdb_init();
941
942         if (boothowto & RB_VERBOSE)
943                 physmem_print_tables();
944
945         early_boot = 0;
946
947         TSEXIT();
948 }
949
950 #undef bzero
951 void
952 bzero(void *buf, size_t len)
953 {
954         uint8_t *p;
955
956         p = buf;
957         while(len-- > 0)
958                 *p++ = 0;
959 }