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