1/*
2 * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 * General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19FILE_LICENCE ( GPL2_OR_LATER );
20
21#include <stdint.h>
22#include <string.h>
23#include <errno.h>
24#include <realmode.h>
25#include <pnpbios.h>
26
27/** @file
28 *
29 * PnP BIOS
30 *
31 */
32
33/** PnP BIOS structure */
34struct pnp_bios {
35	/** Signature
36	 *
37	 * Must be equal to @c PNP_BIOS_SIGNATURE
38	 */
39	uint32_t signature;
40	/** Version as BCD (e.g. 1.0 is 0x10) */
41	uint8_t version;
42	/** Length of this structure */
43	uint8_t length;
44	/** System capabilities */
45	uint16_t control;
46	/** Checksum */
47	uint8_t checksum;
48} __attribute__ (( packed ));
49
50/** Signature for a PnP BIOS structure */
51#define PNP_BIOS_SIGNATURE \
52	( ( '$' << 0 ) + ( 'P' << 8 ) + ( 'n' << 16 ) + ( 'P' << 24 ) )
53
54/**
55 * Test address for PnP BIOS structure
56 *
57 * @v offset		Offset within BIOS segment to test
58 * @ret rc		Return status code
59 */
60static int is_pnp_bios ( unsigned int offset ) {
61	union {
62		struct pnp_bios pnp_bios;
63		uint8_t bytes[256]; /* 256 is maximum length possible */
64	} u;
65	size_t len;
66	unsigned int i;
67	uint8_t sum = 0;
68
69	/* Read start of header and verify signature */
70	copy_from_real ( &u.pnp_bios, BIOS_SEG, offset, sizeof ( u.pnp_bios ));
71	if ( u.pnp_bios.signature != PNP_BIOS_SIGNATURE )
72		return -EINVAL;
73
74	/* Read whole header and verify checksum */
75	len = u.pnp_bios.length;
76	copy_from_real ( &u.bytes, BIOS_SEG, offset, len );
77	for ( i = 0 ; i < len ; i++ ) {
78		sum += u.bytes[i];
79	}
80	if ( sum != 0 )
81		return -EINVAL;
82
83	DBG ( "Found PnP BIOS at %04x:%04x\n", BIOS_SEG, offset );
84
85	return 0;
86}
87
88/**
89 * Locate Plug-and-Play BIOS
90 *
91 * @ret pnp_offset	Offset of PnP BIOS structure within BIOS segment
92 *
93 * The PnP BIOS structure will be at BIOS_SEG:pnp_offset.  If no PnP
94 * BIOS is found, -1 is returned.
95 */
96int find_pnp_bios ( void ) {
97	static int pnp_offset = 0;
98
99	if ( pnp_offset )
100		return pnp_offset;
101
102	for ( pnp_offset = 0 ; pnp_offset < 0x10000 ; pnp_offset += 0x10 ) {
103		if ( is_pnp_bios ( pnp_offset ) == 0 )
104			return pnp_offset;
105	}
106
107	pnp_offset = -1;
108	return pnp_offset;
109}
110