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