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