]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/ia64/ia64/machdep.c
Make sure bus space accesses use unorder memory loads and stores.
[FreeBSD/FreeBSD.git] / sys / ia64 / ia64 / machdep.c
1 /*-
2  * Copyright (c) 2003,2004 Marcel Moolenaar
3  * Copyright (c) 2000,2001 Doug Rabson
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 #include "opt_compat.h"
32 #include "opt_ddb.h"
33 #include "opt_kstack_pages.h"
34 #include "opt_msgbuf.h"
35 #include "opt_sched.h"
36
37 #include <sys/param.h>
38 #include <sys/proc.h>
39 #include <sys/systm.h>
40 #include <sys/bio.h>
41 #include <sys/buf.h>
42 #include <sys/bus.h>
43 #include <sys/cons.h>
44 #include <sys/cpu.h>
45 #include <sys/eventhandler.h>
46 #include <sys/exec.h>
47 #include <sys/imgact.h>
48 #include <sys/kdb.h>
49 #include <sys/kernel.h>
50 #include <sys/linker.h>
51 #include <sys/lock.h>
52 #include <sys/malloc.h>
53 #include <sys/mbuf.h>
54 #include <sys/msgbuf.h>
55 #include <sys/pcpu.h>
56 #include <sys/ptrace.h>
57 #include <sys/random.h>
58 #include <sys/reboot.h>
59 #include <sys/sched.h>
60 #include <sys/signalvar.h>
61 #include <sys/syscall.h>
62 #include <sys/sysctl.h>
63 #include <sys/sysproto.h>
64 #include <sys/ucontext.h>
65 #include <sys/uio.h>
66 #include <sys/uuid.h>
67 #include <sys/vmmeter.h>
68 #include <sys/vnode.h>
69
70 #include <ddb/ddb.h>
71
72 #include <net/netisr.h>
73
74 #include <vm/vm.h>
75 #include <vm/vm_extern.h>
76 #include <vm/vm_kern.h>
77 #include <vm/vm_page.h>
78 #include <vm/vm_map.h>
79 #include <vm/vm_object.h>
80 #include <vm/vm_pager.h>
81
82 #include <machine/bootinfo.h>
83 #include <machine/clock.h>
84 #include <machine/cpu.h>
85 #include <machine/efi.h>
86 #include <machine/elf.h>
87 #include <machine/fpu.h>
88 #include <machine/mca.h>
89 #include <machine/md_var.h>
90 #include <machine/mutex.h>
91 #include <machine/pal.h>
92 #include <machine/pcb.h>
93 #include <machine/reg.h>
94 #include <machine/sal.h>
95 #include <machine/sigframe.h>
96 #ifdef SMP
97 #include <machine/smp.h>
98 #endif
99 #include <machine/unwind.h>
100 #include <machine/vmparam.h>
101
102 #include <i386/include/specialreg.h>
103
104 u_int64_t processor_frequency;
105 u_int64_t bus_frequency;
106 u_int64_t itc_frequency;
107 int cold = 1;
108
109 u_int64_t pa_bootinfo;
110 struct bootinfo bootinfo;
111
112 struct pcpu pcpu0;
113
114 extern u_int64_t kernel_text[], _end[];
115
116 extern u_int64_t ia64_gateway_page[];
117 extern u_int64_t break_sigtramp[];
118 extern u_int64_t epc_sigtramp[];
119
120 struct fpswa_iface *fpswa_iface;
121
122 u_int64_t ia64_pal_base;
123 u_int64_t ia64_port_base;
124
125 static int ia64_sync_icache_needed;
126
127 char machine[] = MACHINE;
128 SYSCTL_STRING(_hw, HW_MACHINE, machine, CTLFLAG_RD, machine, 0, "");
129
130 static char cpu_model[64];
131 SYSCTL_STRING(_hw, HW_MODEL, model, CTLFLAG_RD, cpu_model, 0,
132     "The CPU model name");
133
134 static char cpu_family[64];
135 SYSCTL_STRING(_hw, OID_AUTO, family, CTLFLAG_RD, cpu_family, 0,
136     "The CPU family name");
137
138 #ifdef DDB
139 extern vm_offset_t ksym_start, ksym_end;
140 #endif
141
142
143 struct msgbuf *msgbufp = NULL;
144
145 /* Other subsystems (e.g., ACPI) can hook this later. */
146 void (*cpu_idle_hook)(void) = NULL;
147
148 long Maxmem = 0;
149 long realmem = 0;
150
151 #define PHYSMAP_SIZE    (2 * VM_PHYSSEG_MAX)
152
153 vm_paddr_t phys_avail[PHYSMAP_SIZE + 2];
154
155 /* must be 2 less so 0 0 can signal end of chunks */
156 #define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(vm_offset_t)) - 2)
157
158 struct kva_md_info kmi;
159
160 #define Mhz     1000000L
161 #define Ghz     (1000L*Mhz)
162
163 static void
164 identifycpu(void)
165 {
166         char vendor[17];
167         char *family_name, *model_name;
168         u_int64_t features, tmp;
169         int number, revision, model, family, archrev;
170
171         /*
172          * Assumes little-endian.
173          */
174         *(u_int64_t *) &vendor[0] = ia64_get_cpuid(0);
175         *(u_int64_t *) &vendor[8] = ia64_get_cpuid(1);
176         vendor[16] = '\0';
177
178         tmp = ia64_get_cpuid(3);
179         number = (tmp >> 0) & 0xff;
180         revision = (tmp >> 8) & 0xff;
181         model = (tmp >> 16) & 0xff;
182         family = (tmp >> 24) & 0xff;
183         archrev = (tmp >> 32) & 0xff;
184
185         family_name = model_name = "unknown";
186         switch (family) {
187         case 0x07:
188                 family_name = "Itanium";
189                 model_name = "Merced";
190                 break;
191         case 0x1f:
192                 family_name = "Itanium 2";
193                 switch (model) {
194                 case 0x00:
195                         model_name = "McKinley";
196                         break;
197                 case 0x01:
198                         /*
199                          * Deerfield is a low-voltage variant based on the
200                          * Madison core. We need circumstantial evidence
201                          * (i.e. the clock frequency) to identify those.
202                          * Allow for roughly 1% error margin.
203                          */
204                         tmp = processor_frequency >> 7;
205                         if ((processor_frequency - tmp) < 1*Ghz &&
206                             (processor_frequency + tmp) >= 1*Ghz)
207                                 model_name = "Deerfield";
208                         else
209                                 model_name = "Madison";
210                         break;
211                 case 0x02:
212                         model_name = "Madison II";
213                         break;
214                 }
215                 break;
216         case 0x20:
217                 ia64_sync_icache_needed = 1;
218
219                 family_name = "Itanium 2";
220                 switch (model) {
221                 case 0x00:
222                         model_name = "Montecito";
223                         break;
224                 }
225                 break;
226         }
227         snprintf(cpu_family, sizeof(cpu_family), "%s", family_name);
228         snprintf(cpu_model, sizeof(cpu_model), "%s", model_name);
229
230         features = ia64_get_cpuid(4);
231
232         printf("CPU: %s (", model_name);
233         if (processor_frequency) {
234                 printf("%ld.%02ld-Mhz ",
235                     (processor_frequency + 4999) / Mhz,
236                     ((processor_frequency + 4999) / (Mhz/100)) % 100);
237         }
238         printf("%s)\n", family_name);
239         printf("  Origin = \"%s\"  Revision = %d\n", vendor, revision);
240         printf("  Features = 0x%b\n", (u_int32_t) features,
241             "\020"
242             "\001LB"    /* long branch (brl) instruction. */
243             "\002SD"    /* Spontaneous deferral. */
244             "\003AO"    /* 16-byte atomic operations (ld, st, cmpxchg). */ );
245 }
246
247 static void
248 cpu_startup(void *dummy)
249 {
250         char nodename[16];
251         struct pcpu *pc;
252         struct pcpu_stats *pcs;
253
254         /*
255          * Good {morning,afternoon,evening,night}.
256          */
257         identifycpu();
258
259 #ifdef PERFMON
260         perfmon_init();
261 #endif
262         printf("real memory  = %ld (%ld MB)\n", ia64_ptob(Maxmem),
263             ia64_ptob(Maxmem) / 1048576);
264         realmem = Maxmem;
265
266         /*
267          * Display any holes after the first chunk of extended memory.
268          */
269         if (bootverbose) {
270                 int indx;
271
272                 printf("Physical memory chunk(s):\n");
273                 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
274                         long size1 = phys_avail[indx + 1] - phys_avail[indx];
275
276                         printf("0x%08lx - 0x%08lx, %ld bytes (%ld pages)\n",
277                             phys_avail[indx], phys_avail[indx + 1] - 1, size1,
278                             size1 >> PAGE_SHIFT);
279                 }
280         }
281
282         vm_ksubmap_init(&kmi);
283
284         printf("avail memory = %ld (%ld MB)\n", ptoa(cnt.v_free_count),
285             ptoa(cnt.v_free_count) / 1048576);
286  
287         if (fpswa_iface == NULL)
288                 printf("Warning: no FPSWA package supplied\n");
289         else
290                 printf("FPSWA Revision = 0x%lx, Entry = %p\n",
291                     (long)fpswa_iface->if_rev, (void *)fpswa_iface->if_fpswa);
292
293         /*
294          * Set up buffers, so they can be used to read disk labels.
295          */
296         bufinit();
297         vm_pager_bufferinit();
298
299         /*
300          * Traverse the MADT to discover IOSAPIC and Local SAPIC
301          * information.
302          */
303         ia64_probe_sapics();
304         ia64_mca_init();
305
306         /*
307          * Create sysctl tree for per-CPU information.
308          */
309         SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {
310                 pcs = &pc->pc_stats;
311                 snprintf(nodename, sizeof(nodename), "cpu%u", pc->pc_cpuid);
312                 sysctl_ctx_init(&pcs->pcs_sysctl_ctx);
313                 pcs->pcs_sysctl_tree = SYSCTL_ADD_NODE(&pcs->pcs_sysctl_ctx,
314                     SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO, nodename,
315                     CTLFLAG_RD, NULL, "");
316                 if (pcs->pcs_sysctl_tree == NULL)
317                         continue;
318
319                 SYSCTL_ADD_ULONG(&pcs->pcs_sysctl_ctx,
320                     SYSCTL_CHILDREN(pcs->pcs_sysctl_tree), OID_AUTO,
321                     "nasts", CTLFLAG_RD, &pcs->pcs_nasts,
322                     "Number of IPI_AST interrupts");
323
324                 SYSCTL_ADD_ULONG(&pcs->pcs_sysctl_ctx,
325                     SYSCTL_CHILDREN(pcs->pcs_sysctl_tree), OID_AUTO,
326                     "nclks", CTLFLAG_RD, &pcs->pcs_nclks,
327                     "Number of clock interrupts");
328
329                 SYSCTL_ADD_ULONG(&pcs->pcs_sysctl_ctx,
330                     SYSCTL_CHILDREN(pcs->pcs_sysctl_tree), OID_AUTO,
331                     "nextints", CTLFLAG_RD, &pcs->pcs_nextints,
332                     "Number of ExtINT interrupts");
333
334                 SYSCTL_ADD_ULONG(&pcs->pcs_sysctl_ctx,
335                     SYSCTL_CHILDREN(pcs->pcs_sysctl_tree), OID_AUTO,
336                     "nhighfps", CTLFLAG_RD, &pcs->pcs_nhighfps,
337                     "Number of IPI_HIGH_FP interrupts");
338
339                 SYSCTL_ADD_ULONG(&pcs->pcs_sysctl_ctx,
340                     SYSCTL_CHILDREN(pcs->pcs_sysctl_tree), OID_AUTO,
341                     "nhwints", CTLFLAG_RD, &pcs->pcs_nhwints,
342                     "Number of hardware (device) interrupts");
343
344                 SYSCTL_ADD_ULONG(&pcs->pcs_sysctl_ctx,
345                     SYSCTL_CHILDREN(pcs->pcs_sysctl_tree), OID_AUTO,
346                     "npreempts", CTLFLAG_RD, &pcs->pcs_npreempts,
347                     "Number of IPI_PREEMPT interrupts");
348
349                 SYSCTL_ADD_ULONG(&pcs->pcs_sysctl_ctx,
350                     SYSCTL_CHILDREN(pcs->pcs_sysctl_tree), OID_AUTO,
351                     "nrdvs", CTLFLAG_RD, &pcs->pcs_nrdvs,
352                     "Number of IPI_RENDEZVOUS interrupts");
353
354                 SYSCTL_ADD_ULONG(&pcs->pcs_sysctl_ctx,
355                     SYSCTL_CHILDREN(pcs->pcs_sysctl_tree), OID_AUTO,
356                     "nstops", CTLFLAG_RD, &pcs->pcs_nstops,
357                     "Number of IPI_STOP interrupts");
358
359                 SYSCTL_ADD_ULONG(&pcs->pcs_sysctl_ctx,
360                     SYSCTL_CHILDREN(pcs->pcs_sysctl_tree), OID_AUTO,
361                     "nstrays", CTLFLAG_RD, &pcs->pcs_nstrays,
362                     "Number of stray vectors");
363         }
364 }
365 SYSINIT(cpu_startup, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
366
367 void
368 cpu_boot(int howto)
369 {
370
371         efi_reset_system();
372 }
373
374 void
375 cpu_flush_dcache(void *ptr, size_t len)
376 {
377         vm_offset_t lim, va;
378
379         va = (uintptr_t)ptr & ~31;
380         lim = (uintptr_t)ptr + len;
381         while (va < lim) {
382                 ia64_fc(va);
383                 va += 32;
384         }
385
386         ia64_srlz_d();
387 }
388
389 /* Get current clock frequency for the given cpu id. */
390 int
391 cpu_est_clockrate(int cpu_id, uint64_t *rate)
392 {
393
394         if (pcpu_find(cpu_id) == NULL || rate == NULL)
395                 return (EINVAL);
396         *rate = processor_frequency;
397         return (0);
398 }
399
400 void
401 cpu_halt()
402 {
403
404         efi_reset_system();
405 }
406
407 void
408 cpu_idle(int busy)
409 {
410         struct ia64_pal_result res;
411
412         if (cpu_idle_hook != NULL)
413                 (*cpu_idle_hook)();
414         else
415                 res = ia64_call_pal_static(PAL_HALT_LIGHT, 0, 0, 0);
416 }
417
418 int
419 cpu_idle_wakeup(int cpu)
420 {
421
422         return (0);
423 }
424
425 void
426 cpu_reset()
427 {
428
429         cpu_boot(0);
430 }
431
432 void
433 cpu_switch(struct thread *old, struct thread *new, struct mtx *mtx)
434 {
435         struct pcb *oldpcb, *newpcb;
436
437         oldpcb = old->td_pcb;
438 #ifdef COMPAT_IA32
439         ia32_savectx(oldpcb);
440 #endif
441         if (PCPU_GET(fpcurthread) == old)
442                 old->td_frame->tf_special.psr |= IA64_PSR_DFH;
443         if (!savectx(oldpcb)) {
444                 old->td_lock = mtx;
445 #if defined(SCHED_ULE) && defined(SMP)
446                 /* td_lock is volatile */
447                 while (new->td_lock == &blocked_lock)
448                         ;
449 #endif
450                 newpcb = new->td_pcb;
451                 oldpcb->pcb_current_pmap =
452                     pmap_switch(newpcb->pcb_current_pmap);
453                 PCPU_SET(curthread, new);
454 #ifdef COMPAT_IA32
455                 ia32_restorectx(newpcb);
456 #endif
457                 if (PCPU_GET(fpcurthread) == new)
458                         new->td_frame->tf_special.psr &= ~IA64_PSR_DFH;
459                 restorectx(newpcb);
460                 /* We should not get here. */
461                 panic("cpu_switch: restorectx() returned");
462                 /* NOTREACHED */
463         }
464 }
465
466 void
467 cpu_throw(struct thread *old __unused, struct thread *new)
468 {
469         struct pcb *newpcb;
470
471         newpcb = new->td_pcb;
472         (void)pmap_switch(newpcb->pcb_current_pmap);
473         PCPU_SET(curthread, new);
474 #ifdef COMPAT_IA32
475         ia32_restorectx(newpcb);
476 #endif
477         restorectx(newpcb);
478         /* We should not get here. */
479         panic("cpu_throw: restorectx() returned");
480         /* NOTREACHED */
481 }
482
483 void
484 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
485 {
486
487         /*
488          * Set pc_acpi_id to "uninitialized".
489          * See sys/dev/acpica/acpi_cpu.c
490          */
491         pcpu->pc_acpi_id = 0xffffffff;
492 }
493
494 void
495 spinlock_enter(void)
496 {
497         struct thread *td;
498
499         td = curthread;
500         if (td->td_md.md_spinlock_count == 0)
501                 td->td_md.md_saved_intr = intr_disable();
502         td->td_md.md_spinlock_count++;
503         critical_enter();
504 }
505
506 void
507 spinlock_exit(void)
508 {
509         struct thread *td;
510
511         td = curthread;
512         critical_exit();
513         td->td_md.md_spinlock_count--;
514         if (td->td_md.md_spinlock_count == 0)
515                 intr_restore(td->td_md.md_saved_intr);
516 }
517
518 void
519 map_vhpt(uintptr_t vhpt)
520 {
521         pt_entry_t pte;
522         uint64_t psr;
523
524         pte = PTE_PRESENT | PTE_MA_WB | PTE_ACCESSED | PTE_DIRTY |
525             PTE_PL_KERN | PTE_AR_RW;
526         pte |= vhpt & PTE_PPN_MASK;
527
528         __asm __volatile("ptr.d %0,%1" :: "r"(vhpt),
529             "r"(IA64_ID_PAGE_SHIFT<<2));
530
531         __asm __volatile("mov   %0=psr" : "=r"(psr));
532         __asm __volatile("rsm   psr.ic|psr.i");
533         ia64_srlz_i();
534         ia64_set_ifa(vhpt);
535         ia64_set_itir(IA64_ID_PAGE_SHIFT << 2);
536         ia64_srlz_d();
537         __asm __volatile("itr.d dtr[%0]=%1" :: "r"(2), "r"(pte));
538         __asm __volatile("mov   psr.l=%0" :: "r" (psr));
539         ia64_srlz_i();
540 }
541
542 void
543 map_pal_code(void)
544 {
545         pt_entry_t pte;
546         uint64_t psr;
547
548         if (ia64_pal_base == 0)
549                 return;
550
551         pte = PTE_PRESENT | PTE_MA_WB | PTE_ACCESSED | PTE_DIRTY |
552             PTE_PL_KERN | PTE_AR_RWX;
553         pte |= ia64_pal_base & PTE_PPN_MASK;
554
555         __asm __volatile("ptr.d %0,%1; ptr.i %0,%1" ::
556             "r"(IA64_PHYS_TO_RR7(ia64_pal_base)), "r"(IA64_ID_PAGE_SHIFT<<2));
557
558         __asm __volatile("mov   %0=psr" : "=r"(psr));
559         __asm __volatile("rsm   psr.ic|psr.i");
560         ia64_srlz_i();
561         ia64_set_ifa(IA64_PHYS_TO_RR7(ia64_pal_base));
562         ia64_set_itir(IA64_ID_PAGE_SHIFT << 2);
563         ia64_srlz_d();
564         __asm __volatile("itr.d dtr[%0]=%1" :: "r"(1), "r"(pte));
565         ia64_srlz_d();
566         __asm __volatile("itr.i itr[%0]=%1" :: "r"(1), "r"(pte));
567         __asm __volatile("mov   psr.l=%0" :: "r" (psr));
568         ia64_srlz_i();
569 }
570
571 void
572 map_gateway_page(void)
573 {
574         pt_entry_t pte;
575         uint64_t psr;
576
577         pte = PTE_PRESENT | PTE_MA_WB | PTE_ACCESSED | PTE_DIRTY |
578             PTE_PL_KERN | PTE_AR_X_RX;
579         pte |= (uint64_t)ia64_gateway_page & PTE_PPN_MASK;
580
581         __asm __volatile("ptr.d %0,%1; ptr.i %0,%1" ::
582             "r"(VM_MAX_ADDRESS), "r"(PAGE_SHIFT << 2));
583
584         __asm __volatile("mov   %0=psr" : "=r"(psr));
585         __asm __volatile("rsm   psr.ic|psr.i");
586         ia64_srlz_i();
587         ia64_set_ifa(VM_MAX_ADDRESS);
588         ia64_set_itir(PAGE_SHIFT << 2);
589         ia64_srlz_d();
590         __asm __volatile("itr.d dtr[%0]=%1" :: "r"(3), "r"(pte));
591         ia64_srlz_d();
592         __asm __volatile("itr.i itr[%0]=%1" :: "r"(3), "r"(pte));
593         __asm __volatile("mov   psr.l=%0" :: "r" (psr));
594         ia64_srlz_i();
595
596         /* Expose the mapping to userland in ar.k5 */
597         ia64_set_k5(VM_MAX_ADDRESS);
598 }
599
600 static void
601 calculate_frequencies(void)
602 {
603         struct ia64_sal_result sal;
604         struct ia64_pal_result pal;
605
606         sal = ia64_sal_entry(SAL_FREQ_BASE, 0, 0, 0, 0, 0, 0, 0);
607         pal = ia64_call_pal_static(PAL_FREQ_RATIOS, 0, 0, 0);
608
609         if (sal.sal_status == 0 && pal.pal_status == 0) {
610                 if (bootverbose) {
611                         printf("Platform clock frequency %ld Hz\n",
612                                sal.sal_result[0]);
613                         printf("Processor ratio %ld/%ld, Bus ratio %ld/%ld, "
614                                "ITC ratio %ld/%ld\n",
615                                pal.pal_result[0] >> 32,
616                                pal.pal_result[0] & ((1L << 32) - 1),
617                                pal.pal_result[1] >> 32,
618                                pal.pal_result[1] & ((1L << 32) - 1),
619                                pal.pal_result[2] >> 32,
620                                pal.pal_result[2] & ((1L << 32) - 1));
621                 }
622                 processor_frequency =
623                         sal.sal_result[0] * (pal.pal_result[0] >> 32)
624                         / (pal.pal_result[0] & ((1L << 32) - 1));
625                 bus_frequency =
626                         sal.sal_result[0] * (pal.pal_result[1] >> 32)
627                         / (pal.pal_result[1] & ((1L << 32) - 1));
628                 itc_frequency =
629                         sal.sal_result[0] * (pal.pal_result[2] >> 32)
630                         / (pal.pal_result[2] & ((1L << 32) - 1));
631         }
632 }
633
634 struct ia64_init_return
635 ia64_init(void)
636 {
637         struct ia64_init_return ret;
638         int phys_avail_cnt;
639         vm_offset_t kernstart, kernend;
640         vm_offset_t kernstartpfn, kernendpfn, pfn0, pfn1;
641         char *p;
642         struct efi_md *md;
643         int metadata_missing;
644
645         /* NO OUTPUT ALLOWED UNTIL FURTHER NOTICE */
646
647         /*
648          * TODO: Disable interrupts, floating point etc.
649          * Maybe flush cache and tlb
650          */
651         ia64_set_fpsr(IA64_FPSR_DEFAULT);
652
653         /*
654          * TODO: Get critical system information (if possible, from the
655          * information provided by the boot program).
656          */
657
658         /*
659          * pa_bootinfo is the physical address of the bootinfo block as
660          * passed to us by the loader and set in locore.s.
661          */
662         bootinfo = *(struct bootinfo *)(IA64_PHYS_TO_RR7(pa_bootinfo));
663
664         if (bootinfo.bi_magic != BOOTINFO_MAGIC || bootinfo.bi_version != 1) {
665                 bzero(&bootinfo, sizeof(bootinfo));
666                 bootinfo.bi_kernend = (vm_offset_t) round_page(_end);
667         }
668
669         /*
670          * Look for the I/O ports first - we need them for console
671          * probing.
672          */
673         for (md = efi_md_first(); md != NULL; md = efi_md_next(md)) {
674                 switch (md->md_type) {
675                 case EFI_MD_TYPE_IOPORT:
676                         ia64_port_base = IA64_PHYS_TO_RR6(md->md_phys);
677                         break;
678                 case EFI_MD_TYPE_PALCODE:
679                         ia64_pal_base = md->md_phys;
680                         break;
681                 }
682         }
683
684         metadata_missing = 0;
685         if (bootinfo.bi_modulep)
686                 preload_metadata = (caddr_t)bootinfo.bi_modulep;
687         else
688                 metadata_missing = 1;
689
690         if (envmode == 0 && bootinfo.bi_envp)
691                 kern_envp = (caddr_t)bootinfo.bi_envp;
692         else
693                 kern_envp = static_env;
694
695         /*
696          * Look at arguments passed to us and compute boothowto.
697          */
698         boothowto = bootinfo.bi_boothowto;
699
700         /*
701          * Catch case of boot_verbose set in environment.
702          */
703         if ((p = getenv("boot_verbose")) != NULL) {
704                 if (strcmp(p, "yes") == 0 || strcmp(p, "YES") == 0) {
705                         boothowto |= RB_VERBOSE;
706                 }
707                 freeenv(p);
708         }
709
710         if (boothowto & RB_VERBOSE)
711                 bootverbose = 1;
712
713         /*
714          * Find the beginning and end of the kernel.
715          */
716         kernstart = trunc_page(kernel_text);
717 #ifdef DDB
718         ksym_start = bootinfo.bi_symtab;
719         ksym_end = bootinfo.bi_esymtab;
720         kernend = (vm_offset_t)round_page(ksym_end);
721 #else
722         kernend = (vm_offset_t)round_page(_end);
723 #endif
724         /* But if the bootstrap tells us otherwise, believe it! */
725         if (bootinfo.bi_kernend)
726                 kernend = round_page(bootinfo.bi_kernend);
727
728         /*
729          * Setup the PCPU data for the bootstrap processor. It is needed
730          * by printf(). Also, since printf() has critical sections, we
731          * need to initialize at least pc_curthread.
732          */
733         pcpup = &pcpu0;
734         ia64_set_k4((u_int64_t)pcpup);
735         pcpu_init(pcpup, 0, sizeof(pcpu0));
736         dpcpu_init((void *)kernend, 0);
737         kernend += DPCPU_SIZE;
738         PCPU_SET(curthread, &thread0);
739
740         /*
741          * Initialize the console before we print anything out.
742          */
743         cninit();
744
745         /* OUTPUT NOW ALLOWED */
746
747         if (ia64_pal_base != 0) {
748                 ia64_pal_base &= ~IA64_ID_PAGE_MASK;
749                 /*
750                  * We use a TR to map the first 256M of memory - this might
751                  * cover the palcode too.
752                  */
753                 if (ia64_pal_base == 0)
754                         printf("PAL code mapped by the kernel's TR\n");
755         } else
756                 printf("PAL code not found\n");
757
758         /*
759          * Wire things up so we can call the firmware.
760          */
761         map_pal_code();
762         efi_boot_minimal(bootinfo.bi_systab);
763         ia64_sal_init();
764         calculate_frequencies();
765
766         if (metadata_missing)
767                 printf("WARNING: loader(8) metadata is missing!\n");
768
769         /* Get FPSWA interface */
770         fpswa_iface = (bootinfo.bi_fpswa == 0) ? NULL :
771             (struct fpswa_iface *)IA64_PHYS_TO_RR7(bootinfo.bi_fpswa);
772
773         /* Init basic tunables, including hz */
774         init_param1();
775
776         p = getenv("kernelname");
777         if (p) {
778                 strncpy(kernelname, p, sizeof(kernelname) - 1);
779                 freeenv(p);
780         }
781
782         kernstartpfn = atop(IA64_RR_MASK(kernstart));
783         kernendpfn = atop(IA64_RR_MASK(kernend));
784
785         /*
786          * Size the memory regions and load phys_avail[] with the results.
787          */
788
789         /*
790          * Find out how much memory is available, by looking at
791          * the memory descriptors.
792          */
793
794 #ifdef DEBUG_MD
795         printf("Memory descriptor count: %d\n", mdcount);
796 #endif
797
798         phys_avail_cnt = 0;
799         for (md = efi_md_first(); md != NULL; md = efi_md_next(md)) {
800 #ifdef DEBUG_MD
801                 printf("MD %p: type %d pa 0x%lx cnt 0x%lx\n", md,
802                     md->md_type, md->md_phys, md->md_pages);
803 #endif
804
805                 pfn0 = ia64_btop(round_page(md->md_phys));
806                 pfn1 = ia64_btop(trunc_page(md->md_phys + md->md_pages * 4096));
807                 if (pfn1 <= pfn0)
808                         continue;
809
810                 if (md->md_type != EFI_MD_TYPE_FREE)
811                         continue;
812
813                 /*
814                  * We have a memory descriptor that describes conventional
815                  * memory that is for general use. We must determine if the
816                  * loader has put the kernel in this region.
817                  */
818                 physmem += (pfn1 - pfn0);
819                 if (pfn0 <= kernendpfn && kernstartpfn <= pfn1) {
820                         /*
821                          * Must compute the location of the kernel
822                          * within the segment.
823                          */
824 #ifdef DEBUG_MD
825                         printf("Descriptor %p contains kernel\n", mp);
826 #endif
827                         if (pfn0 < kernstartpfn) {
828                                 /*
829                                  * There is a chunk before the kernel.
830                                  */
831 #ifdef DEBUG_MD
832                                 printf("Loading chunk before kernel: "
833                                        "0x%lx / 0x%lx\n", pfn0, kernstartpfn);
834 #endif
835                                 phys_avail[phys_avail_cnt] = ia64_ptob(pfn0);
836                                 phys_avail[phys_avail_cnt+1] = ia64_ptob(kernstartpfn);
837                                 phys_avail_cnt += 2;
838                         }
839                         if (kernendpfn < pfn1) {
840                                 /*
841                                  * There is a chunk after the kernel.
842                                  */
843 #ifdef DEBUG_MD
844                                 printf("Loading chunk after kernel: "
845                                        "0x%lx / 0x%lx\n", kernendpfn, pfn1);
846 #endif
847                                 phys_avail[phys_avail_cnt] = ia64_ptob(kernendpfn);
848                                 phys_avail[phys_avail_cnt+1] = ia64_ptob(pfn1);
849                                 phys_avail_cnt += 2;
850                         }
851                 } else {
852                         /*
853                          * Just load this cluster as one chunk.
854                          */
855 #ifdef DEBUG_MD
856                         printf("Loading descriptor %d: 0x%lx / 0x%lx\n", i,
857                                pfn0, pfn1);
858 #endif
859                         phys_avail[phys_avail_cnt] = ia64_ptob(pfn0);
860                         phys_avail[phys_avail_cnt+1] = ia64_ptob(pfn1);
861                         phys_avail_cnt += 2;
862                         
863                 }
864         }
865         phys_avail[phys_avail_cnt] = 0;
866
867         Maxmem = physmem;
868         init_param2(physmem);
869
870         /*
871          * Initialize error message buffer (at end of core).
872          */
873         msgbufp = (struct msgbuf *)pmap_steal_memory(MSGBUF_SIZE);
874         msgbufinit(msgbufp, MSGBUF_SIZE);
875
876         proc_linkup0(&proc0, &thread0);
877         /*
878          * Init mapping for kernel stack for proc 0
879          */
880         thread0.td_kstack = pmap_steal_memory(KSTACK_PAGES * PAGE_SIZE);
881         thread0.td_kstack_pages = KSTACK_PAGES;
882
883         mutex_init();
884
885         /*
886          * Initialize the rest of proc 0's PCB.
887          *
888          * Set the kernel sp, reserving space for an (empty) trapframe,
889          * and make proc0's trapframe pointer point to it for sanity.
890          * Initialise proc0's backing store to start after u area.
891          */
892         cpu_thread_alloc(&thread0);
893         thread0.td_frame->tf_flags = FRAME_SYSCALL;
894         thread0.td_pcb->pcb_special.sp =
895             (u_int64_t)thread0.td_frame - 16;
896         thread0.td_pcb->pcb_special.bspstore = thread0.td_kstack;
897
898         /*
899          * Initialize the virtual memory system.
900          */
901         pmap_bootstrap();
902
903         /*
904          * Initialize debuggers, and break into them if appropriate.
905          */
906         kdb_init();
907
908 #ifdef KDB
909         if (boothowto & RB_KDB)
910                 kdb_enter(KDB_WHY_BOOTFLAGS,
911                     "Boot flags requested debugger\n");
912 #endif
913
914         ia64_set_tpr(0);
915         ia64_srlz_d();
916
917         ret.bspstore = thread0.td_pcb->pcb_special.bspstore;
918         ret.sp = thread0.td_pcb->pcb_special.sp;
919         return (ret);
920 }
921
922 void *
923 ia64_ioport_address(u_int port)
924 {
925         uint64_t addr;
926
927         addr = (port > 0xffff) ? IA64_PHYS_TO_RR6((uint64_t)port) :
928             ia64_port_base | ((port & 0xfffc) << 10) | (port & 0xFFF);
929         return ((void *)addr);
930 }
931
932 uint64_t
933 ia64_get_hcdp(void)
934 {
935
936         return (bootinfo.bi_hcdp);
937 }
938
939 void
940 bzero(void *buf, size_t len)
941 {
942         caddr_t p = buf;
943
944         while (((vm_offset_t) p & (sizeof(u_long) - 1)) && len) {
945                 *p++ = 0;
946                 len--;
947         }
948         while (len >= sizeof(u_long) * 8) {
949                 *(u_long*) p = 0;
950                 *((u_long*) p + 1) = 0;
951                 *((u_long*) p + 2) = 0;
952                 *((u_long*) p + 3) = 0;
953                 len -= sizeof(u_long) * 8;
954                 *((u_long*) p + 4) = 0;
955                 *((u_long*) p + 5) = 0;
956                 *((u_long*) p + 6) = 0;
957                 *((u_long*) p + 7) = 0;
958                 p += sizeof(u_long) * 8;
959         }
960         while (len >= sizeof(u_long)) {
961                 *(u_long*) p = 0;
962                 len -= sizeof(u_long);
963                 p += sizeof(u_long);
964         }
965         while (len) {
966                 *p++ = 0;
967                 len--;
968         }
969 }
970
971 void
972 DELAY(int n)
973 {
974         u_int64_t start, end, now;
975
976         sched_pin();
977
978         start = ia64_get_itc();
979         end = start + (itc_frequency * n) / 1000000;
980         /* printf("DELAY from 0x%lx to 0x%lx\n", start, end); */
981         do {
982                 now = ia64_get_itc();
983         } while (now < end || (now > start && end < start));
984
985         sched_unpin();
986 }
987
988 /*
989  * Send an interrupt (signal) to a process.
990  */
991 void
992 sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
993 {
994         struct proc *p;
995         struct thread *td;
996         struct trapframe *tf;
997         struct sigacts *psp;
998         struct sigframe sf, *sfp;
999         u_int64_t sbs, sp;
1000         int oonstack;
1001         int sig;
1002         u_long code;
1003
1004         td = curthread;
1005         p = td->td_proc;
1006         PROC_LOCK_ASSERT(p, MA_OWNED);
1007         sig = ksi->ksi_signo;
1008         code = ksi->ksi_code;
1009         psp = p->p_sigacts;
1010         mtx_assert(&psp->ps_mtx, MA_OWNED);
1011         tf = td->td_frame;
1012         sp = tf->tf_special.sp;
1013         oonstack = sigonstack(sp);
1014         sbs = 0;
1015
1016         /* save user context */
1017         bzero(&sf, sizeof(struct sigframe));
1018         sf.sf_uc.uc_sigmask = *mask;
1019         sf.sf_uc.uc_stack = td->td_sigstk;
1020         sf.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
1021             ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
1022
1023         /*
1024          * Allocate and validate space for the signal handler
1025          * context. Note that if the stack is in P0 space, the
1026          * call to grow() is a nop, and the useracc() check
1027          * will fail if the process has not already allocated
1028          * the space with a `brk'.
1029          */
1030         if ((td->td_pflags & TDP_ALTSTACK) != 0 && !oonstack &&
1031             SIGISMEMBER(psp->ps_sigonstack, sig)) {
1032                 sbs = (u_int64_t)td->td_sigstk.ss_sp;
1033                 sbs = (sbs + 15) & ~15;
1034                 sfp = (struct sigframe *)(sbs + td->td_sigstk.ss_size);
1035 #if defined(COMPAT_43)
1036                 td->td_sigstk.ss_flags |= SS_ONSTACK;
1037 #endif
1038         } else
1039                 sfp = (struct sigframe *)sp;
1040         sfp = (struct sigframe *)((u_int64_t)(sfp - 1) & ~15);
1041
1042         /* Fill in the siginfo structure for POSIX handlers. */
1043         if (SIGISMEMBER(psp->ps_siginfo, sig)) {
1044                 sf.sf_si = ksi->ksi_info;
1045                 sf.sf_si.si_signo = sig;
1046                 /*
1047                  * XXX this shouldn't be here after code in trap.c
1048                  * is fixed
1049                  */
1050                 sf.sf_si.si_addr = (void*)tf->tf_special.ifa;
1051                 code = (u_int64_t)&sfp->sf_si;
1052         }
1053
1054         mtx_unlock(&psp->ps_mtx);
1055         PROC_UNLOCK(p);
1056
1057         get_mcontext(td, &sf.sf_uc.uc_mcontext, 0);
1058
1059         /* Copy the frame out to userland. */
1060         if (copyout(&sf, sfp, sizeof(sf)) != 0) {
1061                 /*
1062                  * Process has trashed its stack; give it an illegal
1063                  * instruction to halt it in its tracks.
1064                  */
1065                 PROC_LOCK(p);
1066                 sigexit(td, SIGILL);
1067                 return;
1068         }
1069
1070         if ((tf->tf_flags & FRAME_SYSCALL) == 0) {
1071                 tf->tf_special.psr &= ~IA64_PSR_RI;
1072                 tf->tf_special.iip = ia64_get_k5() +
1073                     ((uint64_t)break_sigtramp - (uint64_t)ia64_gateway_page);
1074         } else
1075                 tf->tf_special.iip = ia64_get_k5() +
1076                     ((uint64_t)epc_sigtramp - (uint64_t)ia64_gateway_page);
1077
1078         /*
1079          * Setup the trapframe to return to the signal trampoline. We pass
1080          * information to the trampoline in the following registers:
1081          *
1082          *      gp      new backing store or NULL
1083          *      r8      signal number
1084          *      r9      signal code or siginfo pointer
1085          *      r10     signal handler (function descriptor)
1086          */
1087         tf->tf_special.sp = (u_int64_t)sfp - 16;
1088         tf->tf_special.gp = sbs;
1089         tf->tf_special.bspstore = sf.sf_uc.uc_mcontext.mc_special.bspstore;
1090         tf->tf_special.ndirty = 0;
1091         tf->tf_special.rnat = sf.sf_uc.uc_mcontext.mc_special.rnat;
1092         tf->tf_scratch.gr8 = sig;
1093         tf->tf_scratch.gr9 = code;
1094         tf->tf_scratch.gr10 = (u_int64_t)catcher;
1095
1096         PROC_LOCK(p);
1097         mtx_lock(&psp->ps_mtx);
1098 }
1099
1100 /*
1101  * System call to cleanup state after a signal
1102  * has been taken.  Reset signal mask and
1103  * stack state from context left by sendsig (above).
1104  * Return to previous pc and psl as specified by
1105  * context left by sendsig. Check carefully to
1106  * make sure that the user has not modified the
1107  * state to gain improper privileges.
1108  *
1109  * MPSAFE
1110  */
1111 int
1112 sigreturn(struct thread *td,
1113         struct sigreturn_args /* {
1114                 ucontext_t *sigcntxp;
1115         } */ *uap)
1116 {
1117         ucontext_t uc;
1118         struct trapframe *tf;
1119         struct pcb *pcb;
1120
1121         tf = td->td_frame;
1122         pcb = td->td_pcb;
1123
1124         /*
1125          * Fetch the entire context structure at once for speed.
1126          * We don't use a normal argument to simplify RSE handling.
1127          */
1128         if (copyin(uap->sigcntxp, (caddr_t)&uc, sizeof(uc)))
1129                 return (EFAULT);
1130
1131         set_mcontext(td, &uc.uc_mcontext);
1132
1133 #if defined(COMPAT_43)
1134         if (sigonstack(tf->tf_special.sp))
1135                 td->td_sigstk.ss_flags |= SS_ONSTACK;
1136         else
1137                 td->td_sigstk.ss_flags &= ~SS_ONSTACK;
1138 #endif
1139         kern_sigprocmask(td, SIG_SETMASK, &uc.uc_sigmask, NULL, 0);
1140
1141         return (EJUSTRETURN);
1142 }
1143
1144 #ifdef COMPAT_FREEBSD4
1145 int
1146 freebsd4_sigreturn(struct thread *td, struct freebsd4_sigreturn_args *uap)
1147 {
1148
1149         return sigreturn(td, (struct sigreturn_args *)uap);
1150 }
1151 #endif
1152
1153 /*
1154  * Construct a PCB from a trapframe. This is called from kdb_trap() where
1155  * we want to start a backtrace from the function that caused us to enter
1156  * the debugger. We have the context in the trapframe, but base the trace
1157  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
1158  * enough for a backtrace.
1159  */
1160 void
1161 makectx(struct trapframe *tf, struct pcb *pcb)
1162 {
1163
1164         pcb->pcb_special = tf->tf_special;
1165         pcb->pcb_special.__spare = ~0UL;        /* XXX see unwind.c */
1166         save_callee_saved(&pcb->pcb_preserved);
1167         save_callee_saved_fp(&pcb->pcb_preserved_fp);
1168 }
1169
1170 int
1171 ia64_flush_dirty(struct thread *td, struct _special *r)
1172 {
1173         struct iovec iov;
1174         struct uio uio;
1175         uint64_t bspst, kstk, rnat;
1176         int error, locked;
1177
1178         if (r->ndirty == 0)
1179                 return (0);
1180
1181         kstk = td->td_kstack + (r->bspstore & 0x1ffUL);
1182         if (td == curthread) {
1183                 __asm __volatile("mov   ar.rsc=0;;");
1184                 __asm __volatile("mov   %0=ar.bspstore" : "=r"(bspst));
1185                 /* Make sure we have all the user registers written out. */
1186                 if (bspst - kstk < r->ndirty) {
1187                         __asm __volatile("flushrs;;");
1188                         __asm __volatile("mov   %0=ar.bspstore" : "=r"(bspst));
1189                 }
1190                 __asm __volatile("mov   %0=ar.rnat;;" : "=r"(rnat));
1191                 __asm __volatile("mov   ar.rsc=3");
1192                 error = copyout((void*)kstk, (void*)r->bspstore, r->ndirty);
1193                 kstk += r->ndirty;
1194                 r->rnat = (bspst > kstk && (bspst & 0x1ffL) < (kstk & 0x1ffL))
1195                     ? *(uint64_t*)(kstk | 0x1f8L) : rnat;
1196         } else {
1197                 locked = PROC_LOCKED(td->td_proc);
1198                 if (!locked)
1199                         PHOLD(td->td_proc);
1200                 iov.iov_base = (void*)(uintptr_t)kstk;
1201                 iov.iov_len = r->ndirty;
1202                 uio.uio_iov = &iov;
1203                 uio.uio_iovcnt = 1;
1204                 uio.uio_offset = r->bspstore;
1205                 uio.uio_resid = r->ndirty;
1206                 uio.uio_segflg = UIO_SYSSPACE;
1207                 uio.uio_rw = UIO_WRITE;
1208                 uio.uio_td = td;
1209                 error = proc_rwmem(td->td_proc, &uio);
1210                 /*
1211                  * XXX proc_rwmem() doesn't currently return ENOSPC,
1212                  * so I think it can bogusly return 0. Neither do
1213                  * we allow short writes.
1214                  */
1215                 if (uio.uio_resid != 0 && error == 0)
1216                         error = ENOSPC;
1217                 if (!locked)
1218                         PRELE(td->td_proc);
1219         }
1220
1221         r->bspstore += r->ndirty;
1222         r->ndirty = 0;
1223         return (error);
1224 }
1225
1226 int
1227 get_mcontext(struct thread *td, mcontext_t *mc, int flags)
1228 {
1229         struct trapframe *tf;
1230         int error;
1231
1232         tf = td->td_frame;
1233         bzero(mc, sizeof(*mc));
1234         mc->mc_special = tf->tf_special;
1235         error = ia64_flush_dirty(td, &mc->mc_special);
1236         if (tf->tf_flags & FRAME_SYSCALL) {
1237                 mc->mc_flags |= _MC_FLAGS_SYSCALL_CONTEXT;
1238                 mc->mc_scratch = tf->tf_scratch;
1239                 if (flags & GET_MC_CLEAR_RET) {
1240                         mc->mc_scratch.gr8 = 0;
1241                         mc->mc_scratch.gr9 = 0;
1242                         mc->mc_scratch.gr10 = 0;
1243                         mc->mc_scratch.gr11 = 0;
1244                 }
1245         } else {
1246                 mc->mc_flags |= _MC_FLAGS_ASYNC_CONTEXT;
1247                 mc->mc_scratch = tf->tf_scratch;
1248                 mc->mc_scratch_fp = tf->tf_scratch_fp;
1249                 /*
1250                  * XXX If the thread never used the high FP registers, we
1251                  * probably shouldn't waste time saving them.
1252                  */
1253                 ia64_highfp_save(td);
1254                 mc->mc_flags |= _MC_FLAGS_HIGHFP_VALID;
1255                 mc->mc_high_fp = td->td_pcb->pcb_high_fp;
1256         }
1257         save_callee_saved(&mc->mc_preserved);
1258         save_callee_saved_fp(&mc->mc_preserved_fp);
1259         return (error);
1260 }
1261
1262 int
1263 set_mcontext(struct thread *td, const mcontext_t *mc)
1264 {
1265         struct _special s;
1266         struct trapframe *tf;
1267         uint64_t psrmask;
1268
1269         tf = td->td_frame;
1270
1271         KASSERT((tf->tf_special.ndirty & ~PAGE_MASK) == 0,
1272             ("Whoa there! We have more than 8KB of dirty registers!"));
1273
1274         s = mc->mc_special;
1275         /*
1276          * Only copy the user mask and the restart instruction bit from
1277          * the new context.
1278          */
1279         psrmask = IA64_PSR_BE | IA64_PSR_UP | IA64_PSR_AC | IA64_PSR_MFL |
1280             IA64_PSR_MFH | IA64_PSR_RI;
1281         s.psr = (tf->tf_special.psr & ~psrmask) | (s.psr & psrmask);
1282         /* We don't have any dirty registers of the new context. */
1283         s.ndirty = 0;
1284         if (mc->mc_flags & _MC_FLAGS_ASYNC_CONTEXT) {
1285                 /*
1286                  * We can get an async context passed to us while we
1287                  * entered the kernel through a syscall: sigreturn(2)
1288                  * takes contexts that could previously be the result of
1289                  * a trap or interrupt.
1290                  * Hence, we cannot assert that the trapframe is not
1291                  * a syscall frame, but we can assert that it's at
1292                  * least an expected syscall.
1293                  */
1294                 if (tf->tf_flags & FRAME_SYSCALL) {
1295                         KASSERT(tf->tf_scratch.gr15 == SYS_sigreturn, ("foo"));
1296                         tf->tf_flags &= ~FRAME_SYSCALL;
1297                 }
1298                 tf->tf_scratch = mc->mc_scratch;
1299                 tf->tf_scratch_fp = mc->mc_scratch_fp;
1300                 if (mc->mc_flags & _MC_FLAGS_HIGHFP_VALID)
1301                         td->td_pcb->pcb_high_fp = mc->mc_high_fp;
1302         } else {
1303                 KASSERT((tf->tf_flags & FRAME_SYSCALL) != 0, ("foo"));
1304                 if ((mc->mc_flags & _MC_FLAGS_SYSCALL_CONTEXT) == 0) {
1305                         s.cfm = tf->tf_special.cfm;
1306                         s.iip = tf->tf_special.iip;
1307                         tf->tf_scratch.gr15 = 0;        /* Clear syscall nr. */
1308                 } else
1309                         tf->tf_scratch = mc->mc_scratch;
1310         }
1311         tf->tf_special = s;
1312         restore_callee_saved(&mc->mc_preserved);
1313         restore_callee_saved_fp(&mc->mc_preserved_fp);
1314
1315         return (0);
1316 }
1317
1318 /*
1319  * Clear registers on exec.
1320  */
1321 void
1322 exec_setregs(struct thread *td, u_long entry, u_long stack, u_long ps_strings)
1323 {
1324         struct trapframe *tf;
1325         uint64_t *ksttop, *kst;
1326
1327         tf = td->td_frame;
1328         ksttop = (uint64_t*)(td->td_kstack + tf->tf_special.ndirty +
1329             (tf->tf_special.bspstore & 0x1ffUL));
1330
1331         /*
1332          * We can ignore up to 8KB of dirty registers by masking off the
1333          * lower 13 bits in exception_restore() or epc_syscall(). This
1334          * should be enough for a couple of years, but if there are more
1335          * than 8KB of dirty registers, we lose track of the bottom of
1336          * the kernel stack. The solution is to copy the active part of
1337          * the kernel stack down 1 page (or 2, but not more than that)
1338          * so that we always have less than 8KB of dirty registers.
1339          */
1340         KASSERT((tf->tf_special.ndirty & ~PAGE_MASK) == 0,
1341             ("Whoa there! We have more than 8KB of dirty registers!"));
1342
1343         bzero(&tf->tf_special, sizeof(tf->tf_special));
1344         if ((tf->tf_flags & FRAME_SYSCALL) == 0) {      /* break syscalls. */
1345                 bzero(&tf->tf_scratch, sizeof(tf->tf_scratch));
1346                 bzero(&tf->tf_scratch_fp, sizeof(tf->tf_scratch_fp));
1347                 tf->tf_special.cfm = (1UL<<63) | (3UL<<7) | 3UL;
1348                 tf->tf_special.bspstore = IA64_BACKINGSTORE;
1349                 /*
1350                  * Copy the arguments onto the kernel register stack so that
1351                  * they get loaded by the loadrs instruction. Skip over the
1352                  * NaT collection points.
1353                  */
1354                 kst = ksttop - 1;
1355                 if (((uintptr_t)kst & 0x1ff) == 0x1f8)
1356                         *kst-- = 0;
1357                 *kst-- = 0;
1358                 if (((uintptr_t)kst & 0x1ff) == 0x1f8)
1359                         *kst-- = 0;
1360                 *kst-- = ps_strings;
1361                 if (((uintptr_t)kst & 0x1ff) == 0x1f8)
1362                         *kst-- = 0;
1363                 *kst = stack;
1364                 tf->tf_special.ndirty = (ksttop - kst) << 3;
1365         } else {                                /* epc syscalls (default). */
1366                 tf->tf_special.cfm = (3UL<<62) | (3UL<<7) | 3UL;
1367                 tf->tf_special.bspstore = IA64_BACKINGSTORE + 24;
1368                 /*
1369                  * Write values for out0, out1 and out2 to the user's backing
1370                  * store and arrange for them to be restored into the user's
1371                  * initial register frame.
1372                  * Assumes that (bspstore & 0x1f8) < 0x1e0.
1373                  */
1374                 suword((caddr_t)tf->tf_special.bspstore - 24, stack);
1375                 suword((caddr_t)tf->tf_special.bspstore - 16, ps_strings);
1376                 suword((caddr_t)tf->tf_special.bspstore -  8, 0);
1377         }
1378
1379         tf->tf_special.iip = entry;
1380         tf->tf_special.sp = (stack & ~15) - 16;
1381         tf->tf_special.rsc = 0xf;
1382         tf->tf_special.fpsr = IA64_FPSR_DEFAULT;
1383         tf->tf_special.psr = IA64_PSR_IC | IA64_PSR_I | IA64_PSR_IT |
1384             IA64_PSR_DT | IA64_PSR_RT | IA64_PSR_DFH | IA64_PSR_BN |
1385             IA64_PSR_CPL_USER;
1386 }
1387
1388 int
1389 ptrace_set_pc(struct thread *td, unsigned long addr)
1390 {
1391         uint64_t slot;
1392
1393         switch (addr & 0xFUL) {
1394         case 0:
1395                 slot = IA64_PSR_RI_0;
1396                 break;
1397         case 1:
1398                 /* XXX we need to deal with MLX bundles here */
1399                 slot = IA64_PSR_RI_1;
1400                 break;
1401         case 2:
1402                 slot = IA64_PSR_RI_2;
1403                 break;
1404         default:
1405                 return (EINVAL);
1406         }
1407
1408         td->td_frame->tf_special.iip = addr & ~0x0FULL;
1409         td->td_frame->tf_special.psr =
1410             (td->td_frame->tf_special.psr & ~IA64_PSR_RI) | slot;
1411         return (0);
1412 }
1413
1414 int
1415 ptrace_single_step(struct thread *td)
1416 {
1417         struct trapframe *tf;
1418
1419         /*
1420          * There's no way to set single stepping when we're leaving the
1421          * kernel through the EPC syscall path. The way we solve this is
1422          * by enabling the lower-privilege trap so that we re-enter the
1423          * kernel as soon as the privilege level changes. See trap.c for
1424          * how we proceed from there.
1425          */
1426         tf = td->td_frame;
1427         if (tf->tf_flags & FRAME_SYSCALL)
1428                 tf->tf_special.psr |= IA64_PSR_LP;
1429         else
1430                 tf->tf_special.psr |= IA64_PSR_SS;
1431         return (0);
1432 }
1433
1434 int
1435 ptrace_clear_single_step(struct thread *td)
1436 {
1437         struct trapframe *tf;
1438
1439         /*
1440          * Clear any and all status bits we may use to implement single
1441          * stepping.
1442          */
1443         tf = td->td_frame;
1444         tf->tf_special.psr &= ~IA64_PSR_SS;
1445         tf->tf_special.psr &= ~IA64_PSR_LP;
1446         tf->tf_special.psr &= ~IA64_PSR_TB;
1447         return (0);
1448 }
1449
1450 int
1451 fill_regs(struct thread *td, struct reg *regs)
1452 {
1453         struct trapframe *tf;
1454
1455         tf = td->td_frame;
1456         regs->r_special = tf->tf_special;
1457         regs->r_scratch = tf->tf_scratch;
1458         save_callee_saved(&regs->r_preserved);
1459         return (0);
1460 }
1461
1462 int
1463 set_regs(struct thread *td, struct reg *regs)
1464 {
1465         struct trapframe *tf;
1466         int error;
1467
1468         tf = td->td_frame;
1469         error = ia64_flush_dirty(td, &tf->tf_special);
1470         if (!error) {
1471                 tf->tf_special = regs->r_special;
1472                 tf->tf_special.bspstore += tf->tf_special.ndirty;
1473                 tf->tf_special.ndirty = 0;
1474                 tf->tf_scratch = regs->r_scratch;
1475                 restore_callee_saved(&regs->r_preserved);
1476         }
1477         return (error);
1478 }
1479
1480 int
1481 fill_dbregs(struct thread *td, struct dbreg *dbregs)
1482 {
1483
1484         return (ENOSYS);
1485 }
1486
1487 int
1488 set_dbregs(struct thread *td, struct dbreg *dbregs)
1489 {
1490
1491         return (ENOSYS);
1492 }
1493
1494 int
1495 fill_fpregs(struct thread *td, struct fpreg *fpregs)
1496 {
1497         struct trapframe *frame = td->td_frame;
1498         struct pcb *pcb = td->td_pcb;
1499
1500         /* Save the high FP registers. */
1501         ia64_highfp_save(td);
1502
1503         fpregs->fpr_scratch = frame->tf_scratch_fp;
1504         save_callee_saved_fp(&fpregs->fpr_preserved);
1505         fpregs->fpr_high = pcb->pcb_high_fp;
1506         return (0);
1507 }
1508
1509 int
1510 set_fpregs(struct thread *td, struct fpreg *fpregs)
1511 {
1512         struct trapframe *frame = td->td_frame;
1513         struct pcb *pcb = td->td_pcb;
1514
1515         /* Throw away the high FP registers (should be redundant). */
1516         ia64_highfp_drop(td);
1517
1518         frame->tf_scratch_fp = fpregs->fpr_scratch;
1519         restore_callee_saved_fp(&fpregs->fpr_preserved);
1520         pcb->pcb_high_fp = fpregs->fpr_high;
1521         return (0);
1522 }
1523
1524 void
1525 ia64_sync_icache(vm_offset_t va, vm_offset_t sz)
1526 {
1527         vm_offset_t lim;
1528
1529         if (!ia64_sync_icache_needed)
1530                 return;
1531
1532         lim = va + sz;
1533         while (va < lim) {
1534                 ia64_fc_i(va);
1535                 va += 32;       /* XXX */
1536         }
1537
1538         ia64_sync_i();
1539         ia64_srlz_i();
1540 }