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