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