xref: /freebsd/sys/i386/i386/bios.c (revision a1a4f1a0d87b594d3f17a97dc0127eec1417e6f6)
1 /*-
2  * Copyright (c) 1997 Michael Smith
3  * Copyright (c) 1998 Jonathan Lemon
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  * $FreeBSD$
28  */
29 
30 /*
31  * Code for dealing with the BIOS in x86 PC systems.
32  */
33 
34 #include <sys/param.h>
35 #include <sys/proc.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/malloc.h>
39 #include <vm/vm.h>
40 #include <vm/pmap.h>
41 #include <machine/md_var.h>
42 #include <machine/segments.h>
43 #include <machine/stdarg.h>
44 #include <machine/tss.h>
45 #include <machine/vmparam.h>
46 #include <machine/pc/bios.h>
47 #include <i386/isa/isa_device.h>
48 #include <i386/isa/pnp.h>
49 
50 #define BIOS_START	0xe0000
51 #define BIOS_SIZE	0x20000
52 
53 /* exported lookup results */
54 struct bios32_SDentry		PCIbios = {entry : 0};
55 struct PnPBIOS_table		*PnPBIOStable = 0;
56 
57 static u_int			bios32_SDCI = 0;
58 
59 /* start fairly early */
60 static void			bios32_init(void *junk);
61 SYSINIT(bios32, SI_SUB_CPU, SI_ORDER_ANY, bios32_init, NULL);
62 
63 static void	pnpbios_scan(void);
64 static char 	*pnp_eisaformat(u_int8_t *data);
65 
66 
67 /*
68  * bios32_init
69  *
70  * Locate various bios32 entities.
71  */
72 static void
73 bios32_init(void *junk)
74 {
75     u_long			sigaddr;
76     struct bios32_SDheader	*sdh;
77     struct PnPBIOS_table	*pt;
78     u_int8_t			ck, *cv;
79     int				i;
80 
81     /*
82      * BIOS32 Service Directory
83      */
84 
85     /* look for the signature */
86     if ((sigaddr = bios_sigsearch(0, "_32_", 4, 16, 0)) != 0) {
87 
88 	/* get a virtual pointer to the structure */
89 	sdh = (struct bios32_SDheader *)(uintptr_t)BIOS_PADDRTOVADDR(sigaddr);
90 	for (cv = (u_int8_t *)sdh, ck = 0, i = 0; i < (sdh->len * 16); i++) {
91 	    ck += cv[i];
92 	}
93 	/* If checksum is OK, enable use of the entrypoint */
94 	if ((ck == 0) && (sdh->entry < (BIOS_START + BIOS_SIZE))) {
95 	    bios32_SDCI = BIOS_PADDRTOVADDR(sdh->entry);
96 	    if (bootverbose) {
97 		printf("bios32: Found BIOS32 Service Directory header at %p\n", sdh);
98 		printf("bios32: Entry = 0x%x (%x)  Rev = %d  Len = %d\n",
99 		       sdh->entry, bios32_SDCI, sdh->revision, sdh->len);
100 	    }
101 	    /* See if there's a PCI BIOS entrypoint here */
102 	    PCIbios.ident.id = 0x49435024;	/* PCI systems should have this */
103 	    if (!bios32_SDlookup(&PCIbios) && bootverbose)
104 		printf("pcibios: PCI BIOS entry at 0x%x\n", PCIbios.entry);
105 	} else {
106 	    printf("bios32: Bad BIOS32 Service Directory\n");
107 	}
108     }
109 
110     /*
111      * PnP BIOS
112      */
113     if ((sigaddr = bios_sigsearch(0, "$PnP", 4, 16, 0)) != 0) {
114 
115 	/* get a virtual pointer to the structure */
116 	pt = (struct PnPBIOS_table *)(uintptr_t)BIOS_PADDRTOVADDR(sigaddr);
117 	for (cv = (u_int8_t *)pt, ck = 0, i = 0; i < pt->len; i++) {
118 	    ck += cv[i];
119 	}
120 	/* If checksum is OK, enable use of the entrypoint */
121 	if (ck == 0) {
122 	    PnPBIOStable = pt;
123 	    if (bootverbose) {
124 		printf("pnpbios: Found PnP BIOS data at %p\n", pt);
125 		printf("pnpbios: Entry = %x:%x  Rev = %d.%d\n",
126 		       pt->pmentrybase, pt->pmentryoffset, pt->version >> 4, pt->version & 0xf);
127 		if ((pt->control & 0x3) == 0x01)
128 		    printf("pnpbios: Event flag at %x\n", pt->evflagaddr);
129 		if (pt->oemdevid != 0)
130 		    printf("pnpbios: OEM ID %x\n", pt->oemdevid);
131 
132 	    }
133 	    pnpbios_scan();
134 	} else {
135 	    printf("pnpbios: Bad PnP BIOS data checksum\n");
136 	}
137     }
138 
139     if (bootverbose) {
140 	    /* look for other know signatures */
141 	    printf("Other BIOS signatures found:\n");
142 	    printf("ACPI: %08x\n", bios_sigsearch(0, "RST PTR", 8, 16, 0));
143     }
144 }
145 
146 /*
147  * bios32_SDlookup
148  *
149  * Query the BIOS32 Service Directory for the service named in (ent),
150  * returns nonzero if the lookup fails.  The caller must fill in
151  * (ent->ident), the remainder are populated on a successful lookup.
152  */
153 int
154 bios32_SDlookup(struct bios32_SDentry *ent)
155 {
156     struct bios_regs args;
157 
158     if (bios32_SDCI == 0)
159 	return (1);
160 
161     args.eax = ent->ident.id;		/* set up arguments */
162     args.ebx = args.ecx = args.edx = 0;
163     bios32(&args, bios32_SDCI, GSEL(GCODE_SEL, SEL_KPL));
164     if ((args.eax & 0xff) == 0) {	/* success? */
165 	ent->base = args.ebx;
166 	ent->len = args.ecx;
167 	ent->entry = args.edx;
168 	return (0);			/* all OK */
169     }
170     return (1);				/* failed */
171 }
172 
173 
174 /*
175  * bios_sigsearch
176  *
177  * Search some or all of the BIOS region for a signature string.
178  *
179  * (start)	Optional offset returned from this function
180  *		(for searching for multiple matches), or NULL
181  *		to start the search from the base of the BIOS.
182  *		Note that this will be a _physical_ address in
183  *		the range 0xe0000 - 0xfffff.
184  * (sig)	is a pointer to the byte(s) of the signature.
185  * (siglen)	number of bytes in the signature.
186  * (paralen)	signature paragraph (alignment) size.
187  * (sigofs)	offset of the signature within the paragraph.
188  *
189  * Returns the _physical_ address of the found signature, 0 if the
190  * signature was not found.
191  */
192 
193 u_int32_t
194 bios_sigsearch(u_int32_t start, u_char *sig, int siglen, int paralen, int sigofs)
195 {
196     u_char	*sp, *end;
197 
198     /* compute the starting address */
199     if ((start >= BIOS_START) && (start <= (BIOS_START + BIOS_SIZE))) {
200 	sp = (char *)BIOS_PADDRTOVADDR(start);
201     } else if (start == 0) {
202 	sp = (char *)BIOS_PADDRTOVADDR(BIOS_START);
203     } else {
204 	return 0;				/* bogus start address */
205     }
206 
207     /* compute the end address */
208     end = (u_char *)BIOS_PADDRTOVADDR(BIOS_START + BIOS_SIZE);
209 
210     /* loop searching */
211     while ((sp + sigofs + siglen) < end) {
212 
213 	/* compare here */
214 	if (!bcmp(sp + sigofs, sig, siglen)) {
215 	    /* convert back to physical address */
216 	    return((u_int32_t)BIOS_VADDRTOPADDR(sp));
217 	}
218 	sp += paralen;
219     }
220     return(0);
221 }
222 
223 /*
224  * do not staticize, used by bioscall.s
225  */
226 union {
227     struct {
228 	u_short	offset;
229 	u_short	segment;
230     } vec16;
231     struct {
232 	u_int	offset;
233 	u_short	segment;
234     } vec32;
235 } bioscall_vector;			/* bios jump vector */
236 
237 void
238 set_bios_selectors(struct bios_segments *seg, int flags)
239 {
240     struct soft_segment_descriptor ssd = {
241 	0,			/* segment base address (overwritten) */
242 	0,			/* length (overwritten) */
243 	SDT_MEMERA,		/* segment type (overwritten) */
244 	0,			/* priority level */
245 	1,			/* descriptor present */
246 	0, 0,
247 	1,			/* descriptor size (overwritten) */
248 	0			/* granularity == byte units */
249     };
250     union descriptor *p_gdt;
251 
252 #ifdef SMP
253     p_gdt = &gdt[cpuid];
254 #else
255     p_gdt = gdt;
256 #endif
257 
258     ssd.ssd_base = seg->code32.base;
259     ssd.ssd_limit = seg->code32.limit;
260     ssdtosd(&ssd, &p_gdt[GBIOSCODE32_SEL].sd);
261 
262     ssd.ssd_def32 = 0;
263     if (flags & BIOSCODE_FLAG) {
264 	ssd.ssd_base = seg->code16.base;
265 	ssd.ssd_limit = seg->code16.limit;
266 	ssdtosd(&ssd, &p_gdt[GBIOSCODE16_SEL].sd);
267     }
268 
269     ssd.ssd_type = SDT_MEMRWA;
270     if (flags & BIOSDATA_FLAG) {
271 	ssd.ssd_base = seg->data.base;
272 	ssd.ssd_limit = seg->data.limit;
273 	ssdtosd(&ssd, &p_gdt[GBIOSDATA_SEL].sd);
274     }
275 
276     if (flags & BIOSUTIL_FLAG) {
277 	ssd.ssd_base = seg->util.base;
278 	ssd.ssd_limit = seg->util.limit;
279 	ssdtosd(&ssd, &p_gdt[GBIOSUTIL_SEL].sd);
280     }
281 
282     if (flags & BIOSARGS_FLAG) {
283 	ssd.ssd_base = seg->args.base;
284 	ssd.ssd_limit = seg->args.limit;
285 	ssdtosd(&ssd, &p_gdt[GBIOSARGS_SEL].sd);
286     }
287 }
288 
289 extern int vm86pa;
290 extern void bios16_jmp(void);
291 
292 /*
293  * this routine is really greedy with selectors, and uses 5:
294  *
295  * 32-bit code selector:	to return to kernel
296  * 16-bit code selector:	for running code
297  *        data selector:	for 16-bit data
298  *        util selector:	extra utility selector
299  *        args selector:	to handle pointers
300  *
301  * the util selector is set from the util16 entry in bios16_args, if a
302  * "U" specifier is seen.
303  *
304  * See <machine/pc/bios.h> for description of format specifiers
305  */
306 int
307 bios16(struct bios_args *args, char *fmt, ...)
308 {
309     char	*p, *stack, *stack_top;
310     va_list 	ap;
311     int 	flags = BIOSCODE_FLAG | BIOSDATA_FLAG;
312     u_int 	i, arg_start, arg_end;
313     u_int 	*pte, *ptd;
314 
315     arg_start = 0xffffffff;
316     arg_end = 0;
317 
318     /*
319      * Some BIOS entrypoints attempt to copy the largest-case
320      * argument frame (in order to generalise handling for
321      * different entry types).  If our argument frame is
322      * smaller than this, the BIOS will reach off the top of
323      * our constructed stack segment.  Pad the top of the stack
324      * with some garbage to avoid this.
325      */
326     stack = (caddr_t)PAGE_SIZE - 32;
327 
328     va_start(ap, fmt);
329     for (p = fmt; p && *p; p++) {
330 	switch (*p) {
331 	case 'p':			/* 32-bit pointer */
332 	    i = va_arg(ap, u_int);
333 	    arg_start = min(arg_start, i);
334 	    arg_end = max(arg_end, i);
335 	    flags |= BIOSARGS_FLAG;
336 	    stack -= 4;
337 	    break;
338 
339 	case 'i':			/* 32-bit integer */
340 	    i = va_arg(ap, u_int);
341 	    stack -= 4;
342 	    break;
343 
344 	case 'U':			/* 16-bit selector */
345 	    flags |= BIOSUTIL_FLAG;
346 	    /* FALLTHROUGH */
347 	case 'D':			/* 16-bit selector */
348 	case 'C':			/* 16-bit selector */
349 	    stack -= 2;
350 	    break;
351 
352 	case 's':			/* 16-bit integer */
353 	    i = va_arg(ap, u_short);
354 	    stack -= 2;
355 	    break;
356 
357 	default:
358 	    return (EINVAL);
359 	}
360     }
361 
362     if (flags & BIOSARGS_FLAG) {
363 	if (arg_end - arg_start > ctob(16))
364 	    return (EACCES);
365 	args->seg.args.base = arg_start;
366 	args->seg.args.limit = 0xffff;
367     }
368 
369     args->seg.code32.base = (u_int)&bios16_jmp & PG_FRAME;
370     args->seg.code32.limit = 0xffff;
371 
372     ptd = (u_int *)rcr3();
373     if (ptd == IdlePTD) {
374 	/*
375 	 * no page table, so create one and install it.
376 	 */
377 	pte = (u_int *)malloc(PAGE_SIZE, M_TEMP, M_WAITOK);
378 	ptd = (u_int *)((u_int)ptd + KERNBASE);
379 	*ptd = vtophys(pte) | PG_RW | PG_V;
380     } else {
381 	/*
382 	 * this is a user-level page table
383 	 */
384 	pte = (u_int *)&PTmap;
385     }
386     /*
387      * install pointer to page 0.  we don't need to flush the tlb,
388      * since there should not be a previous mapping for page 0.
389      */
390     *pte = (vm86pa - PAGE_SIZE) | PG_RW | PG_V;
391 
392     stack_top = stack;
393     va_start(ap, fmt);
394     for (p = fmt; p && *p; p++) {
395 	switch (*p) {
396 	case 'p':			/* 32-bit pointer */
397 	    i = va_arg(ap, u_int);
398 	    *(u_int *)stack = (i - arg_start) |
399 		(GSEL(GBIOSARGS_SEL, SEL_KPL) << 16);
400 	    stack += 4;
401 	    break;
402 
403 	case 'i':			/* 32-bit integer */
404 	    i = va_arg(ap, u_int);
405 	    *(u_int *)stack = i;
406 	    stack += 4;
407 	    break;
408 
409 	case 'U':			/* 16-bit selector */
410 	    *(u_short *)stack = GSEL(GBIOSUTIL_SEL, SEL_KPL);
411 	    stack += 2;
412 	    break;
413 
414 	case 'D':			/* 16-bit selector */
415 	    *(u_short *)stack = GSEL(GBIOSDATA_SEL, SEL_KPL);
416 	    stack += 2;
417 	    break;
418 
419 	case 'C':			/* 16-bit selector */
420 	    *(u_short *)stack = GSEL(GBIOSCODE16_SEL, SEL_KPL);
421 	    stack += 2;
422 	    break;
423 
424 	case 's':			/* 16-bit integer */
425 	    i = va_arg(ap, u_short);
426 	    *(u_short *)stack = i;
427 	    stack += 2;
428 	    break;
429 
430 	default:
431 	    return (EINVAL);
432 	}
433     }
434 
435     set_bios_selectors(&args->seg, flags);
436     bioscall_vector.vec16.offset = (u_short)args->entry;
437     bioscall_vector.vec16.segment = GSEL(GBIOSCODE16_SEL, SEL_KPL);
438 
439     i = bios16_call(&args->r, stack_top);
440 
441     if (pte == (u_int *)&PTmap) {
442 	*pte = 0;			/* remove entry */
443     } else {
444 	*ptd = 0;			/* remove page table */
445 	free(pte, M_TEMP);		/* ... and free it */
446     }
447 
448     /*
449      * XXX only needs to be invlpg(0) but that doesn't work on the 386
450      */
451     invltlb();
452 
453     return (i);
454 }
455 
456 /*
457  * PnP BIOS interface; enumerate devices only known to the system
458  * BIOS and save information about them for later use.
459  */
460 
461 struct pnp_sysdev
462 {
463     u_int16_t	size;
464     u_int8_t	handle;
465     u_int32_t	devid;
466     u_int8_t	type[3];
467     u_int16_t	attrib;
468 #define PNPATTR_NODISABLE	(1<<0)	/* can't be disabled */
469 #define PNPATTR_NOCONFIG	(1<<1)	/* can't be configured */
470 #define PNPATTR_OUTPUT		(1<<2)	/* can be primary output */
471 #define PNPATTR_INPUT		(1<<3)	/* can be primary input */
472 #define PNPATTR_BOOTABLE	(1<<4)	/* can be booted from */
473 #define PNPATTR_DOCK		(1<<5)	/* is a docking station */
474 #define PNPATTR_REMOVEABLE	(1<<6)	/* device is removeable */
475 #define PNPATTR_CONFIG_STATIC	0x00
476 #define PNPATTR_CONFIG_DYNAMIC	0x07
477 #define PNPATTR_CONFIG_DYNONLY	0x17
478     /* device-specific data comes here */
479     u_int8_t	devdata[0];
480 } __attribute__ ((packed));
481 
482 /* We have to cluster arguments within a 64k range for the bios16 call */
483 struct pnp_sysdevargs
484 {
485     u_int16_t	next;
486     struct pnp_sysdev node;
487 };
488 
489 /*
490  * Quiz the PnP BIOS, build a list of PNP IDs and resource data.
491  */
492 static void
493 pnpbios_scan(void)
494 {
495     struct PnPBIOS_table	*pt = PnPBIOStable;
496     struct bios_args		args;
497     struct pnp_sysdev		*pd;
498     struct pnp_sysdevargs	*pda;
499     u_int16_t			ndevs, bigdev;
500     int				error, currdev;
501     u_int8_t			*devnodebuf, tag;
502     u_int32_t			*devid, *compid;
503     int				idx, left;
504 
505     /* no PnP BIOS information */
506     if (pt == NULL)
507 	return;
508 
509     bzero(&args, sizeof(args));
510     args.seg.code16.base = BIOS_PADDRTOVADDR(pt->pmentrybase);
511     args.seg.code16.limit = 0xffff;		/* XXX ? */
512     args.seg.data.base = BIOS_PADDRTOVADDR(pt->pmdataseg);
513     args.seg.data.limit = 0xffff;
514     args.entry = pt->pmentryoffset;
515 
516     if ((error = bios16(&args, PNP_COUNT_DEVNODES, &ndevs, &bigdev)) || (args.r.eax & 0xff))
517 	printf("pnpbios: error %d/%x getting device count/size limit\n", error, args.r.eax);
518     if (bootverbose)
519 	printf("pnpbios: %d devices, largest %d bytes\n", ndevs, bigdev);
520 
521     devnodebuf = malloc(bigdev + (sizeof(struct pnp_sysdevargs) - sizeof(struct pnp_sysdev)),
522 			M_DEVBUF, M_NOWAIT);
523     pda = (struct pnp_sysdevargs *)devnodebuf;
524     pd = &pda->node;
525 
526     for (currdev = 0, left = ndevs; (currdev != 0xff) && (left > 0); left--) {
527 
528 	bzero(pd, bigdev);
529 	pda->next = currdev;
530 	/* get current configuration */
531 	if ((error = bios16(&args, PNP_GET_DEVNODE, &pda->next, &pda->node, (u_int16_t)1))) {
532 	    printf("pnpbios: error %d making BIOS16 call\n", error);
533 	    break;
534 	}
535 	if ((error = (args.r.eax & 0xff))) {
536 	    if (bootverbose)
537 		printf("pnpbios: %s 0x%x fetching node %d\n", error & 0x80 ? "error" : "warning", error, currdev);
538 	    if (error & 0x80)
539 		break;
540 	}
541 	currdev = pda->next;
542 	if (pd->size < sizeof(struct pnp_sysdev)) {
543 	    printf("pnpbios: bogus system node data, aborting scan\n");
544 	    break;
545 	}
546 
547 	/* Find device IDs */
548 	devid = &pd->devid;
549 	compid = NULL;
550 
551 	/* look for a compatible device ID too */
552 	left = pd->size - sizeof(struct pnp_sysdev);
553 	idx = 0;
554 	while (idx < left) {
555 	    tag = pd->devdata[idx++];
556 	    if (PNP_RES_TYPE(tag) == 0) {
557 		/* Small resource */
558 		switch (PNP_SRES_NUM(tag)) {
559 		case COMP_DEVICE_ID:
560 		    compid = (u_int32_t *)(pd->devdata + idx);
561 		    if (bootverbose)
562 			printf("pnpbios: node %d compat ID 0x%08x\n", pd->handle, *compid);
563 		    /* FALLTHROUGH */
564 		case END_TAG:
565 		    idx = left;
566 		    break;
567 		default:
568 		    idx += PNP_SRES_LEN(tag);
569 		    break;
570 		}
571 	    } else
572 		/* Large resource, skip it */
573 		idx += *(u_int16_t *)(pd->devdata + idx) + 2;
574 	}
575 	if (bootverbose) {
576 	    printf("pnpbios: handle %d device ID %s (%08x)",
577 		   pd->handle, pnp_eisaformat((u_int8_t *)devid), *devid);
578 	    if (compid != NULL)
579 		printf(" compat ID %s (%08x)",
580 		       pnp_eisaformat((u_int8_t *)compid), *compid);
581 	    printf("\n");
582 	}
583     }
584 }
585 
586 /* XXX should be somewhere else */
587 static char *
588 pnp_eisaformat(u_int8_t *data)
589 {
590     static char idbuf[8];
591     const char  hextoascii[] = "0123456789abcdef";
592 
593     idbuf[0] = '@' + ((data[0] & 0x7c) >> 2);
594     idbuf[1] = '@' + (((data[0] & 0x3) << 3) + ((data[1] & 0xe0) >> 5));
595     idbuf[2] = '@' + (data[1] & 0x1f);
596     idbuf[3] = hextoascii[(data[2] >> 4)];
597     idbuf[4] = hextoascii[(data[2] & 0xf)];
598     idbuf[5] = hextoascii[(data[3] >> 4)];
599     idbuf[6] = hextoascii[(data[3] & 0xf)];
600     idbuf[7] = 0;
601     return(idbuf);
602 }
603