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