xserver/hw/xorg/common Makefile.am, NONE, 1.1 atKeynames.h, NONE, 1.1 compiler.h, NONE, 1.1 fourcc.h, NONE, 1.1 xf86.h, NONE, 1.1 xf86Bus.c, NONE, 1.1 xf86Bus.h, NONE, 1.1 xf86Config.c, NONE, 1.1 xf86Config.h, NONE, 1.1 xf86Configure.c, NONE, 1.1 xf86Cursor.c, NONE, 1.1 xf86DGA.c, NONE, 1.1 xf86DPMS.c, NONE, 1.1 xf86Debug.c, NONE, 1.1 xf86DefModes.c, NONE, 1.1 xf86DoProbe.c, NONE, 1.1 xf86DoScanPci.c, NONE, 1.1 xf86Events.c, NONE, 1.1 xf86Globals.c, NONE, 1.1 xf86Helper.c, NONE, 1.1 xf86InPriv.h, NONE, 1.1 xf86Init.c, NONE, 1.1 xf86Io.c, NONE, 1.1 xf86Kbd.c, NONE, 1.1 xf86KbdBSD.c, NONE, 1.1 xf86KbdLnx.c, NONE, 1.1 xf86KbdMach.c, NONE, 1.1 xf86Keymap.h, NONE, 1.1 xf86MiscExt.c, NONE, 1.1 xf86Mode.c, NONE, 1.1 xf86Module.h, NONE, 1.1 xf86Opt.h, NONE, 1.1 xf86Option.c, NONE, 1.1 xf86PM.c, NONE, 1.1 xf86PciInfo.h, NONE, 1.1 xf86Priv.h, NONE, 1.1 xf86Privstr.h, NONE, 1.1 xf86RandR.c, NONE, 1.1 xf86Resources.h, NONE, 1.1 xf86Versions.c, NONE, 1.1 xf86VidMode.c, NONE, 1.1 xf86XKB.c, NONE, 1.1 xf86Xinput.c, NONE, 1.1 xf86Xinput.h, NONE, 1.1 xf86bigfont.c, NONE, 1.1 xf86cmap.c, NONE, 1.1 xf86cmap.h, NONE, 1.1 xf86dga.c, NONE, 1.1 xf86dga2.c, NONE, 1.1 xf86dgaext.h, NONE, 1.1 xf86fbBus.c, NONE, 1.1 xf86fbman.c, NONE, 1.1 xf86fbman.h, NONE, 1.1 xf86isaBus.c, NONE, 1.1 xf86misc.c, NONE, 1.1 xf86miscproc.h, NONE, 1.1 xf86noBus.c, NONE, 1.1 xf86pciBus.c, NONE, 1.1 xf86pciBus.h, NONE, 1.1 xf86sbusBus.c, NONE, 1.1 xf86sbusBus.h, NONE, 1.1 xf86str.h, NONE, 1.1 xf86vmode.c, NONE, 1.1 xf86xv.c, NONE, 1.1 xf86xv.h, NONE, 1.1 xf86xvmc.c, NONE, 1.1 xf86xvmc.h, NONE, 1.1 xf86xvpriv.h, NONE, 1.1 xisb.c, NONE, 1.1 xisb.h, NONE, 1.1

Daniel Stone xserver-commit at pdx.freedesktop.org
Sun Apr 25 23:52:16 EST 2004


Committed by: daniel

Update of /cvs/xserver/xserver/hw/xorg/common
In directory pdx:/tmp/cvs-serv17025/hw/xorg/common

Added Files:
	Makefile.am atKeynames.h compiler.h fourcc.h xf86.h xf86Bus.c 
	xf86Bus.h xf86Config.c xf86Config.h xf86Configure.c 
	xf86Cursor.c xf86DGA.c xf86DPMS.c xf86Debug.c xf86DefModes.c 
	xf86DoProbe.c xf86DoScanPci.c xf86Events.c xf86Globals.c 
	xf86Helper.c xf86InPriv.h xf86Init.c xf86Io.c xf86Kbd.c 
	xf86KbdBSD.c xf86KbdLnx.c xf86KbdMach.c xf86Keymap.h 
	xf86MiscExt.c xf86Mode.c xf86Module.h xf86Opt.h xf86Option.c 
	xf86PM.c xf86PciInfo.h xf86Priv.h xf86Privstr.h xf86RandR.c 
	xf86Resources.h xf86Versions.c xf86VidMode.c xf86XKB.c 
	xf86Xinput.c xf86Xinput.h xf86bigfont.c xf86cmap.c xf86cmap.h 
	xf86dga.c xf86dga2.c xf86dgaext.h xf86fbBus.c xf86fbman.c 
	xf86fbman.h xf86isaBus.c xf86misc.c xf86miscproc.h xf86noBus.c 
	xf86pciBus.c xf86pciBus.h xf86sbusBus.c xf86sbusBus.h 
	xf86str.h xf86vmode.c xf86xv.c xf86xv.h xf86xvmc.c xf86xvmc.h 
	xf86xvpriv.h xisb.c xisb.h 
Log Message:
Xizzle is dead, long live Xorg.

Re-import the DDX from X11R6.7, complete with automakey goodness, and do the
requisite configure.ac, et al, updates; also import the XKB extension from the
6.7 DIX.

Currently it'll link and then hang solid in RADEONInitAccel(), or the next
function if you enable NoAccel.


--- NEW FILE: Makefile.am ---
lib_LIBRARIES = libxorgcommon.a libxorghelper.a libxorgmode.a libxorginit.a

if XORG_BUS_SBUS
SBUS_SOURCES = xf86sbusBus.c
endif

#if DEBUG
#DEBUGSOURCES = xf86Debug.c
#endif

#if BUILDXV
XVSOURCES = xf86xv.c xf86xvmc.c
XVSDKINCS = xf86xv.h xf86xvmc.h
#endif

#if XKB
XKBSOURCES = xf86XKB.c
#endif

#if XINPUT
XISOURCES = xf86Xinput.c xisb.c
XISDKINCS = xf86Xinput.h xisb.h
#endif

RANDRSOURCES = xf86RandR.c

BUSSOURCES = xf86isaBus.c xf86pciBus.c xf86fbBus.c xf86noBus.c $(SBUS_SOURCES)

#if LINUX
KBDSOURCES = xf86KbdLnx.c
# XXX psuedocodeish
#else if BSD
#KBDSOURCES = xf86KbdBSD.c
#else if Mach && !GNU/Mach
#KBDSOURCES = xf86KbdMach.c
#else
#KBDSOURCES = xf86Kbd.c
#endif

EXTSOURCES = xf86dga.c xf86dga2.c xf86vmode.c xf86misc.c xf86bigfont.c

# shouldn't isaBus and pciBus only be built on the relevant architectures? -ds
# ditto DoScanPci
libxorgcommon_a_SOURCES = xf86Configure.c xf86Bus.c xf86Config.c \
                            xf86Cursor.c xf86DGA.c xf86DPMS.c xf86DefModes.c \
                            xf86DoProbe.c xf86DoScanPci.c xf86Events.c \
                            xf86Globals.c xf86Io.c \
                            xf86MiscExt.c xf86Option.c xf86PM.c \
                            xf86VidMode.c xf86fbman.c xf86cmap.c \
                            xf86Versions.c ../scanpci/xf86ScanPci.c \
                            $(XVSOURCES) $(BUSSOURCES) $(XKBSOURCES) \
                            $(DEBUGSOURCES) $(XISOURCES) $(RANDRSOURCES) \
                            $(KBDSOURCES) $(EXTSOURCES)
libxorghelper_a_SOURCES = xf86Helper.c
libxorgmode_a_SOURCES = xf86Mode.c
libxorginit_a_SOURCES = xf86Init.c

AM_CFLAGS = $(XORG_CFLAGS)

INCLUDES = $(XORG_INCS) -I$(srcdir)/../loader -I$(srcdir)/../ddc \
           -I$(srcdir)/../rac -I$(srcdir)/../vbe -I$(srcdir)/../int10 \
           -I$(srcdir)/../i2c -I$(srcdir)/../parser -I$(srcdir)/../vgahw \
           -I$(srcdir)/../scanpci -I$(top_srcdir)/Xi

sdk_INCLUDEDIR = $(includedir)/xorg
sdk_INCLUDES = compiler.h fourcc.h xf86.h xf86Module.h xf8Opt.h xf86Pci.h \
               xf86PciInfo.h xf86Priv.h xf86Privstr.h xf86Resources.h \
               xf86Version.h xf86cmap.h xf86fbman.h xf86str.h $(XISDKINCS) \
               $(XVSDKINCS)

--- NEW FILE: atKeynames.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/atKeynames.h,v 3.21 2003/10/09 11:43:59 pascal Exp $ */
/*
 * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name of Thomas Roell not be used in
 * advertising or publicity pertaining to distribution of the software without
 * specific, written prior permission.  Thomas Roell makes no representations
 * about the suitability of this software for any purpose.  It is provided
 * "as is" without express or implied warranty.
 *
 * THOMAS ROELL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 * EVENT SHALL THOMAS ROELL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
 * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 *
 */
/*
 * Copyright (c) 1994-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/* $XConsortium: atKeynames.h /main/11 1996/03/09 11:17:41 kaleb $ */

#ifndef _ATKEYNAMES_H
#define _ATKEYNAMES_H

#define XK_TECHNICAL
#define	XK_KATAKANA
#include <X11/keysym.h>
#include <X11/XF86keysym.h>

#define GLYPHS_PER_KEY	4
#define NUM_KEYCODES	248
#define MIN_KEYCODE     8
#define MAX_KEYCODE     (NUM_KEYCODES + MIN_KEYCODE - 1)

#define AltMask		Mod1Mask
#define NumLockMask	Mod2Mask
#define AltLangMask	Mod3Mask
#define KanaMask	Mod4Mask
#define ScrollLockMask	Mod5Mask

#define KeyPressed(k) (keyc->down[k >> 3] & (1 << (k & 7)))
#define ModifierDown(k) ((keyc->state & (k)) == (k))

/*
 * NOTE: The AT/MF keyboards can generate (via the 8042) two (MF: three)
 *       sets of scancodes. Set3 can only be generated by a MF keyboard.
 *       Set2 sends a makecode for keypress, and the same code prefixed by a
 *       F0 for keyrelease. This is a little bit ugly to handle. Thus we use
 *       here for X386 the PC/XT compatible Set1. This set uses 8bit scancodes.
 *       Bit 7 ist set if the key is released. The code E0 switches to a
 *       different meaning to add the new MF cursorkeys, while not breaking old
 *       applications. E1 is another special prefix. Since I assume that there
 *       will be further versions of PC/XT scancode compatible keyboards, we
 *       may be in trouble one day.
 *
 * IDEA: 1) Use Set2 on AT84 keyboards and translate it to MF Set3.
 *       2) Use the keyboards native set and translate it to common keysyms.
 */

/*
 * definition of the AT84/MF101/MF102 Keyboard:
 * ============================================================
 *       Defined             Key Cap Glyphs       Pressed value
 *      Key Name            Main       Also       (hex)    (dec)
 *      ----------------   ---------- -------    ------    ------
 */

#define KEY_Escape       /* Escape                0x01  */    1  
#define KEY_1            /* 1           !         0x02  */    2 
#define KEY_2            /* 2           @         0x03  */    3 
#define KEY_3            /* 3           #         0x04  */    4 
#define KEY_4            /* 4           $         0x05  */    5 
#define KEY_5            /* 5           %         0x06  */    6 
#define KEY_6            /* 6           ^         0x07  */    7 
#define KEY_7            /* 7           &         0x08  */    8 
#define KEY_8            /* 8           *         0x09  */    9 
#define KEY_9            /* 9           (         0x0a  */   10 
#define KEY_0            /* 0           )         0x0b  */   11 
#define KEY_Minus        /* - (Minus)   _ (Under) 0x0c  */   12
#define KEY_Equal        /* = (Equal)   +         0x0d  */   13 
#define KEY_BackSpace    /* Back Space            0x0e  */   14 
#define KEY_Tab          /* Tab                   0x0f  */   15
#define KEY_Q            /* Q                     0x10  */   16
#define KEY_W            /* W                     0x11  */   17
#define KEY_E            /* E                     0x12  */   18
#define KEY_R            /* R                     0x13  */   19
#define KEY_T            /* T                     0x14  */   20
#define KEY_Y            /* Y                     0x15  */   21
#define KEY_U            /* U                     0x16  */   22
#define KEY_I            /* I                     0x17  */   23
#define KEY_O            /* O                     0x18  */   24
#define KEY_P            /* P                     0x19  */   25
#define KEY_LBrace       /* [           {         0x1a  */   26
#define KEY_RBrace       /* ]           }         0x1b  */   27 
#define KEY_Enter        /* Enter                 0x1c  */   28
#define KEY_LCtrl        /* Ctrl(left)            0x1d  */   29
#define KEY_A            /* A                     0x1e  */   30
#define KEY_S            /* S                     0x1f  */   31
#define KEY_D            /* D                     0x20  */   32 
#define KEY_F            /* F                     0x21  */   33
#define KEY_G            /* G                     0x22  */   34
#define KEY_H            /* H                     0x23  */   35
#define KEY_J            /* J                     0x24  */   36
#define KEY_K            /* K                     0x25  */   37
#define KEY_L            /* L                     0x26  */   38
#define KEY_SemiColon    /* ;(SemiColon) :(Colon) 0x27  */   39
#define KEY_Quote        /* ' (Apostr)  " (Quote) 0x28  */   40
#define KEY_Tilde        /* ` (Accent)  ~ (Tilde) 0x29  */   41
#define KEY_ShiftL       /* Shift(left)           0x2a  */   42
#define KEY_BSlash       /* \(BckSlash) |(VertBar)0x2b  */   43
#define KEY_Z            /* Z                     0x2c  */   44
#define KEY_X            /* X                     0x2d  */   45
#define KEY_C            /* C                     0x2e  */   46
#define KEY_V            /* V                     0x2f  */   47
#define KEY_B            /* B                     0x30  */   48
#define KEY_N            /* N                     0x31  */   49
#define KEY_M            /* M                     0x32  */   50
#define KEY_Comma        /* , (Comma)   < (Less)  0x33  */   51
#define KEY_Period       /* . (Period)  >(Greater)0x34  */   52
#define KEY_Slash        /* / (Slash)   ?         0x35  */   53
#define KEY_ShiftR       /* Shift(right)          0x36  */   54
#define KEY_KP_Multiply  /* *                     0x37  */   55
#define KEY_Alt          /* Alt(left)             0x38  */   56
#define KEY_Space        /*   (SpaceBar)          0x39  */   57
#define KEY_CapsLock     /* CapsLock              0x3a  */   58
#define KEY_F1           /* F1                    0x3b  */   59
#define KEY_F2           /* F2                    0x3c  */   60
#define KEY_F3           /* F3                    0x3d  */   61
#define KEY_F4           /* F4                    0x3e  */   62
#define KEY_F5           /* F5                    0x3f  */   63
#define KEY_F6           /* F6                    0x40  */   64
#define KEY_F7           /* F7                    0x41  */   65
#define KEY_F8           /* F8                    0x42  */   66
#define KEY_F9           /* F9                    0x43  */   67
#define KEY_F10          /* F10                   0x44  */   68
#define KEY_NumLock      /* NumLock               0x45  */   69
#define KEY_ScrollLock   /* ScrollLock            0x46  */   70
#define KEY_KP_7         /* 7           Home      0x47  */   71 
#define KEY_KP_8         /* 8           Up        0x48  */   72 
#define KEY_KP_9         /* 9           PgUp      0x49  */   73 
#define KEY_KP_Minus     /* - (Minus)             0x4a  */   74
#define KEY_KP_4         /* 4           Left      0x4b  */   75
#define KEY_KP_5         /* 5                     0x4c  */   76
#define KEY_KP_6         /* 6           Right     0x4d  */   77
#define KEY_KP_Plus      /* + (Plus)              0x4e  */   78
#define KEY_KP_1         /* 1           End       0x4f  */   79
#define KEY_KP_2         /* 2           Down      0x50  */   80
#define KEY_KP_3         /* 3           PgDown    0x51  */   81
#define KEY_KP_0         /* 0           Insert    0x52  */   82
#define KEY_KP_Decimal   /* . (Decimal) Delete    0x53  */   83 
#define KEY_SysReqest    /* SysReqest             0x54  */   84
                         /* NOTUSED               0x55  */
#define KEY_Less         /* < (Less)   >(Greater) 0x56  */   86
#define KEY_F11          /* F11                   0x57  */   87
#define KEY_F12          /* F12                   0x58  */   88

#define KEY_Prefix0      /* special               0x60  */   96
#define KEY_Prefix1      /* specail               0x61  */   97

/*
 * The 'scancodes' below are generated by the server, because the MF101/102
 * keyboard sends them as sequence of other scancodes
 */
#define KEY_Home         /* Home                  0x59  */   89
#define KEY_Up           /* Up                    0x5a  */   90
#define KEY_PgUp         /* PgUp                  0x5b  */   91
#define KEY_Left         /* Left                  0x5c  */   92
#define KEY_Begin        /* Begin                 0x5d  */   93
#define KEY_Right        /* Right                 0x5e  */   94
#define KEY_End          /* End                   0x5f  */   95
#define KEY_Down         /* Down                  0x60  */   96
#define KEY_PgDown       /* PgDown                0x61  */   97
#define KEY_Insert       /* Insert                0x62  */   98
#define KEY_Delete       /* Delete                0x63  */   99
#define KEY_KP_Enter     /* Enter                 0x64  */  100
#define KEY_RCtrl        /* Ctrl(right)           0x65  */  101
#define KEY_Pause        /* Pause                 0x66  */  102
#define KEY_Print        /* Print                 0x67  */  103
#define KEY_KP_Divide    /* Divide                0x68  */  104
#define KEY_AltLang      /* AtlLang(right)        0x69  */  105
#define KEY_Break        /* Break                 0x6a  */  106
#define KEY_LMeta        /* Left Meta             0x6b  */  107
#define KEY_RMeta        /* Right Meta            0x6c  */  108
#define KEY_Menu         /* Menu                  0x6d  */  109
#define KEY_F13          /* F13                   0x6e  */  110
#define KEY_F14          /* F14                   0x6f  */  111
#define KEY_F15          /* F15                   0x70  */  112
#define KEY_HKTG         /* Hirugana/Katakana tog 0x70  */  112
#define KEY_F16          /* F16                   0x71  */  113
#define KEY_F17          /* F17                   0x72  */  114
#define KEY_KP_DEC       /* KP_DEC                0x73  */  115
#define KEY_BSlash2      /* \           _         0x73  */  115
#define KEY_KP_Equal	 /* Equal (Keypad)        0x76  */  118
#define KEY_XFER         /* Kanji Transfer        0x79  */  121
#define KEY_NFER         /* No Kanji Transfer     0x7b  */  123
#define KEY_Yen          /* Yen                   0x7d  */  125

#define KEY_Power        /* Power Key             0x84  */  132
#define KEY_Mute         /* Audio Mute            0x85  */  133
#define KEY_AudioLower   /* Audio Lower           0x86  */  134
#define KEY_AudioRaise   /* Audio Raise           0x87  */  135
#define KEY_Help         /* Help                  0x88  */  136
#define KEY_L1           /* Stop                  0x89  */  137
#define KEY_L2           /* Again                 0x8a  */  138
#define KEY_L3           /* Props                 0x8b  */  139
#define KEY_L4           /* Undo                  0x8c  */  140
#define KEY_L5           /* Front                 0x8d  */  141
#define KEY_L6           /* Copy                  0x8e  */  142
#define KEY_L7           /* Open                  0x8f  */  143
#define KEY_L8           /* Paste                 0x90  */  144
#define KEY_L9           /* Find                  0x91  */  145
#define KEY_L10          /* Cut                   0x92  */  146

/*
 * Fake 'scancodes' in the following ranges are generated for 2-byte
 * codes not handled elsewhere.  These correspond to most extended keys
 * on so-called "Internet" keyboards:
 *
 *	0x79-0x93
 *	0x96-0xa1
 *	0xa3-0xac
 *	0xb1-0xb4
 *	0xba-0xbd
 *	0xc2
 *	0xcc-0xd2
 *	0xd6-0xf7
 */

/*
 * Remapped 'scancodes' are generated for single-byte codes in the range
 * 0x59-0x5f,0x62-0x76.  These are used for some extra keys on some keyboards.
 */

#define KEY_0x59		0x95
#define KEY_0x5A		0xA2
#define KEY_0x5B		0xAD
#define KEY_0x5C		KEY_KP_EQUAL
#define KEY_0x5D		0xAE
#define KEY_0x5E		0xAF
#define KEY_0x5F		0xB0
#define KEY_0x62		0xB5
#define KEY_0x63		0xB6
#define KEY_0x64		0xB7
#define KEY_0x65		0xB8
#define KEY_0x66		0xB9
#define KEY_0x67		0xBE
#define KEY_0x68		0xBF
#define KEY_0x69		0xC0
#define KEY_0x6A		0xC1
#define KEY_0x6B		0xC3
#define KEY_0x6C		0xC4
#define KEY_0x6D		0xC5
#define KEY_0x6E		0xC6
#define KEY_0x6F		0xC7
#define KEY_0x70		0xC8
#define KEY_0x71		0xC9
#define KEY_0x72		0xCA
#define KEY_0x73		0xCB
#define KEY_0x74		0xD3
#define KEY_0x75		0xD4
#define KEY_0x76		0xD5

/* These are for "notused" and "unknown" entries in translation maps. */
#define KEY_NOTUSED	  0
#define KEY_UNKNOWN	255

#endif /* _ATKEYNAMES_H */

--- NEW FILE: compiler.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/compiler.h,v 3.106 2004/02/02 03:55:28 dawes Exp $ */
/*
 * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name of Thomas Roell not be used in
 * advertising or publicity pertaining to distribution of the software without
 * specific, written prior permission.  Thomas Roell makes no representations
 * about the suitability of this software for any purpose.  It is provided
 * "as is" without express or implied warranty.
 *
 * THOMAS ROELL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 * EVENT SHALL THOMAS ROELL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
 * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
[...1772 lines suppressed...]
#  define MMIO_ONB32(base, offset, val) MMIO_OUT32(base, offset, val) 

#  define MMIO_MOVE32(base, offset, val) MMIO_OUT32(base, offset, val)

# endif /* __alpha__ */

/*
 * With Intel, the version in os-support/misc/SlowBcopy.s is used.
 * This avoids port I/O during the copy (which causes problems with
 * some hardware).
 */
# ifdef __alpha__
#  define slowbcopy_tobus(src,dst,count) xf86SlowBCopyToBus(src,dst,count)
#  define slowbcopy_frombus(src,dst,count) xf86SlowBCopyFromBus(src,dst,count)
# else /* __alpha__ */
#  define slowbcopy_tobus(src,dst,count) xf86SlowBcopy(src,dst,count)
#  define slowbcopy_frombus(src,dst,count) xf86SlowBcopy(src,dst,count)
# endif /* __alpha__ */

#endif /* _COMPILER_H */

--- NEW FILE: fourcc.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/fourcc.h,v 1.5 2003/08/24 17:36:48 dawes Exp $ */

/*
 * Copyright (c) 2000-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
   This header file contains listings of STANDARD guids for video formats.
   Please do not place non-registered, or incomplete entries in this file.
   A list of some popular fourcc's are at: http://www.webartz.com/fourcc/
   For an explanation of fourcc <-> guid mappings see RFC2361.
*/

#ifndef _XF86_FOURCC_H_
#define _XF86_FOURCC_H_ 1

#define FOURCC_YUY2 0x32595559
#define XVIMAGE_YUY2 \
   { \
	FOURCC_YUY2, \
        XvYUV, \
	LSBFirst, \
	{'Y','U','Y','2', \
	  0x00,0x00,0x00,0x10,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71}, \
	16, \
	XvPacked, \
	1, \
	0, 0, 0, 0, \
	8, 8, 8, \
	1, 2, 2, \
	1, 1, 1, \
	{'Y','U','Y','V', \
	  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, \
	XvTopToBottom \
   }

#define FOURCC_YV12 0x32315659
#define XVIMAGE_YV12 \
   { \
	FOURCC_YV12, \
        XvYUV, \
	LSBFirst, \
	{'Y','V','1','2', \
	  0x00,0x00,0x00,0x10,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71}, \
	12, \
	XvPlanar, \
	3, \
	0, 0, 0, 0, \
	8, 8, 8, \
	1, 2, 2, \
	1, 2, 2, \
	{'Y','V','U', \
	  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, \
	XvTopToBottom \
   }

#define FOURCC_I420 0x30323449
#define XVIMAGE_I420 \
   { \
	FOURCC_I420, \
        XvYUV, \
	LSBFirst, \
	{'I','4','2','0', \
	  0x00,0x00,0x00,0x10,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71}, \
	12, \
	XvPlanar, \
	3, \
	0, 0, 0, 0, \
	8, 8, 8, \
	1, 2, 2, \
	1, 2, 2, \
	{'Y','U','V', \
	  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, \
	XvTopToBottom \
   }


#define FOURCC_UYVY 0x59565955
#define XVIMAGE_UYVY \
   { \
	FOURCC_UYVY, \
        XvYUV, \
	LSBFirst, \
	{'U','Y','V','Y', \
	  0x00,0x00,0x00,0x10,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71}, \
	16, \
	XvPacked, \
	1, \
	0, 0, 0, 0, \
	8, 8, 8, \
	1, 2, 2, \
	1, 1, 1, \
	{'U','Y','V','Y', \
	  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, \
	XvTopToBottom \
   }

#define FOURCC_IA44 0x34344149
#define XVIMAGE_IA44 \
   { \
        FOURCC_IA44, \
        XvYUV, \
        LSBFirst, \
        {'I','A','4','4', \
          0x00,0x00,0x00,0x10,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71}, \
        8, \
        XvPacked, \
        1, \
        0, 0, 0, 0, \
        8, 8, 8, \
        1, 1, 1, \
        1, 1, 1, \
        {'A','I', \
          0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, \
        XvTopToBottom \
   }

#define FOURCC_AI44 0x34344941
#define XVIMAGE_AI44 \
   { \
        FOURCC_AI44, \
        XvYUV, \
        LSBFirst, \
        {'A','I','4','4', \
          0x00,0x00,0x00,0x10,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71}, \
        8, \
        XvPacked, \
        1, \
        0, 0, 0, 0, \
        8, 8, 8, \
        1, 1, 1, \
        1, 1, 1, \
        {'I','A', \
          0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, \
        XvTopToBottom \
   }

#endif /* _XF86_FOURCC_H_ */

--- NEW FILE: xf86.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86.h,v 3.173 2004/01/27 01:31:44 dawes Exp $ */

/*
 * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 * This file contains declarations for public XFree86 functions and variables,
 * and definitions of public macros.
 *
 * "public" means available to video drivers.
 */

#ifndef _XF86_H
#define _XF86_H

#define PIXPRIV
#include "xf86str.h"
#include "xf86Opt.h"
#include <X11/Xfuncproto.h>
#ifndef IN_MODULE
#include <stdarg.h>
#else
#include "xf86_ansic.h"
#endif
#include "modularDefs.h"

#include "propertyst.h"

/* General parameters */
extern int xf86DoConfigure;
extern Bool xf86DoConfigurePass1;
extern int xf86ScreenIndex;		/* Index into pScreen.devPrivates */
extern int xf86CreateRootWindowIndex;	/* Index into pScreen.devPrivates */
extern int xf86PixmapIndex;
extern Bool xf86ResAccessEnter;
extern ScrnInfoPtr *xf86Screens;	/* List of pointers to ScrnInfoRecs */
extern const unsigned char byte_reversed[256];
extern ScrnInfoPtr xf86CurrentScreen;
extern Bool pciSlotClaimed;
extern Bool isaSlotClaimed;
extern Bool fbSlotClaimed;
#ifdef __sparc__
extern Bool sbusSlotClaimed;
#endif
extern confDRIRec xf86ConfigDRI;
extern Bool xf86inSuspend;

#define XF86SCRNINFO(p) ((ScrnInfoPtr)((p)->devPrivates[xf86ScreenIndex].ptr))

#define XF86FLIP_PIXELS() \
	do { \
	    if (xf86GetFlipPixels()) { \
		pScreen->whitePixel = (pScreen->whitePixel) ? 0 : 1; \
		pScreen->blackPixel = (pScreen->blackPixel) ? 0 : 1; \
	   } \
	while (0)

#define BOOLTOSTRING(b) ((b) ? "TRUE" : "FALSE")

#define PIX24TOBPP(p) (((p) == Pix24Use24) ? 24 : \
			(((p) == Pix24Use32) ? 32 : 0))

/* variables for debugging */
#ifdef BUILDDEBUG
extern char* xf86p8bit[];
extern CARD32 xf86DummyVar1;
extern CARD32 xf86DummyVar2;
extern CARD32 xf86DummyVar3;
#endif

/* Function Prototypes */
#ifndef _NO_XF86_PROTOTYPES

/* xf86Bus.c */

Bool xf86CheckPciSlot(int bus, int device, int func);
int xf86ClaimPciSlot(int bus, int device, int func, DriverPtr drvp,
		     int chipset, GDevPtr dev, Bool active);
Bool xf86ParsePciBusString(const char *busID, int *bus, int *device,
			   int *func);
Bool xf86ComparePciBusString(const char *busID, int bus, int device, int func);
void xf86FormatPciBusNumber(int busnum, char *buffer);
pciVideoPtr *xf86GetPciVideoInfo(void);
pciConfigPtr *xf86GetPciConfigInfo(void);
void xf86SetPciVideo(pciVideoPtr, resType);
void xf86PrintResList(int verb, resPtr list);
resPtr xf86AddRangesToList(resPtr list, resRange *pRange, int entityIndex);
int xf86ClaimIsaSlot(DriverPtr drvp, int chipset, GDevPtr dev, Bool active);
int xf86GetIsaInfoForScreen(int scrnIndex);
int  xf86GetFbInfoForScreen(int scrnIndex);
Bool xf86ParseIsaBusString(const char *busID);
int xf86ClaimFbSlot(DriverPtr drvp, int chipset, GDevPtr dev, Bool active);
int xf86ClaimNoSlot(DriverPtr drvp, int chipset, GDevPtr dev, Bool active);
void xf86EnableAccess(ScrnInfoPtr pScrn);
void xf86SetCurrentAccess(Bool Enable, ScrnInfoPtr pScrn);
Bool xf86IsPrimaryPci(pciVideoPtr pPci);
Bool xf86IsPrimaryIsa(void);
int xf86CheckPciGAType(pciVideoPtr pPci);
/* new RAC */
resPtr xf86AddResToList(resPtr rlist, resRange *Range, int entityIndex);
resPtr xf86JoinResLists(resPtr rlist1, resPtr rlist2);
resPtr xf86DupResList(const resPtr rlist);
void xf86FreeResList(resPtr rlist);
void xf86ClaimFixedResources(resList list, int entityIndex);
Bool xf86DriverHasEntities(DriverPtr drvp);
void xf86AddEntityToScreen(ScrnInfoPtr pScrn, int entityIndex);
void xf86SetEntityInstanceForScreen(ScrnInfoPtr pScrn, int entityIndex,
				    int instance);
int xf86GetNumEntityInstances(int entityIndex);
GDevPtr xf86GetDevFromEntity(int entityIndex, int instance);
void xf86RemoveEntityFromScreen(ScrnInfoPtr pScrn, int entityIndex);
EntityInfoPtr xf86GetEntityInfo(int entityIndex);
pciVideoPtr xf86GetPciInfoForEntity(int entityIndex);
int xf86GetPciEntity(int bus, int dev, int func);
Bool xf86SetEntityFuncs(int entityIndex, EntityProc init,
			EntityProc enter, EntityProc leave, pointer);
void xf86DeallocateResourcesForEntity(int entityIndex, unsigned long type);
resPtr xf86RegisterResources(int entityIndex, resList list, 
			     unsigned long Access);
Bool xf86CheckPciMemBase(pciVideoPtr pPci, memType base);
void xf86SetAccessFuncs(EntityInfoPtr pEnt, xf86SetAccessFuncPtr funcs,
			xf86SetAccessFuncPtr oldFuncs);
Bool xf86IsEntityPrimary(int entityIndex);
Bool xf86FixPciResource(int entityIndex, int prt, memType alignment,
			unsigned long type);
resPtr xf86ReallocatePciResources(int entityIndex, resPtr pRes);
resPtr xf86SetOperatingState(resList list, int entityIndex, int mask);
void xf86EnterServerState(xf86State state);
resRange xf86GetBlock(unsigned long type, memType size,
		      memType window_start, memType window_end,
		      memType align_mask, resPtr avoid);
resRange xf86GetSparse(unsigned long type, memType fixed_bits,
		       memType decode_mask, memType address_mask,
		       resPtr avoid);
memType xf86ChkConflict(resRange *rgp, int entityIndex);
Bool xf86IsPciDevPresent(int bus, int dev, int func);
ScrnInfoPtr xf86FindScreenForEntity(int entityIndex);
Bool xf86NoSharedResources(int screenIndex, resType res);
resPtr xf86FindIntersectOfLists(resPtr l1, resPtr l2);
pciVideoPtr xf86FindPciDeviceVendor(CARD16 vendorID, CARD16 deviceID,
				    char n, pciVideoPtr pvp_exclude);
pciVideoPtr xf86FindPciClass(CARD8 intf, CARD8 subClass, CARD16 class,
			     char n, pciVideoPtr pvp_exclude);
#ifdef INCLUDE_DEPRECATED
void xf86EnablePciBusMaster(pciVideoPtr pPci, Bool enable);
#endif
void xf86RegisterStateChangeNotificationCallback(xf86StateChangeNotificationCallbackFunc func, pointer arg);
Bool xf86DeregisterStateChangeNotificationCallback(xf86StateChangeNotificationCallbackFunc func);
#ifdef async
Bool xf86QueueAsyncEvent(void (*func)(pointer),pointer arg);
#endif

int xf86GetLastScrnFlag(int entityIndex);
void xf86SetLastScrnFlag(int entityIndex, int scrnIndex);
Bool xf86IsEntityShared(int entityIndex);
void xf86SetEntityShared(int entityIndex);
Bool xf86IsEntitySharable(int entityIndex);
void xf86SetEntitySharable(int entityIndex);
Bool xf86IsPrimInitDone(int entityIndex);
void xf86SetPrimInitDone(int entityIndex);
void xf86ClearPrimInitDone(int entityIndex);
int xf86AllocateEntityPrivateIndex(void);
DevUnion *xf86GetEntityPrivate(int entityIndex, int privIndex);

/* xf86Configure.c */
GDevPtr xf86AddBusDeviceToConfigure(const char *driver, BusType bus,
				    void *busData, int chipset);
GDevPtr xf86AddDeviceToConfigure(const char *driver, pciVideoPtr pVideo,
				 int chipset);
 
/* xf86Cursor.c */

void xf86LockZoom(ScreenPtr pScreen, int lock);
void xf86InitViewport(ScrnInfoPtr pScr);
void xf86SetViewport(ScreenPtr pScreen, int x, int y);
void xf86ZoomViewport(ScreenPtr pScreen, int zoom);
Bool xf86SwitchMode(ScreenPtr pScreen, DisplayModePtr mode);
void *xf86GetPointerScreenFuncs(void);
void xf86InitOrigins(void);
void xf86ReconfigureLayout(void);
 
/* xf86DPMS.c */

Bool xf86DPMSInit(ScreenPtr pScreen, DPMSSetProcPtr set, int flags);

/* xf86DGA.c */

Bool DGAInit(ScreenPtr pScreen, DGAFunctionPtr funcs, DGAModePtr modes, 
			int num);
xf86SetDGAModeProc xf86SetDGAMode;

/* xf86Events.c */

void SetTimeSinceLastInputEvent(void);
pointer xf86AddInputHandler(int fd, InputHandlerProc proc, pointer data);
int xf86RemoveInputHandler(pointer handler);
void xf86DisableInputHandler(pointer handler);
void xf86EnableInputHandler(pointer handler);
void xf86InterceptSignals(int *signo);
Bool xf86EnableVTSwitch(Bool new);
Bool xf86CommonSpecialKey(int key, Bool down, int modifiers);
void xf86ProcessActionEvent(ActionEvent action, void *arg);

/* xf86Helper.c */

#ifdef printf
#define printf_defined
#undef printf
#endif

void xf86AddDriver(DriverPtr driver, pointer module, int flags);
void xf86DeleteDriver(int drvIndex);
ScrnInfoPtr xf86AllocateScreen(DriverPtr drv, int flags);
void xf86DeleteScreen(int scrnIndex, int flags);
int xf86AllocateScrnInfoPrivateIndex(void);
Bool xf86AddPixFormat(ScrnInfoPtr pScrn, int depth, int bpp, int pad);
Bool xf86SetDepthBpp(ScrnInfoPtr scrp, int depth, int bpp, int fbbpp,
		     int depth24flags);
void xf86PrintDepthBpp(ScrnInfoPtr scrp);
Bool xf86SetWeight(ScrnInfoPtr scrp, rgb weight, rgb mask);
Bool xf86SetDefaultVisual(ScrnInfoPtr scrp, int visual);
Bool xf86SetGamma(ScrnInfoPtr scrp, Gamma newGamma);
void xf86SetDpi(ScrnInfoPtr pScrn, int x, int y);
void xf86SetBlackWhitePixels(ScreenPtr pScreen);
void xf86EnableDisableFBAccess(int scrnIndex, Bool enable);
void xf86VDrvMsgVerb(int scrnIndex, MessageType type, int verb,
		     const char *format, va_list args);
void xf86DrvMsgVerb(int scrnIndex, MessageType type, int verb,
		    const char *format, ...) _printf_attribute(4,5);
void xf86DrvMsg(int scrnIndex, MessageType type, const char *format, ...)
		_printf_attribute(3,4);
void xf86MsgVerb(MessageType type, int verb, const char *format, ...)
		_printf_attribute(3,4);
void xf86Msg(MessageType type, const char *format, ...) _printf_attribute(2,3);
void xf86ErrorFVerb(int verb, const char *format, ...) _printf_attribute(2,3);
void xf86ErrorF(const char *format, ...) _printf_attribute(1,2);
const char *xf86TokenToString(SymTabPtr table, int token);
int xf86StringToToken(SymTabPtr table, const char *string);
void xf86ShowClocks(ScrnInfoPtr scrp, MessageType from);
void xf86PrintChipsets(const char *drvname, const char *drvmsg,
		       SymTabPtr chips);
int xf86MatchDevice(const char *drivername, GDevPtr **driversectlist);
int xf86MatchPciInstances(const char *driverName, int vendorID, 
		      SymTabPtr chipsets, PciChipsets *PCIchipsets,
		      GDevPtr *devList, int numDevs, DriverPtr drvp,
		      int **foundEntities);
int xf86MatchIsaInstances(const char *driverName, SymTabPtr chipsets,
			  IsaChipsets *ISAchipsets, DriverPtr drvp,
			  FindIsaDevProc FindIsaDevice, GDevPtr *devList,
			  int numDevs, int **foundEntities);
void xf86GetClocks(ScrnInfoPtr pScrn, int num,
		   Bool (*ClockFunc)(ScrnInfoPtr, int),
		   void (*ProtectRegs)(ScrnInfoPtr, Bool),
		   void (*BlankScreen)(ScrnInfoPtr, Bool),
		   IOADDRESS vertsyncreg, int maskval,
		   int knownclkindex, int knownclkvalue);
void xf86SetPriority(Bool up);
const char *xf86GetVisualName(int visual);
int xf86GetVerbosity(void);
Pix24Flags xf86GetPix24(void);
int xf86GetDepth(void);
rgb xf86GetWeight(void);
Gamma xf86GetGamma(void);
Bool xf86GetFlipPixels(void);
const char *xf86GetServerName(void);
Bool xf86ServerIsExiting(void);
Bool xf86ServerIsResetting(void);
Bool xf86ServerIsInitialising(void);
Bool xf86ServerIsOnlyDetecting(void);
Bool xf86ServerIsOnlyProbing(void);
Bool xf86CaughtSignal(void);
Bool xf86GetVidModeAllowNonLocal(void);
Bool xf86GetVidModeEnabled(void);
Bool xf86GetModInDevAllowNonLocal(void);
Bool xf86GetModInDevEnabled(void);
Bool xf86GetAllowMouseOpenFail(void);
Bool xf86IsPc98(void);
void xf86DisableRandR(void);
CARD32 xf86GetVersion(void);
CARD32 xf86GetModuleVersion(pointer module);
pointer xf86LoadDrvSubModule(DriverPtr drv, const char *name);
pointer xf86LoadSubModule(ScrnInfoPtr pScrn, const char *name);
pointer xf86LoadOneModule(char *name, pointer optlist);
void xf86UnloadSubModule(pointer mod);
Bool xf86LoaderCheckSymbol(const char *name);
void xf86LoaderReqSymLists(const char **, ...);
void xf86LoaderReqSymbols(const char *, ...);
void xf86LoaderRefSymLists(const char **, ...);
void xf86LoaderRefSymbols(const char *, ...);
void xf86SetBackingStore(ScreenPtr pScreen);
void xf86SetSilkenMouse(ScreenPtr pScreen);
int xf86NewSerialNumber(WindowPtr p, pointer unused);
pointer xf86FindXvOptions(int scrnIndex, int adapt_index, char *port_name,
			  char **adaptor_name, pointer *adaptor_options);
void xf86GetOS(const char **name, int *major, int *minor, int *teeny);
ScrnInfoPtr xf86ConfigPciEntity(ScrnInfoPtr pScrn, int scrnFlag,
				int entityIndex,PciChipsets *p_chip,
				resList res, EntityProc init,
				EntityProc enter, EntityProc leave,
				pointer private);
ScrnInfoPtr xf86ConfigIsaEntity(ScrnInfoPtr pScrn, int scrnFlag,
				int entityIndex, IsaChipsets *i_chip,
				resList res, EntityProc init,
				EntityProc enter, EntityProc leave,
				pointer private); 
ScrnInfoPtr xf86ConfigFbEntity(ScrnInfoPtr pScrn, int scrnFlag, 
			       int entityIndex, EntityProc init, 
			       EntityProc enter, EntityProc leave, 
			       pointer private);
/* Obsolete! don't use */
Bool xf86ConfigActivePciEntity(ScrnInfoPtr pScrn,
				int entityIndex,PciChipsets *p_chip,
				resList res, EntityProc init,
				EntityProc enter, EntityProc leave,
				pointer private);
/* Obsolete! don't use */
Bool xf86ConfigActiveIsaEntity(ScrnInfoPtr pScrn,
				int entityIndex, IsaChipsets *i_chip,
				resList res, EntityProc init,
				EntityProc enter, EntityProc leave,
				pointer private); 
void xf86ConfigPciEntityInactive(EntityInfoPtr pEnt, PciChipsets *p_chip,
				 resList res, EntityProc init,
				 EntityProc enter, EntityProc leave,
				 pointer private);
void xf86ConfigIsaEntityInactive(EntityInfoPtr pEnt, IsaChipsets *i_chip,
				 resList res, EntityProc init,
				 EntityProc enter, EntityProc leave,
				 pointer private);
void xf86ConfigFbEntityInactive(EntityInfoPtr pEnt, EntityProc init, 
				EntityProc enter, EntityProc leave, 
				pointer private);
Bool xf86IsScreenPrimary(int scrnIndex);
int  xf86RegisterRootWindowProperty(int ScrnIndex, Atom	property, Atom type,
				    int format, unsigned long len,
				    pointer value);
Bool xf86IsUnblank(int mode);

#ifdef XFree86LOADER
void xf86AddModuleInfo(ModuleInfoPtr info, pointer module);
void xf86DeleteModuleInfo(int idx);
#endif

#ifdef printf_defined
#define printf xf86printf
#undef printf_defined
#endif

/* xf86Debug.c */
#ifdef BUILDDEBUG
 void xf86Break1(void);
void xf86Break2(void);
void xf86Break3(void);
CARD8  xf86PeekFb8(CARD8  *p);
CARD16 xf86PeekFb16(CARD16 *p);
CARD32 xf86PeekFb32(CARD32 *p);
void xf86PokeFb8(CARD8  *p, CARD8  v);
void xf86PokeFb16(CARD16 *p, CARD16 v);
void xf86PokeFb32(CARD16 *p, CARD32 v);
CARD8  xf86PeekMmio8(pointer Base, unsigned long Offset);
CARD16 xf86PeekMmio16(pointer Base, unsigned long Offset);
CARD32 xf86PeekMmio32(pointer Base, unsigned long Offset);
void xf86PokeMmio8(pointer Base, unsigned long Offset, CARD8  v);
void xf86PokeMmio16(pointer Base, unsigned long Offset, CARD16 v);
void xf86PokeMmio32(pointer Base, unsigned long Offset, CARD32 v);
extern void xf86SPTimestamp(xf86TsPtr* timestamp, char* string);
extern void xf86STimestamp(xf86TsPtr* timestamp);
#endif
 
/* xf86Init.c */

PixmapFormatPtr xf86GetPixFormat(ScrnInfoPtr pScrn, int depth);
int xf86GetBppFromDepth(ScrnInfoPtr pScrn, int depth);

/* xf86Mode.c */

int xf86GetNearestClock(ScrnInfoPtr scrp, int freq, Bool allowDiv2,
			int DivFactor, int MulFactor, int *divider);
const char *xf86ModeStatusToString(ModeStatus status);
ModeStatus xf86LookupMode(ScrnInfoPtr scrp, DisplayModePtr modep,
			  ClockRangePtr clockRanges, LookupModeFlags strategy);
ModeStatus xf86CheckModeForMonitor(DisplayModePtr mode, MonPtr monitor);
ModeStatus xf86InitialCheckModeForDriver(ScrnInfoPtr scrp, DisplayModePtr mode,
					 ClockRangePtr clockRanges,
					 LookupModeFlags strategy,
					 int maxPitch, int virtualX,
					 int virtualY);
ModeStatus xf86CheckModeForDriver(ScrnInfoPtr scrp, DisplayModePtr mode,
				  int flags);
int xf86ValidateModes(ScrnInfoPtr scrp, DisplayModePtr availModes,
		      char **modeNames, ClockRangePtr clockRanges,
		      int *linePitches, int minPitch, int maxPitch,
		      int minHeight, int maxHeight, int pitchInc,
		      int virtualX, int virtualY, int apertureSize,
		      LookupModeFlags strategy);
void xf86DeleteMode(DisplayModePtr *modeList, DisplayModePtr mode);
void xf86PruneDriverModes(ScrnInfoPtr scrp);
void xf86SetCrtcForModes(ScrnInfoPtr scrp, int adjustFlags);
void xf86PrintModes(ScrnInfoPtr scrp);
void xf86ShowClockRanges(ScrnInfoPtr scrp, ClockRangePtr clockRanges);

/* xf86Option.c */

void xf86CollectOptions(ScrnInfoPtr pScrn, pointer extraOpts);


/* xf86RandR.c */
#ifdef RANDR
Bool xf86RandRInit (ScreenPtr    pScreen);
void xf86RandRSetInitialMode (ScreenPtr pScreen);
#endif

/* xf86VidModeExtentionInit.c */

Bool VidModeExtensionInit(ScreenPtr pScreen);

/* xf86Versions.c */
CARD32 xf86GetBuiltinInterfaceVersion(BuiltinInterface iface, int flag);
Bool xf86RegisterBuiltinInterfaceVersion(BuiltinInterface iface,
					 CARD32 version, int flags);


#endif /* _NO_XF86_PROTOTYPES */

#endif /* _XF86_H */

--- NEW FILE: xf86Bus.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Bus.c,v 1.80 2004/02/05 18:24:59 eich Exp $ */
/*
 * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
[...3188 lines suppressed...]
    for (i = 0; i < xf86NumEntities; i++) {
	pEnt = xf86Entities[i];
	nprivs = xnfrealloc(pEnt->entityPrivates,
			    xf86EntityPrivateCount * sizeof(DevUnion));
	/* Zero the new private */
	bzero(&nprivs[idx], sizeof(DevUnion));
	pEnt->entityPrivates = nprivs;
    }
    return idx;
}

DevUnion *
xf86GetEntityPrivate(int entityIndex, int privIndex)
{
    if (entityIndex >= xf86NumEntities || privIndex >= xf86EntityPrivateCount)
	return NULL;

    return &(xf86Entities[entityIndex]->entityPrivates[privIndex]);
}


--- NEW FILE: xf86Bus.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Bus.h,v 1.23 2003/08/24 17:36:50 dawes Exp $ */

/*
 * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 * This file contains definitions of the bus-related data structures/types.
 * Everything contained here is private to xf86Bus.c.  In particular the
 * video drivers must not include this file.
 */

#ifndef _XF86_BUS_H
#define _XF86_BUS_H

#include "xf86pciBus.h"
#ifdef __sparc__
#include "xf86sbusBus.h"
#endif

typedef struct racInfo {
    xf86AccessPtr mem_new;
    xf86AccessPtr io_new;
    xf86AccessPtr io_mem_new;
    xf86SetAccessFuncPtr old;
} AccessFuncRec, *AccessFuncPtr;


typedef struct {
    DriverPtr                   driver;
    int                         chipset;
    int                         entityProp;
    EntityProc                  entityInit;
    EntityProc                  entityEnter;
    EntityProc                  entityLeave;
    pointer                     private;
    resPtr                      resources;
    Bool                        active;
    Bool                        inUse;
    BusRec                      bus;
    EntityAccessPtr             access;
    AccessFuncPtr               rac;
    pointer                     busAcc;
    int                         lastScrnFlag;
    DevUnion *                  entityPrivates;
    int                         numInstances;
    GDevPtr *                   devices;   
    IOADDRESS                   domainIO;
} EntityRec, *EntityPtr;

/* asynchronous event handling */
#ifdef async
typedef struct _AsyncQRec {
    void (*func)(pointer);
    pointer arg;
    struct _AsyncQRec *next;
} AsyncQRec, *AsyncQPtr;
#endif

#define NO_SEPARATE_IO_FROM_MEM 0x0001
#define NO_SEPARATE_MEM_FROM_IO 0x0002
#define NEED_VGA_ROUTED 0x0004
#define NEED_VGA_ROUTED_SETUP 0x0008
#define NEED_MEM 0x0010
#define NEED_IO  0x0020
#define NEED_MEM_SHARED 0x0040
#define NEED_IO_SHARED 0x0080
#define ACCEL_IS_SHARABLE 0x0100
#define IS_SHARED_ACCEL 0x0200
#define SA_PRIM_INIT_DONE 0x0400
#define NEED_VGA_MEM 0x1000
#define NEED_VGA_IO  0x2000

#define NEED_SHARED (NEED_MEM_SHARED | NEED_IO_SHARED)

#define busType bus.type
#define pciBusId bus.id.pci
#define isaBusId bus.id.isa
#define sbusBusId bus.id.sbus

struct x_BusAccRec;
typedef void (*BusAccProcPtr)(struct x_BusAccRec *ptr);

typedef struct x_BusAccRec {
    BusAccProcPtr set_f;
    BusAccProcPtr enable_f;
    BusAccProcPtr disable_f;
    BusAccProcPtr save_f;
    BusAccProcPtr restore_f;
    struct x_BusAccRec *current; /* pointer to bridge open on this bus */
    struct x_BusAccRec *primary; /* pointer to the bus connecting to this */
    struct x_BusAccRec *next;    /* this links the different buses together */
    BusType type;
    BusType busdep_type;
    /* Bus-specific fields */
    union {
	struct {
	    int bus;
	    int primary_bus;
	    PCITAG acc;
	    pciBridgesSave save;
	} pci;
    } busdep;
} BusAccRec, *BusAccPtr;

/* state change notification callback */
typedef struct _stateChange {
    xf86StateChangeNotificationCallbackFunc func;
    pointer arg;
    struct _stateChange *next;
} StateChangeNotificationRec, *StateChangeNotificationPtr;


extern EntityPtr *xf86Entities;
extern int xf86NumEntities;
extern xf86AccessRec AccessNULL;
extern BusRec primaryBus;
extern resPtr Acc;
extern resPtr osRes;
extern resPtr ResRange;
extern BusAccPtr xf86BusAccInfo;

int xf86AllocateEntity(void);
BusType StringToBusType(const char* busID, const char **retID);
memType ChkConflict(resRange *rgp, resPtr res, xf86State state);
Bool xf86IsSubsetOf(resRange range, resPtr list);
Bool xf86IsListSubsetOf(resPtr list, resPtr BaseList);
resPtr xf86ExtractTypeFromList(resPtr list, unsigned long type);
resPtr findIntersect(resRange Range, resPtr list);
resPtr xf86FindIntersect(resRange Range, resPtr list);
void RemoveOverlaps(resPtr target, resPtr list, Bool pow2Alignment,
		    Bool useEstimated);
void xf86ConvertListToHost(int entityIndex, resPtr list);

#endif /* _XF86_BUS_H */

--- NEW FILE: xf86Config.c ---
/* $XdotOrg: xc/programs/Xserver/hw/xfree86/common/xf86Config.c,v 1.1.4.4.2.4 2004/04/02 21:47:17 eich Exp $ */
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Config.c,v 3.276 2003/10/08 14:58:26 dawes Exp $ */


/*
 * Loosely based on code bearing the following copyright:
 *
 *   Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
 */

/*
 * Copyright 1992-2003 by The XFree86 Project, Inc.
 * Copyright 1997 by Metro Link, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
[...2561 lines suppressed...]
    if (xf86AllowMouseOpenFail)
	xf86Info.allowMouseOpenFail = TRUE;

    return CONFIG_OK;
}


/* These make the equivalent parser functions visible to the common layer. */
Bool
xf86PathIsAbsolute(const char *path)
{
    return (xf86pathIsAbsolute(path) != 0);
}

Bool
xf86PathIsSafe(const char *path)
{
    return (xf86pathIsSafe(path) != 0);
}


--- NEW FILE: xf86Config.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Config.h,v 1.7 2003/10/08 14:58:27 dawes Exp $ */

/*
 * Copyright (c) 1997-2000 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

#ifndef _xf86_config_h
#define _xf86_config_h

#ifdef HAVE_PARSER_DECLS
/*
 * global structure that holds the result of parsing the config file
 */
extern XF86ConfigPtr xf86configptr;
#endif

typedef enum _ConfigStatus {
    CONFIG_OK = 0,
    CONFIG_PARSE_ERROR,
    CONFIG_NOFILE
} ConfigStatus;

/*
 * prototypes
 */
char ** xf86ModulelistFromConfig(pointer **);
char ** xf86DriverlistFromConfig(void);
char ** xf86DriverlistFromCompile(void);
char ** xf86InputDriverlistFromConfig(void);
char ** xf86InputDriverlistFromCompile(void);
Bool xf86BuiltinInputDriver(const char *);
ConfigStatus xf86HandleConfigFile(Bool);

Bool xf86AutoConfig(void);

#endif /* _xf86_config_h */

--- NEW FILE: xf86Configure.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Configure.c,v 3.80 2003/10/08 14:58:27 dawes Exp $ */
/* $XdotOrg: xc/programs/Xserver/hw/xfree86/common/xf86Configure.c,v 1.1.4.1.6.4 2004/04/02 21:47:17 eich Exp $ */
/*
 * Copyright 2000-2002 by Alan Hourihane, Flint Mountain, North Wales.
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name of Alan Hourihane not be used in
 * advertising or publicity pertaining to distribution of the software without
 * specific, written prior permission.  Alan Hourihane makes no representations
 * about the suitability of this software for any purpose.  It is provided
 * "as is" without express or implied warranty.
 *
 * ALAN HOURIHANE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 * EVENT SHALL ALAN HOURIHANE BE LIABLE FOR ANY SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
[...975 lines suppressed...]
	       " tries to autodetect\n"
		"the protocol.\n",DFLT_MOUSE_DEV);
#endif
    }
#endif /* !SCO */

    if (xf86NumScreens > 1) {
	ErrorF("\n"__XSERVERNAME__
	       " has configured a multihead system, please check your config.\n");
    }

    ErrorF("\nYour %s file is %s\n\n", XF86CONFIGFILE ,filename);
    ErrorF("To test the server, run 'X -xf86config %s'\n\n", filename);

bail:
    OsCleanup(TRUE);
    AbortDDX();
    fflush(stderr);
    exit(0);
}

--- NEW FILE: xf86Cursor.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Cursor.c,v 3.37 2003/11/07 22:20:17 dawes Exp $ */
/*
 * Copyright (c) 1994-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/* $XConsortium: xf86Cursor.c /main/10 1996/10/19 17:58:23 kaleb $ */

#define NEED_EVENTS
#include <X11/X.h>
#include <X11/Xmd.h>
#include "input.h"
#include "cursor.h"
#include "mipointer.h"
#include "scrnintstr.h"
#include "globals.h"

#include "compiler.h"

#include "xf86.h"
#include "xf86Priv.h"
#include "xf86_OSproc.h"

#ifdef XINPUT
#include <X11/extensions/XIproto.h>
#include "xf86Xinput.h"
#endif

#ifdef XFreeXDGA
#include "dgaproc.h"
#endif

typedef struct _xf86EdgeRec {
   short screen;
   short start;
   short end;
   DDXPointRec offset;
   struct _xf86EdgeRec *next;
} xf86EdgeRec, *xf86EdgePtr;

typedef struct {
    xf86EdgePtr	left, right, up, down;
} xf86ScreenLayoutRec, *xf86ScreenLayoutPtr;

static Bool xf86CursorOffScreen(ScreenPtr *pScreen, int *x, int *y);
static void xf86CrossScreen(ScreenPtr pScreen, Bool entering);
static void xf86WarpCursor(ScreenPtr pScreen, int x, int y);

static void xf86PointerMoved(int scrnIndex, int x, int y);

static miPointerScreenFuncRec xf86PointerScreenFuncs = {
  xf86CursorOffScreen,
  xf86CrossScreen,
  xf86WarpCursor,
#ifdef XINPUT
  xf86eqEnqueue,
  xf86eqSwitchScreen
#else
  /* let miPointerInitialize take care of these */
  NULL,
  NULL
#endif
};

static xf86ScreenLayoutRec xf86ScreenLayout[MAXSCREENS];

static Bool HardEdges;

/*
 * xf86InitViewport --
 *      Initialize paning & zooming parameters, so that a driver must only
 *      check what resolutions are possible and whether the virtual area
 *      is valid if specified.
 */

void
xf86InitViewport(ScrnInfoPtr pScr)
{

  pScr->PointerMoved = xf86PointerMoved;

  /*
   * Compute the initial Viewport if necessary
   */
  if (pScr->display) {
    if (pScr->display->frameX0 < 0) {
      pScr->frameX0 = (pScr->virtualX - pScr->modes->HDisplay) / 2;
      pScr->frameY0 = (pScr->virtualY - pScr->modes->VDisplay) / 2;
    } else {
      pScr->frameX0 = pScr->display->frameX0;
      pScr->frameY0 = pScr->display->frameY0;
    }
  }

  pScr->frameX1 = pScr->frameX0 + pScr->modes->HDisplay - 1;
  pScr->frameY1 = pScr->frameY0 + pScr->modes->VDisplay - 1;

  /*
   * Now adjust the initial Viewport, so it lies within the virtual area
   */
  if (pScr->frameX1 >= pScr->virtualX)
    {
	pScr->frameX0 = pScr->virtualX - pScr->modes->HDisplay;
	pScr->frameX1 = pScr->frameX0 + pScr->modes->HDisplay - 1;
    }

  if (pScr->frameY1 >= pScr->virtualY)
    {
	pScr->frameY0 = pScr->virtualY - pScr->modes->VDisplay;
	pScr->frameY1 = pScr->frameY0 + pScr->modes->VDisplay - 1;
    }
}


/*
 * xf86SetViewport --
 *      Scroll the visual part of the screen so the pointer is visible.
 */

void
xf86SetViewport(ScreenPtr pScreen, int x, int y)
{
  ScrnInfoPtr   pScr = XF86SCRNINFO(pScreen);

  (*pScr->PointerMoved)(pScreen->myNum, x, y);
}


static void 
xf86PointerMoved(int scrnIndex, int x, int y)
{
  Bool          frameChanged = FALSE;
  ScrnInfoPtr   pScr = xf86Screens[scrnIndex];

  /*
   * check wether (x,y) belongs to the visual part of the screen
   * if not, change the base of the displayed frame accoring
   */
  if ( pScr->frameX0 > x) { 
    pScr->frameX0 = x;
    pScr->frameX1 = x + pScr->currentMode->HDisplay - 1;
    frameChanged = TRUE ;
  }
  
  if ( pScr->frameX1 < x) { 
    pScr->frameX1 = x + 1;
    pScr->frameX0 = x - pScr->currentMode->HDisplay + 1;
    frameChanged = TRUE ;
  }
  
  if ( pScr->frameY0 > y) { 
    pScr->frameY0 = y;
    pScr->frameY1 = y + pScr->currentMode->VDisplay - 1;
    frameChanged = TRUE;
  }
  
  if ( pScr->frameY1 < y) { 
    pScr->frameY1 = y;
    pScr->frameY0 = y - pScr->currentMode->VDisplay + 1;
    frameChanged = TRUE; 
  }
  
  if (frameChanged && pScr->AdjustFrame != NULL)
    pScr->AdjustFrame(pScr->scrnIndex, pScr->frameX0, pScr->frameY0, 0);
}

/*
 * xf86LockZoom --
 *	Enable/disable ZoomViewport
 */

void
xf86LockZoom(ScreenPtr pScreen, Bool lock)
{
  XF86SCRNINFO(pScreen)->zoomLocked = lock;
}

/*
 * xf86SwitchMode --
 *	This is called by both keyboard processing and the VidMode extension to
 *	set a new mode.
 */

Bool
xf86SwitchMode(ScreenPtr pScreen, DisplayModePtr mode)
{
  ScrnInfoPtr pScr = XF86SCRNINFO(pScreen);
  ScreenPtr   pCursorScreen;
  Bool        Switched;
  int         px, py;

  if (!pScr->vtSema || !mode || !pScr->SwitchMode)
    return FALSE;

#ifdef XFreeXDGA
  if (DGAActive(pScr->scrnIndex))
    return FALSE;
#endif

  if (mode == pScr->currentMode)
    return TRUE;

  if (mode->HDisplay > pScreen->width || mode->VDisplay > pScreen->height)
    return FALSE;

  pCursorScreen = miPointerCurrentScreen();
  if (pScreen == pCursorScreen)
    miPointerPosition(&px, &py);

  xf86EnterServerState(SETUP);
  Switched = (*pScr->SwitchMode)(pScr->scrnIndex, mode, 0);
  xf86EnterServerState(OPERATING);
  if (Switched) {
    pScr->currentMode = mode;

    /*
     * Adjust frame for new display size.
     */
    if (pScreen == pCursorScreen)
      pScr->frameX0 = px - (mode->HDisplay / 2) + 1;
    else
      pScr->frameX0 = (pScr->frameX0 + pScr->frameX1 + 1 - mode->HDisplay) / 2;

    if (pScr->frameX0 < 0)
      pScr->frameX0 = 0;

    pScr->frameX1 = pScr->frameX0 + mode->HDisplay - 1;
    if (pScr->frameX1 >= pScr->virtualX) {
      pScr->frameX0 = pScr->virtualX - mode->HDisplay;
      pScr->frameX1 = pScr->virtualX - 1;
    }

    if (pScreen == pCursorScreen)
      pScr->frameY0 = py - (mode->VDisplay / 2) + 1;
    else
      pScr->frameY0 = (pScr->frameY0 + pScr->frameY1 + 1 - mode->VDisplay) / 2;

    if (pScr->frameY0 < 0)
      pScr->frameY0 = 0;

    pScr->frameY1 = pScr->frameY0 + mode->VDisplay - 1;
    if (pScr->frameY1 >= pScr->virtualY) {
      pScr->frameY0 = pScr->virtualY - mode->VDisplay;
      pScr->frameY1 = pScr->virtualY - 1;
    }
  }

  if (pScr->AdjustFrame)
    (*pScr->AdjustFrame)(pScr->scrnIndex, pScr->frameX0, pScr->frameY0, 0);

  if (pScreen == pCursorScreen)
    xf86WarpCursor(pScreen, px, py);

  return Switched;
}
    
/*
 * xf86ZoomViewport --
 *      Reinitialize the visual part of the screen for another mode.
 */

void
xf86ZoomViewport(ScreenPtr pScreen, int zoom)
{
  ScrnInfoPtr    pScr = XF86SCRNINFO(pScreen);
  DisplayModePtr mode;

  if (pScr->zoomLocked || !(mode = pScr->currentMode))
    return;

  do {
    if (zoom > 0)
      mode = mode->next;
    else
      mode = mode->prev;
  } while (mode != pScr->currentMode && !(mode->type & M_T_USERDEF));

  (void)xf86SwitchMode(pScreen, mode);
}


static xf86EdgePtr
FindEdge(xf86EdgePtr edge, int val)
{
    while(edge && (edge->end <= val))
	edge = edge->next;

    if(edge && (edge->start <= val))
	return edge;

    return NULL;
}

/*
 * xf86CursorOffScreen --
 *      Check whether it is necessary to switch to another screen
 */

static Bool
xf86CursorOffScreen(ScreenPtr *pScreen, int *x, int *y)
{
    xf86EdgePtr edge;
    int tmp;

    if(screenInfo.numScreens == 1)
	return FALSE;

    if(*x < 0) {
        tmp = *y;
	if(tmp < 0) tmp = 0;
	if(tmp >= (*pScreen)->height) tmp = (*pScreen)->height - 1;

	if((edge = xf86ScreenLayout[(*pScreen)->myNum].left))
	   edge = FindEdge(edge, tmp);

	if(!edge) *x = 0;
	else {
	    *x += edge->offset.x;
	    *y += edge->offset.y;
	    *pScreen = xf86Screens[edge->screen]->pScreen;
	}
    }

    if(*x >= (*pScreen)->width) {
        tmp = *y;
	if(tmp < 0) tmp = 0;
	if(tmp >= (*pScreen)->height) tmp = (*pScreen)->height - 1;

	if((edge = xf86ScreenLayout[(*pScreen)->myNum].right))
	   edge = FindEdge(edge, tmp);

	if(!edge) *x = (*pScreen)->width - 1;
	else {
	    *x += edge->offset.x;
	    *y += edge->offset.y;
	    *pScreen = xf86Screens[edge->screen]->pScreen;
	}
    }

    if(*y < 0) {
        tmp = *x;
	if(tmp < 0) tmp = 0;
	if(tmp >= (*pScreen)->width) tmp = (*pScreen)->width - 1;

	if((edge = xf86ScreenLayout[(*pScreen)->myNum].up))
	   edge = FindEdge(edge, tmp);

	if(!edge) *y = 0;
	else {
	    *x += edge->offset.x;
	    *y += edge->offset.y;
	    *pScreen = xf86Screens[edge->screen]->pScreen;
	}
    }

    if(*y >= (*pScreen)->height) {
        tmp = *x;
	if(tmp < 0) tmp = 0;
	if(tmp >= (*pScreen)->width) tmp = (*pScreen)->width - 1;

	if((edge = xf86ScreenLayout[(*pScreen)->myNum].down))
	   edge = FindEdge(edge, tmp);

	if(!edge) *y = (*pScreen)->height - 1;
	else {
	    *x += edge->offset.x;
	    *y += edge->offset.y;
	    (*pScreen) = xf86Screens[edge->screen]->pScreen;
	}
    }


#if 0
    /* This presents problems for overlapping screens when
 	HardEdges is used.  Have to think about the logic more */
    if((*x < 0) || (*x >= (*pScreen)->width) || 
       (*y < 0) || (*y >= (*pScreen)->height)) {
	/* We may have crossed more than one screen */
	xf86CursorOffScreen(pScreen, x, y);
    }
#endif

    return TRUE;
}



/*
 * xf86CrossScreen --
 *      Switch to another screen
 */

/* NEED TO CHECK THIS */
/* ARGSUSED */
static void
xf86CrossScreen (ScreenPtr pScreen, Bool entering)
{
#if 0
  if (xf86Info.sharedMonitor)
    (XF86SCRNINFO(pScreen)->EnterLeaveMonitor)(entering);
  (XF86SCRNINFO(pScreen)->EnterLeaveCursor)(entering);
#endif
}


/*
 * xf86WarpCursor --
 *      Warp possible to another screen
 */

/* ARGSUSED */
static void
xf86WarpCursor (ScreenPtr pScreen, int x, int y)
{
    int    sigstate;
    sigstate = xf86BlockSIGIO ();
  miPointerWarpCursor(pScreen,x,y);

  xf86Info.currentScreen = pScreen;
    xf86UnblockSIGIO (sigstate);
}


void *
xf86GetPointerScreenFuncs(void)
{
    return (void *)&xf86PointerScreenFuncs;
}


static xf86EdgePtr
AddEdge(
   xf86EdgePtr edge, 
   short min, 
   short max,
   short dx,
   short dy,
   short screen
){
   xf86EdgePtr pEdge = edge, pPrev = NULL, pNew;

   while(1) {
	while(pEdge && (min >= pEdge->end)) {
	    pPrev = pEdge;
	    pEdge = pEdge->next;
	}  

	if(!pEdge) {
	    if(!(pNew = xalloc(sizeof(xf86EdgeRec))))
		break;

	    pNew->screen = screen;
	    pNew->start = min;  
	    pNew->end = max;   
	    pNew->offset.x = dx;
	    pNew->offset.y = dy;
	    pNew->next = NULL;

	    if(pPrev)
		pPrev->next = pNew;
	    else
		edge = pNew;
	    
	    break;
	} else if (min < pEdge->start) {
	    if(!(pNew = xalloc(sizeof(xf86EdgeRec))))
		break;

	    pNew->screen = screen;
	    pNew->start = min;  
	    pNew->offset.x = dx;
	    pNew->offset.y = dy;
	    pNew->next = pEdge;

	    if(pPrev) pPrev->next = pNew;
	    else edge = pNew;

	    if(max <= pEdge->start) {
		pNew->end = max;   
		break;
	    } else {
		pNew->end = pEdge->start;
		min = pEdge->end;
	    }
	} else
	    min = pEdge->end;

	pPrev = pEdge;
	pEdge = pEdge->next;

	if(max <= min) break;
   }
	
   return edge;
}

static void
FillOutEdge(xf86EdgePtr pEdge, int limit)
{
    xf86EdgePtr pNext;
    int diff;

    if(pEdge->start > 0) pEdge->start = 0;

    while((pNext = pEdge->next)) {
	diff = pNext->start - pEdge->end;
	if(diff > 0) {	
	    pEdge->end += diff >> 1;
	    pNext->start -= diff - (diff >> 1);
	}
	pEdge = pNext;
    }

    if(pEdge->end < limit)
	pEdge->end = limit;    
}

/*
 * xf86InitOrigins() can deal with a maximum of 32 screens
 * on 32 bit architectures, 64 on 64 bit architectures.
 */

void
xf86InitOrigins(void)
{
    unsigned long screensLeft, prevScreensLeft, mask;
    screenLayoutPtr screen;
    ScreenPtr pScreen;
    int x1, x2, y1, y2, left, right, top, bottom;
    int i, j, ref, minX, minY, min, max;
    xf86ScreenLayoutPtr pLayout;
    Bool OldStyleConfig = FALSE;

    /* need to have this set up with a config file option */
    HardEdges = FALSE;

    bzero(xf86ScreenLayout, MAXSCREENS * sizeof(xf86ScreenLayoutRec));
	
    screensLeft = prevScreensLeft = (1 << xf86NumScreens) - 1;

    while(1) {
	for(mask = screensLeft, i = 0; mask; mask >>= 1, i++) {
	    if(!(mask & 1L)) continue;

	    screen = &xf86ConfigLayout.screens[i];

	    switch(screen->where) {
	    case PosObsolete:
		OldStyleConfig = TRUE;
		pLayout = &xf86ScreenLayout[i];
		/* force edge lists */
		if(screen->left) {
		    ref = screen->left->screennum;
		    pLayout->left = AddEdge(pLayout->left, 
			0, xf86Screens[i]->pScreen->height,
			xf86Screens[ref]->pScreen->width, 0, ref);
		}
		if(screen->right) {
		    ref = screen->right->screennum;
		    pScreen = xf86Screens[i]->pScreen;
		    pLayout->right = AddEdge(pLayout->right, 
			0, pScreen->height, -pScreen->width, 0, ref);
		}
		if(screen->top) {
		    ref = screen->top->screennum;
		    pLayout->up = AddEdge(pLayout->up, 
			0, xf86Screens[i]->pScreen->width,
			0, xf86Screens[ref]->pScreen->height, ref);
		}
		if(screen->bottom) {
		    ref = screen->bottom->screennum;
		    pScreen = xf86Screens[i]->pScreen;
		    pLayout->down = AddEdge(pLayout->down, 
			0, pScreen->width, 0, -pScreen->height, ref);
		}
	        /* we could also try to place it based on those
		   relative locations if we wanted to */
		screen->x = screen->y = 0;
		/* FALLTHROUGH */
	    case PosAbsolute:
		dixScreenOrigins[i].x = screen->x;
		dixScreenOrigins[i].y = screen->y;
		screensLeft &= ~(1 << i);
		break;
	    case PosRelative:
		ref = screen->refscreen->screennum;
		if(screensLeft & (1 << ref)) break;
		dixScreenOrigins[i].x = dixScreenOrigins[ref].x + screen->x;
		dixScreenOrigins[i].y = dixScreenOrigins[ref].y + screen->y;
		screensLeft &= ~(1 << i);
		break;
	    case PosRightOf:
		ref = screen->refscreen->screennum;
		if(screensLeft & (1 << ref)) break;
		pScreen = xf86Screens[ref]->pScreen;
		dixScreenOrigins[i].x = 
			dixScreenOrigins[ref].x + pScreen->width;
		dixScreenOrigins[i].y = dixScreenOrigins[ref].y;
		screensLeft &= ~(1 << i);
		break;
	    case PosLeftOf:
		ref = screen->refscreen->screennum;
		if(screensLeft & (1 << ref)) break;
		pScreen = xf86Screens[i]->pScreen;
		dixScreenOrigins[i].x = 
			dixScreenOrigins[ref].x - pScreen->width;
		dixScreenOrigins[i].y = dixScreenOrigins[ref].y;
		screensLeft &= ~(1 << i);
		break;
	    case PosBelow:
		ref = screen->refscreen->screennum;
		if(screensLeft & (1 << ref)) break;
		pScreen = xf86Screens[ref]->pScreen;
		dixScreenOrigins[i].x = dixScreenOrigins[ref].x;
		dixScreenOrigins[i].y = 
			dixScreenOrigins[ref].y + pScreen->height;
		screensLeft &= ~(1 << i);
		break;
	    case PosAbove:
		ref = screen->refscreen->screennum;
		if(screensLeft & (1 << ref)) break;
		pScreen = xf86Screens[i]->pScreen;
		dixScreenOrigins[i].x = dixScreenOrigins[ref].x;
		dixScreenOrigins[i].y = 
			dixScreenOrigins[ref].y - pScreen->height;
		screensLeft &= ~(1 << i);
		break;
	    default:
		ErrorF("Illegal placement keyword in Layout!\n");
		break;
	    }

	}

	if(!screensLeft) break;

	if(screensLeft == prevScreensLeft) {
	/* All the remaining screens are referencing each other.
	   Assign a value to one of them and go through again */
	    i = 0;
	    while(!((1 << i) & screensLeft)){ i++; }

	    ref = xf86ConfigLayout.screens[i].refscreen->screennum;
	    dixScreenOrigins[ref].x = dixScreenOrigins[ref].y = 0;
	    screensLeft &= ~(1 << ref);
	}

	prevScreensLeft = screensLeft;
    }

    /* justify the topmost and leftmost to (0,0) */
    minX = dixScreenOrigins[0].x;
    minY = dixScreenOrigins[0].y;

    for(i = 1; i < xf86NumScreens; i++) {
	if(dixScreenOrigins[i].x < minX)
	  minX = dixScreenOrigins[i].x;
	if(dixScreenOrigins[i].y < minY)
	  minY = dixScreenOrigins[i].y;
    }

    if (minX || minY) {
	for(i = 0; i < xf86NumScreens; i++) {
	   dixScreenOrigins[i].x -= minX;
	   dixScreenOrigins[i].y -= minY;
	}
    }


    /* Create the edge lists */

    if(!OldStyleConfig) {
      for(i = 0; i < xf86NumScreens; i++) {
	pLayout = &xf86ScreenLayout[i];

	pScreen = xf86Screens[i]->pScreen;

	left = dixScreenOrigins[i].x;
	right = left + pScreen->width;
	top = dixScreenOrigins[i].y;
	bottom = top + pScreen->height;

	for(j = 0; j < xf86NumScreens; j++) {
	    if(i == j) continue;

	    x1 = dixScreenOrigins[j].x;
	    x2 = x1 + xf86Screens[j]->pScreen->width;
	    y1 = dixScreenOrigins[j].y;
	    y2 = y1 + xf86Screens[j]->pScreen->height;

	    if((bottom > y1) && (top < y2)) {
		min = y1 - top;
		if(min < 0) min = 0;
		max = pScreen->height - (bottom - y2);
		if(max > pScreen->height) max = pScreen->height;

		if(((left - 1) >= x1) && ((left - 1) < x2))
		    pLayout->left = AddEdge(pLayout->left, min, max,
			dixScreenOrigins[i].x - dixScreenOrigins[j].x,
			dixScreenOrigins[i].y - dixScreenOrigins[j].y, j);

		if((right >= x1) && (right < x2))	
		    pLayout->right = AddEdge(pLayout->right, min, max,
			dixScreenOrigins[i].x - dixScreenOrigins[j].x,
			dixScreenOrigins[i].y - dixScreenOrigins[j].y, j);
	    }


	    if((left < x2) && (right > x1)) {
		min = x1 - left;
		if(min < 0) min = 0;
		max = pScreen->width - (right - x2);
		if(max > pScreen->width) max = pScreen->width;

		if(((top - 1) >= y1) && ((top - 1) < y2))
		    pLayout->up = AddEdge(pLayout->up, min, max,
			dixScreenOrigins[i].x - dixScreenOrigins[j].x,
			dixScreenOrigins[i].y - dixScreenOrigins[j].y, j);

		if((bottom >= y1) && (bottom < y2))
		    pLayout->down = AddEdge(pLayout->down, min, max,
			dixScreenOrigins[i].x - dixScreenOrigins[j].x,
			dixScreenOrigins[i].y - dixScreenOrigins[j].y, j);
	    }
	}
      }
    }

    if(!HardEdges && !OldStyleConfig) {
	for(i = 0; i < xf86NumScreens; i++) {
	    pLayout = &xf86ScreenLayout[i];
	    pScreen = xf86Screens[i]->pScreen;
	    if(pLayout->left) 
		FillOutEdge(pLayout->left, pScreen->height);
	    if(pLayout->right) 
		FillOutEdge(pLayout->right, pScreen->height);
	    if(pLayout->up) 
		FillOutEdge(pLayout->up, pScreen->width);
	    if(pLayout->down) 
		FillOutEdge(pLayout->down, pScreen->width);
	}
    }
}

void
xf86ReconfigureLayout(void)
{
    int i;

    for (i = 0; i < MAXSCREENS; i++) {
	xf86ScreenLayoutPtr sl = &xf86ScreenLayout[i];
	/* we don't have to zero these, xf86InitOrigins() takes care of that */
	if (sl->left) xfree(sl->left);
	if (sl->right) xfree(sl->right);
	if (sl->up) xfree(sl->up);
	if (sl->down) xfree(sl->down);
    }

    xf86InitOrigins();
}

	

--- NEW FILE: xf86DGA.c ---
/* $XdotOrg: xc/programs/Xserver/hw/xfree86/common/xf86DGA.c,v 1.1.4.3.2.3 2004/03/04 20:16:18 kaleb Exp $ */
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86DGA.c,v 1.46 2002/12/03 18:17:40 tsi Exp $ */
/*
 * Copyright (c) 1998-2002 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
[...1166 lines suppressed...]

   w = pScrn->currentMode->HDisplay;
   h = pScrn->currentMode->VDisplay;
   p = ((pScrn->displayWidth * (pScrn->bitsPerPixel >> 3)) + 3) & ~3L;

   for(i = 0; i < pScreenPriv->numModes; i++) {
	mode = &(pScreenPriv->modes[i]);
  	      
	if((mode->viewportWidth == w) && (mode->viewportHeight == h) &&
		(mode->bytesPerScanline == p) && 
		(mode->bitsPerPixel == pScrn->bitsPerPixel) &&
		(mode->depth == pScrn->depth)) {

		return mode->num;
	}
   }

   return 0;
}


--- NEW FILE: xf86DPMS.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86DPMS.c,v 1.11 2003/11/11 21:02:28 dawes Exp $ */

/*
 * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 * This file contains the DPMS functions required by the extension.
 */

#include <X11/X.h>
#include "os.h"
#include "globals.h"
#include "xf86.h"
#include "xf86Priv.h"
#ifdef DPMSExtension
#define DPMS_SERVER
#include <X11/extensions/dpms.h>
#include "dpmsproc.h"
#endif


#ifdef DPMSExtension
static int DPMSGeneration = 0;
static int DPMSIndex = -1;
static Bool DPMSClose(int i, ScreenPtr pScreen);
static int DPMSCount = 0;
#endif


Bool
xf86DPMSInit(ScreenPtr pScreen, DPMSSetProcPtr set, int flags)
{
#ifdef DPMSExtension
    ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
    DPMSPtr pDPMS;
    pointer DPMSOpt;

    if (serverGeneration != DPMSGeneration) {
	if ((DPMSIndex = AllocateScreenPrivateIndex()) < 0)
	    return FALSE;
	DPMSGeneration = serverGeneration;
    }

    if (DPMSDisabledSwitch)
	DPMSEnabled = FALSE;
    if (!(pScreen->devPrivates[DPMSIndex].ptr = xcalloc(sizeof(DPMSRec), 1)))
	return FALSE;

    pDPMS = (DPMSPtr)pScreen->devPrivates[DPMSIndex].ptr;
    pScrn->DPMSSet = set;
    pDPMS->Flags = flags;
    DPMSOpt = xf86FindOption(pScrn->options, "dpms");
    if (DPMSOpt) {
	if ((pDPMS->Enabled
	    = xf86SetBoolOption(pScrn->options, "dpms", FALSE))
	    && !DPMSDisabledSwitch)
	    DPMSEnabled = TRUE;
	xf86MarkOptionUsed(DPMSOpt);
	xf86DrvMsg(pScreen->myNum, X_CONFIG, "DPMS enabled\n");
    } else if (DPMSEnabledSwitch) {
	if (!DPMSDisabledSwitch)
	    DPMSEnabled = TRUE;
	pDPMS->Enabled = TRUE;
    }  
    else {
	pDPMS->Enabled = FALSE;
    }
    pDPMS->CloseScreen = pScreen->CloseScreen;
    pScreen->CloseScreen = DPMSClose;
    DPMSCount++;
    return TRUE;
#else
    return FALSE;
#endif
}


#ifdef DPMSExtension

static Bool
DPMSClose(int i, ScreenPtr pScreen)
{
    DPMSPtr pDPMS;

    /* This shouldn't happen */
    if (DPMSIndex < 0)
	return FALSE;

    pDPMS = (DPMSPtr)pScreen->devPrivates[DPMSIndex].ptr;

    /* This shouldn't happen */
    if (!pDPMS)
	return FALSE;

    pScreen->CloseScreen = pDPMS->CloseScreen;

    xfree((pointer)pDPMS);
    pScreen->devPrivates[DPMSIndex].ptr = NULL;
    if (--DPMSCount == 0)
	DPMSIndex = -1;
    return pScreen->CloseScreen(i, pScreen);
}


/*
 * DPMSSet --
 *	Device dependent DPMS mode setting hook.  This is called whenever
 *	the DPMS mode is to be changed.
 */
void
DPMSSet(int level)
{
    int i;
    DPMSPtr pDPMS;
    ScrnInfoPtr pScrn;

    DPMSPowerLevel = level;

    if (DPMSIndex < 0)
	return;

    if (level != DPMSModeOn)
	SaveScreens(SCREEN_SAVER_FORCER, ScreenSaverActive);

    /* For each screen, set the DPMS level */
    for (i = 0; i < xf86NumScreens; i++) {
    	pScrn = xf86Screens[i];
	pDPMS = (DPMSPtr)screenInfo.screens[i]->devPrivates[DPMSIndex].ptr;
	if (pDPMS && pScrn->DPMSSet && pDPMS->Enabled && pScrn->vtSema) { 
	    xf86EnableAccess(pScrn);
	    pScrn->DPMSSet(pScrn, level, 0);
	}
    }
}


/*
 * DPMSSupported --
 *	Return TRUE if any screen supports DPMS.
 */
Bool
DPMSSupported(void)
{
    int i;
    DPMSPtr pDPMS;
    ScrnInfoPtr pScrn;

    if (DPMSIndex < 0) {
	return FALSE;
    }

    /* For each screen, check if DPMS is supported */
    for (i = 0; i < xf86NumScreens; i++) {
    	pScrn = xf86Screens[i];
	pDPMS = (DPMSPtr)screenInfo.screens[i]->devPrivates[DPMSIndex].ptr;
	if (pDPMS && pScrn->DPMSSet)
	    return TRUE;
    }
    return FALSE;
}


/*
 * DPMSGet --
 *	Device dependent DPMS mode getting hook.  This returns the current
 *	DPMS mode, or -1 if DPMS is not supported.
 *
 *	This should hook in to the appropriate driver-level function, which
 *	will be added to the ScrnInfoRec.
 *
 *	NOTES:
 *	 1. the calling interface should be changed to specify which
 *	    screen to check.
 *	 2. It isn't clear that this function is ever used or what it should
 *	    return.
 */
int
DPMSGet(int *level)
{
    return DPMSPowerLevel;
}

#endif /* DPMSExtension */

--- NEW FILE: xf86Debug.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Debug.c,v 1.7 2003/09/24 02:43:17 dawes Exp $ */

/*
 * Copyright (c) 2000-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

#ifdef __UNIXOS2__
#define I_NEED_OS2_H
#endif

#include <sys/time.h>
#include <unistd.h> 
#include <X11/X.h>
#include "os.h"
#include "xf86.h"
#include "xf86Priv.h"
#include "xf86_OSlib.h"
#include "compiler.h"

void xf86Break1(void)
{
}

void xf86Break2(void)
{
}

void xf86Break3(void)
{
}

char *xf86p8bit[] = { "00000000", "00000001", "00000010", "00000011", 
		      "00000100", "00000101", "00000110", "00000111", 
		      "00001000", "00001001", "00001010", "00001011", 
		      "00001100", "00001101", "00001110", "00001111", 
		      "00010000", "00010001", "00010010", "00010011", 
		      "00010100", "00010101", "00010110", "00010111", 
		      "00011000", "00011001", "00011010", "00011011", 
		      "00011100", "00011101", "00011110", "00011111", 
		      "00100000", "00100001", "00100010", "00100011", 
		      "00100100", "00100101", "00100110", "00100111", 
		      "00101000", "00101001", "00101010", "00101011", 
		      "00101100", "00101101", "00101110", "00101111", 
		      "00110000", "00110001", "00110010", "00110011", 
		      "00110100", "00110101", "00110110", "00110111", 
		      "00111000", "00111001", "00111010", "00111011", 
		      "00111100", "00111101", "00111110", "00111111", 
		      "01000000", "01000001", "01000010", "01000011", 
		      "01000100", "01000101", "01000110", "01000111", 
		      "01001000", "01001001", "01001010", "01001011", 
		      "01001100", "01001101", "01001110", "01001111", 
		      "01010000", "01010001", "01010010", "01010011", 
		      "01010100", "01010101", "01010110", "01010111", 
		      "01011000", "01011001", "01011010", "01011011", 
		      "01011100", "01011101", "01011110", "01011111", 
		      "01100000", "01100001", "01100010", "01100011", 
		      "01100100", "01100101", "01100110", "01100111", 
		      "01101000", "01101001", "01101010", "01101011", 
		      "01101100", "01101101", "01101110", "01101111", 
		      "01110000", "01110001", "01110010", "01110011", 
		      "01110100", "01110101", "01110110", "01110111", 
		      "01111000", "01111001", "01111010", "01111011", 
		      "01111100", "01111101", "01111110", "01111111", 
		      "10000000", "10000001", "10000010", "10000011", 
		      "10000100", "10000101", "10000110", "10000111", 
		      "10001000", "10001001", "10001010", "10001011", 
		      "10001100", "10001101", "10001110", "10001111", 
		      "10010000", "10010001", "10010010", "10010011", 
		      "10010100", "10010101", "10010110", "10010111", 
		      "10011000", "10011001", "10011010", "10011011", 
		      "10011100", "10011101", "10011110", "10011111", 
		      "10100000", "10100001", "10100010", "10100011", 
		      "10100100", "10100101", "10100110", "10100111", 
		      "10101000", "10101001", "10101010", "10101011", 
		      "10101100", "10101101", "10101110", "10101111", 
		      "10110000", "10110001", "10110010", "10110011", 
		      "10110100", "10110101", "10110110", "10110111", 
		      "10111000", "10111001", "10111010", "10111011", 
		      "10111100", "10111101", "10111110", "10111111", 
		      "11000000", "11000001", "11000010", "11000011", 
		      "11000100", "11000101", "11000110", "11000111", 
		      "11001000", "11001001", "11001010", "11001011", 
		      "11001100", "11001101", "11001110", "11001111", 
		      "11010000", "11010001", "11010010", "11010011", 
		      "11010100", "11010101", "11010110", "11010111", 
		      "11011000", "11011001", "11011010", "11011011", 
		      "11011100", "11011101", "11011110", "11011111", 
		      "11100000", "11100001", "11100010", "11100011", 
		      "11100100", "11100101", "11100110", "11100111", 
		      "11101000", "11101001", "11101010", "11101011", 
		      "11101100", "11101101", "11101110", "11101111", 
		      "11110000", "11110001", "11110010", "11110011", 
		      "11110100", "11110101", "11110110", "11110111", 
		      "11111000", "11111001", "11111010", "11111011", 
		      "11111100", "11111101", "11111110", "11111111"
};

CARD32 xf86DummyVar1;
CARD32 xf86DummyVar2;
CARD32 xf86DummyVar3;

CARD8  xf86PeekFb8(CARD8  *p) { return *p; }
CARD16 xf86PeekFb16(CARD16 *p) { return *p; }
CARD32 xf86PeekFb32(CARD32 *p) { return *p; }
void xf86PokeFb8(CARD8  *p, CARD8  v) { *p = v; }
void xf86PokeFb16(CARD16 *p, CARD16 v) { *p = v; }
void xf86PokeFb32(CARD16 *p, CARD32 v) { *p = v; }

CARD8  xf86PeekMmio8(pointer Base, unsigned long Offset)
{
    return MMIO_IN8(Base,Offset);
}

CARD16 xf86PeekMmio16(pointer Base, unsigned long Offset)
{
    return MMIO_IN16(Base,Offset);
}

CARD32 xf86PeekMmio32(pointer Base, unsigned long Offset)
{
    return MMIO_IN32(Base,Offset);
}

void xf86PokeMmio8(pointer Base, unsigned long Offset, CARD8  v)
{
    MMIO_OUT8(Base,Offset,v);
}

void xf86PokeMmio16(pointer Base, unsigned long Offset, CARD16 v)
{
    MMIO_OUT16(Base,Offset,v);
}

void xf86PokeMmio32(pointer Base, unsigned long Offset, CARD32 v)
{
    MMIO_OUT32(Base,Offset,v);
}


void
xf86STimestamp(xf86TsPtr* timestamp)
{
    if (*timestamp) {
	gettimeofday((struct timeval*)*timestamp,NULL);
    } else {
	*timestamp = xnfalloc(sizeof(xf86TsRec));
	gettimeofday((struct timeval*)*timestamp,NULL);
    }
}

void
xf86SPTimestamp(xf86TsPtr* timestamp, char *str)
{
    if (*timestamp) {
	long diff;
	struct timeval ts;
	ts = **(struct timeval**)timestamp;
	gettimeofday((struct timeval*)*timestamp,NULL);
	if (ts.tv_usec > (*timestamp)->usec) 
	    diff = ((*timestamp)->sec - ts.tv_sec - 1) * 1000
		+ (ts.tv_usec - (*timestamp)->usec) / 1000;
	else
	    diff =  ((*timestamp)->sec - ts.tv_sec) * 1000
		+(- ts.tv_usec + (*timestamp)->usec) / 1000;
	ErrorF("%s Elapsed: %li\n",str,diff);
    } else {
	*timestamp = xnfalloc(sizeof(xf86TsRec));
	gettimeofday((struct timeval*)*timestamp,NULL);
    }
}

--- NEW FILE: xf86DefModes.c ---
/* $XFree86$ */

/* THIS FILE IS AUTOMATICALLY GENERATED -- DO NOT EDIT -- LOOK at
 * modeline2c.pl */

/*
 * Copyright 1999-2003 by The XFree86 Project, Inc.
 *
 * Author: Dirk Hohndel <hohndel at XFree86.Org>
 */

#ifdef __UNIXOS2__
#define I_NEED_OS2_H
#endif
#include "xf86.h"
#include "xf86Config.h"
#include "xf86Priv.h"
#include "xf86_OSlib.h"

#include "globals.h"

#define MODEPREFIX(name) NULL, NULL, name, MODE_OK, M_T_DEFAULT
#define MODESUFFIX       0,0, 0,0,0,0,0,0,0, 0,0,0,0,0,0,FALSE,FALSE,0,NULL,0,0.0,0.0

DisplayModeRec xf86DefaultModes [] = {
/* 640x350 @ 85Hz (VESA) hsync: 37.9kHz */
	{MODEPREFIX("640x350"),31500, 640,672,736,832,0, 350,382,385,445,0, V_PHSYNC | V_NVSYNC, MODESUFFIX},
	{MODEPREFIX("320x175"),15750, 320,336,368,416,0, 175,191,192,222,0, V_PHSYNC | V_NVSYNC | V_DBLSCAN, MODESUFFIX},
/* 640x400 @ 85Hz (VESA) hsync: 37.9kHz */
	{MODEPREFIX("640x400"),31500, 640,672,736,832,0, 400,401,404,445,0, V_NHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("320x200"),15750, 320,336,368,416,0, 200,200,202,222,0, V_NHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 720x400 @ 85Hz (VESA) hsync: 37.9kHz */
	{MODEPREFIX("720x400"),35500, 720,756,828,936,0, 400,401,404,446,0, V_NHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("360x200"),17750, 360,378,414,468,0, 200,200,202,223,0, V_NHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 640x480 @ 60Hz (Industry standard) hsync: 31.5kHz */
	{MODEPREFIX("640x480"),25200, 640,656,752,800,0, 480,490,492,525,0, V_NHSYNC | V_NVSYNC, MODESUFFIX},
	{MODEPREFIX("320x240"),12600, 320,328,376,400,0, 240,245,246,262,0, V_NHSYNC | V_NVSYNC | V_DBLSCAN, MODESUFFIX},
/* 640x480 @ 72Hz (VESA) hsync: 37.9kHz */
	{MODEPREFIX("640x480"),31500, 640,664,704,832,0, 480,489,491,520,0, V_NHSYNC | V_NVSYNC, MODESUFFIX},
	{MODEPREFIX("320x240"),15750, 320,332,352,416,0, 240,244,245,260,0, V_NHSYNC | V_NVSYNC | V_DBLSCAN, MODESUFFIX},
/* 640x480 @ 75Hz (VESA) hsync: 37.5kHz */
	{MODEPREFIX("640x480"),31500, 640,656,720,840,0, 480,481,484,500,0, V_NHSYNC | V_NVSYNC, MODESUFFIX},
	{MODEPREFIX("320x240"),15750, 320,328,360,420,0, 240,240,242,250,0, V_NHSYNC | V_NVSYNC | V_DBLSCAN, MODESUFFIX},
/* 640x480 @ 85Hz (VESA) hsync: 43.3kHz */
	{MODEPREFIX("640x480"),36000, 640,696,752,832,0, 480,481,484,509,0, V_NHSYNC | V_NVSYNC, MODESUFFIX},
	{MODEPREFIX("320x240"),18000, 320,348,376,416,0, 240,240,242,254,0, V_NHSYNC | V_NVSYNC | V_DBLSCAN, MODESUFFIX},
/* 800x600 @ 56Hz (VESA) hsync: 35.2kHz */
	{MODEPREFIX("800x600"),36000, 800,824,896,1024,0, 600,601,603,625,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("400x300"),18000, 400,412,448,512,0, 300,300,301,312,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 800x600 @ 60Hz (VESA) hsync: 37.9kHz */
	{MODEPREFIX("800x600"),40000, 800,840,968,1056,0, 600,601,605,628,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("400x300"),20000, 400,420,484,528,0, 300,300,302,314,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 800x600 @ 72Hz (VESA) hsync: 48.1kHz */
	{MODEPREFIX("800x600"),50000, 800,856,976,1040,0, 600,637,643,666,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("400x300"),25000, 400,428,488,520,0, 300,318,321,333,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 800x600 @ 75Hz (VESA) hsync: 46.9kHz */
	{MODEPREFIX("800x600"),49500, 800,816,896,1056,0, 600,601,604,625,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("400x300"),24750, 400,408,448,528,0, 300,300,302,312,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 800x600 @ 85Hz (VESA) hsync: 53.7kHz */
	{MODEPREFIX("800x600"),56300, 800,832,896,1048,0, 600,601,604,631,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("400x300"),28150, 400,416,448,524,0, 300,300,302,315,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1024x768i @ 43Hz (industry standard) hsync: 35.5kHz */
	{MODEPREFIX("1024x768"),44900, 1024,1032,1208,1264,0, 768,768,776,817,0, V_PHSYNC | V_PVSYNC | V_INTERLACE, MODESUFFIX},
	{MODEPREFIX("512x384"),22450, 512,516,604,632,0, 384,384,388,408,0, V_PHSYNC | V_PVSYNC | V_INTERLACE | V_DBLSCAN, MODESUFFIX},
/* 1024x768 @ 60Hz (VESA) hsync: 48.4kHz */
	{MODEPREFIX("1024x768"),65000, 1024,1048,1184,1344,0, 768,771,777,806,0, V_NHSYNC | V_NVSYNC, MODESUFFIX},
	{MODEPREFIX("512x384"),32500, 512,524,592,672,0, 384,385,388,403,0, V_NHSYNC | V_NVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1024x768 @ 70Hz (VESA) hsync: 56.5kHz */
	{MODEPREFIX("1024x768"),75000, 1024,1048,1184,1328,0, 768,771,777,806,0, V_NHSYNC | V_NVSYNC, MODESUFFIX},
	{MODEPREFIX("512x384"),37500, 512,524,592,664,0, 384,385,388,403,0, V_NHSYNC | V_NVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1024x768 @ 75Hz (VESA) hsync: 60.0kHz */
	{MODEPREFIX("1024x768"),78800, 1024,1040,1136,1312,0, 768,769,772,800,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("512x384"),39400, 512,520,568,656,0, 384,384,386,400,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1024x768 @ 85Hz (VESA) hsync: 68.7kHz */
	{MODEPREFIX("1024x768"),94500, 1024,1072,1168,1376,0, 768,769,772,808,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("512x384"),47250, 512,536,584,688,0, 384,384,386,404,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1152x864 @ 75Hz (VESA) hsync: 67.5kHz */
	{MODEPREFIX("1152x864"),108000, 1152,1216,1344,1600,0, 864,865,868,900,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("576x432"),54000, 576,608,672,800,0, 432,432,434,450,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1280x960 @ 60Hz (VESA) hsync: 60.0kHz */
	{MODEPREFIX("1280x960"),108000, 1280,1376,1488,1800,0, 960,961,964,1000,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("640x480"),54000, 640,688,744,900,0, 480,480,482,500,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1280x960 @ 85Hz (VESA) hsync: 85.9kHz */
	{MODEPREFIX("1280x960"),148500, 1280,1344,1504,1728,0, 960,961,964,1011,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("640x480"),74250, 640,672,752,864,0, 480,480,482,505,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1280x1024 @ 60Hz (VESA) hsync: 64.0kHz */
	{MODEPREFIX("1280x1024"),108000, 1280,1328,1440,1688,0, 1024,1025,1028,1066,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("640x512"),54000, 640,664,720,844,0, 512,512,514,533,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1280x1024 @ 75Hz (VESA) hsync: 80.0kHz */
	{MODEPREFIX("1280x1024"),135000, 1280,1296,1440,1688,0, 1024,1025,1028,1066,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("640x512"),67500, 640,648,720,844,0, 512,512,514,533,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1280x1024 @ 85Hz (VESA) hsync: 91.1kHz */
	{MODEPREFIX("1280x1024"),157500, 1280,1344,1504,1728,0, 1024,1025,1028,1072,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("640x512"),78750, 640,672,752,864,0, 512,512,514,536,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1600x1200 @ 60Hz (VESA) hsync: 75.0kHz */
	{MODEPREFIX("1600x1200"),162000, 1600,1664,1856,2160,0, 1200,1201,1204,1250,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("800x600"),81000, 800,832,928,1080,0, 600,600,602,625,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1600x1200 @ 65Hz (VESA) hsync: 81.3kHz */
	{MODEPREFIX("1600x1200"),175500, 1600,1664,1856,2160,0, 1200,1201,1204,1250,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("800x600"),87750, 800,832,928,1080,0, 600,600,602,625,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1600x1200 @ 70Hz (VESA) hsync: 87.5kHz */
	{MODEPREFIX("1600x1200"),189000, 1600,1664,1856,2160,0, 1200,1201,1204,1250,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("800x600"),94500, 800,832,928,1080,0, 600,600,602,625,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1600x1200 @ 75Hz (VESA) hsync: 93.8kHz */
	{MODEPREFIX("1600x1200"),202500, 1600,1664,1856,2160,0, 1200,1201,1204,1250,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("800x600"),101250, 800,832,928,1080,0, 600,600,602,625,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1600x1200 @ 85Hz (VESA) hsync: 106.3kHz */
	{MODEPREFIX("1600x1200"),229500, 1600,1664,1856,2160,0, 1200,1201,1204,1250,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("800x600"),114750, 800,832,928,1080,0, 600,600,602,625,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1792x1344 @ 60Hz (VESA) hsync: 83.6kHz */
	{MODEPREFIX("1792x1344"),204800, 1792,1920,2120,2448,0, 1344,1345,1348,1394,0, V_NHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("896x672"),102400, 896,960,1060,1224,0, 672,672,674,697,0, V_NHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1792x1344 @ 75Hz (VESA) hsync: 106.3kHz */
	{MODEPREFIX("1792x1344"),261000, 1792,1888,2104,2456,0, 1344,1345,1348,1417,0, V_NHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("896x672"),130500, 896,944,1052,1228,0, 672,672,674,708,0, V_NHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1856x1392 @ 60Hz (VESA) hsync: 86.3kHz */
	{MODEPREFIX("1856x1392"),218300, 1856,1952,2176,2528,0, 1392,1393,1396,1439,0, V_NHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("928x696"),109150, 928,976,1088,1264,0, 696,696,698,719,0, V_NHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1856x1392 @ 75Hz (VESA) hsync: 112.5kHz */
	{MODEPREFIX("1856x1392"),288000, 1856,1984,2208,2560,0, 1392,1393,1396,1500,0, V_NHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("928x696"),144000, 928,992,1104,1280,0, 696,696,698,750,0, V_NHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1920x1440 @ 60Hz (VESA) hsync: 90.0kHz */
	{MODEPREFIX("1920x1440"),234000, 1920,2048,2256,2600,0, 1440,1441,1444,1500,0, V_NHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("960x720"),117000, 960,1024,1128,1300,0, 720,720,722,750,0, V_NHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1920x1440 @ 75Hz (VESA) hsync: 112.5kHz */
	{MODEPREFIX("1920x1440"),297000, 1920,2064,2288,2640,0, 1440,1441,1444,1500,0, V_NHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("960x720"),148500, 960,1032,1144,1320,0, 720,720,722,750,0, V_NHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 832x624 @ 75Hz (74.55Hz) (fix if the official/Apple spec is different) hsync: 49.725kHz */
	{MODEPREFIX("832x624"),57284, 832,864,928,1152,0, 624,625,628,667,0, V_NHSYNC | V_NVSYNC, MODESUFFIX},
	{MODEPREFIX("416x312"),28642, 416,432,464,576,0, 312,312,314,333,0, V_NHSYNC | V_NVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1152x768 @ 54.8Hz (Titanium PowerBook) hsync: 44.2kHz */
	{MODEPREFIX("1152x768"),64995, 1152,1178,1314,1472,0, 768,771,777,806,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("576x384"),32497, 576,589,657,736,0, 384,385,388,403,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1400x1050 @ 60Hz (VESA GTF) hsync: 65.5kHz */
	{MODEPREFIX("1400x1050"),122000, 1400,1488,1640,1880,0, 1050,1052,1064,1082,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("700x525"),61000, 700,744,820,940,0, 525,526,532,541,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1400x1050 @ 75Hz (VESA GTF) hsync: 82.2kHz */
	{MODEPREFIX("1400x1050"),155800, 1400,1464,1784,1912,0, 1050,1052,1064,1090,0, V_PHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("700x525"),77900, 700,732,892,956,0, 525,526,532,545,0, V_PHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1600x1024 @ 60Hz (SGI 1600SW) hsync: 64.0kHz */
	{MODEPREFIX("1600x1024"),106910, 1600,1620,1640,1670,0, 1024,1027,1030,1067,0, V_NHSYNC | V_NVSYNC, MODESUFFIX},
	{MODEPREFIX("800x512"),53455, 800,810,820,835,0, 512,513,515,533,0, V_NHSYNC | V_NVSYNC | V_DBLSCAN, MODESUFFIX},
/* 1920x1440 @ 85Hz (VESA GTF) hsync: 128.5kHz */
	{MODEPREFIX("1920x1440"),341350, 1920,2072,2288,2656,0, 1440,1441,1444,1512,0, V_NHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("960x720"),170675, 960,1036,1144,1328,0, 720,720,722,756,0, V_NHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 2048x1536 @ 60Hz (VESA GTF) hsync: 95.3kHz */
	{MODEPREFIX("2048x1536"),266950, 2048,2200,2424,2800,0, 1536,1537,1540,1589,0, V_NHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("1024x768"),133475, 1024,1100,1212,1400,0, 768,768,770,794,0, V_NHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 2048x1536 @ 75Hz (VESA GTF) hsync: 120.2kHz */
	{MODEPREFIX("2048x1536"),340480, 2048,2216,2440,2832,0, 1536,1537,1540,1603,0, V_NHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("1024x768"),170240, 1024,1108,1220,1416,0, 768,768,770,801,0, V_NHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
/* 2048x1536 @ 85Hz (VESA GTF) hsync: 137.0kHz */
	{MODEPREFIX("2048x1536"),388040, 2048,2216,2440,2832,0, 1536,1537,1540,1612,0, V_NHSYNC | V_PVSYNC, MODESUFFIX},
	{MODEPREFIX("1024x768"),194020, 1024,1108,1220,1416,0, 768,768,770,806,0, V_NHSYNC | V_PVSYNC | V_DBLSCAN, MODESUFFIX},
	{MODEPREFIX(NULL),0,0,0,0,0,0,0,0,0,0,0,0,MODESUFFIX}
};

--- NEW FILE: xf86DoProbe.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86DoProbe.c,v 1.14 2003/10/29 04:17:21 dawes Exp $ */
/*
 * Copyright (c) 1999-2002 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 * finish setting up the server
 * Load the driver modules and call their probe functions.
 */

#include <ctype.h>
#include <stdlib.h>
#include <X11/X.h>
#include <X11/Xmd.h>
#include "os.h"
#ifdef XFree86LOADER
#include "loaderProcs.h"
#include "xf86Config.h"
#endif /* XFree86LOADER */
#include "xf86.h"
#include "xf86Priv.h"

void
DoProbeArgs(int argc, char **argv, int i)
{
}

void
DoProbe()
{
    int i;
    Bool probeResult;

#ifdef XFree86LOADER
    /* Find the list of video driver modules. */
    char **list = xf86DriverlistFromCompile();
    char **l;

    if (list) {
	ErrorF("List of video driver modules:\n");
	for (l = list; *l; l++)
	    ErrorF("\t%s\n", *l);
    } else {
	ErrorF("No video driver modules found\n");
    }

    /* Load all the drivers that were found. */
    xf86LoadModules(list, NULL);
#endif /* XFree86LOADER */

    /* Disable PCI devices */
    xf86AccessInit();

    /* Call all of the probe functions, reporting the results. */
    for (i = 0; i < xf86NumDrivers; i++) {
	if (xf86DriverList[i]->Probe == NULL) continue;

	xf86MsgVerb(X_INFO, 3, "Probing in driver %s\n",
	    xf86DriverList[i]->driverName);
	probeResult =
	    (*xf86DriverList[i]->Probe)(xf86DriverList[i], PROBE_DETECT);
	if (!probeResult) {
	    xf86ErrorF("Probe in driver `%s' returns FALSE\n",
		xf86DriverList[i]->driverName);
	} else {
	    xf86ErrorF("Probe in driver `%s' returns TRUE\n",
		xf86DriverList[i]->driverName);

	    /* If we have a result, then call driver's Identify function */
	    if (xf86DriverList[i]->Identify != NULL) {
		int verbose = xf86SetVerbosity(1);
		(*xf86DriverList[i]->Identify)(0);
		xf86SetVerbosity(verbose);
	    }
	}
    }

    OsCleanup(TRUE);
    AbortDDX();
    fflush(stderr);
    exit(0);
}

--- NEW FILE: xf86DoScanPci.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86DoScanPci.c,v 1.15 2003/09/23 06:43:46 dawes Exp $ */
/*
 * Copyright (c) 1999-2002 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 * Finish setting up the server.
 * Call the functions from the scanpci module.
 */

#include <ctype.h>
#include <stdlib.h>
#include <X11/X.h>
#include <X11/Xmd.h>
#include "os.h"
#ifdef XFree86LOADER
#include "loaderProcs.h"
#endif
#include "xf86.h"
#include "xf86Priv.h"
#include "xf86Pci.h"
#include "xf86ScanPci.h"


void DoScanPci(int argc, char **argv, int i)
{
  int j,skip,globalVerbose,scanpciVerbose;
  ScanPciSetupProcPtr PciSetup;
  ScanPciDisplayCardInfoProcPtr DisplayPCICardInfo;
#ifdef XFree86LOADER
  int errmaj, errmin;
#endif

  /*
   * first we need to finish setup of the OS so that we can call other
   * functions in the server
   */
  OsInit();

  /*
   * The old verbosity processing that was here isn't useful anymore, but
   * for compatibility purposes, ignore verbosity changes after the -scanpci
   * flag.
   */
  globalVerbose = xf86Verbose;

  /*
   * next we process the arguments that are remaining on the command line,
   * so that things like the module path can be set there
   */
  for ( j = i+1; j < argc; j++ ) {
    if ((skip = ddxProcessArgument(argc, argv, j)))
	j += (skip - 1);
  } 

  /*
   * Was the verbosity level increased?  If so, set it back.
   */
  if (xf86Verbose > globalVerbose)
    xf86SetVerbosity(globalVerbose);

  /*
   * Setting scanpciVerbose to 0 will ensure that the output will go to
   * stderr for all reasonable default stderr verbosity levels.
   */
  scanpciVerbose = 0;

  /*
   * now get the loader set up and load the scanpci module
   */
#ifdef XFree86LOADER
  /* Initialise the loader */
  LoaderInit();
  /* Tell the loader the default module search path */
  LoaderSetPath(xf86ModulePath);

  if (!LoadModule("scanpci", NULL, NULL, NULL, NULL, NULL,
                  &errmaj, &errmin)) {
    LoaderErrorMsg(NULL, "scanpci", errmaj, errmin);
    exit(1);
  }
  if (LoaderCheckUnresolved(LD_RESOLV_IFDONE)) {
      /* For now, just a warning */
      xf86Msg(X_WARNING, "Some symbols could not be resolved!\n");
  }
  PciSetup = (ScanPciSetupProcPtr)LoaderSymbol("ScanPciSetupPciIds");
  DisplayPCICardInfo =
    (ScanPciDisplayCardInfoProcPtr)LoaderSymbol("ScanPciDisplayPCICardInfo");
#else
  PciSetup = ScanPciSetupPciIds;
  DisplayPCICardInfo = ScanPciDisplayPCICardInfo;
#endif

  if (!(*PciSetup)())
    FatalError("ScanPciSetupPciIds() failed\n");
  (*DisplayPCICardInfo)(scanpciVerbose);

  /*
   * That's it; we really should clean things up, but a simple
   * exit seems to be all we need.
   */
  exit(0);
}

--- NEW FILE: xf86Events.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Events.c,v 3.159 2003/11/22 04:22:11 dawes Exp $ */
/*
 * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name of Thomas Roell not be used in
 * advertising or publicity pertaining to distribution of the software without
 * specific, written prior permission.  Thomas Roell makes no representations
 * about the suitability of this software for any purpose.  It is provided
 * "as is" without express or implied warranty.
 *
 * THOMAS ROELL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 * EVENT SHALL THOMAS ROELL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
 * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
[...1589 lines suppressed...]
xf86PostWSKbdEvent(struct wscons_event *event)
{
  int type = event->type;
  int value = event->value;
  unsigned int keycode;
  int blocked;
  
  if (type == WSCONS_EVENT_KEY_UP || type == WSCONS_EVENT_KEY_DOWN) {
    Bool down = (type == WSCONS_EVENT_KEY_DOWN ? TRUE : FALSE);

    /* map the scancodes to standard XFree86 scancode */  	
    keycode = WSKbdToKeycode(value);
    if (!down) keycode |= 0x80;
    /* It seems better to block SIGIO there */
    blocked = xf86BlockSIGIO();
    xf86PostKbdEvent(keycode);
    xf86UnblockSIGIO(blocked);
  }
}
#endif /* WSCONS_SUPPORT */

--- NEW FILE: xf86Globals.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Globals.c,v 1.42 2004/01/27 01:31:44 dawes Exp $ */

/*
 * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 * This file contains all the XFree86 global variables.
 */

#include <X11/X.h>
#include "os.h"
#include "windowstr.h"
#include "propertyst.h"
#include "xf86.h"
#include "xf86Priv.h"
#include "xf86Parser.h"
#include "xf86Xinput.h"
#include "xf86InPriv.h"

/* Globals that video drivers may access */

int xf86ScreenIndex = -1;	/* Index of ScrnInfo in pScreen.devPrivates */
int xf86CreateRootWindowIndex = -1;	/* Index into pScreen.devPrivates */
ScrnInfoPtr *xf86Screens = NULL;	/* List of ScrnInfos */
int xf86PixmapIndex = 0;
const unsigned char byte_reversed[256] =
{
    0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0,
    0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
    0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,
    0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
    0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4,
    0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
    0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec,
    0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
    0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2,
    0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
    0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea,
    0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
    0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6,
    0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
    0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee,
    0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe,
    0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1,
    0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
    0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9,
    0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9,
    0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5,
    0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5,
    0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed,
    0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
    0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3,
    0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3,
    0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb,
    0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb,
    0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7,
    0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
    0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef,
    0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff,
};

/* Globals that input drivers may access */
InputInfoPtr xf86InputDevs = NULL;


/* Globals that video drivers may not access */

xf86InfoRec xf86Info = {
	NULL,		/* pKeyboard */
	NULL,		/* kbdProc */
	NULL,		/* kbdEvents */
	-1,		/* consoleFd */
	-1,		/* kbdFd */
	-1,		/* vtno */
	-1,		/* kbdType */
	-1,		/* kbdRate */
	-1, 		/* kbdDelay */
	-1,		/* bell_pitch */
	-1,		/* bell_duration */
	TRUE,		/* autoRepeat */
	0,		/* leds */
	0,		/* xleds */
	NULL,		/* vtinit */
	0,		/* scanPrefix */
	FALSE,		/* capsLock */
	FALSE,		/* numLock */
	FALSE,		/* scrollLock */
	FALSE,		/* modeSwitchLock */
	FALSE,		/* composeLock */
	FALSE,		/* vtSysreq */
	SKWhenNeeded,	/* ddxSpecialKeys */
	FALSE,		/* ActionKeyBindingsSet */
#if defined(SVR4) && defined(i386)
	FALSE,		/* panix106 */
#endif
#if defined(__OpenBSD__) || defined(__NetBSD__)
	0,		/* wskbdType */
#endif
	NULL,		/* pMouse */
#ifdef XINPUT
	NULL,		/* mouseLocal */
#endif
	-1,		/* lastEventTime */
	FALSE,		/* vtRequestsPending */
	FALSE,		/* inputPending */
	FALSE,		/* dontVTSwitch */
	FALSE,		/* dontZap */
	FALSE,		/* dontZoom */
	FALSE,		/* notrapSignals */
	FALSE,		/* caughtSignal */
	FALSE,		/* sharedMonitor */
	NULL,		/* currentScreen */
#ifdef CSRG_BASED
	-1,		/* screenFd */
	-1,		/* consType */
#endif
#ifdef XKB
	NULL,		/* xkbkeymap */
	NULL,		/* xkbkeycodes */
	NULL,		/* xkbtypes */
	NULL,		/* xkbcompat */
	NULL,		/* xkbsymbols */
	NULL,		/* xkbgeometry */
	FALSE,		/* xkbcomponents_specified */
	NULL,		/* xkbrules */
	NULL,		/* xkbmodel */
	NULL,		/* xkblayout */
	NULL,		/* xkbvariant */
	NULL,		/* xkboptions */
#endif
	FALSE,		/* allowMouseOpenFail */
	TRUE,		/* vidModeEnabled */
	FALSE,		/* vidModeAllowNonLocal */
	TRUE,		/* miscModInDevEnabled */
	FALSE,		/* miscModInDevAllowNonLocal */
	PCIProbe1,	/* pciFlags */
	Pix24DontCare,	/* pixmap24 */
	X_DEFAULT,	/* pix24From */
#if defined(i386) || defined(__i386__)
	FALSE,		/* pc98 */
#endif
	TRUE,		/* pmFlag */
	LogNone,	/* syncLog */
	0,		/* estimateSizesAggressively */
	FALSE,		/* kbdCustomKeycodes */
	FALSE,		/* disableRandR */
	X_DEFAULT	/* randRFrom */
};
const char *xf86ConfigFile = NULL;
const char *xf86InputDeviceList = NULL;
const char *xf86ModulePath = DEFAULT_MODULE_PATH;
MessageType xf86ModPathFrom = X_DEFAULT;
const char *xf86LogFile = DEFAULT_LOGPREFIX;
MessageType xf86LogFileFrom = X_DEFAULT;
Bool xf86LogFileWasOpened = FALSE;
serverLayoutRec xf86ConfigLayout = {NULL, };
confDRIRec xf86ConfigDRI = {0, };
XF86ConfigPtr xf86configptr = NULL;
Bool xf86Resetting = FALSE;
Bool xf86Initialising = FALSE;
Bool xf86ProbeFailed = FALSE;
Bool xf86DoProbe = FALSE;
Bool xf86DoConfigure = FALSE;
#ifdef XFree86LOADER
DriverPtr *xf86DriverList = NULL;
int xf86NumDrivers = 0;
InputDriverPtr *xf86InputDriverList = NULL;
int xf86NumInputDrivers = 0;
ModuleInfoPtr *xf86ModuleInfoList = NULL;
int xf86NumModuleInfos = 0;
#endif
int xf86NumScreens = 0;

const char *xf86VisualNames[] = {
	"StaticGray",
	"GrayScale",
	"StaticColor",
	"PseudoColor",
	"TrueColor",
	"DirectColor"
};

/* Parameters set only from the command line */
char *xf86ServerName = "no-name";
Bool xf86fpFlag = FALSE;
Bool xf86coFlag = FALSE;
Bool xf86sFlag = FALSE;
Bool xf86bsEnableFlag = FALSE;
Bool xf86bsDisableFlag = FALSE;
Bool xf86silkenMouseDisableFlag = FALSE;
char *xf86LayoutName = NULL;
char *xf86ScreenName = NULL;
char *xf86PointerName = NULL;
char *xf86KeyboardName = NULL;
Bool xf86ProbeOnly = FALSE;
int xf86Verbose = DEFAULT_VERBOSE;
int xf86LogVerbose = DEFAULT_LOG_VERBOSE;
int xf86FbBpp = -1;
Pix24Flags xf86Pix24 = Pix24DontCare;
int xf86Depth = -1;
rgb xf86Weight = {0, 0, 0};
Bool xf86FlipPixels = FALSE;
Gamma xf86Gamma = {0.0, 0.0, 0.0};
Bool xf86ShowUnresolved = DEFAULT_UNRESOLVED;
Bool xf86BestRefresh = DEFAULT_BEST_REFRESH;
Bool xf86AllowMouseOpenFail = FALSE;
#ifdef XF86VIDMODE
Bool xf86VidModeDisabled = FALSE;
Bool xf86VidModeAllowNonLocal = FALSE;
#endif
#ifdef XF86MISC
Bool xf86MiscModInDevDisabled = FALSE;
Bool xf86MiscModInDevAllowNonLocal = FALSE;
#endif
RootWinPropPtr *xf86RegisteredPropertiesTable = NULL;
Bool xf86inSuspend = FALSE;

#ifdef DPMSExtension
#define DEFAULT_STANDBY_TIME DEFAULT_SCREEN_SAVER_TIME * 2
#define DEFAULT_SUSPEND_TIME DEFAULT_SCREEN_SAVER_TIME * 3
#define DEFAULT_OFF_TIME DEFAULT_SCREEN_SAVER_TIME * 4
CARD32 defaultDPMSStandbyTime = DEFAULT_STANDBY_TIME;
CARD32 defaultDPMSSuspendTime = DEFAULT_SUSPEND_TIME;
CARD32 defaultDPMSOffTime = DEFAULT_OFF_TIME;
CARD16 DPMSPowerLevel = 0;
Bool defaultDPMSEnabled = FALSE;
Bool DPMSEnabledSwitch = FALSE;   /* these denote the DPMS command line */
Bool DPMSDisabledSwitch = FALSE;  /*                      switch states */
Bool DPMSCapableFlag = FALSE;
CARD32 DPMSStandbyTime;
CARD32 DPMSSuspendTime;
CARD32 DPMSOffTime;
Bool DPMSEnabled;
#endif

#ifdef DLOPEN_HACK
/*
 * This stuff is a hack to allow dlopen() modules to work.  It is intended
 * only to be used when using dlopen() modules for debugging purposes.
 */
#endif

--- NEW FILE: xf86Helper.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Helper.c,v 1.136 2004/01/27 01:31:45 dawes Exp $ */

/*
 * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
[...2953 lines suppressed...]
    ErrorF("xf86RegisterRootWindowProperty succeeded\n");
#endif
    return(Success);    
}

Bool
xf86IsUnblank(int mode)
{
    switch(mode) {
    case SCREEN_SAVER_OFF:
    case SCREEN_SAVER_FORCER:
	return TRUE;
    case SCREEN_SAVER_ON:
    case SCREEN_SAVER_CYCLE:
	return FALSE;
    default:
	xf86MsgVerb(X_WARNING, 0, "Unexpected save screen mode: %d\n", mode);
	return TRUE;
    }
}

--- NEW FILE: xf86InPriv.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86InPriv.h,v 1.5 2003/08/24 17:36:52 dawes Exp $ */

/*
 * Copyright (c) 1999 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

#ifndef _xf86InPriv_h
#define _xf86InPriv_h

/* xf86Globals.c */
#ifdef XFree86LOADER
extern InputDriverPtr *xf86InputDriverList;
#else
extern InputDriverPtr xf86InputDriverList[];
#endif
extern int xf86NumInputDrivers;

/* xf86Xinput.c */
void xf86ActivateDevice(InputInfoPtr pInfo);

#endif /* _xf86InPriv_h */

--- NEW FILE: xf86Init.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Init.c,v 3.212 2004/01/27 01:31:45 dawes Exp $ */

/*
 * Loosely based on code bearing the following copyright:
 *
 *   Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
 */
/*
 * Copyright (c) 1992-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
[...1901 lines suppressed...]
		break;
	if (i != pScrn->numFormats)
	    return &pScrn->formats[i];
    }
    return NULL;
}

int
xf86GetBppFromDepth(ScrnInfoPtr pScrn, int depth)
{
    PixmapFormatPtr format;

   
    format = xf86GetPixFormat(pScrn, depth);
    if (format)
	return format->bitsPerPixel;
    else
	return 0;
}


--- NEW FILE: xf86Io.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Io.c,v 3.56 2003/11/03 05:11:02 tsi Exp $ */
/*
 * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name of Thomas Roell not be used in
 * advertising or publicity pertaining to distribution of the software without
 * specific, written prior permission.  Thomas Roell makes no representations
 * about the suitability of this software for any purpose.  It is provided
 * "as is" without express or implied warranty.
 *
 * THOMAS ROELL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 * EVENT SHALL THOMAS ROELL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
 * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 *
 */
/*
 * Copyright (c) 1992-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/* $XConsortium: xf86Io.c /main/27 1996/10/19 17:58:55 kaleb $ */

#define NEED_EVENTS
#include <X11/X.h>
#include <X11/Xproto.h>
#include "inputstr.h"
#include "scrnintstr.h"

#include "compiler.h"

#include "xf86.h"
#include "xf86Priv.h"
#define XF86_OS_PRIVS
#include "xf86_OSlib.h"
#include "mipointer.h"

#ifdef XINPUT
#include "xf86Xinput.h"
#include <X11/extensions/XIproto.h>
#include "exevents.h"
#endif

#ifdef XKB
#include <X11/extensions/XKB.h>
#include <X11/extensions/XKBstr.h>
#include <X11/extensions/XKBsrv.h>
#endif

unsigned int xf86InitialCaps = 0;
unsigned int xf86InitialNum = 0;
unsigned int xf86InitialScroll = 0;

#include "atKeynames.h"

/*
 * xf86KbdBell --
 *	Ring the terminal/keyboard bell for an amount of time proportional to
 *      "loudness".
 */

void
xf86KbdBell(percent, pKeyboard, ctrl, unused)
     int           percent;          /* Percentage of full volume */
     DeviceIntPtr  pKeyboard;        /* Keyboard to ring */
     pointer	   ctrl;	
     int	   unused;	
{
  xf86SoundKbdBell(percent, xf86Info.bell_pitch, xf86Info.bell_duration);
}

void
xf86UpdateKbdLeds()
{
  int leds = 0;
  if (xf86Info.capsLock) leds |= XLED1;
  if (xf86Info.numLock)  leds |= XLED2;
  if (xf86Info.scrollLock || xf86Info.modeSwitchLock) leds |= XLED3;
  if (xf86Info.composeLock) leds |= XLED4;
  xf86Info.leds = (xf86Info.leds & xf86Info.xleds) | (leds & ~xf86Info.xleds);
  xf86KbdLeds();
}

void
xf86KbdLeds ()
{
  int leds, real_leds = 0;

#if defined (__sparc__) && defined(__linux__)
  static int kbdSun = -1;
  if (kbdSun == -1) {
  if ((xf86Info.xkbmodel && !strcmp(xf86Info.xkbmodel, "sun")) ||
      (xf86Info.xkbrules && !strcmp(xf86Info.xkbrules, "sun")))
      kbdSun = 1;
  else
      kbdSun = 0;
  }
  if (kbdSun) {
     if (xf86Info.leds & 0x08) real_leds |= XLED1;
     if (xf86Info.leds & 0x04) real_leds |= XLED3;
     if (xf86Info.leds & 0x02) real_leds |= XLED4;
     if (xf86Info.leds & 0x01) real_leds |= XLED2;
     leds = real_leds;
     real_leds = 0;
  } else {
     leds = xf86Info.leds;
  }
#else
  leds = xf86Info.leds;
#endif /* defined (__sparc__) */

#ifdef LED_CAP
  if (leds & XLED1)  real_leds |= LED_CAP;
  if (leds & XLED2)  real_leds |= LED_NUM;
  if (leds & XLED3)  real_leds |= LED_SCR;
#ifdef LED_COMP
  if (leds & XLED4)  real_leds |= LED_COMP;
#else
  if (leds & XLED4)  real_leds |= LED_SCR;
#endif
#endif
  xf86SetKbdLeds(real_leds);
  (void)leds;
}

/*
 * xf86KbdCtrl --
 *      Alter some of the keyboard control parameters. All special protocol
 *      values are handled by dix (ProgChangeKeyboardControl)
 */

void
xf86KbdCtrl (pKeyboard, ctrl)
     DevicePtr     pKeyboard;        /* Keyboard to alter */
     KeybdCtrl     *ctrl;
{
  int leds;
  xf86Info.bell_pitch    = ctrl->bell_pitch;
  xf86Info.bell_duration = ctrl->bell_duration;
  xf86Info.autoRepeat    = ctrl->autoRepeat;

  xf86Info.composeLock   = (ctrl->leds & XCOMP) ? TRUE : FALSE;

  leds = (ctrl->leds & ~(XCAPS | XNUM | XSCR));
#ifdef XKB
  if (noXkbExtension) {
#endif
      xf86Info.leds = (leds & xf86Info.xleds)|(xf86Info.leds & ~xf86Info.xleds);
#ifdef XKB
  } else {
      xf86Info.leds = leds;
  }
#endif

  xf86KbdLeds();
}

/*
 * xf86InitKBD --
 *      Reinitialize the keyboard. Only set Lockkeys according to ours leds.
 *      Depress all other keys.
 */

void
xf86InitKBD(init)
Bool init;
{
  char            leds = 0, rad;
  unsigned int    i;
  xEvent          kevent;
  DeviceIntPtr    pKeyboard = xf86Info.pKeyboard;
  KeyClassRec     *keyc = xf86Info.pKeyboard->key;
  KeySym          *map = keyc->curKeySyms.map;

  kevent.u.keyButtonPointer.time = GetTimeInMillis();
  kevent.u.keyButtonPointer.rootX = 0;
  kevent.u.keyButtonPointer.rootY = 0;

  /*
   * Hmm... here is the biggest hack of every time !
   * It may be possible that a switch-vt procedure has finished BEFORE
   * you released all keys neccessary to do this. That peculiar behavior
   * can fool the X-server pretty much, cause it assumes that some keys
   * were not released. TWM may stuck alsmost completly....
   * OK, what we are doing here is after returning from the vt-switch
   * exeplicitely unrelease all keyboard keys before the input-devices
   * are reenabled.
   */
  for (i = keyc->curKeySyms.minKeyCode, map = keyc->curKeySyms.map;
       i < keyc->curKeySyms.maxKeyCode;
       i++, map += keyc->curKeySyms.mapWidth)
    if (KeyPressed(i))
      {
        switch (*map) {
	/* Don't release the lock keys */
        case XK_Caps_Lock:
        case XK_Shift_Lock:
        case XK_Num_Lock:
        case XK_Scroll_Lock:
        case XK_Kana_Lock:
	  break;
        default:
	  kevent.u.u.detail = i;
	  kevent.u.u.type = KeyRelease;
	  (* pKeyboard->public.processInputProc)(&kevent, pKeyboard, 1);
        }
      }
  
  xf86Info.scanPrefix      = 0;

  if (init)
    {
      /*
       * we must deal here with the fact, that on some cases the numlock or
       * capslock key are enabled BEFORE the server is started up. So look
       * here at the state on the according LEDS to determine whether a
       * lock-key is already set.
       */

      xf86Info.capsLock        = FALSE;
      xf86Info.numLock         = FALSE;
      xf86Info.scrollLock      = FALSE;
      xf86Info.modeSwitchLock  = FALSE;
      xf86Info.composeLock     = FALSE;
    
#ifdef LED_CAP
#ifdef INHERIT_LOCK_STATE
      leds = xf86Info.leds;

      for (i = keyc->curKeySyms.minKeyCode, map = keyc->curKeySyms.map;
           i < keyc->curKeySyms.maxKeyCode;
           i++, map += keyc->curKeySyms.mapWidth)

        switch(*map) {

        case XK_Caps_Lock:
        case XK_Shift_Lock:
          if (leds & LED_CAP) 
	    {
	      xf86InitialCaps = i;
	      xf86Info.capsLock = TRUE;
	    }
          break;

        case XK_Num_Lock:
          if (leds & LED_NUM)
	    {
	      xf86InitialNum = i;
	      xf86Info.numLock = TRUE;
	    }
          break;

        case XK_Scroll_Lock:
        case XK_Kana_Lock:
          if (leds & LED_SCR)
	    {
	      xf86InitialScroll = i;
	      xf86Info.scrollLock = TRUE;
	    }
          break;
        }
#endif /* INHERIT_LOCK_STATE */
      xf86SetKbdLeds(leds);
#endif /* LED_CAP */
      (void)leds;

      if      (xf86Info.kbdDelay <= 375) rad = 0x00;
      else if (xf86Info.kbdDelay <= 625) rad = 0x20;
      else if (xf86Info.kbdDelay <= 875) rad = 0x40;
      else                               rad = 0x60;
    
      if      (xf86Info.kbdRate <=  2)   rad |= 0x1F;
      else if (xf86Info.kbdRate >= 30)   rad |= 0x00;
      else                               rad |= ((58 / xf86Info.kbdRate) - 2);
    
      xf86SetKbdRepeat(rad);
    }
}

/*
 * xf86KbdProc --
 *	Handle the initialization, etc. of a keyboard.
 */

int
xf86KbdProc (pKeyboard, what)
     DeviceIntPtr pKeyboard;	/* Keyboard to manipulate */
     int       what;	    	/* What to do to it */
{
  KeySymsRec           keySyms;
  CARD8                modMap[MAP_LENGTH];
  int                  kbdFd;

  switch (what) {

  case DEVICE_INIT:
    /*
     * First open and find the current state of the keyboard.
     */

    xf86KbdInit();

    xf86KbdGetMapping(&keySyms, modMap);
    

#ifndef XKB
    defaultKeyboardControl.leds = xf86GetKbdLeds();
#else
    defaultKeyboardControl.leds = 0;
#endif

    /*
     * Perform final initialization of the system private keyboard
     * structure and fill in various slots in the device record
     * itself which couldn't be filled in before.
     */

    pKeyboard->public.on = FALSE;

#ifdef XKB
    if (noXkbExtension) {
#endif
    InitKeyboardDeviceStruct((DevicePtr)xf86Info.pKeyboard,
			     &keySyms,
			     modMap,
			     xf86KbdBell,
			     (KbdCtrlProcPtr)xf86KbdCtrl);
#ifdef XKB
    } else {
 	XkbComponentNamesRec	names;
	XkbDescPtr		desc;
	Bool			foundTerminate = FALSE;
	int			keyc;
	if (XkbInitialMap) {
	    if ((xf86Info.xkbkeymap = strchr(XkbInitialMap, '/')) != NULL)
		xf86Info.xkbkeymap++;
	    else
		xf86Info.xkbkeymap = XkbInitialMap;
	}
	if (xf86Info.xkbkeymap) {
	    names.keymap = xf86Info.xkbkeymap;
	    names.keycodes = NULL;
	    names.types = NULL;
	    names.compat = NULL;
	    names.symbols = NULL;
	    names.geometry = NULL;
	} else {
	    names.keymap = NULL;
	    names.keycodes = xf86Info.xkbkeycodes;
	    names.types = xf86Info.xkbtypes;
	    names.compat = xf86Info.xkbcompat;
	    names.symbols = xf86Info.xkbsymbols;
	    names.geometry = xf86Info.xkbgeometry;
	}
	if ((xf86Info.xkbkeymap || xf86Info.xkbcomponents_specified)
	   && (xf86Info.xkbmodel == NULL || xf86Info.xkblayout == NULL)) {
		xf86Info.xkbrules = NULL;
	}
	XkbSetRulesDflts(xf86Info.xkbrules, xf86Info.xkbmodel,
			 xf86Info.xkblayout, xf86Info.xkbvariant,
			 xf86Info.xkboptions);
	
	XkbInitKeyboardDeviceStruct(pKeyboard, 
				    &names,
				    &keySyms, 
				    modMap, 
				    xf86KbdBell,
				    (KbdCtrlProcPtr)xf86KbdCtrl);

	/* Search keymap for Terminate action */
	desc  = pKeyboard->key->xkbInfo->desc;
	for (keyc = desc->min_key_code; keyc <= desc->max_key_code; keyc++) {
	    int i;
	    for (i = 1; i <= XkbKeyNumActions(desc, keyc); i++) {
		if (XkbKeyAction(desc, keyc, i)
		  && XkbKeyAction(desc, keyc, i)->type == XkbSA_Terminate) {
		    foundTerminate = TRUE;
		    goto searchdone;
		}
	    }
  	}
searchdone:
	xf86Info.ActionKeyBindingsSet = foundTerminate;
	if (!foundTerminate)
	    xf86Msg(X_INFO, "Server_Terminate keybinding not found\n");
    }
#endif
    
    xf86InitKBD(TRUE);
    break;
    
  case DEVICE_ON:
    /*
     * Set the keyboard into "direct" mode and turn on
     * event translation.
     */

    kbdFd = xf86KbdOn();
    /*
     * Discard any pending input after a VT switch to prevent the server
     * passing on parts of the VT switch sequence.
     */
    sleep(1);
#if defined(WSCONS_SUPPORT)
    if (xf86Info.consType != WSCONS) {
#endif
	if (kbdFd != -1) {
		char buf[16];
		read(kbdFd, buf, 16);
    	}
#if defined(WSCONS_SUPPORT)
    }
#endif

#if !defined(__UNIXOS2__) /* Under EMX, keyboard cannot be select()'ed */
    if (kbdFd != -1)
      AddEnabledDevice(kbdFd);
#endif  /* __UNIXOS2__ */

    pKeyboard->public.on = TRUE;
    xf86InitKBD(FALSE);
    break;
    
  case DEVICE_CLOSE:
  case DEVICE_OFF:
    /*
     * Restore original keyboard directness and translation.
     */

    kbdFd = xf86KbdOff();

    if (kbdFd != -1)
      RemoveEnabledDevice(kbdFd);

    pKeyboard->public.on = FALSE;
    break;

  }
  return (Success);
}

#if defined(DDXTIME) && !defined(QNX4)
/*
 * These are getting tossed in here until I can think of where
 * they really belong
 */
#define HALFMONTH ((unsigned long) 1<<31)
CARD32
GetTimeInMillis()
{
    struct timeval  tp;
    register CARD32 val;
    register INT32 diff;
    static CARD32 oldval = 0;
    static CARD32 time = 0;

    gettimeofday(&tp, 0);
    val = (tp.tv_sec * 1000) + (tp.tv_usec / 1000);
    if (oldval) {
	diff = val - oldval;
	if (diff > 0)
	    time += diff;
    }
    oldval = val;

    return time;
}
#endif /* DDXTIME && !QNX4 */


--- NEW FILE: xf86Kbd.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Kbd.c,v 3.26 2003/08/24 17:36:53 dawes Exp $ */
/*
 * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name of Thomas Roell not be used in
 * advertising or publicity pertaining to distribution of the software without
 * specific, written prior permission.  Thomas Roell makes no representations
 * about the suitability of this software for any purpose.  It is provided
 * "as is" without express or implied warranty.
 *
 * THOMAS ROELL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 * EVENT SHALL THOMAS ROELL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
 * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 *
 */
/*
 * Copyright (c) 1992-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/* $XConsortium: xf86Kbd.c /main/10 1996/02/21 17:38:32 kaleb $ */

#ifdef __UNIXOS2__
#define I_NEED_OS2_H
#endif

#include <X11/X.h>
#include <X11/Xmd.h>
#include "input.h"
#include "scrnintstr.h"

#include "compiler.h"

#include "xf86.h"
#include "xf86Priv.h"
#include "xf86_OSlib.h"
#include "atKeynames.h"
#include "xf86Config.h"

#include "xf86Keymap.h"

#if defined(KDGKBTYPE) && \
	!defined(Lynx) && \
	!defined(__UNIXOS2__) && !defined(__mips__) && \
	!defined(__arm32__) && !defined(__GNU__) && !defined(__QNX__)
#define HAS_GETKBTYPE
#endif
#if defined(GIO_KEYMAP) && \
	!defined(Lynx) && \
	!defined(__UNIXOS2__) && !defined(__mips__) && \
	!defined(__arm32__) && !defined(__GNU__) && !defined(DGUX) && \
	!defined(__QNX__)
#define HAS_GETKEYMAP

#define KD_GET_ENTRY(i,n) \
  eascii_to_x[((keymap.key[i].spcl << (n+1)) & 0x100) + keymap.key[i].map[n]]

/*
 * NOTE: Not all possible remappable symbols are remapped. There are two main
 *       reasons:
 *                 a) The mapping between scancode and SYSV/386 - symboltable
 *                    is inconsistent between different versions and has some
 *                    BIG mistakes.
 *                 b) In X-Windows there is a difference between numpad-keys
 *                    and normal keys. SYSV/386 uses for both kinds of keys
 *                    the same symbol.
 *
 *       Thus only the alpha keypad and the function keys are translated.
 *       Also CapsLock, NumLock, ScrollLock, Shift, Control & Alt.
 */

static unsigned char remap[128] = {
     0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,   /* 0x00 - 0x07 */
  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,   /* 0x08 - 0x0f */
  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,   /* 0x10 - 0x17 */
  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,   /* 0x18 - 0x1f */
  0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,   /* 0x20 - 0x27 */
  0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,   /* 0x28 - 0x2f */
  0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36,    0,   /* 0x30 - 0x37 */
  0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,   /* 0x38 - 0x3f */
  0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46,    0,   /* 0x40 - 0x47 */
     0,    0,    0,    0,    0,    0,    0,    0,   /* 0x48 - 0x4f */
     0,    0,    0,    0,    0,    0, 0x56, 0x57,   /* 0x50 - 0x57 */
  0x58,    0,    0,    0,    0,    0,    0,    0,   /* 0x58 - 0x5f */
     0,    0,    0,    0,    0,    0,    0,    0,   /* 0x60 - 0x67 */
     0,    0,    0,    0,    0,    0,    0,    0,   /* 0x68 - 0x6f */
     0,    0, 0x69, 0x65,    0,    0,    0,    0,   /* 0x70 - 0x77 */
     0,    0,    0,    0,    0,    0,    0,    0,   /* 0x78 - 0x7f */
};

static KeySym eascii_to_x[512] = {
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	XK_BackSpace,	XK_Tab,		XK_Linefeed,	NoSymbol,
	NoSymbol,	XK_Return,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	XK_Escape,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	XK_space,	XK_exclam,	XK_quotedbl,	XK_numbersign,
	XK_dollar,	XK_percent,	XK_ampersand,	XK_apostrophe,
	XK_parenleft,	XK_parenright,	XK_asterisk,	XK_plus,
	XK_comma,	XK_minus,	XK_period,	XK_slash,
	XK_0,		XK_1,		XK_2,		XK_3,
	XK_4,		XK_5,		XK_6,		XK_7,
	XK_8,		XK_9,		XK_colon,	XK_semicolon,
	XK_less,	XK_equal,	XK_greater,	XK_question,
	XK_at,		XK_A,		XK_B,		XK_C,
	XK_D,		XK_E,		XK_F,		XK_G,
	XK_H,		XK_I,		XK_J,		XK_K,
	XK_L,		XK_M,		XK_N,		XK_O,
	XK_P,		XK_Q,		XK_R,		XK_S,
	XK_T,		XK_U,		XK_V,		XK_W,
	XK_X,		XK_Y,		XK_Z,		XK_bracketleft,
	XK_backslash,	XK_bracketright,XK_asciicircum,	XK_underscore,
	XK_grave,	XK_a,		XK_b,		XK_c,
	XK_d,		XK_e,		XK_f,		XK_g,
	XK_h,		XK_i,		XK_j,		XK_k,
	XK_l,		XK_m,		XK_n,		XK_o,
	XK_p,		XK_q,		XK_r,		XK_s,
	XK_t,		XK_u,		XK_v,		XK_w,
	XK_x,		XK_y,		XK_z,		XK_braceleft,
	XK_bar,		XK_braceright,	XK_asciitilde,	XK_Delete,
	XK_Ccedilla,	XK_udiaeresis,	XK_eacute,	XK_acircumflex,
	XK_adiaeresis,	XK_agrave,	XK_aring,	XK_ccedilla,
	XK_ecircumflex,	XK_ediaeresis,	XK_egrave,	XK_idiaeresis,
	XK_icircumflex,	XK_igrave,	XK_Adiaeresis,	XK_Aring,
	XK_Eacute,	XK_ae,		XK_AE,		XK_ocircumflex,
	XK_odiaeresis,	XK_ograve,	XK_ucircumflex,	XK_ugrave,
	XK_ydiaeresis,	XK_Odiaeresis,	XK_Udiaeresis,	XK_cent,
	XK_sterling,	XK_yen,		XK_paragraph,	XK_section,
	XK_aacute,	XK_iacute,	XK_oacute,	XK_uacute,
	XK_ntilde,	XK_Ntilde,	XK_ordfeminine,	XK_masculine,
	XK_questiondown,XK_hyphen,	XK_notsign,	XK_onehalf,
	XK_onequarter,	XK_exclamdown,	XK_guillemotleft,XK_guillemotright,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	XK_Greek_alpha,	XK_ssharp,	XK_Greek_GAMMA,	XK_Greek_pi,
	XK_Greek_SIGMA,	XK_Greek_sigma,	XK_mu,	        XK_Greek_tau,
	XK_Greek_PHI,	XK_Greek_THETA,	XK_Greek_OMEGA,	XK_Greek_delta,
	XK_infinity,	XK_Ooblique,	XK_Greek_epsilon, XK_intersection,
	XK_identical,	XK_plusminus,	XK_greaterthanequal, XK_lessthanequal,
	XK_topintegral,	XK_botintegral,	XK_division,	XK_similarequal,
	XK_degree,	NoSymbol,	NoSymbol,	XK_radical,
	XK_Greek_eta,	XK_twosuperior,	XK_periodcentered, NoSymbol,

	/* 
	 * special marked entries (256 + x)
	 */

	NoSymbol,	NoSymbol,	XK_Shift_L,	XK_Shift_R,
	XK_Caps_Lock,	XK_Num_Lock,	XK_Scroll_Lock,	XK_Alt_L,
	NoSymbol,	XK_Control_L,	XK_Alt_L,	XK_Alt_R,
	XK_Control_L,	XK_Control_R,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	XK_F1,
	XK_F2,		XK_F3,		XK_F4,		XK_F5,
	XK_F6,		XK_F7,		XK_F8,		XK_F9,
	XK_F10,		XK_F11,		XK_F12,		NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
      };

#endif /* HAS_GETKEYMAP */

/*
 * LegalModifier --
 *      determine whether a key is a legal modifier key, i.e send a
 *      press/release sequence.
 */

/*ARGSUSED*/
Bool
LegalModifier(key, pDev)
     unsigned int  key;
     DevicePtr	pDev;
{
  return (TRUE);
}


      
/*
 * xf86KbdGetMapping --
 *	Get the national keyboard mapping. The keyboard type is set, a new map
 *      and the modifiermap is computed.
 */

void
xf86KbdGetMapping (pKeySyms, pModMap)
     KeySymsPtr pKeySyms;
     CARD8      *pModMap;
{
  KeySym        *k;
#ifdef HAS_GETKEYMAP
  keymap_t      keymap;
#endif
  int           i;
  KeySym        *pMap;

#ifdef HAS_GETKBTYPE
  char          type;
  
  xf86Info.kbdType =
    ioctl(xf86Info.consoleFd, KDGKBTYPE, &type) != -1 ? type : KB_101;
  if (xf86Info.kbdType == KB_84)
    pMap = map84;
  else
    pMap = map;
#else
/* OS/2 sets the keyboard type during xf86OpenKbd */
#ifndef __UNIXOS2__
  xf86Info.kbdType = 0;
#endif
  pMap = map;
#endif

#ifdef HAS_GETKEYMAP
  /*
   * use the keymap, which can be gotten from our oringinal vt??.
   * ( ttymap(1) !!!! )
   */
  if (ioctl(xf86Info.consoleFd, GIO_KEYMAP, &keymap) != -1) {
    for (i = 0; i < keymap.n_keys && i < NUM_KEYCODES; i++)
      
      if (remap[i]) {
	
	k = pMap + (remap[i] << 2);
	
	k[0] = KD_GET_ENTRY(i,0);             /* non-shifed */
	k[1] = KD_GET_ENTRY(i,1);	      /* shifted */
	k[2] = KD_GET_ENTRY(i,4);	      /* alt */
	k[3] = KD_GET_ENTRY(i,5);	      /* alt - shifted */

	if (k[3] == k[2]) k[3] = NoSymbol;
	if (k[2] == k[1]) k[2] = NoSymbol;
	if (k[1] == k[0]) k[1] = NoSymbol;
	if (k[0] == k[2] && k[1] == k[3]) k[2] = k[3] = NoSymbol;
      }
  }
#endif

  /*
   * compute the modifier map
   */
  for (i = 0; i < MAP_LENGTH; i++)
    pModMap[i] = NoSymbol;  /* make sure it is restored */
  
  for (k = pMap, i = MIN_KEYCODE;
       i < (NUM_KEYCODES + MIN_KEYCODE);
       i++, k += 4)
    
    switch(*k) {
      
    case XK_Shift_L:
    case XK_Shift_R:
      pModMap[i] = ShiftMask;
      break;
      
    case XK_Control_L:
    case XK_Control_R:
      pModMap[i] = ControlMask;
      break;
      
    case XK_Caps_Lock:
      pModMap[i] = LockMask;
      break;
      
    case XK_Alt_L:
    case XK_Alt_R:
      pModMap[i] = AltMask;
      break;
      
    case XK_Num_Lock:
      pModMap[i] = NumLockMask;
      break;

    case XK_Scroll_Lock:
      pModMap[i] = ScrollLockMask;
      break;

      /* kana support */
    case XK_Kana_Lock:
    case XK_Kana_Shift:
      pModMap[i] = KanaMask;
      break;

      /* alternate toggle for multinational support */
    case XK_Mode_switch:
      pModMap[i] = AltLangMask;
      break;

    }
  
  pKeySyms->map        = pMap;
  pKeySyms->mapWidth   = GLYPHS_PER_KEY;
  pKeySyms->minKeyCode = MIN_KEYCODE;
  pKeySyms->maxKeyCode = MAX_KEYCODE;
}

--- NEW FILE: xf86KbdBSD.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86KbdBSD.c,v 3.22 2003/10/07 22:00:52 herrb Exp $ */
/*
 * Derived from xf86Kbd.c by S_ren Schmidt (sos at login.dkuug.dk)
 * which is Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
 * and from xf86KbdCODrv.c by Holger Veit
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name of Thomas Roell not be used in
 * advertising or publicity pertaining to distribution of the software without
 * specific, written prior permission.  Thomas Roell makes no representations
 * about the suitability of this software for any purpose.  It is provided
 * "as is" without express or implied warranty.
 *
 * THOMAS ROELL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 * EVENT SHALL THOMAS ROELL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
[...1223 lines suppressed...]
		else 
			return wsAdbMap[keycode];
#endif
#ifdef WSKBD_TYPE_SUN
	case WSKBD_TYPE_SUN:
#ifdef WSKBD_TYPE_SUN5
	case WSKBD_TYPE_SUN5:
#endif
		if (keycode < 0 || keycode >= WS_SUN_MAP_SIZE)
			return KEY_UNKNOWN;
		else
			return wsSunMap[keycode];
#endif
	default:
		ErrorF("Unknown wskbd type %d\n", xf86Info.wsKbdType);
		return KEY_UNKNOWN;
	}
}

#endif /* WSCONS_SUPPORT */

--- NEW FILE: xf86KbdLnx.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86KbdLnx.c,v 3.17 2003/08/24 17:36:53 dawes Exp $ */
/*
 * Linux version of keymapping setup. The kernel (since 0.99.14) has support
 * for fully remapping the keyboard, but there are some differences between
 * the Linux map and the SVR4 map (esp. in the extended keycodes). We also
 * remove the restriction on what keycodes can be remapped.
 * Orest Zborowski.
 */
/*
 * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name of Thomas Roell not be used in
 * advertising or publicity pertaining to distribution of the software without
 * specific, written prior permission.  Thomas Roell makes no representations
 * about the suitability of this software for any purpose.  It is provided
 * "as is" without express or implied warranty.
 *
 * THOMAS ROELL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 * EVENT SHALL THOMAS ROELL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
 * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 *
 */
/*
 * Copyright (c) 1994-2001 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/* $XConsortium: xf86KbdLnx.c /main/7 1996/10/19 17:59:00 kaleb $ */

#include <X11/X.h>
#include <X11/Xmd.h>
#include "input.h"
#include "scrnintstr.h"

#include "compiler.h"

#include "xf86.h"
#include "xf86Priv.h"
#include "xf86_OSlib.h"
#include "atKeynames.h"

#include "xf86Keymap.h"
#include <X11/DECkeysym.h>

/*
 * LegalModifier --
 *      determine whether a key is a legal modifier key, i.e send a
 *      press/release sequence.
 */

/*ARGSUSED*/
Bool
LegalModifier(unsigned int key, DevicePtr pDev)
{
  return (TRUE);
}

/*
 * xf86KbdGetMapping --
 *	Get the national keyboard mapping. The keyboard type is set, a new map
 *      and the modifiermap is computed.
 */

static void readKernelMapping(KeySymsPtr pKeySyms, CARD8 *pModMap);

void
xf86KbdGetMapping (KeySymsPtr pKeySyms, CARD8 *pModMap)
{
  KeySym        *k;
  char          type;
  int           i;

  readKernelMapping(pKeySyms, pModMap);

  /*
   * compute the modifier map
   */
  for (i = 0; i < MAP_LENGTH; i++)
    pModMap[i] = NoSymbol;  /* make sure it is restored */
  
  for (k = map, i = MIN_KEYCODE;
       i < (NUM_KEYCODES + MIN_KEYCODE);
       i++, k += 4)
    
    switch(*k) {
      
    case XK_Shift_L:
    case XK_Shift_R:
      pModMap[i] = ShiftMask;
      break;
      
    case XK_Control_L:
    case XK_Control_R:
      pModMap[i] = ControlMask;
      break;
      
    case XK_Caps_Lock:
      pModMap[i] = LockMask;
      break;
      
    case XK_Alt_L:
    case XK_Alt_R:
      pModMap[i] = AltMask;
      break;
      
    case XK_Num_Lock:
      pModMap[i] = NumLockMask;
      break;

    case XK_Scroll_Lock:
      pModMap[i] = ScrollLockMask;
      break;

      /* kana support */
    case XK_Kana_Lock:
    case XK_Kana_Shift:
      pModMap[i] = KanaMask;
      break;

      /* alternate toggle for multinational support */
    case XK_Mode_switch:
      pModMap[i] = AltLangMask;
      break;

    }
  
  xf86Info.kbdType =
    ioctl(xf86Info.consoleFd, KDGKBTYPE, &type) != -1 ? type : KB_101;

  pKeySyms->map        = map;
  pKeySyms->mapWidth   = GLYPHS_PER_KEY;
  pKeySyms->minKeyCode = MIN_KEYCODE;
  pKeySyms->maxKeyCode = MAX_KEYCODE; 
}

#include <linux/keyboard.h>

static KeySym linux_to_x[256] = {
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	XK_BackSpace,	XK_Tab,		XK_Linefeed,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	XK_Escape,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	XK_space,	XK_exclam,	XK_quotedbl,	XK_numbersign,
	XK_dollar,	XK_percent,	XK_ampersand,	XK_apostrophe,
	XK_parenleft,	XK_parenright,	XK_asterisk,	XK_plus,
	XK_comma,	XK_minus,	XK_period,	XK_slash,
	XK_0,		XK_1,		XK_2,		XK_3,
	XK_4,		XK_5,		XK_6,		XK_7,
	XK_8,		XK_9,		XK_colon,	XK_semicolon,
	XK_less,	XK_equal,	XK_greater,	XK_question,
	XK_at,		XK_A,		XK_B,		XK_C,
	XK_D,		XK_E,		XK_F,		XK_G,
	XK_H,		XK_I,		XK_J,		XK_K,
	XK_L,		XK_M,		XK_N,		XK_O,
	XK_P,		XK_Q,		XK_R,		XK_S,
	XK_T,		XK_U,		XK_V,		XK_W,
	XK_X,		XK_Y,		XK_Z,		XK_bracketleft,
	XK_backslash,	XK_bracketright,XK_asciicircum,	XK_underscore,
	XK_grave,	XK_a,		XK_b,		XK_c,
	XK_d,		XK_e,		XK_f,		XK_g,
	XK_h,		XK_i,		XK_j,		XK_k,
	XK_l,		XK_m,		XK_n,		XK_o,
	XK_p,		XK_q,		XK_r,		XK_s,
	XK_t,		XK_u,		XK_v,		XK_w,
	XK_x,		XK_y,		XK_z,		XK_braceleft,
	XK_bar,		XK_braceright,	XK_asciitilde,	XK_BackSpace,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	XK_nobreakspace,XK_exclamdown,	XK_cent,	XK_sterling,
	XK_currency,	XK_yen,		XK_brokenbar,	XK_section,
	XK_diaeresis,	XK_copyright,	XK_ordfeminine,	XK_guillemotleft,
	XK_notsign,	XK_hyphen,	XK_registered,	XK_macron,
	XK_degree,	XK_plusminus,	XK_twosuperior,	XK_threesuperior,
	XK_acute,	XK_mu,		XK_paragraph,	XK_periodcentered,
	XK_cedilla,	XK_onesuperior,	XK_masculine,	XK_guillemotright,
	XK_onequarter,	XK_onehalf,	XK_threequarters,XK_questiondown,
	XK_Agrave,	XK_Aacute,	XK_Acircumflex,	XK_Atilde,
	XK_Adiaeresis,	XK_Aring,	XK_AE,		XK_Ccedilla,
	XK_Egrave,	XK_Eacute,	XK_Ecircumflex,	XK_Ediaeresis,
	XK_Igrave,	XK_Iacute,	XK_Icircumflex,	XK_Idiaeresis,
	XK_ETH,		XK_Ntilde,	XK_Ograve,	XK_Oacute,
	XK_Ocircumflex,	XK_Otilde,	XK_Odiaeresis,	XK_multiply,
	XK_Ooblique,	XK_Ugrave,	XK_Uacute,	XK_Ucircumflex,
	XK_Udiaeresis,	XK_Yacute,	XK_THORN,	XK_ssharp,
	XK_agrave,	XK_aacute,	XK_acircumflex,	XK_atilde,
	XK_adiaeresis,	XK_aring,	XK_ae,		XK_ccedilla,
	XK_egrave,	XK_eacute,	XK_ecircumflex,	XK_ediaeresis,
	XK_igrave,	XK_iacute,	XK_icircumflex,	XK_idiaeresis,
	XK_eth,		XK_ntilde,	XK_ograve,	XK_oacute,
	XK_ocircumflex,	XK_otilde,	XK_odiaeresis,	XK_division,
	XK_oslash,	XK_ugrave,	XK_uacute,	XK_ucircumflex,
	XK_udiaeresis,	XK_yacute,	XK_thorn,	XK_ydiaeresis
};

/*
 * Maps the AT keycodes to Linux keycodes
 */
static unsigned char at2lnx[NUM_KEYCODES] =
{
	0x01,	/* KEY_Escape */	0x02,	/* KEY_1 */
	0x03,	/* KEY_2 */		0x04,	/* KEY_3 */
	0x05,	/* KEY_4 */		0x06,	/* KEY_5 */
	0x07,	/* KEY_6 */		0x08,	/* KEY_7 */
	0x09,	/* KEY_8 */		0x0a,	/* KEY_9 */
	0x0b,	/* KEY_0 */		0x0c,	/* KEY_Minus */
	0x0d,	/* KEY_Equal */		0x0e,	/* KEY_BackSpace */
	0x0f,	/* KEY_Tab */		0x10,	/* KEY_Q */
	0x11,	/* KEY_W */		0x12,	/* KEY_E */
	0x13,	/* KEY_R */		0x14,	/* KEY_T */
	0x15,	/* KEY_Y */		0x16,	/* KEY_U */
	0x17,	/* KEY_I */		0x18,	/* KEY_O */
	0x19,	/* KEY_P */		0x1a,	/* KEY_LBrace */
	0x1b,	/* KEY_RBrace */	0x1c,	/* KEY_Enter */
	0x1d,	/* KEY_LCtrl */		0x1e,	/* KEY_A */
	0x1f,	/* KEY_S */		0x20,	/* KEY_D */
	0x21,	/* KEY_F */		0x22,	/* KEY_G */
	0x23,	/* KEY_H */		0x24,	/* KEY_J */
	0x25,	/* KEY_K */		0x26,	/* KEY_L */
	0x27,	/* KEY_SemiColon */	0x28,	/* KEY_Quote */
	0x29,	/* KEY_Tilde */		0x2a,	/* KEY_ShiftL */
	0x2b,	/* KEY_BSlash */	0x2c,	/* KEY_Z */
	0x2d,	/* KEY_X */		0x2e,	/* KEY_C */
	0x2f,	/* KEY_V */		0x30,	/* KEY_B */
	0x31,	/* KEY_N */		0x32,	/* KEY_M */
	0x33,	/* KEY_Comma */		0x34,	/* KEY_Period */
	0x35,	/* KEY_Slash */		0x36,	/* KEY_ShiftR */
	0x37,	/* KEY_KP_Multiply */	0x38,	/* KEY_Alt */
	0x39,	/* KEY_Space */		0x3a,	/* KEY_CapsLock */
	0x3b,	/* KEY_F1 */		0x3c,	/* KEY_F2 */
	0x3d,	/* KEY_F3 */		0x3e,	/* KEY_F4 */
	0x3f,	/* KEY_F5 */		0x40,	/* KEY_F6 */
	0x41,	/* KEY_F7 */		0x42,	/* KEY_F8 */
	0x43,	/* KEY_F9 */		0x44,	/* KEY_F10 */
	0x45,	/* KEY_NumLock */	0x46,	/* KEY_ScrollLock */
	0x47,	/* KEY_KP_7 */		0x48,	/* KEY_KP_8 */
	0x49,	/* KEY_KP_9 */		0x4a,	/* KEY_KP_Minus */
	0x4b,	/* KEY_KP_4 */		0x4c,	/* KEY_KP_5 */
	0x4d,	/* KEY_KP_6 */		0x4e,	/* KEY_KP_Plus */
	0x4f,	/* KEY_KP_1 */		0x50,	/* KEY_KP_2 */
	0x51,	/* KEY_KP_3 */		0x52,	/* KEY_KP_0 */
	0x53,	/* KEY_KP_Decimal */	0x54,	/* KEY_SysReqest */
	0x00,	/* 0x55 */		0x56,	/* KEY_Less */
	0x57,	/* KEY_F11 */		0x58,	/* KEY_F12 */
	0x66,	/* KEY_Home */		0x67,	/* KEY_Up */
	0x68,	/* KEY_PgUp */		0x69,	/* KEY_Left */
	0x5d,	/* KEY_Begin */		0x6a,	/* KEY_Right */
	0x6b,	/* KEY_End */		0x6c,	/* KEY_Down */
	0x6d,	/* KEY_PgDown */	0x6e,	/* KEY_Insert */
	0x6f,	/* KEY_Delete */	0x60,	/* KEY_KP_Enter */
	0x61,	/* KEY_RCtrl */		0x77,	/* KEY_Pause */
	0x63,	/* KEY_Print */		0x62,	/* KEY_KP_Divide */
	0x64,	/* KEY_AltLang */	0x65,	/* KEY_Break */
	0x00,	/* KEY_LMeta */		0x00,	/* KEY_RMeta */
	0x7A,	/* KEY_Menu/FOCUS_PF11*/0x00,	/* 0x6e */
	0x7B,	/* FOCUS_PF12 */	0x00,	/* 0x70 */
	0x00,	/* 0x71 */		0x00,	/* 0x72 */
	0x59,	/* FOCUS_PF2 */		0x78,	/* FOCUS_PF9 */
	0x00,	/* 0x75 */		0x00,	/* 0x76 */
	0x5A,	/* FOCUS_PF3 */		0x5B,	/* FOCUS_PF4 */
	0x5C,	/* FOCUS_PF5 */		0x5D,	/* FOCUS_PF6 */
	0x5E,	/* FOCUS_PF7 */		0x5F,	/* FOCUS_PF8 */
	0x7C,	/* JAP_86 */		0x79,	/* FOCUS_PF10 */
	0x00,	/* 0x7f */
};
#define NUM_AT2LNX (sizeof(at2lnx) / sizeof(at2lnx[0]))

#define NUM_CUSTOMKEYS	NR_KEYS

u_char SpecialServerMap[NUM_CUSTOMKEYS];

static void
readKernelMapping(KeySymsPtr pKeySyms, CARD8 *pModMap)
{
  KeySym        *k;
  int           i;
  int           maxkey;
  static unsigned char tbl[GLYPHS_PER_KEY] =
  {
	0,	/* unshifted */
	1,	/* shifted */
	0,	/* modeswitch unshifted */
	0	/* modeswitch shifted */
  };

  /*
   * Read the mapping from the kernel.
   * Since we're still using the XFree86 scancode->AT keycode mapping
   * routines, we need to convert the AT keycodes to Linux keycodes,
   * then translate the Linux keysyms into X keysyms.
   *
   * First, figure out which tables to use for the modeswitch columns
   * above, from the XF86Config fields.
   */
  tbl[2] = 8;	/* alt */
  tbl[3] = tbl[2] | 1;

  if (xf86Info.kbdCustomKeycodes) {
    k = map;
    maxkey = NUM_CUSTOMKEYS;
  }
  else {
    k = map+GLYPHS_PER_KEY;
    maxkey = NUM_AT2LNX;
  }

  for (i = 0; i < maxkey; ++i)
  {
    struct kbentry kbe;
    int j;

    if (xf86Info.kbdCustomKeycodes)
      kbe.kb_index = i;
    else
      kbe.kb_index = at2lnx[i];

    for (j = 0; j < GLYPHS_PER_KEY; ++j, ++k)
    {
      unsigned short kval;

      *k = NoSymbol;

      kbe.kb_table = tbl[j];
      if (
	  (!xf86Info.kbdCustomKeycodes && kbe.kb_index == 0) ||
	  ioctl(xf86Info.consoleFd, KDGKBENT, &kbe))
	continue;

      kval = KVAL(kbe.kb_value);
      switch (KTYP(kbe.kb_value))
      {
      case KT_LATIN:
      case KT_LETTER:
	*k = linux_to_x[kval];
	break;

      case KT_FN:
	if (kval <= 19)
	  *k = XK_F1 + kval;
	else switch (kbe.kb_value)
	{
	case K_FIND:
	  *k = XK_Home; /* or XK_Find */
	  break;
	case K_INSERT:
	  *k = XK_Insert;
	  break;
	case K_REMOVE:
	  *k = XK_Delete;
	  break;
	case K_SELECT:
	  *k = XK_End; /* or XK_Select */
	  break;
	case K_PGUP:
	  *k = XK_Prior;
	  break;
	case K_PGDN:
	  *k = XK_Next;
	  break;
	case K_HELP:
	  *k = XK_Help;
	  break;
	case K_DO:
	  *k = XK_Execute;
	  break;
	case K_PAUSE:
	  *k = XK_Pause;
	  break;
	case K_MACRO:
	  *k = XK_Menu;
	  break;
	default:
	  break;
	}
	break;

      case KT_SPEC:
	switch (kbe.kb_value)
	{
	case K_ENTER:
	  *k = XK_Return;
	  break;
	case K_BREAK:
	  *k = XK_Break;
	  break;
	case K_CAPS:
	  *k = XK_Caps_Lock;
	  break;
	case K_NUM:
	  *k = XK_Num_Lock;
	  break;
	case K_HOLD:
	  *k = XK_Scroll_Lock;
	  break;
	case K_COMPOSE:
          *k = XK_Multi_key;
	  break;
	default:
	  break;
	}
	break;

      case KT_PAD:
	switch (kbe.kb_value)
	{
	case K_PPLUS:
	  *k = XK_KP_Add;
	  break;
	case K_PMINUS:
	  *k = XK_KP_Subtract;
	  break;
	case K_PSTAR:
	  *k = XK_KP_Multiply;
	  break;
	case K_PSLASH:
	  *k = XK_KP_Divide;
	  break;
	case K_PENTER:
	  *k = XK_KP_Enter;
	  break;
	case K_PCOMMA:
	  *k = XK_KP_Separator;
	  break;
	case K_PDOT:
	  *k = XK_KP_Decimal;
	  break;
	case K_PPLUSMINUS:
	  *k = XK_KP_Subtract;
	  break;
	default:
	  if (kval <= 9)
	    *k = XK_KP_0 + kval;
	  break;
	}
	break;

      /*
       * KT_DEAD keys are for accelerated diacritical creation.
       */
      case KT_DEAD:
	switch (kbe.kb_value)
	  {
	  case K_DGRAVE:
	    *k = XK_dead_grave;
	    break;
	  case K_DACUTE:
	    *k = XK_dead_acute;
	    break;
	  case K_DCIRCM:
	    *k = XK_dead_circumflex;
	    break;
	  case K_DTILDE:
	    *k = XK_dead_tilde;
	    break;
	  case K_DDIERE:
	    *k = XK_dead_diaeresis;
	    break;
	  }
	break;

      case KT_CUR:
	switch (kbe.kb_value)
	{
	case K_DOWN:
	  *k = XK_Down;
	  break;
	case K_LEFT:
	  *k = XK_Left;
	  break;
	case K_RIGHT:
	  *k = XK_Right;
	  break;
	case K_UP:
	  *k = XK_Up;
	  break;
	}
	break;

      case KT_SHIFT:
	switch (kbe.kb_value)
	{
	case K_ALTGR:
	  *k = XK_Alt_R;
	  break;
	case K_ALT:
	  *k = (kbe.kb_index == 0x64 ?
		XK_Alt_R : XK_Alt_L);
	  break;
	case K_CTRL:
	  *k = (kbe.kb_index == 0x61 ?
		XK_Control_R : XK_Control_L);
	  break;
        case K_CTRLL:
	  *k = XK_Control_L;
	  break;
        case K_CTRLR:
	  *k = XK_Control_R;
	  break;
	case K_SHIFT:
	  *k = (kbe.kb_index == 0x36 ?
		XK_Shift_R : XK_Shift_L);
	  break;
        case K_SHIFTL:
	  *k = XK_Shift_L;
	  break;
        case K_SHIFTR:
	  *k = XK_Shift_R;
	  break;
	default:
	  break;
	}
	break;

      /*
       * KT_ASCII keys accumulate a 3 digit decimal number that gets
       * emitted when the shift state changes. We can't emulate that.
       */
      case KT_ASCII:
	break;

      case KT_LOCK:
	if (kbe.kb_value == K_SHIFTLOCK)
	  *k = XK_Shift_Lock;
	break;

      default:
	break;
      }
    }

    if (k[-1] == k[-2]) k[-1] = NoSymbol;
    if (k[-2] == k[-3]) k[-2] = NoSymbol;
    if (k[-3] == k[-4]) k[-3] = NoSymbol;
    if (k[-4] == k[-2] && k[-3] == k[-1]) k[-2] = k[-1] = NoSymbol;
    if (k[-1] == k[-4] && k[-2] == k[-3] && k[-2] == NoSymbol) k[-1] =NoSymbol;
  }

  if (!xf86Info.kbdCustomKeycodes)
    return;

  /*
   * Find the Mapping for the special server functions
   */
  for (i = 0; i < NUM_CUSTOMKEYS; ++i) {
    struct kbentry kbe;
    int special = 0;

    kbe.kb_index = i;
    kbe.kb_table = 0; /* Plain map */
    if (!ioctl(xf86Info.consoleFd, KDGKBENT, &kbe))
      switch (kbe.kb_value) {
	case K(KT_LATIN,0x7f):	/* This catches DEL too... But who cares? */
	  special = KEY_BackSpace;
	  break;
	case K_PMINUS:
	  special = KEY_KP_Minus;
	  break;
	case K_PPLUS:
	  special = KEY_KP_Plus;
	  break;
	case K_F1:
	  special = KEY_F1;
	  break;
	case K_F2:
	  special = KEY_F2;
	  break;
	case K_F3:
	  special = KEY_F3;
	  break;
	case K_F4:
	  special = KEY_F4;
	  break;
	case K_F5:
	  special = KEY_F5;
	  break;
	case K_F6:
	  special = KEY_F6;
	  break;
	case K_F7:
	  special = KEY_F7;
	  break;
	case K_F8:
	  special = KEY_F8;
	  break;
	case K_F9:
	  special = KEY_F9;
	  break;
	case K_F10:
	  special = KEY_F10;
	  break;
	case K_F11:
	  special = KEY_F11;
	  break;
	case K_F12:
	  special = KEY_F12;
	  break;
	case K_ALT:
	  special = KEY_Alt;
	  break;
	case K_ALTGR:
	  special = KEY_AltLang;
	  break;
	case K_CONS:
	  special = KEY_SysReqest;
	  break;
      }
    SpecialServerMap[i] = special;
  }
}

--- NEW FILE: xf86KbdMach.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86KbdMach.c,v 3.7.4.2 1998/06/04 17:35:20 dawes Exp $ */
/*
 *****************************************************************************
 * HISTORY
 * Log:	xf86KbdMach.c,v
 * Revision 2.1.2.1  92/06/25  10:32:08  moore
 * 	Incorporate the Elliot Dresselhaus's, Ernest Hua's and local changes
 * 	to run Thomas Roell's I386 color X11R5.  Original code only worked
 * 	with SCO Unix.  New code works with 2.5 and 3.0 Mach
 * 	[92/06/24            rvb]
 * 
 * 	EndLog
 * 
 *****************************************************************************
 */
/*
 * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name of Thomas Roell not be used in
 * advertising or publicity pertaining to distribution of the software without
 * specific, written prior permission.  Thomas Roell makes no representations
 * about the suitability of this software for any purpose.  It is provided
 * "as is" without express or implied warranty.
 *
 * THOMAS ROELL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 * EVENT SHALL THOMAS ROELL BE LIABLE FOR ANY SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
 * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 *
 */
/* $XConsortium: xf86KbdMach.c /main/9 1996/02/21 17:38:43 kaleb $ */

#include <X11/X.h>
#include <X11/Xmd.h>
#include "input.h"
#include "scrnintstr.h"

#include "compiler.h"

#include "xf86.h"
#include "xf86Priv.h"
#include "xf86_OSlib.h"
#include "atKeynames.h"
#include "xf86Config.h"

#include "xf86Keymap.h"

static KeySym ascii_to_x[256] = {
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	XK_BackSpace,	XK_Tab,		XK_Linefeed,	NoSymbol,
	NoSymbol,	XK_Return,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	XK_Escape,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	XK_space,	XK_exclam,	XK_quotedbl,	XK_numbersign,
	XK_dollar,	XK_percent,	XK_ampersand,	XK_apostrophe,
	XK_parenleft,	XK_parenright,	XK_asterisk,	XK_plus,
	XK_comma,	XK_minus,	XK_period,	XK_slash,
	XK_0,		XK_1,		XK_2,		XK_3,
	XK_4,		XK_5,		XK_6,		XK_7,
	XK_8,		XK_9,		XK_colon,	XK_semicolon,
	XK_less,	XK_equal,	XK_greater,	XK_question,
	XK_at,		XK_A,		XK_B,		XK_C,
	XK_D,		XK_E,		XK_F,		XK_G,
	XK_H,		XK_I,		XK_J,		XK_K,
	XK_L,		XK_M,		XK_N,		XK_O,
	XK_P,		XK_Q,		XK_R,		XK_S,
	XK_T,		XK_U,		XK_V,		XK_W,
	XK_X,		XK_Y,		XK_Z,		XK_bracketleft,
	XK_backslash,	XK_bracketright,XK_asciicircum,	XK_underscore,
	XK_grave,	XK_a,		XK_b,		XK_c,
	XK_d,		XK_e,		XK_f,		XK_g,
	XK_h,		XK_i,		XK_j,		XK_k,
	XK_l,		XK_m,		XK_n,		XK_o,
	XK_p,		XK_q,		XK_r,		XK_s,
	XK_t,		XK_u,		XK_v,		XK_w,
	XK_x,		XK_y,		XK_z,		XK_braceleft,
	XK_bar,		XK_braceright,	XK_asciitilde,	XK_Delete,
	XK_Ccedilla,	XK_udiaeresis,	XK_eacute,	XK_acircumflex,
	XK_adiaeresis,	XK_agrave,	XK_aring,	XK_ccedilla,
	XK_ecircumflex,	XK_ediaeresis,	XK_egrave,	XK_idiaeresis,
	XK_icircumflex,	XK_igrave,	XK_Adiaeresis,	XK_Aring,
	XK_Eacute,	XK_ae,		XK_AE,		XK_ocircumflex,
	XK_odiaeresis,	XK_ograve,	XK_ucircumflex,	XK_ugrave,
	XK_ydiaeresis,	XK_Odiaeresis,	XK_Udiaeresis,	XK_cent,
	XK_sterling,	XK_yen,		XK_paragraph,	XK_section,
	XK_aacute,	XK_iacute,	XK_oacute,	XK_uacute,
	XK_ntilde,	XK_Ntilde,	XK_ordfeminine,	XK_masculine,
	XK_questiondown,XK_hyphen,	XK_notsign,	XK_onehalf,
	XK_onequarter,	XK_exclamdown,	XK_guillemotleft,XK_guillemotright,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
	XK_Greek_alpha,	XK_ssharp,	XK_Greek_GAMMA,	XK_Greek_pi,
	XK_Greek_SIGMA,	XK_Greek_sigma,	XK_mu,	        XK_Greek_tau,
	XK_Greek_PHI,	XK_Greek_THETA,	XK_Greek_OMEGA,	XK_Greek_delta,
	XK_infinity,	XK_Ooblique,	XK_Greek_epsilon, XK_intersection,
	XK_identical,	XK_plusminus,	XK_greaterthanequal, XK_lessthanequal,
	XK_topintegral,	XK_botintegral,	XK_division,	XK_similarequal,
	XK_degree,	NoSymbol,	NoSymbol,	XK_radical,
	XK_Greek_eta,	XK_twosuperior,	XK_periodcentered, NoSymbol,
      };

/*
 * LegalModifier --
 *      determine whether a key is a legal modifier key, i.e send a
 *      press/release sequence.
 */

/*ARGSUSED*/
Bool
LegalModifier(key, pDev)
     unsigned int  key;
     DevicePtr  pDev;
{
  return (TRUE);
}


      
/*
 * xf86KbdGetMapping --
 *	Get the national keyboard mapping. The keyboard type is set, a new map
 *      and the modifiermap is computed.
 */

void
xf86KbdGetMapping (pKeySyms, pModMap)
     KeySymsPtr pKeySyms;
     CARD8      *pModMap;
{
  KeySym        *k;
  struct	kbentry kbe;
  char          type;
  int           i, j;
  
  for (i = 0; i < NUMKEYS; i++)
    {
      static int states[] = { NORM_STATE, SHIFT_STATE, ALT_STATE, SHIFT_ALT };
      int j;

      k = &map[i*4];
      kbe.kb_index = i;
	
      for (j = 0; j < 4; j++)
	{
	  kbe.kb_state = states[j];

	  if (ioctl (xf86Info.consoleFd, KDGKBENT, &kbe) != -1)
	    continue;
      
	  if (kbe.kb_value [0] == K_SCAN)
	    {
	      int keycode = -1;
	      switch (kbe.kb_value [1])
		{
		case K_CTLSC: keycode = XK_Control_L; break;
		case K_LSHSC: keycode = XK_Shift_L; break;
		case K_RSHSC: keycode = XK_Shift_R; break;
		case K_ALTSC: keycode = XK_Alt_L; break;
		case K_CLCKSC: keycode = XK_Caps_Lock; break;
		case K_NLCKSC: keycode = XK_Num_Lock; break;
		default: break;
		}
	      if (keycode > 0)
		k[j] = keycode;
	    }
	  else if (kbe.kb_value[1] != NC)
	    {
	      /* How to handle multiple characters?
	         Ignore them for now. */
	    }
	  else
	    {
	      k[j] = ascii_to_x[kbe.kb_value[0]];
	    }
	}
    }

  /*
   * Apply the special key mapping specified in XF86Config 
   */
  for (k = map, i = MIN_KEYCODE;
       i < (NUM_KEYCODES + MIN_KEYCODE);
       i++, k += 4) {
    switch (k[0]) {
      case XK_Alt_L:
        j = K_INDEX_LEFTALT;
        break;
      case XK_Alt_R:
        j = K_INDEX_RIGHTALT;
        break;
      case XK_Scroll_Lock:
        j = K_INDEX_SCROLLLOCK;
        break;
      case XK_Control_R:
        j = K_INDEX_RIGHTCTL;
        break;
      default:
        j = -1;
    }
    if (j >= 0)
      switch (xf86Info.specialKeyMap[j]) {
        case KM_META:
          if (k[0] == XK_Alt_R)
            k[1] = XK_Meta_R;
          else {
            k[0] = XK_Alt_L;
            k[1] = XK_Meta_L;
          }
          break;
        case KM_COMPOSE:
          k[0] = XK_Multi_key;
          break;
        case KM_MODESHIFT:
          k[0] = XK_Mode_switch;
          k[1] = NoSymbol;
          break;
        case KM_MODELOCK:
          k[0] = XK_Mode_switch;
          k[1] = XF86XK_ModeLock;
          break;
        case KM_SCROLLLOCK:
          k[0] = XK_Scroll_Lock;
          break;
        case KM_CONTROL:
          k[0] = XK_Control_R;
          break;
      }
  }

  /*
   * compute the modifier map
   */
  for (i = 0; i < MAP_LENGTH; i++)
    pModMap[i] = NoSymbol;  /* make sure it is restored */
  
  for (k = map, i = MIN_KEYCODE;
       i < (NUM_KEYCODES + MIN_KEYCODE);
       i++, k += 4)
    
    switch(*k) {
      
    case XK_Shift_L:
    case XK_Shift_R:
      pModMap[i] = ShiftMask;
      break;
      
    case XK_Control_L:
    case XK_Control_R:
      pModMap[i] = ControlMask;
      break;
      
    case XK_Caps_Lock:
      pModMap[i] = LockMask;
      break;
      
    case XK_Alt_L:
    case XK_Alt_R:
      pModMap[i] = AltMask;
      break;
      
    case XK_Num_Lock:
      if (!xf86Info.serverNumLock) pModMap[i] = NumLockMask;
      break;

    case XK_Scroll_Lock:
      pModMap[i] = ScrollLockMask;
      break;

      /* kana support */
    case XK_Kana_Lock:
    case XK_Kana_Shift:
      pModMap[i] = KanaMask;
      break;

      /* alternate toggle for multinational support */
    case XK_Mode_switch:
      pModMap[i] = AltLangMask;
      break;

    }
  
  xf86Info.kbdType =
    ioctl(xf86Info.kbdFd, KDGKBDTYPE, &type) != -1 ? type : KB_VANILLAKB;

  pKeySyms->map        = map;
  pKeySyms->mapWidth   = GLYPHS_PER_KEY;
  pKeySyms->minKeyCode = MIN_KEYCODE;
  if (xf86Info.serverNumLock)
    pKeySyms->maxKeyCode = MAX_KEYCODE; 
  else
    pKeySyms->maxKeyCode = MAX_STD_KEYCODE;

}

--- NEW FILE: xf86Keymap.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Keymap.h,v 3.20 2003/08/24 17:36:53 dawes Exp $ */

/*
 * Copyright (c) 1994-2002 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 *
 * For Scancodes see notes in atKeynames.h  !!!!
 *
 */
/* $XConsortium: xf86Keymap.h /main/14 1996/02/21 17:38:47 kaleb $ */

static KeySym map[NUM_KEYCODES * GLYPHS_PER_KEY] = {

#if !defined(__SOL8__) && (!defined(sun) || defined(i386))

    /* 0x00 */  NoSymbol,       NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x01 */  XK_Escape,      NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x02 */  XK_1,           XK_exclam,	NoSymbol,	NoSymbol,
    /* 0x03 */  XK_2,           XK_at,		NoSymbol,	NoSymbol,
    /* 0x04 */  XK_3,           XK_numbersign,	NoSymbol,	NoSymbol,
    /* 0x05 */  XK_4,           XK_dollar,	NoSymbol,	NoSymbol,
    /* 0x06 */  XK_5,           XK_percent,	NoSymbol,	NoSymbol,
    /* 0x07 */  XK_6,           XK_asciicircum,	NoSymbol,	NoSymbol,
    /* 0x08 */  XK_7,           XK_ampersand,	NoSymbol,	NoSymbol,
    /* 0x09 */  XK_8,           XK_asterisk,	NoSymbol,	NoSymbol,
    /* 0x0a */  XK_9,           XK_parenleft,	NoSymbol,	NoSymbol,
    /* 0x0b */  XK_0,           XK_parenright,	NoSymbol,	NoSymbol,
    /* 0x0c */  XK_minus,       XK_underscore,	NoSymbol,	NoSymbol,
    /* 0x0d */  XK_equal,       XK_plus,	NoSymbol,	NoSymbol,
    /* 0x0e */  XK_BackSpace,   NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x0f */  XK_Tab,         XK_ISO_Left_Tab,NoSymbol,	NoSymbol,
    /* 0x10 */  XK_Q,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x11 */  XK_W,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x12 */  XK_E,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x13 */  XK_R,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x14 */  XK_T,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x15 */  XK_Y,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x16 */  XK_U,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x17 */  XK_I,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x18 */  XK_O,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x19 */  XK_P,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x1a */  XK_bracketleft, XK_braceleft,	NoSymbol,	NoSymbol,
    /* 0x1b */  XK_bracketright,XK_braceright,	NoSymbol,	NoSymbol,
    /* 0x1c */  XK_Return,      NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x1d */  XK_Control_L,   NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x1e */  XK_A,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x1f */  XK_S,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x20 */  XK_D,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x21 */  XK_F,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x22 */  XK_G,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x23 */  XK_H,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x24 */  XK_J,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x25 */  XK_K,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x26 */  XK_L,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x27 */  XK_semicolon,   XK_colon,	NoSymbol,	NoSymbol,
    /* 0x28 */  XK_quoteright,  XK_quotedbl,	NoSymbol,	NoSymbol,
    /* 0x29 */  XK_quoteleft,	XK_asciitilde,	NoSymbol,	NoSymbol,
    /* 0x2a */  XK_Shift_L,     NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x2b */  XK_backslash,   XK_bar,		NoSymbol,	NoSymbol,
    /* 0x2c */  XK_Z,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x2d */  XK_X,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x2e */  XK_C,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x2f */  XK_V,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x30 */  XK_B,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x31 */  XK_N,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x32 */  XK_M,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x33 */  XK_comma,       XK_less,	NoSymbol,	NoSymbol,
    /* 0x34 */  XK_period,      XK_greater,	NoSymbol,	NoSymbol,
    /* 0x35 */  XK_slash,       XK_question,	NoSymbol,	NoSymbol,
    /* 0x36 */  XK_Shift_R,     NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x37 */  XK_KP_Multiply, NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x38 */  XK_Alt_L,	XK_Meta_L,	NoSymbol,	NoSymbol,
    /* 0x39 */  XK_space,       NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x3a */  XK_Caps_Lock,   NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x3b */  XK_F1,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x3c */  XK_F2,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x3d */  XK_F3,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x3e */  XK_F4,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x3f */  XK_F5,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x40 */  XK_F6,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x41 */  XK_F7,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x42 */  XK_F8,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x43 */  XK_F9,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x44 */  XK_F10,         NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x45 */  XK_Num_Lock,    NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x46 */  XK_Scroll_Lock,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x47 */  XK_KP_Home,	XK_KP_7,	NoSymbol,	NoSymbol,
    /* 0x48 */  XK_KP_Up,	XK_KP_8,	NoSymbol,	NoSymbol,
    /* 0x49 */  XK_KP_Prior,	XK_KP_9,	NoSymbol,	NoSymbol,
    /* 0x4a */  XK_KP_Subtract, NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x4b */  XK_KP_Left,	XK_KP_4,	NoSymbol,	NoSymbol,
    /* 0x4c */  XK_KP_Begin,	XK_KP_5,	NoSymbol,	NoSymbol,
    /* 0x4d */  XK_KP_Right,	XK_KP_6,	NoSymbol,	NoSymbol,
    /* 0x4e */  XK_KP_Add,      NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x4f */  XK_KP_End,	XK_KP_1,	NoSymbol,	NoSymbol,
    /* 0x50 */  XK_KP_Down,	XK_KP_2,	NoSymbol,	NoSymbol,
    /* 0x51 */  XK_KP_Next,	XK_KP_3,	NoSymbol,	NoSymbol,
    /* 0x52 */  XK_KP_Insert,	XK_KP_0,	NoSymbol,	NoSymbol,
    /* 0x53 */  XK_KP_Delete,	XK_KP_Decimal,	NoSymbol,	NoSymbol,
    /* 0x54 */  XK_Sys_Req,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x55 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x56 */  XK_less,	XK_greater,	NoSymbol,	NoSymbol,
    /* 0x57 */  XK_F11,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x58 */  XK_F12,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x59 */  XK_Home,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x5a */  XK_Up,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x5b */  XK_Prior,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x5c */  XK_Left,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x5d */  XK_Begin,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x5e */  XK_Right,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x5f */  XK_End,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x60 */  XK_Down,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x61 */  XK_Next,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x62 */  XK_Insert,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x63 */  XK_Delete,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x64 */  XK_KP_Enter,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x65 */  XK_Control_R,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x66 */  XK_Pause,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x67 */  XK_Print,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x68 */  XK_KP_Divide,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x69 */  XK_Alt_R,	XK_Meta_R,	NoSymbol,	NoSymbol,
    /* 0x6a */  XK_Break,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x6b */  XK_Meta_L,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x6c */  XK_Meta_R,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x6d */  XK_Menu,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x6e */  XK_F13,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x6f */  XK_F14,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x70 */  XK_F15,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x71 */  XK_F16,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x72 */  XK_F17,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x73 */  XK_backslash,	XK_underscore,	NoSymbol,	NoSymbol,
    /* 0x74 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x75 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x76 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x77 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x78 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x79 */  XK_Henkan,	XK_Mode_switch,	NoSymbol,	NoSymbol,
    /* 0x7a */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x7b */  XK_Muhenkan,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x7c */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x7d */  XK_backslash,	XK_bar,		NoSymbol,	NoSymbol,
    /* 0x7e */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x7f */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,

#else /* SunOS */

/* Assumes a US English keyboard as default - sorry 'bout that
 *
 * Hopefully it'll be enough someone can have a sorta working
 * keyboard, if they're not using XKB
 *
 * DWH 9/12/99
 */

    /* 0x00 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x01 */  XK_quoteleft,	XK_asciitilde,	NoSymbol,	NoSymbol,
    /* 0x02 */  XK_1,		XK_exclam,	NoSymbol,	NoSymbol,
    /* 0x03 */  XK_2,		XK_at,		NoSymbol,	NoSymbol,
    /* 0x04 */  XK_3,		XK_numbersign,	NoSymbol,	NoSymbol,
    /* 0x05 */  XK_4,		XK_dollar,	NoSymbol,	NoSymbol,
    /* 0x06 */  XK_5,		XK_percent,	NoSymbol,	NoSymbol,
    /* 0x07 */  XK_6,		XK_asciicircum,	NoSymbol,	NoSymbol,
    /* 0x08 */  XK_7,		XK_ampersand,	NoSymbol,	NoSymbol,
    /* 0x09 */  XK_8,		XK_asterisk,	NoSymbol,	NoSymbol,
    /* 0x0a */  XK_9,		XK_parenleft,	NoSymbol,	NoSymbol,
    /* 0x0b */  XK_0,		XK_parenright,	NoSymbol,	NoSymbol,
    /* 0x0c */  XK_minus,	XK_underscore,	NoSymbol,	NoSymbol,
    /* 0x0d */  XK_equal,	XK_plus,	NoSymbol,	NoSymbol,
    /* 0x0e */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x0f */  XK_BackSpace,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x10 */  XK_Tab,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x11 */  XK_Q,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x12 */  XK_W,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x13 */  XK_E,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x14 */  XK_R,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x15 */  XK_T,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x16 */  XK_Y,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x17 */  XK_U,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x18 */  XK_I,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x19 */  XK_O,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x1a */  XK_P,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x1b */  XK_bracketleft,	XK_braceleft,	NoSymbol,	NoSymbol,
    /* 0x1c */  XK_bracketright,XK_braceright,	NoSymbol,	NoSymbol,
    /* 0x1d */  XK_backslash,	XK_bar,		NoSymbol,	NoSymbol,
    /* 0x1e */  XK_Caps_Lock,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x1f */  XK_A,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x20 */  XK_S,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x21 */  XK_D,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x22 */  XK_F,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x23 */  XK_G,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x24 */  XK_H,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x25 */  XK_J,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x26 */  XK_K,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x27 */  XK_L,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x28 */  XK_semicolon,	XK_colon,	NoSymbol,	NoSymbol,
    /* 0x29 */  XK_quoteright,	XK_quotedbl,	NoSymbol,	NoSymbol,
    /* 0x2a */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x2b */  XK_Return,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x2c */  XK_Shift_L,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x2d */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x2e */  XK_Z,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x2f */  XK_X,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x30 */  XK_C,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x31 */  XK_V,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x32 */  XK_B,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x33 */  XK_N,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x34 */  XK_M,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x35 */  XK_comma,	XK_less,	NoSymbol,	NoSymbol,
    /* 0x36 */  XK_period,	XK_greater,	NoSymbol,	NoSymbol,
    /* 0x37 */  XK_slash,	XK_question,	NoSymbol,	NoSymbol,
    /* 0x38 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x39 */  XK_Shift_R,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x3a */  XK_Control_L,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x3b */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x3c */  XK_Alt_L,	XK_Meta_L,	NoSymbol,	NoSymbol,
    /* 0x3d */  XK_space,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x3e */  XK_Alt_R,	XK_Meta_R,	NoSymbol,	NoSymbol,
    /* 0x3f */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x40 */  XK_Control_R,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x41 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x42 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x43 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x44 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x45 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x46 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x47 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x48 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x49 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x4a */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x4b */  XK_Insert,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x4c */  XK_Delete,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x4d */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x4e */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x4f */  XK_Left,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x50 */  XK_Home,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x51 */  XK_End,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x52 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x53 */  XK_Up,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x54 */  XK_Down,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x55 */  XK_Prior,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x56 */  XK_Next,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x57 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x58 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x59 */  XK_Right,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x5a */  XK_Num_Lock,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x5b */  XK_KP_Home,	XK_KP_7,	NoSymbol,	NoSymbol,
    /* 0x5c */  XK_KP_Left,	XK_KP_4,	NoSymbol,	NoSymbol,
    /* 0x5d */  XK_KP_End,	XK_KP_1,	NoSymbol,	NoSymbol,
    /* 0x5e */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x5f */  XK_KP_Divide,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x60 */  XK_KP_Up,	XK_KP_8,	NoSymbol,	NoSymbol,
    /* 0x61 */  NoSymbol,	XK_KP_5,	NoSymbol,	NoSymbol,
    /* 0x62 */  XK_KP_Down,	XK_KP_2,	NoSymbol,	NoSymbol,
    /* 0x63 */  XK_KP_Insert,	XK_KP_0,	NoSymbol,	NoSymbol,
    /* 0x64 */  XK_KP_Multiply,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x65 */  XK_KP_Prior,	XK_KP_9,	NoSymbol,	NoSymbol,
    /* 0x66 */  XK_KP_Right,	XK_KP_6,	NoSymbol,	NoSymbol,
    /* 0x67 */  XK_KP_Next,	XK_KP_3,	NoSymbol,	NoSymbol,
    /* 0x68 */  XK_KP_Delete,	XK_KP_Decimal,	NoSymbol,	NoSymbol,
    /* 0x69 */  XK_KP_Subtract,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x6a */  XK_KP_Add,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x6b */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x6c */  XK_KP_Enter,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x6d */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x6e */  XK_Escape,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x6f */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x70 */  XK_F1,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x71 */  XK_F2,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x72 */  XK_F3,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x73 */  XK_F4,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x74 */  XK_F5,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x75 */  XK_F6,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x76 */  XK_F7,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x77 */  XK_F8,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x78 */  XK_F9,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x79 */  XK_F10,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x7a */  XK_F11,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x7b */  XK_F12,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x7c */  XK_Print,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x7d */  XK_Scroll_Lock,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x7e */  XK_Pause,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x7f */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,

#endif /* SunOS */

};

#if !defined(Lynx) && \
    !defined(__UNIXOS2__) && \
    !defined(__mips__) && \
    !defined(linux) && \
    !defined(CSRG_BASED) && \
    !defined(__CYGWIN__) && \
    !defined(__SOL8__) && \
    (!defined(sun) || defined(i386))

static KeySym map84[NUM_KEYCODES * GLYPHS_PER_KEY] = {
    /* 0x00 */  NoSymbol,       NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x01 */  XK_Escape,      NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x02 */  XK_1,           XK_exclam,	NoSymbol,	NoSymbol,
    /* 0x03 */  XK_2,           XK_at,		NoSymbol,	NoSymbol,
    /* 0x04 */  XK_3,           XK_numbersign,	NoSymbol,	NoSymbol,
    /* 0x05 */  XK_4,           XK_dollar,	NoSymbol,	NoSymbol,
    /* 0x06 */  XK_5,           XK_percent,	NoSymbol,	NoSymbol,
    /* 0x07 */  XK_6,           XK_asciicircum,	NoSymbol,	NoSymbol,
    /* 0x08 */  XK_7,           XK_ampersand,	NoSymbol,	NoSymbol,
    /* 0x09 */  XK_8,           XK_asterisk,	NoSymbol,	NoSymbol,
    /* 0x0a */  XK_9,           XK_parenleft,	NoSymbol,	NoSymbol,
    /* 0x0b */  XK_0,           XK_parenright,	NoSymbol,	NoSymbol,
    /* 0x0c */  XK_minus,       XK_underscore,	NoSymbol,	NoSymbol,
    /* 0x0d */  XK_equal,       XK_plus,	NoSymbol,	NoSymbol,
    /* 0x0e */  XK_BackSpace,   NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x0f */  XK_Tab,         NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x10 */  XK_Q,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x11 */  XK_W,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x12 */  XK_E,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x13 */  XK_R,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x14 */  XK_T,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x15 */  XK_Y,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x16 */  XK_U,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x17 */  XK_I,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x18 */  XK_O,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x19 */  XK_P,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x1a */  XK_bracketleft, XK_braceleft,	NoSymbol,	NoSymbol,
    /* 0x1b */  XK_bracketright,XK_braceright,	NoSymbol,	NoSymbol,
    /* 0x1c */  XK_Return,      NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x1d */  XK_Control_L,   NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x1e */  XK_A,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x1f */  XK_S,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x20 */  XK_D,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x21 */  XK_F,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x22 */  XK_G,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x23 */  XK_H,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x24 */  XK_J,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x25 */  XK_K,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x26 */  XK_L,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x27 */  XK_semicolon,   XK_colon,	NoSymbol,	NoSymbol,
    /* 0x28 */  XK_quoteright,  XK_quotedbl,	NoSymbol,	NoSymbol,
    /* 0x29 */  XK_quoteleft,	XK_asciitilde,	NoSymbol,	NoSymbol,
    /* 0x2a */  XK_Shift_L,     NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x2b */  XK_backslash,   XK_bar,		NoSymbol,	NoSymbol,
    /* 0x2c */  XK_Z,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x2d */  XK_X,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x2e */  XK_C,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x2f */  XK_V,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x30 */  XK_B,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x31 */  XK_N,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x32 */  XK_M,           NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x33 */  XK_comma,       XK_less,	NoSymbol,	NoSymbol,
    /* 0x34 */  XK_period,      XK_greater,	NoSymbol,	NoSymbol,
    /* 0x35 */  XK_slash,       XK_question,	NoSymbol,	NoSymbol,
    /* 0x36 */  XK_Shift_R,     NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x37 */  XK_KP_Multiply, NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x38 */  XK_Alt_L,	XK_Meta_L,	NoSymbol,	NoSymbol,
    /* 0x39 */  XK_space,       NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x3a */  XK_Caps_Lock,   NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x3b */  XK_F1,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x3c */  XK_F2,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x3d */  XK_F3,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x3e */  XK_F4,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x3f */  XK_F5,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x40 */  XK_F6,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x41 */  XK_F7,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x42 */  XK_F8,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x43 */  XK_F9,          NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x44 */  XK_F10,         NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x45 */  XK_Num_Lock,    NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x46 */  XK_Scroll_Lock,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x47 */  XK_KP_Home,	XK_KP_7,	NoSymbol,	NoSymbol,
    /* 0x48 */  XK_KP_Up,	XK_KP_8,	NoSymbol,	NoSymbol,
    /* 0x49 */  XK_KP_Prior,	XK_KP_9,	NoSymbol,	NoSymbol,
    /* 0x4a */  XK_KP_Subtract, NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x4b */  XK_KP_Left,	XK_KP_4,	NoSymbol,	NoSymbol,
    /* 0x4c */  NoSymbol,	XK_KP_5,	NoSymbol,	NoSymbol,
    /* 0x4d */  XK_KP_Right,	XK_KP_6,	NoSymbol,	NoSymbol,
    /* 0x4e */  XK_KP_Add,      NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x4f */  XK_KP_End,	XK_KP_1,	NoSymbol,	NoSymbol,
    /* 0x50 */  XK_KP_Down,	XK_KP_2,	NoSymbol,	NoSymbol,
    /* 0x51 */  XK_KP_Next,	XK_KP_3,	NoSymbol,	NoSymbol,
    /* 0x52 */  XK_KP_Insert,	XK_KP_0,	NoSymbol,	NoSymbol,
    /* 0x53 */  XK_KP_Delete,	XK_KP_Decimal,	NoSymbol,	NoSymbol,
    /* 0x54 */  XK_Sys_Req,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x55 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x56 */  XK_less,	XK_greater,	NoSymbol,	NoSymbol,
    /* 0x57 */  XK_F11,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x58 */  XK_F12,		NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x59 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x5a */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x5b */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x5c */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x5d */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x5e */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x5f */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x60 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x61 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x62 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x63 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x64 */  XK_KP_Enter,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x65 */  XK_Control_R,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x66 */  XK_Pause,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x67 */  XK_Print,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x68 */  XK_KP_Divide,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x69 */  XK_Alt_R,	XK_Meta_R,	NoSymbol,	NoSymbol,
    /* 0x6a */  XK_Break,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x6b */  XK_Meta_L,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x6c */  XK_Meta_R,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x6d */  XK_Menu,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x6e */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x6f */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x70 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x71 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x72 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x73 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x74 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x75 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x76 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x77 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x78 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x79 */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x7a */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x7b */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x7c */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x7d */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
    /* 0x7e */  NoSymbol,	NoSymbol,	NoSymbol,	NoSymbol,
};
#endif

--- NEW FILE: xf86MiscExt.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86MiscExt.c,v 1.16 2003/11/03 05:11:02 tsi Exp $ */
/*
 * Copyright (c) 1999-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 * This file contains the Pointer/Keyboard functions needed by the 
 * XFree86-Misc extension.
 */

#ifdef __UNIXOS2__
#define I_NEED_OS2_H
#endif

#include <X11/X.h>
#include "os.h"
#include "xf86.h"
#include "xf86Priv.h"

#ifdef XF86MISC
#define _XF86MISC_SERVER_
#include "xf86misc.h"
#include "xf86miscproc.h"
#endif

#define XF86_OS_PRIVS
#include "xf86_OSlib.h"

#ifdef XINPUT
#include <X11/extensions/XI.h>
#include <X11/extensions/XIproto.h>
#include "xf86Xinput.h"
#else
#include "inputstr.h"
#endif

#include "xf86OSmouse.h"
#include "../input/mouse/mouse.h"

#ifdef DEBUG
# define DEBUG_P(x) ErrorF(x"\n");
#else
# define DEBUG_P(x) /**/
#endif

#ifdef XF86MISC

typedef struct {
	int	type;
	int	baudrate;
	int	samplerate;
	int	resolution;
	int	buttons;
	Bool	em3buttons;
	int	em3timeout;
	Bool	chordmiddle;
	int	flags;
        char*   device;
        pointer	private;
} mseParamsRec, *mseParamsPtr;

typedef struct {
	int	type;
	int	rate;
	int	delay;
	int	serverNumLock;	/* obsolete */
} kbdParamsRec, *kbdParamsPtr;

/*
    Sigh...

    The extension should probably be changed to use protocol
    names instead of ID numbers
*/
static struct mouse_map {
    int mtype;
    MouseProtocolID proto;
} m_map[] =
{
	{ MTYPE_MICROSOFT, PROT_MS },
	{ MTYPE_MOUSESYS, PROT_MSC },
	{ MTYPE_MMSERIES, PROT_MM },
	{ MTYPE_LOGITECH, PROT_LOGI },
	{ MTYPE_LOGIMAN, PROT_LOGIMAN },
	{ MTYPE_MMHIT, PROT_MMHIT },
	{ MTYPE_GLIDEPOINT, PROT_GLIDE },
	{ MTYPE_IMSERIAL, PROT_IMSERIAL },
	{ MTYPE_THINKING, PROT_THINKING },
	{ MTYPE_ACECAD, PROT_ACECAD },
	{ MTYPE_PS_2, PROT_PS2 },
	{ MTYPE_IMPS2, PROT_IMPS2 },
	{ MTYPE_EXPPS2, PROT_EXPPS2 },
	{ MTYPE_THINKINGPS2, PROT_THINKPS2 },
	{ MTYPE_MMANPLUSPS2, PROT_MMPS2 },
	{ MTYPE_GLIDEPOINTPS2, PROT_GLIDEPS2 },
	{ MTYPE_NETPS2, PROT_NETPS2 },
	{ MTYPE_NETSCROLLPS2, PROT_NETSCPS2 },
	{ MTYPE_BUSMOUSE, PROT_BM },
	{ MTYPE_AUTOMOUSE, PROT_AUTO },
	{ MTYPE_SYSMOUSE, PROT_SYSMOUSE },
	{ MTYPE_UNKNOWN, PROT_UNKNOWN }
};

static int
MapMseProtoToMisc(MouseProtocolID proto)
{
    int i;
    
	for (i = 0; m_map[i].proto != PROT_UNKNOWN; i++)
	if (proto == m_map[i].proto)
	    return m_map[i].mtype;

	return MTYPE_UNKNOWN;
}

static MouseProtocolID
MapMseMiscToProto(int proto)
{
    int i;

	for (i = 0; m_map[i].mtype != MTYPE_UNKNOWN; i++)
	if (proto == m_map[i].mtype)
	    return m_map[i].proto;

	return PROT_UNKNOWN;
}

Bool
MiscExtGetMouseSettings(pointer *mouse, char **devname)
{
    mseParamsPtr mseptr;

    DEBUG_P("MiscExtGetMouseSettings");

    mseptr = MiscExtCreateStruct(MISC_POINTER);
    if (!mseptr)
	return FALSE;

    {
	InputInfoPtr pInfo = mseptr->private;
	MouseDevPtr pMse;

	*devname = xf86FindOptionValue(pInfo->options, "Device");
	pMse = pInfo->private;

	mseptr->type =		MapMseProtoToMisc(pMse->protocolID);
	mseptr->baudrate =	pMse->baudRate;
	mseptr->samplerate =	pMse->sampleRate;
	mseptr->resolution =	pMse->resolution;
	mseptr->buttons =	pMse->buttons;
	mseptr->em3buttons =	pMse->emulate3Buttons;
	mseptr->em3timeout =	pMse->emulate3Timeout;
	mseptr->chordmiddle =	pMse->chordMiddle;
	mseptr->flags =		pMse->mouseFlags;
    }
    *mouse = mseptr;
    return TRUE;
}

int
MiscExtGetMouseValue(pointer mouse, MiscExtMseValType valtype)
{
    mseParamsPtr mse = mouse;

    DEBUG_P("MiscExtGetMouseValue");

    switch (valtype) {
	case MISC_MSE_PROTO:		return mse->type;
	case MISC_MSE_BAUDRATE:		return mse->baudrate;
	case MISC_MSE_SAMPLERATE:	return mse->samplerate;
	case MISC_MSE_RESOLUTION:	return mse->resolution;
	case MISC_MSE_BUTTONS:		return mse->buttons;
	case MISC_MSE_EM3BUTTONS:	return mse->em3buttons;
	case MISC_MSE_EM3TIMEOUT:	return mse->em3timeout;
	case MISC_MSE_CHORDMIDDLE:	return mse->chordmiddle;
	case MISC_MSE_FLAGS:		return mse->flags;
    }
    return 0;
}

Bool
MiscExtSetMouseValue(pointer mouse, MiscExtMseValType valtype, int value)
{
    mseParamsPtr mse = mouse;

    DEBUG_P("MiscExtSetMouseValue");

    switch (valtype) {
	case MISC_MSE_PROTO:
	    mse->type = value;
		return TRUE;
	case MISC_MSE_BAUDRATE:
		mse->baudrate = value;
		return TRUE;
	case MISC_MSE_SAMPLERATE:
		mse->samplerate = value;
		return TRUE;
	case MISC_MSE_RESOLUTION:
		mse->resolution = value;
		return TRUE;
	case MISC_MSE_BUTTONS:
		mse->buttons = value;
		return TRUE;
	case MISC_MSE_EM3BUTTONS:
		mse->em3buttons = value;
		return TRUE;
	case MISC_MSE_EM3TIMEOUT:
		mse->em3timeout = value;
		return TRUE;
	case MISC_MSE_CHORDMIDDLE:
		mse->chordmiddle = value;
		return TRUE;
	case MISC_MSE_FLAGS:
		mse->flags = value;
		return TRUE;
    }
    return FALSE;
}

Bool
MiscExtSetMouseDevice(pointer mouse, char* device)
{
    mseParamsPtr mse = mouse;

    mse->device = device;
    
    return TRUE;
}

Bool
MiscExtGetKbdSettings(pointer *kbd)
{
    kbdParamsPtr kbdptr;

    DEBUG_P("MiscExtGetKbdSettings");

    kbdptr = MiscExtCreateStruct(MISC_KEYBOARD);
    if (!kbdptr)
	return FALSE;
    kbdptr->type  = xf86Info.kbdType;
    kbdptr->rate  = xf86Info.kbdRate;
    kbdptr->delay = xf86Info.kbdDelay;
    *kbd = kbdptr;
    return TRUE;
}

int
MiscExtGetKbdValue(pointer keyboard, MiscExtKbdValType valtype)
{
    kbdParamsPtr kbd = keyboard;

    DEBUG_P("MiscExtGetKbdValue");
    switch (valtype) {
	case MISC_KBD_TYPE:		return kbd->type;
	case MISC_KBD_RATE:		return kbd->rate;
	case MISC_KBD_DELAY:		return kbd->delay;
	case MISC_KBD_SERVNUMLOCK:	return 0;
    }
    return 0;
}

Bool
MiscExtSetKbdValue(pointer keyboard, MiscExtKbdValType valtype, int value)
{
    kbdParamsPtr kbd = keyboard;

    DEBUG_P("MiscExtSetKbdValue");
    switch (valtype) {
	case MISC_KBD_TYPE:
		kbd->type = value;
		return TRUE;
	case MISC_KBD_RATE:
		kbd->rate = value;
		return TRUE;
	case MISC_KBD_DELAY:
		kbd->delay = value;
		return TRUE;
	case MISC_KBD_SERVNUMLOCK:
		return TRUE;
    }
    return FALSE;
}

static void
MiscExtClientStateCallback(CallbackListPtr *callbacks,
			   pointer data, pointer args)
{
    NewClientInfoRec *clientinfo = (NewClientInfoRec*)args;

    if (clientinfo->client == xf86Info.grabInfo.override &&
	clientinfo->client->clientState == ClientStateGone) {
	xf86Info.grabInfo.override = NULL;
	xf86Info.grabInfo.disabled = 0;
	DeleteCallback(&ClientStateCallback, MiscExtClientStateCallback, NULL);
    }
}

#define MiscExtGrabStateSuccess	0	/* No errors */
#define MiscExtGrabStateLocked	1	/* A client already requested that
					 * grabs cannot be removed/killed */
#define MiscExtGrabStateAlready	2	/* Request for enabling/disabling
					 * grab removeal/kill already done */
int
MiscExtSetGrabKeysState(ClientPtr client, int state)
{
    DEBUG_P("MiscExtSetGrabKeysState");

    if (xf86Info.grabInfo.override == NULL ||
	xf86Info.grabInfo.override == client) {
	if (state == 0 && xf86Info.grabInfo.disabled == 0) {
	    xf86Info.grabInfo.disabled = 1;
	    AddCallback(&ClientStateCallback,
			MiscExtClientStateCallback, NULL);
	    xf86Info.grabInfo.override = client;
	}
	else if (state == 1 && xf86Info.grabInfo.disabled == 1) {
	    xf86Info.grabInfo.disabled = 0;
	    DeleteCallback(&ClientStateCallback,
			   MiscExtClientStateCallback, NULL);
	    xf86Info.grabInfo.override = NULL;
	}
	else
	    return MiscExtGrabStateAlready;

	return MiscExtGrabStateSuccess;
    }

    return MiscExtGrabStateLocked;
}

pointer
MiscExtCreateStruct(MiscExtStructType mse_or_kbd)
{
    DEBUG_P("MiscExtCreateStruct");
    
    switch (mse_or_kbd) {
    case MISC_POINTER:
    {
	mseParamsPtr mseptr;
	InputInfoPtr pInfo = xf86InputDevs;
	
	while (pInfo) {
	    if (xf86IsCorePointer(pInfo->dev))
		break;
	    pInfo = pInfo->next;
	}
	if (!pInfo)
	    return NULL;
	
	mseptr = xcalloc(sizeof(mseParamsRec),1);
	if (mseptr)
	    mseptr->private = pInfo;
	return mseptr;
    }
    case MISC_KEYBOARD:
	return xcalloc(sizeof(kbdParamsRec),1);
    }
    return 0;
}

void
MiscExtDestroyStruct(pointer structure, MiscExtStructType mse_or_kbd)
{
    DEBUG_P("MiscExtDestroyStruct");

    switch (mse_or_kbd) {
	case MISC_POINTER:
	case MISC_KEYBOARD:
		xfree(structure);
    }
}

static Bool
MiscExtAuthorizeDevice(InputInfoPtr pInfo, char *device)
{
    Bool authorized = FALSE;
    char *elem;
    struct stat dev, dev_list;
    const char *olddev = xf86FindOptionValue(pInfo->options, "Device");
    
    if (stat(device,&dev))
	return FALSE;

    if (!S_ISCHR(dev.st_mode))
	return FALSE;

    if (!stat(olddev,&dev_list)) {
	if (dev_list.st_dev == dev.st_dev
	    && dev_list.st_ino == dev.st_ino) {
	    authorized = TRUE;
	}
    }

    if (!authorized) {
	char *path;

	if (!xf86InputDeviceList
	    || (path = strdup(xf86InputDeviceList)) == NULL) 
	    return FALSE;
	
	elem = strtok(path,",");
	
	while (elem) {
	    
	    if (!stat(elem,&dev_list)) {
		if (dev_list.st_dev == dev.st_dev
		    && dev_list.st_ino == dev.st_ino) {
		    authorized = TRUE;
		    break;

		}
	    }
	    elem = strtok(NULL,",");
	}
	xfree(path);
    }
#if 0
    ErrorF("AUTHORIZED: %s\n",authorized?"Yes":"No");
#endif
    return (authorized);
}

MiscExtReturn
MiscExtApply(pointer structure, MiscExtStructType mse_or_kbd)
{
    DEBUG_P("MiscExtApply");

    if (mse_or_kbd == MISC_POINTER) {
	Bool protoChanged = FALSE;
	int oldflags;
	Bool reopen = FALSE;
	MouseProtocolID newProtocol;
	mseParamsPtr mse = structure;
	InputInfoPtr pInfo;
	MouseDevPtr pMse;
#ifdef XFree86LOADER
	pointer xf86MouseProtocolIDToName
	    = LoaderSymbol("xf86MouseProtocolIDToName");
	if (!xf86MouseProtocolIDToName)
	    return MISC_RET_NOMODULE;
#endif
	if (mse->type < MTYPE_MICROSOFT
		|| ( mse->type > MTYPE_EXPPS2
		    && (mse->type!=MTYPE_OSMOUSE && mse->type!=MTYPE_XQUEUE)))
	    return MISC_RET_BADMSEPROTO;
#ifdef OSMOUSE_ONLY
	if (mse->type != MTYPE_OSMOUSE)
	    return MISC_RET_BADMSEPROTO;
#else
	if (mse->type == MTYPE_XQUEUE)
	    return MISC_RET_BADMSEPROTO;
	if (mse->type == MTYPE_OSMOUSE)
	    return MISC_RET_BADMSEPROTO;
#endif /* OSMOUSE_ONLY */

	if (mse->em3timeout < 0)
	    return MISC_RET_BADVAL;

	if (mse->type == MTYPE_LOGIMAN
	    && !(mse->baudrate == 0
		 || mse->baudrate == 1200
		 || mse->baudrate == 9600))
	    return MISC_RET_BADBAUDRATE;
	if (mse->type == MTYPE_LOGIMAN && mse->samplerate)
	    return MISC_RET_BADCOMBO;

	if (mse->flags & MF_REOPEN) {
	    reopen = TRUE;
	    mse->flags &= ~MF_REOPEN;
	}
	if (mse->type != MTYPE_OSMOUSE
		&& mse->type != MTYPE_XQUEUE
		&& mse->type != MTYPE_PS_2
		&& mse->type != MTYPE_BUSMOUSE
		&& mse->type != MTYPE_IMPS2
		&& mse->type != MTYPE_THINKINGPS2
		&& mse->type != MTYPE_MMANPLUSPS2
		&& mse->type != MTYPE_GLIDEPOINTPS2
		&& mse->type != MTYPE_NETPS2
		&& mse->type != MTYPE_NETSCROLLPS2
		&& mse->type != MTYPE_SYSMOUSE)
	{
	    if (mse->baudrate % 1200 != 0
		|| (mse->baudrate != 0 && mse->baudrate < 1200)
		|| mse->baudrate > 9600)
		return MISC_RET_BADBAUDRATE;
	}
	if ((mse->flags & (MF_CLEAR_DTR|MF_CLEAR_RTS))
		&& (mse->type != MTYPE_MOUSESYS))
	    return MISC_RET_BADFLAGS;

	if (mse->type != MTYPE_OSMOUSE
		&& mse->type != MTYPE_XQUEUE
		&& mse->type != MTYPE_BUSMOUSE)
	{
	    if (mse->samplerate < 0)
		return MISC_RET_BADVAL;
	}

	if (mse->resolution < 0)
	    return MISC_RET_BADVAL;
	if (mse->chordmiddle)
	{
	    if (mse->em3buttons || !(mse->type == MTYPE_MICROSOFT
				    || mse->type == MTYPE_LOGIMAN) )
		return MISC_RET_BADCOMBO;
	}

	/* XXX - This still needs work */

	pInfo = mse->private;
	pMse = pInfo->private;
	oldflags = pMse->mouseFlags;
	
	newProtocol = MapMseMiscToProto(mse->type);
	protoChanged = pMse->protocolID != newProtocol;
	if (protoChanged
		|| pMse->baudRate != mse->baudrate
		|| pMse->sampleRate != mse->samplerate
		|| pMse->resolution != mse->resolution
		|| pMse->mouseFlags != mse->flags)
	    reopen = TRUE;

	if (mse->device)
	    reopen = TRUE;

	if (reopen)
	    (pMse->device->deviceProc)(pMse->device, DEVICE_CLOSE);
	
	pMse->protocolID      = newProtocol;
	pMse->baudRate        = mse->baudrate;
	pMse->sampleRate      = mse->samplerate;
	pMse->resolution      = mse->resolution;
	pMse->buttons         = mse->buttons;
	pMse->emulate3Buttons = mse->em3buttons;
	pMse->emulate3Timeout = mse->em3timeout;
	pMse->chordMiddle     = mse->chordmiddle;
	pMse->mouseFlags      = mse->flags;

#ifdef XFree86LOADER
	pMse->protocol = ((const char *(*)(MouseProtocolID))
			  xf86MouseProtocolIDToName)(pMse->protocolID);
#else
	pMse->protocol = xf86MouseProtocolIDToName(pMse->protocolID);
#endif
	
	if (mse->device) {
	    if (MiscExtAuthorizeDevice(pInfo, mse->device)) {
		xf86ReplaceStrOption(pInfo->options, "Device", mse->device);
	    } else {
		return MISC_RET_BADVAL;
	    }
	}
	
	if (reopen) {
	    /* Only if protocol is changed explicitely disable auto detect */
	    if (protoChanged)
		pMse->autoProbe = FALSE;
	    (pMse->device->deviceProc)(pMse->device, DEVICE_ON);
	}
	/* Set pInfo->options too */
	
       if ((oldflags & MF_CLEAR_DTR) != (pMse->mouseFlags & MF_CLEAR_DTR))
	   xf86ReplaceBoolOption(pInfo->options, "ClearDTR",
				 pMse->mouseFlags | MF_CLEAR_DTR);
       if ((oldflags & MF_CLEAR_RTS) != (pMse->mouseFlags & MF_CLEAR_RTS))
	   xf86ReplaceBoolOption(pInfo->options, "ClearRTS",
				 pMse->mouseFlags | MF_CLEAR_RTS);
    }
    if (mse_or_kbd == MISC_KEYBOARD) {
	kbdParamsPtr kbd = structure;

	if (kbd->rate < 0)
	    return MISC_RET_BADVAL;
	if (kbd->delay < 0)
	    return MISC_RET_BADVAL;
	if (kbd->type < KTYPE_UNKNOWN || kbd->type > KTYPE_XQUEUE)
	    return MISC_RET_BADKBDTYPE;

	if (xf86Info.kbdRate!=kbd->rate || xf86Info.kbdDelay!=kbd->delay) {
	    char rad;

	    xf86Info.kbdRate = kbd->rate;
	    xf86Info.kbdDelay = kbd->delay;
	    if      (xf86Info.kbdDelay <= 375) rad = 0x00;
	    else if (xf86Info.kbdDelay <= 625) rad = 0x20;
	    else if (xf86Info.kbdDelay <= 875) rad = 0x40;
	    else                               rad = 0x60;

	    if      (xf86Info.kbdRate <=  2)   rad |= 0x1F;
	    else if (xf86Info.kbdRate >= 30)   rad |= 0x00;
	    else                               rad |= ((58/xf86Info.kbdRate)-2);

	    xf86SetKbdRepeat(rad);
	}
#if 0   /* Not done yet */
	xf86Info.kbdType = kbd->kbdtype;
#endif
    }
    return MISC_RET_SUCCESS;
}

Bool
MiscExtGetFilePaths(const char **configfile, const char **modulepath,
		    const char **logfile)
{
    DEBUG_P("MiscExtGetFilePaths");

    *configfile = xf86ConfigFile;
    *modulepath = xf86ModulePath;
    *logfile    = xf86LogFile;

    return TRUE;
}

int
MiscExtPassMessage(int scrnIndex, const char *msgtype, const char *msgval,
		   char **retstr)
{
    ScrnInfoPtr pScr = xf86Screens[scrnIndex];

    DEBUG_P("MiscExtPassMessage");

    if (*pScr->HandleMessage == NULL)
	    return BadImplementation;
    return (*pScr->HandleMessage)(scrnIndex, msgtype, msgval, retstr);
}

#endif /* XF86MISC */


--- NEW FILE: xf86Mode.c ---
/* $XdotOrg: xc/programs/Xserver/hw/xfree86/common/xf86Mode.c,v 1.1.4.3.2.1 2004/02/27 21:30:59 eich Exp $ */
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Mode.c,v 1.69 2003/10/08 14:58:28 dawes Exp $ */
/*
 * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
[...2138 lines suppressed...]
		xf86DrvMsg(scrp->scrnIndex, X_PROBED,
			   "%s%s %dx%d (unnamed)\n",
			   uprefix, prefix, p->HDisplay, p->VDisplay);
	} else if (p->Clock == p->SynthClock) {
	    xf86DrvMsg(scrp->scrnIndex, X_CONFIG,
			"%s%s \"%s\": %.1f MHz, %.1f kHz, %.1f Hz%s%s\n",
			uprefix, prefix, p->name, p->Clock / 1000.0,
			hsync, refresh, desc, desc2);
	} else {
	    xf86DrvMsg(scrp->scrnIndex, X_CONFIG,
			"%s%s \"%s\": %.1f MHz (scaled from %.1f MHz), "
			"%.1f kHz, %.1f Hz%s%s\n",
			uprefix, prefix, p->name, p->Clock / 1000.0,
			p->SynthClock / 1000.0, hsync, refresh, desc, desc2);
	}
	if (hsync != 0 && refresh != 0)
	    PrintModeline(scrp->scrnIndex,p);
	p = p->next;
    } while (p != NULL && p != scrp->modes);
}

--- NEW FILE: xf86Module.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Module.h,v 1.37 2003/08/24 17:36:54 dawes Exp $ */

/*
 * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 * This file contains the parts of the loader interface that are visible
 * to modules.  This is the only loader-related header that modules should
 * include.
 *
 * It should include a bare minimum of other headers.
 *
 * Longer term, the module/loader code should probably live directly under
 * Xserver/.
 *
 * XXX This file arguably belongs in xfree86/loader/.
 */

#ifndef _XF86MODULE_H
#define _XF86MODULE_H

#include "misc.h"
#include "xf86Version.h"
#include "modularDefs.h"
#ifndef NULL
#define NULL ((void *)0)
#endif

typedef enum {
    LD_RESOLV_IFDONE		= 0,	/* only check if no more
					   delays pending */
    LD_RESOLV_NOW		= 1,	/* finish one delay step */
    LD_RESOLV_FORCE		= 2	/* force checking... */
} LoaderResolveOptions;

#define DEFAULT_LIST ((char *)-1)

/* This indicates a special module that doesn't have the usual entry point */
#define EXTERN_MODULE ((pointer)-1)

/* Built-in ABI classes.  These definitions must not be changed. */
#define ABI_CLASS_NONE		NULL
#define ABI_CLASS_ANSIC		"X.Org ANSI C Emulation"
#define ABI_CLASS_VIDEODRV	"X.Org Video Driver"
#define ABI_CLASS_XINPUT	"X.Org XInput driver"
#define ABI_CLASS_EXTENSION	"X.Org Server Extension"
#define ABI_CLASS_FONT		"X.Org Font Renderer"

#define ABI_MINOR_MASK		0x0000FFFF
#define ABI_MAJOR_MASK		0xFFFF0000
#define GET_ABI_MINOR(v)	((v) & ABI_MINOR_MASK)
#define GET_ABI_MAJOR(v)	(((v) & ABI_MAJOR_MASK) >> 16)
#define SET_ABI_VERSION(maj, min) \
		((((maj) << 16) & ABI_MAJOR_MASK) | ((min) & ABI_MINOR_MASK))

/*
 * ABI versions.  Each version has a major and minor revision.  Modules
 * using lower minor revisions must work with servers of a higher minor
 * revision.  There is no compatibility between different major revisions.
 * Whenever the ABI_ANSIC_VERSION is changed, the others must also be
 * changed.  The minor revision mask is 0x0000FFFF and the major revision
 * mask is 0xFFFF0000.
 */
#define ABI_ANSIC_VERSION	SET_ABI_VERSION(0, 2)
#define ABI_VIDEODRV_VERSION	SET_ABI_VERSION(0, 7)
#define ABI_XINPUT_VERSION	SET_ABI_VERSION(0, 4)
#define ABI_EXTENSION_VERSION	SET_ABI_VERSION(0, 2)
#define ABI_FONT_VERSION	SET_ABI_VERSION(0, 4)

#define MODINFOSTRING1	0xef23fdc5
#define MODINFOSTRING2	0x10dc023a

#ifndef MODULEVENDORSTRING
#ifndef __OS2ELF__
#define MODULEVENDORSTRING	"X.Org Foundation"
#else
#define MODULEVENDORSTRING	"X.Org Foundation - OS2"
#endif
#endif

/* Error return codes for errmaj.  New codes must only be added at the end. */
typedef enum {
    LDR_NOERROR = 0,
    LDR_NOMEM,		/* memory allocation failed */
    LDR_NOENT,		/* Module file does not exist */
    LDR_NOSUBENT,	/* pre-requsite file to be sub-loaded does not exist */
    LDR_NOSPACE,	/* internal module array full */
    LDR_NOMODOPEN,	/* module file could not be opened (check errmin) */
    LDR_UNKTYPE,	/* file is not a recognized module type */
    LDR_NOLOAD,		/* type specific loader failed */
    LDR_ONCEONLY,	/* Module should only be loaded once (not an error) */
    LDR_NOPORTOPEN,	/* could not open port (check errmin) */
    LDR_NOHARDWARE,	/* could not query/initialize the hardware device */
    LDR_MISMATCH,	/* the module didn't match the spec'd requirments */
    LDR_BADUSAGE,	/* LoadModule is called with bad arguments */
    LDR_INVALID,	/* The module doesn't have a valid ModuleData object */
    LDR_BADOS,		/* The module doesn't support the OS */
    LDR_MODSPECIFIC	/* A module-specific error in the SetupProc */
} LoaderErrorCode;

/*
 * Some common module classes.  The moduleclass can be used to identify
 * that modules loaded are of the correct type.  This is a finer
 * classification than the ABI classes even though the default set of
 * classes have the same names.  For example, not all modules that require
 * the video driver ABI are themselves video drivers.
 */
#define MOD_CLASS_NONE		NULL
#define MOD_CLASS_VIDEODRV	"X.Org Video Driver"
#define MOD_CLASS_XINPUT	"X.Org XInput Driver"
#define MOD_CLASS_FONT		"X.Org Font Renderer"
#define MOD_CLASS_EXTENSION	"X.Org Server Extension"

/* This structure is expected to be returned by the initfunc */
typedef struct {
    const char * modname;	/* name of module, e.g. "foo" */
    const char * vendor;	/* vendor specific string */
    CARD32	 _modinfo1_;	/* constant MODINFOSTRING1/2 to find */
    CARD32	 _modinfo2_;	/* infoarea with a binary editor or sign tool */
    CARD32	 xf86version;	/* contains XF86_VERSION_CURRENT */
    CARD8	 majorversion;	/* module-specific major version */
    CARD8	 minorversion;	/* module-specific minor version */
    CARD16	 patchlevel;	/* module-specific patch level */
    const char * abiclass;	/* ABI class that the module uses */
    CARD32	 abiversion;	/* ABI version */
    const char * moduleclass;	/* module class description */
    CARD32	 checksum[4];	/* contains a digital signature of the */
				/* version info structure */
} XF86ModuleVersionInfo;

/*
 * This structure can be used to callers of LoadModule and LoadSubModule to
 * specify version and/or ABI requirements.
 */
typedef struct {
    CARD8	 majorversion;	/* module-specific major version */
    CARD8	 minorversion;	/* moudle-specific minor version */
    CARD16	 patchlevel;	/* module-specific patch level */
    const char * abiclass;	/* ABI class that the module uses */
    CARD32	 abiversion;	/* ABI version */
    const char * moduleclass;	/* module class */
} XF86ModReqInfo;

/* values to indicate unspecified fields in XF86ModReqInfo. */
#define MAJOR_UNSPEC		0xFF
#define MINOR_UNSPEC		0xFF
#define PATCH_UNSPEC		0xFFFF
#define ABI_VERS_UNSPEC		0xFFFFFFFF

#define MODULE_VERSION_NUMERIC(maj, min, patch) \
	((((maj) & 0xFF) << 24) | (((min) & 0xFF) << 16) | (patch & 0xFFFF))
#define GET_MODULE_MAJOR_VERSION(vers)	(((vers) >> 24) & 0xFF)
#define GET_MODULE_MINOR_VERSION(vers)	(((vers) >> 16) & 0xFF)
#define GET_MODULE_PATCHLEVEL(vers)	((vers) & 0xFFFF)

#define INITARGS void

typedef void (*InitExtension)(INITARGS);

typedef struct {
    InitExtension	initFunc;
    const char *	name;
    Bool		*disablePtr;
    InitExtension	setupFunc;	
    const char **	initDependencies;
} ExtensionModule;

extern ExtensionModule *ExtensionModuleList;

/* Prototypes for Loader functions that are exported to modules */
#ifndef IN_LOADER
/* Prototypes with opaque pointers for use by modules */
pointer LoadSubModule(pointer, const char *, const char **,
		      const char **, pointer, const XF86ModReqInfo *,
		      int *, int *);
void UnloadSubModule(pointer);
void LoadFont(pointer);
void UnloadModule (pointer);
#endif
pointer LoaderSymbol(const char *);
char **LoaderListDirs(const char **, const char **);
void LoaderFreeDirList(char **);
void LoaderErrorMsg(const char *, const char *, int, int);
void LoadExtension(ExtensionModule *, Bool);
void LoaderRefSymLists(const char **, ...);
void LoaderRefSymbols(const char *, ...);
void LoaderReqSymLists(const char **, ...);
void LoaderReqSymbols(const char *, ...);
int LoaderCheckUnresolved(int);
void LoaderGetOS(const char **name, int *major, int *minor, int *teeny);

typedef pointer (*ModuleSetupProc)(pointer, pointer, int *, int *);
typedef void (*ModuleTearDownProc)(pointer);
#define MODULESETUPPROTO(func) pointer func(pointer, pointer, int*, int*)
#define MODULETEARDOWNPROTO(func) void func(pointer)

typedef struct {
    XF86ModuleVersionInfo *	vers;
    ModuleSetupProc		setup;
    ModuleTearDownProc		teardown;
} XF86ModuleData;

#endif /* _XF86STR_H */

--- NEW FILE: xf86Opt.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Opt.h,v 1.15 2003/10/08 14:30:38 dawes Exp $ */

/*
 * Copyright (c) 1998-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/* Option handling things that ModuleSetup procs can use */

#ifndef _XF86_OPT_H_
#define _XF86_OPT_H_

typedef struct {
    double freq;
    int units;
} OptFrequency;

typedef union {
    unsigned long       num;
    char *              str;
    double              realnum;
    Bool		bool;
    OptFrequency	freq;
} ValueUnion;
    
typedef enum {
    OPTV_NONE = 0,
    OPTV_INTEGER,
    OPTV_STRING,                /* a non-empty string */
    OPTV_ANYSTR,                /* Any string, including an empty one */
    OPTV_REAL,
    OPTV_BOOLEAN,
    OPTV_FREQ
} OptionValueType;

typedef enum {
    OPTUNITS_HZ = 1,
    OPTUNITS_KHZ,
    OPTUNITS_MHZ
} OptFreqUnits;

typedef struct {
    int                 token;
    const char*         name;
    OptionValueType     type;
    ValueUnion          value;
    Bool                found;
} OptionInfoRec, *OptionInfoPtr;

int xf86SetIntOption(pointer optlist, const char *name, int deflt);
double xf86SetRealOption(pointer optlist, const char *name, double deflt);
char *xf86SetStrOption(pointer optlist, const char *name, char *deflt);
int xf86SetBoolOption(pointer list, const char *name, int deflt );
int xf86CheckIntOption(pointer optlist, const char *name, int deflt);
double xf86CheckRealOption(pointer optlist, const char *name, double deflt);
char *xf86CheckStrOption(pointer optlist, const char *name, char *deflt);
int xf86CheckBoolOption(pointer list, const char *name, int deflt );
pointer xf86AddNewOption(pointer head, const char *name, const char *val );
pointer xf86NewOption(char *name, char *value );
pointer xf86NextOption(pointer list );
pointer xf86OptionListCreate(const char **options, int count, int used);
pointer xf86OptionListMerge(pointer head, pointer tail);
void xf86OptionListFree(pointer opt);
char *xf86OptionName(pointer opt);
char *xf86OptionValue(pointer opt);
void xf86OptionListReport(pointer parm);
pointer xf86FindOption(pointer options, const char *name);
char *xf86FindOptionValue(pointer options, const char *name);
void xf86MarkOptionUsed(pointer option);
void xf86MarkOptionUsedByName(pointer options, const char *name);
Bool xf86CheckIfOptionUsed(pointer option);
Bool xf86CheckIfOptionUsedByName(pointer options, const char *name);
void xf86ShowUnusedOptions(int scrnIndex, pointer options);
void xf86ProcessOptions(int scrnIndex, pointer options, OptionInfoPtr optinfo);
OptionInfoPtr xf86TokenToOptinfo(const OptionInfoRec *table, int token);
const char *xf86TokenToOptName(const OptionInfoRec *table, int token);
Bool xf86IsOptionSet(const OptionInfoRec *table, int token);
char *xf86GetOptValString(const OptionInfoRec *table, int token);
Bool xf86GetOptValInteger(const OptionInfoRec *table, int token, int *value);
Bool xf86GetOptValULong(const OptionInfoRec *table, int token, unsigned long *value);
Bool xf86GetOptValReal(const OptionInfoRec *table, int token, double *value);
Bool xf86GetOptValFreq(const OptionInfoRec *table, int token,
			OptFreqUnits expectedUnits, double *value);
Bool xf86GetOptValBool(const OptionInfoRec *table, int token, Bool *value);
Bool xf86ReturnOptValBool(const OptionInfoRec *table, int token, Bool def);
int xf86NameCmp(const char *s1, const char *s2);
char *xf86NormalizeName(const char *s);
pointer xf86ReplaceIntOption(pointer optlist,  const char *name, const int val);
pointer xf86ReplaceRealOption(pointer optlist,  const char *name, const double val);
pointer xf86ReplaceBoolOption(pointer optlist, const char *name, const Bool val);
pointer xf86ReplaceStrOption(pointer optlist,  const char *name, const char* val);        
#endif

--- NEW FILE: xf86Option.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Option.c,v 1.29 2003/10/18 12:34:19 dawes Exp $ */
/*
 * Copyright (c) 1998-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 * Author: David Dawes <dawes at xfree86.org>
 *
 * This file includes public option handling functions.
 */

#include <stdlib.h>
#include <ctype.h>
#include <X11/X.h>
#include "os.h"
#include "xf86.h"
#include "xf86Xinput.h"
#include "xf86Optrec.h"

static Bool ParseOptionValue(int scrnIndex, pointer options, OptionInfoPtr p,
			     Bool markUsed);

/*
 * xf86CollectOptions collects the options from each of the config file
 * sections used by the screen and puts the combined list in pScrn->options.
 * This function requires that the following have been initialised:
 *
 *	pScrn->confScreen
 *	pScrn->Entities[i]->device
 *	pScrn->display
 *	pScrn->monitor
 *
 * The extraOpts parameter may optionally contain a list of additional options
 * to include.
 *
 * The order of precedence for options is:
 *
 *   extraOpts, display, confScreen, monitor, device
 */

void
xf86CollectOptions(ScrnInfoPtr pScrn, pointer extraOpts)
{
    XF86OptionPtr tmp;
    XF86OptionPtr extras = (XF86OptionPtr)extraOpts;
    GDevPtr device;
    
    int i;

    pScrn->options = NULL;

    for (i=pScrn->numEntities - 1; i >= 0; i--) {
	device = xf86GetDevFromEntity(pScrn->entityList[i],
					pScrn->entityInstanceList[i]);
	if (device && device->options) {
	    tmp = xf86optionListDup(device->options);
	    if (pScrn->options)
		xf86optionListMerge(pScrn->options,tmp);
	    else
		pScrn->options = tmp;
	}
    }
    if (pScrn->monitor->options) {
	tmp = xf86optionListDup(pScrn->monitor->options);
	if (pScrn->options)
	    pScrn->options = xf86optionListMerge(pScrn->options, tmp);
	else
	    pScrn->options = tmp;
    }
    if (pScrn->confScreen->options) {
	tmp = xf86optionListDup(pScrn->confScreen->options);
	if (pScrn->options)
	    pScrn->options = xf86optionListMerge(pScrn->options, tmp);
	else
	    pScrn->options = tmp;
    }
    if (pScrn->display->options) {
	tmp = xf86optionListDup(pScrn->display->options);
	if (pScrn->options)
	    pScrn->options = xf86optionListMerge(pScrn->options, tmp);
	else
	    pScrn->options = tmp;
    }
    if (extras) {
	tmp = xf86optionListDup(extras);
	if (pScrn->options)
	    pScrn->options = xf86optionListMerge(pScrn->options, tmp);
	else
	    pScrn->options = tmp;
    }
}

/*
 * xf86CollectInputOptions collects the options for an InputDevice.
 * This function requires that the following has been initialised:
 *
 *	pInfo->conf_idev
 *
 * The extraOpts parameter may optionally contain a list of additional options
 * to include.
 *
 * The order of precedence for options is:
 *
 *   extraOpts, pInfo->conf_idev->extraOptions,
 *   pInfo->conf_idev->commonOptions, defaultOpts
 */

void
xf86CollectInputOptions(InputInfoPtr pInfo, const char **defaultOpts,
			pointer extraOpts)
{
    XF86OptionPtr tmp;
    XF86OptionPtr extras = (XF86OptionPtr)extraOpts;

    pInfo->options = NULL;
    if (defaultOpts) {
	pInfo->options = xf86OptionListCreate(defaultOpts, -1, 0);
    }
    if (pInfo->conf_idev->commonOptions) {
	tmp = xf86optionListDup(pInfo->conf_idev->commonOptions);
	if (pInfo->options)
	    pInfo->options = xf86optionListMerge(pInfo->options, tmp);
	else
	    pInfo->options = tmp;
    }
    if (pInfo->conf_idev->extraOptions) {
	tmp = xf86optionListDup(pInfo->conf_idev->extraOptions);
	if (pInfo->options)
	    pInfo->options = xf86optionListMerge(pInfo->options, tmp);
	else
	    pInfo->options = tmp;
    }
    if (extras) {
	tmp = xf86optionListDup(extras);
	if (pInfo->options)
	    pInfo->options = xf86optionListMerge(pInfo->options, tmp);
	else
	    pInfo->options = tmp;
    }
}

/* Created for new XInput stuff -- essentially extensions to the parser	*/

static int
LookupIntOption(pointer optlist, const char *name, int deflt, Bool markUsed)
{
    OptionInfoRec o;

    o.name = name;
    o.type = OPTV_INTEGER;
    if (ParseOptionValue(-1, optlist, &o, markUsed))
	deflt = o.value.num;
    return deflt;
}


static double
LookupRealOption(pointer optlist, const char *name, double deflt,
		 Bool markUsed)
{
    OptionInfoRec o;

    o.name = name;
    o.type = OPTV_REAL;
    if (ParseOptionValue(-1, optlist, &o, markUsed))
	deflt = o.value.realnum;
    return deflt;
}


static char *
LookupStrOption(pointer optlist, const char *name, char *deflt, Bool markUsed)
{
    OptionInfoRec o;

    o.name = name;
    o.type = OPTV_STRING;
    if (ParseOptionValue(-1, optlist, &o, markUsed))
        deflt = o.value.str;
    if (deflt)
	return xstrdup(deflt);
    else
	return NULL;
}


static int
LookupBoolOption(pointer optlist, const char *name, int deflt, Bool markUsed)
{
    OptionInfoRec o;

    o.name = name;
    o.type = OPTV_BOOLEAN;
    if (ParseOptionValue(-1, optlist, &o, markUsed))
	deflt = o.value.bool;
    return deflt;
}

/* These xf86Set* functions are intended for use by non-screen specific code */

int
xf86SetIntOption(pointer optlist, const char *name, int deflt)
{
    return LookupIntOption(optlist, name, deflt, TRUE);
}


double
xf86SetRealOption(pointer optlist, const char *name, double deflt)
{
    return LookupRealOption(optlist, name, deflt, TRUE);
}


char *
xf86SetStrOption(pointer optlist, const char *name, char *deflt)
{
    return LookupStrOption(optlist, name, deflt, TRUE);
}


int
xf86SetBoolOption(pointer optlist, const char *name, int deflt)
{
    return LookupBoolOption(optlist, name, deflt, TRUE);
}

/*
 * These are like the Set*Option functions, but they don't mark the options
 * as used.
 */
int
xf86CheckIntOption(pointer optlist, const char *name, int deflt)
{
    return LookupIntOption(optlist, name, deflt, FALSE);
}


double
xf86CheckRealOption(pointer optlist, const char *name, double deflt)
{
    return LookupRealOption(optlist, name, deflt, FALSE);
}


char *
xf86CheckStrOption(pointer optlist, const char *name, char *deflt)
{
    return LookupStrOption(optlist, name, deflt, FALSE);
}


int
xf86CheckBoolOption(pointer optlist, const char *name, int deflt)
{
    return LookupBoolOption(optlist, name, deflt, FALSE);
}

/*
 * addNewOption() has the required property of replacing the option value
 * if the option is already present.
 */
pointer
xf86ReplaceIntOption(pointer optlist, const char *name, const int val)
{
    char *tmp = xnfalloc(16);
    sprintf(tmp,"%i",val);
    return xf86AddNewOption(optlist,name,tmp);
}

pointer
xf86ReplaceRealOption(pointer optlist, const char *name, const double val)
{
    char *tmp = xnfalloc(32);
    snprintf(tmp,32,"%f",val);
    return xf86AddNewOption(optlist,name,tmp);
}

pointer
xf86ReplaceBoolOption(pointer optlist, const char *name, const Bool val)
{
    return xf86AddNewOption(optlist,name,val?"True":"False");
}

pointer
xf86ReplaceStrOption(pointer optlist, const char *name, const char* val)
{
      return xf86AddNewOption(optlist,name,val);
}

pointer
xf86AddNewOption(pointer head, const char *name, const char *val)
{
    /* XXX These should actually be allocated in the parser library. */
    char *tmp = strdup(val);
    char *tmp_name = strdup(name);

    return xf86addNewOption(head, tmp_name, tmp);
}


pointer
xf86NewOption(char *name, char *value)
{
    return xf86newOption(name, value);
}


pointer
xf86NextOption(pointer list)
{
    return xf86nextOption(list);
}

pointer
xf86OptionListCreate(const char **options, int count, int used)
{
	return xf86optionListCreate(options, count, used);
}

pointer
xf86OptionListMerge(pointer head, pointer tail)
{
	return xf86optionListMerge(head, tail);
}

void
xf86OptionListFree(pointer opt)
{
	xf86optionListFree(opt);
}

char *
xf86OptionName(pointer opt)
{
	return xf86optionName(opt);
}

char *
xf86OptionValue(pointer opt)
{
	return xf86optionValue(opt);
}

void
xf86OptionListReport(pointer parm)
{
    XF86OptionPtr opts = parm;

    while(opts) {
	if (xf86optionValue(opts))
	    xf86ErrorFVerb(5, "\tOption \"%s\" \"%s\"\n",
			    xf86optionName(opts), xf86optionValue(opts));
	else
	    xf86ErrorFVerb( 5, "\tOption \"%s\"\n", xf86optionName(opts));
	opts = xf86nextOption(opts);
    }
}

/* End of XInput-caused section	*/

pointer
xf86FindOption(pointer options, const char *name)
{
    return xf86findOption(options, name);
}


char *
xf86FindOptionValue(pointer options, const char *name)
{
    return xf86findOptionValue(options, name);
}


void
xf86MarkOptionUsed(pointer option)
{
    if (option != NULL)
	((XF86OptionPtr)option)->opt_used = TRUE;
}


void
xf86MarkOptionUsedByName(pointer options, const char *name)
{
    XF86OptionPtr opt;

    opt = xf86findOption(options, name);
    if (opt != NULL)
	opt->opt_used = TRUE;
}

Bool
xf86CheckIfOptionUsed(pointer option)
{
    if (option != NULL)
	return ((XF86OptionPtr)option)->opt_used;
    else
	return FALSE;
}

Bool
xf86CheckIfOptionUsedByName(pointer options, const char *name)
{
    XF86OptionPtr opt;

    opt = xf86findOption(options, name);
    if (opt != NULL)
	return opt->opt_used;
    else
	return FALSE;
}

void
xf86ShowUnusedOptions(int scrnIndex, pointer options)
{
    XF86OptionPtr opt = options;

    while (opt) {
	if (opt->opt_name && !opt->opt_used) {
	    xf86DrvMsg(scrnIndex, X_WARNING, "Option \"%s\" is not used\n",
			opt->opt_name);
	}
	opt = opt->list.next;
    }
}


static Bool
GetBoolValue(OptionInfoPtr p, const char *s)
{
    if (*s == '\0') {
	p->value.bool = TRUE;
    } else {
	if (xf86NameCmp(s, "1") == 0)
	    p->value.bool = TRUE;
	else if (xf86NameCmp(s, "on") == 0)
	    p->value.bool = TRUE;
	else if (xf86NameCmp(s, "true") == 0)
	    p->value.bool = TRUE;
	else if (xf86NameCmp(s, "yes") == 0)
	    p->value.bool = TRUE;
	else if (xf86NameCmp(s, "0") == 0)
	    p->value.bool = FALSE;
	else if (xf86NameCmp(s, "off") == 0)
	    p->value.bool = FALSE;
	else if (xf86NameCmp(s, "false") == 0)
	    p->value.bool = FALSE;
	else if (xf86NameCmp(s, "no") == 0)
	    p->value.bool = FALSE;
	else
	    return FALSE;
    }
    return TRUE;
}

static Bool
ParseOptionValue(int scrnIndex, pointer options, OptionInfoPtr p,
		 Bool markUsed)
{
    char *s, *end;
    Bool wasUsed = FALSE;

    if ((s = xf86findOptionValue(options, p->name)) != NULL) {
	if (markUsed) {
	    wasUsed = xf86CheckIfOptionUsedByName(options, p->name);
	    xf86MarkOptionUsedByName(options, p->name);
	}
	switch (p->type) {
	case OPTV_INTEGER:
	    if (*s == '\0') {
		xf86DrvMsg(scrnIndex, X_WARNING,
			   "Option \"%s\" requires an integer value\n",
			   p->name);
		p->found = FALSE;
	    } else {
		p->value.num = strtoul(s, &end, 0);
		if (*end == '\0') {
		    p->found = TRUE;
		} else {
		    xf86DrvMsg(scrnIndex, X_WARNING,
			       "Option \"%s\" requires an integer value\n",
			        p->name);
		    p->found = FALSE;
		}
	    }
	    break;
	case OPTV_STRING:
	    if (*s == '\0') {
		xf86DrvMsg(scrnIndex, X_WARNING,
			   "Option \"%s\" requires an string value\n",
			   p->name);
		p->found = FALSE;
	    } else {
		p->value.str = s;
		p->found = TRUE;
	    }
	    break;
	case OPTV_ANYSTR:
	    p->value.str = s;
	    p->found = TRUE;
	    break;
	case OPTV_REAL:	
	    if (*s == '\0') {
		xf86DrvMsg(scrnIndex, X_WARNING,
			   "Option \"%s\" requires a floating point value\n",
			   p->name);
		p->found = FALSE;
	    } else {
		p->value.realnum = strtod(s, &end);
		if (*end == '\0') {
		    p->found = TRUE;
		} else {
		    xf86DrvMsg(scrnIndex, X_WARNING,
			    "Option \"%s\" requires a floating point value\n",
			    p->name);
		    p->found = FALSE;
		}
	    }
	    break;
	case OPTV_BOOLEAN:
	    if (GetBoolValue(p, s)) {
		p->found = TRUE;
	    } else {
		xf86DrvMsg(scrnIndex, X_WARNING,
			   "Option \"%s\" requires a boolean value\n", p->name);
		p->found = FALSE;
	    }
	    break;
	case OPTV_FREQ:	
	    if (*s == '\0') {
		xf86DrvMsg(scrnIndex, X_WARNING,
			   "Option \"%s\" requires a frequency value\n",
			   p->name);
		p->found = FALSE;
	    } else {
		double freq = strtod(s, &end);
		int    units = 0;

		if (end != s) {
		    p->found = TRUE;
		    if (!xf86NameCmp(end, "Hz"))
			units = 1;
		    else if (!xf86NameCmp(end, "kHz") ||
			     !xf86NameCmp(end, "k"))
			units = 1000;
		    else if (!xf86NameCmp(end, "MHz") ||
			     !xf86NameCmp(end, "M"))
			units = 1000000;
		    else {
			xf86DrvMsg(scrnIndex, X_WARNING,
			    "Option \"%s\" requires a frequency value\n",
			    p->name);
			p->found = FALSE;
		    }
		    if (p->found)
			freq *= (double)units;
		} else {
		    xf86DrvMsg(scrnIndex, X_WARNING,
			    "Option \"%s\" requires a frequency value\n",
			    p->name);
		    p->found = FALSE;
		}
		if (p->found) {
		    p->value.freq.freq = freq;
		    p->value.freq.units = units;
		}
	    }
	    break;
	case OPTV_NONE:
	    /* Should never get here */
	    p->found = FALSE;
	    break;
	}
	if (p->found && markUsed) {
	    int verb = 2;
	    if (wasUsed)
		verb = 4;
	    xf86DrvMsgVerb(scrnIndex, X_CONFIG, verb, "Option \"%s\"", p->name);
	    if (!(p->type == OPTV_BOOLEAN && *s == 0)) {
		xf86ErrorFVerb(verb, " \"%s\"", s);
	    }
	    xf86ErrorFVerb(verb, "\n");
	}
    } else if (p->type == OPTV_BOOLEAN) {
	/* Look for matches with options with or without a "No" prefix. */
	char *n, *newn;
	OptionInfoRec opt;

	n = xf86NormalizeName(p->name);
	if (!n) {
	    p->found = FALSE;
	    return FALSE;
	}
	if (strncmp(n, "no", 2) == 0) {
	    newn = n + 2;
	} else {
	    xfree(n);
	    n = xalloc(strlen(p->name) + 2 + 1);
	    if (!n) {
		p->found = FALSE;
		return FALSE;
	    }
	    strcpy(n, "No");
	    strcat(n, p->name);
	    newn = n;
	}
	if ((s = xf86findOptionValue(options, newn)) != NULL) {
	    if (markUsed)
		xf86MarkOptionUsedByName(options, newn);
	    if (GetBoolValue(&opt, s)) {
		p->value.bool = !opt.value.bool;
		p->found = TRUE;
	    } else {
		xf86DrvMsg(scrnIndex, X_WARNING,
			   "Option \"%s\" requires a boolean value\n", newn);
		p->found = FALSE;
	    }
	} else {
	    p->found = FALSE;
	}
	if (p->found && markUsed) {
	    xf86DrvMsgVerb(scrnIndex, X_CONFIG, 2, "Option \"%s\"", newn);
	    if (*s != 0) {
		xf86ErrorFVerb(2, " \"%s\"", s);
	    }
	    xf86ErrorFVerb(2, "\n");
	}
	xfree(n);
    } else {
	p->found = FALSE;
    }
    return p->found;
}


void
xf86ProcessOptions(int scrnIndex, pointer options, OptionInfoPtr optinfo)
{
    OptionInfoPtr p;

    for (p = optinfo; p->name != NULL; p++) {
	ParseOptionValue(scrnIndex, options, p, TRUE);
    }
}


OptionInfoPtr
xf86TokenToOptinfo(const OptionInfoRec *table, int token)
{
    const OptionInfoRec *p, *match = NULL, *set = NULL;

    if (!table) {
	ErrorF("xf86TokenToOptinfo: table is NULL\n");
	return NULL;
    }

    for (p = table; p->token >= 0; p++) {
	if (p->token == token) {
	    match = p;
	    if (p->found)
		set = p;
	}
    }

    if (set)
	return (OptionInfoPtr)set;
    else if (match)
	return (OptionInfoPtr)match;
    else
	return NULL;
}


const char *
xf86TokenToOptName(const OptionInfoRec *table, int token)
{
    const OptionInfoRec *p;

    p = xf86TokenToOptinfo(table, token);
    return p->name;
}


Bool
xf86IsOptionSet(const OptionInfoRec *table, int token)
{
    OptionInfoPtr p;

    p = xf86TokenToOptinfo(table, token);
    return (p && p->found);
}


char *
xf86GetOptValString(const OptionInfoRec *table, int token)
{
    OptionInfoPtr p;

    p = xf86TokenToOptinfo(table, token);
    if (p && p->found)
	return p->value.str;
    else
	return NULL;
}


Bool
xf86GetOptValInteger(const OptionInfoRec *table, int token, int *value)
{
    OptionInfoPtr p;

    p = xf86TokenToOptinfo(table, token);
    if (p && p->found) {
	*value = p->value.num;
	return TRUE;
    } else
	return FALSE;
}


Bool
xf86GetOptValULong(const OptionInfoRec *table, int token, unsigned long *value)
{
    OptionInfoPtr p;

    p = xf86TokenToOptinfo(table, token);
    if (p && p->found) {
	*value = p->value.num;
	return TRUE;
    } else
	return FALSE;
}


Bool
xf86GetOptValReal(const OptionInfoRec *table, int token, double *value)
{
    OptionInfoPtr p;

    p = xf86TokenToOptinfo(table, token);
    if (p && p->found) {
	*value = p->value.realnum;
	return TRUE;
    } else
	return FALSE;
}


Bool
xf86GetOptValFreq(const OptionInfoRec *table, int token,
		  OptFreqUnits expectedUnits, double *value)
{
    OptionInfoPtr p;

    p = xf86TokenToOptinfo(table, token);
    if (p && p->found) {
	if (p->value.freq.units > 0) {
	    /* Units give, so the scaling is known. */
	    switch (expectedUnits) {
	    case OPTUNITS_HZ:
		*value = p->value.freq.freq;
		break;
	    case OPTUNITS_KHZ:
		*value = p->value.freq.freq / 1000.0;
		break;
	    case OPTUNITS_MHZ:
		*value = p->value.freq.freq / 1000000.0;
		break;
	    }
	} else {
	    /* No units given, so try to guess the scaling. */
	    switch (expectedUnits) {
	    case OPTUNITS_HZ:
		*value = p->value.freq.freq;
		break;
	    case OPTUNITS_KHZ:
		if (p->value.freq.freq > 1000.0)
		    *value = p->value.freq.freq / 1000.0;
		else
		    *value = p->value.freq.freq;
		break;
	    case OPTUNITS_MHZ:
		if (p->value.freq.freq > 1000000.0)
		    *value = p->value.freq.freq / 1000000.0;
		else if (p->value.freq.freq > 1000.0)
		    *value = p->value.freq.freq / 1000.0;
		else
		    *value = p->value.freq.freq;
	    }
	}
	return TRUE;
    } else
	return FALSE;
}


Bool
xf86GetOptValBool(const OptionInfoRec *table, int token, Bool *value)
{
    OptionInfoPtr p;

    p = xf86TokenToOptinfo(table, token);
    if (p && p->found) {
	*value = p->value.bool;
	return TRUE;
    } else
	return FALSE;
}


Bool
xf86ReturnOptValBool(const OptionInfoRec *table, int token, Bool def)
{
    OptionInfoPtr p;

    p = xf86TokenToOptinfo(table, token);
    if (p && p->found) {
	return p->value.bool;
    } else
	return def;
}


int
xf86NameCmp(const char *s1, const char *s2)
{
    return xf86nameCompare(s1, s2);
}

char *
xf86NormalizeName(const char *s)
{
    char *ret, *q;
    const char *p;

    if (s == NULL)
	return NULL;

    ret = xalloc(strlen(s) + 1);
    for (p = s, q = ret; *p != 0; p++) {
	switch (*p) {
	case '_':
	case ' ':
	case '\t':
	    continue;
	default:
	    if (isupper(*p))
		*q++ = tolower(*p);
	    else
		*q++ = *p;
	}
    }
    *q = '\0';
    return ret;
}

--- NEW FILE: xf86PM.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86PM.c,v 3.9 2003/08/24 17:36:54 dawes Exp $ */
/*
 * Copyright (c) 2000-2002 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

#include <X11/X.h>
#include "xf86.h"
#include "xf86Priv.h"
#include "xf86Xinput.h"

int (*xf86PMGetEventFromOs)(int fd,pmEvent *events,int num) = NULL;
pmWait (*xf86PMConfirmEventToOs)(int fd,pmEvent event) = NULL;

static Bool suspended = FALSE;

static char *
eventName(pmEvent event)
{
    switch(event) {
    case XF86_APM_SYS_STANDBY: return ("System Standby Request");
    case XF86_APM_SYS_SUSPEND: return ("System Suspend Request");
    case XF86_APM_CRITICAL_SUSPEND: return ("Critical Suspend");
    case XF86_APM_USER_STANDBY: return ("User System Standby Request");
    case XF86_APM_USER_SUSPEND: return ("User System Suspend Request");
    case XF86_APM_STANDBY_RESUME: return ("System Standby Resume");
    case XF86_APM_NORMAL_RESUME: return ("Normal Resume System");
    case XF86_APM_CRITICAL_RESUME: return ("Critical Resume System");
    case XF86_APM_LOW_BATTERY: return ("Battery Low");
    case XF86_APM_POWER_STATUS_CHANGE: return ("Power Status Change");
    case XF86_APM_UPDATE_TIME: return ("Update Time");
    case XF86_APM_CAPABILITY_CHANGED: return ("Capability Changed");
    case XF86_APM_STANDBY_FAILED: return ("Standby Request Failed");
    case XF86_APM_SUSPEND_FAILED: return ("Suspend Request Failed");
    default: return ("Unknown Event");
    }
}

static void
suspend (pmEvent event, Bool undo)
{
    int i;
    InputInfoPtr pInfo;

   xf86inSuspend = TRUE;
    
    for (i = 0; i < xf86NumScreens; i++) {
        xf86EnableAccess(xf86Screens[i]);
	if (xf86Screens[i]->EnableDisableFBAccess)
	    (*xf86Screens[i]->EnableDisableFBAccess) (i, FALSE);
    }
#if !defined(__EMX__)
    pInfo = xf86InputDevs;
    while (pInfo) {
	DisableDevice(pInfo->dev);
	pInfo = pInfo->next;
    }
#endif
    xf86EnterServerState(SETUP);
    for (i = 0; i < xf86NumScreens; i++) {
        xf86EnableAccess(xf86Screens[i]);
	if (xf86Screens[i]->PMEvent)
	    xf86Screens[i]->PMEvent(i,event,undo);
	else {
	    xf86Screens[i]->LeaveVT(i, 0);
	    xf86Screens[i]->vtSema = FALSE;
	}
    }
    xf86AccessLeave();      
    xf86AccessLeaveState(); 
}

static void
resume(pmEvent event, Bool undo)
{
    int i;
    InputInfoPtr pInfo;

    xf86AccessEnter();
    xf86EnterServerState(SETUP);
    for (i = 0; i < xf86NumScreens; i++) {
        xf86EnableAccess(xf86Screens[i]);
	if (xf86Screens[i]->PMEvent)
	    xf86Screens[i]->PMEvent(i,event,undo);
	else {
	    xf86Screens[i]->vtSema = TRUE;
	    xf86Screens[i]->EnterVT(i, 0);
	}
    }
    xf86EnterServerState(OPERATING);
    for (i = 0; i < xf86NumScreens; i++) {
        xf86EnableAccess(xf86Screens[i]);
	if (xf86Screens[i]->EnableDisableFBAccess)
	    (*xf86Screens[i]->EnableDisableFBAccess) (i, TRUE);
    }
    SaveScreens(SCREEN_SAVER_FORCER, ScreenSaverReset);
#if !defined(__EMX__)
    pInfo = xf86InputDevs;
    while (pInfo) {
	EnableDevice(pInfo->dev);
	pInfo = pInfo->next;
    }
#endif
    xf86inSuspend = FALSE;
}

static void
DoApmEvent(pmEvent event, Bool undo)
{
    /* 
     * we leave that as a global function for now. I don't know if 
     * this might cause problems in the future. It is a global server 
     * variable therefore it needs to be in a server info structure
     */
    int i;
    
    switch(event) {
    case XF86_APM_SYS_STANDBY:
    case XF86_APM_SYS_SUSPEND:
    case XF86_APM_CRITICAL_SUSPEND: /*do we want to delay a critical suspend?*/
    case XF86_APM_USER_STANDBY:
    case XF86_APM_USER_SUSPEND:
	/* should we do this ? */
	if (!undo && !suspended) {
	    suspend(event,undo);
	    suspended = TRUE;
	} else if (undo && suspended) {
	    resume(event,undo);
	    suspended = FALSE;
	}
	break;
    case XF86_APM_STANDBY_RESUME:
    case XF86_APM_NORMAL_RESUME:
    case XF86_APM_CRITICAL_RESUME:
	if (suspended) {
	    resume(event,undo);
	    suspended = FALSE;
	}
	break;
    default:
	xf86EnterServerState(SETUP);
	for (i = 0; i < xf86NumScreens; i++) {
	    xf86EnableAccess(xf86Screens[i]);
	    if (xf86Screens[i]->PMEvent)
		xf86Screens[i]->PMEvent(i,event,undo);
	}
	xf86EnterServerState(OPERATING);
	break;
    }
}

#define MAX_NO_EVENTS 8

void
xf86HandlePMEvents(int fd, pointer data)
{
    pmEvent events[MAX_NO_EVENTS];
    int i,n;
    Bool wait = FALSE;

    if (!xf86PMGetEventFromOs)
	return;

    if ((n = xf86PMGetEventFromOs(fd,events,MAX_NO_EVENTS))) {
	do {
	    for (i = 0; i < n; i++) {
		xf86MsgVerb(X_INFO,3,"PM Event received: %s\n",
			    eventName(events[i]));
		DoApmEvent(events[i],FALSE);
		switch (xf86PMConfirmEventToOs(fd,events[i])) {
		case PM_WAIT:
		    wait = TRUE;
		    break;
		case PM_CONTINUE:
		    wait = FALSE;
		    break;
		case PM_FAILED:
		    DoApmEvent(events[i],TRUE);
		    wait = FALSE;
		    break;
		default:
		    break;
		}
	    }
	    if (wait)
		n = xf86PMGetEventFromOs(fd,events,MAX_NO_EVENTS);
	    else
		break;
	} while (1);
    }
}

--- NEW FILE: xf86PciInfo.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86PciInfo.h,v 1.156 2003/10/30 15:26:33 tsi Exp $ */

/*
 * Copyright (c) 1995-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 * This file contains macros for the PCI Vendor and Device IDs for video
 * cards plus a few other things that are needed in drivers or elsewhere.
 * This information is used in several ways:
 *   1. It is used by drivers and/or other code.
 *   2. It is used by the pciid2c.pl script to determine what vendor data to
 *      include in the pcidata module that the X server loads.
 *   3. A side-effect of 2. affects how config-generation works for
 *      otherwise "unknown" cards.
 *
 * Don't add entries here for vendors that don't make video cards,
 * or for non-video devices unless they're needed by a driver or elsewhere.
 * A comprehensive set of PCI vendor, device and subsystem data is
 * auto-generated from the ../etc/pci.ids file using the pciids2c.pl script,
 * and is used in both the scanpci module and the scanpci utility.  Don't
 * modify the pci.ids file.  If new/corrected entries are required, add them
 * to ../etc/extrapci.ids.
 */


#ifndef _XF86_PCIINFO_H
#define _XF86_PCIINFO_H

/* PCI Pseudo Vendor */
#define PCI_VENDOR_GENERIC		0x00FF

#define PCI_VENDOR_REAL3D		0x003D
#define PCI_VENDOR_COMPAQ		0x0E11
#define PCI_VENDOR_ATI			0x1002
#define PCI_VENDOR_AVANCE		0x1005
#define PCI_VENDOR_TSENG		0x100C
#define PCI_VENDOR_NS			0x100B
#define PCI_VENDOR_WEITEK		0x100E
#define PCI_VENDOR_VIDEOLOGIC		0x1010
#define PCI_VENDOR_DIGITAL		0x1011
#define PCI_VENDOR_CIRRUS		0x1013
#define PCI_VENDOR_AMD			0x1022
#define PCI_VENDOR_TRIDENT		0x1023
#define PCI_VENDOR_ALI			0x1025
#define PCI_VENDOR_DELL			0x1028
#define PCI_VENDOR_MATROX		0x102B
#define PCI_VENDOR_CHIPSTECH		0x102C
#define PCI_VENDOR_MIRO			0x1031
#define PCI_VENDOR_NEC			0x1033
#define PCI_VENDOR_SIS			0x1039
#define PCI_VENDOR_HP			0x103C
#define PCI_VENDOR_SGS			0x104A
#define PCI_VENDOR_TI			0x104C
#define PCI_VENDOR_SONY			0x104D
#define PCI_VENDOR_OAK			0x104E
#define PCI_VENDOR_MOTOROLA		0x1057
#define PCI_VENDOR_NUMNINE		0x105D
#define PCI_VENDOR_CYRIX		0x1078
#define PCI_VENDOR_SUN			0x108E
#define PCI_VENDOR_DIAMOND		0x1092
#define PCI_VENDOR_BROOKTREE		0x109E
#define PCI_VENDOR_NEOMAGIC		0x10C8
#define PCI_VENDOR_NVIDIA		0x10DE
#define PCI_VENDOR_IMS			0x10E0
#define PCI_VENDOR_INTEGRAPHICS 	0x10EA
#define PCI_VENDOR_ALLIANCE		0x1142
#define PCI_VENDOR_RENDITION		0x1163
#define PCI_VENDOR_3DFX			0x121A
#define PCI_VENDOR_SMI			0x126F
#define PCI_VENDOR_TRITECH		0x1292
#define PCI_VENDOR_NVIDIA_SGS		0x12D2
#define PCI_VENDOR_VMWARE		0x15AD
#define PCI_VENDOR_3DLABS		0x3D3D
#define PCI_VENDOR_AVANCE_2		0x4005
#define PCI_VENDOR_HERCULES		0x4843
#define PCI_VENDOR_S3			0x5333
#define PCI_VENDOR_INTEL		0x8086
#define PCI_VENDOR_ARK			0xEDD8


/* Generic */
#define PCI_CHIP_VGA			0x0000
#define PCI_CHIP_8514			0x0001

/* Real 3D */
#define PCI_CHIP_I740_PCI		0x00D1

/* Compaq */
#define PCI_CHIP_QV1280			0x3033

/* ATI */
#define PCI_CHIP_RS100_4136		0x4136
#define PCI_CHIP_RS200_4137		0x4137
#define PCI_CHIP_R300_AD		0x4144
#define PCI_CHIP_R300_AE		0x4145
#define PCI_CHIP_R300_AF		0x4146
#define PCI_CHIP_R300_AG		0x4147
#define PCI_CHIP_R350_AH                0x4148
#define PCI_CHIP_R350_AI                0x4149
#define PCI_CHIP_R350_AJ                0x414A
#define PCI_CHIP_R350_AK                0x414B
#define PCI_CHIP_RV350_AP               0x4150
#define PCI_CHIP_RV350_AQ               0x4151
#define PCI_CHIP_RV360_AR               0x4152
#define PCI_CHIP_RV350_AS               0x4153
#define PCI_CHIP_RV350_AT               0x4154
#define PCI_CHIP_RV350_AV               0x4156
#define PCI_CHIP_MACH32			0x4158
#define PCI_CHIP_RS250_4237		0x4237
#define PCI_CHIP_R200_BB		0x4242
#define PCI_CHIP_R200_BC		0x4243
#define PCI_CHIP_RS100_4336		0x4336
#define PCI_CHIP_RS200_4337		0x4337
#define PCI_CHIP_MACH64CT		0x4354
#define PCI_CHIP_MACH64CX		0x4358
#define PCI_CHIP_RS250_4437		0x4437
#define PCI_CHIP_MACH64ET		0x4554
#define PCI_CHIP_MACH64GB		0x4742
#define PCI_CHIP_MACH64GD		0x4744
#define PCI_CHIP_MACH64GI		0x4749
#define PCI_CHIP_MACH64GL		0x474C
#define PCI_CHIP_MACH64GM		0x474D
#define PCI_CHIP_MACH64GN		0x474E
#define PCI_CHIP_MACH64GO		0x474F
#define PCI_CHIP_MACH64GP		0x4750
#define PCI_CHIP_MACH64GQ		0x4751
#define PCI_CHIP_MACH64GR		0x4752
#define PCI_CHIP_MACH64GS		0x4753
#define PCI_CHIP_MACH64GT		0x4754
#define PCI_CHIP_MACH64GU		0x4755
#define PCI_CHIP_MACH64GV		0x4756
#define PCI_CHIP_MACH64GW		0x4757
#define PCI_CHIP_MACH64GX		0x4758
#define PCI_CHIP_MACH64GY		0x4759
#define PCI_CHIP_MACH64GZ		0x475A
#define PCI_CHIP_RV250_Id		0x4964
#define PCI_CHIP_RV250_Ie		0x4965
#define PCI_CHIP_RV250_If		0x4966
#define PCI_CHIP_RV250_Ig		0x4967
#define PCI_CHIP_MACH64LB		0x4C42
#define PCI_CHIP_MACH64LD		0x4C44
#define PCI_CHIP_RAGE128LE		0x4C45
#define PCI_CHIP_RAGE128LF		0x4C46
#define PCI_CHIP_MACH64LG		0x4C47
#define PCI_CHIP_MACH64LI		0x4C49
#define PCI_CHIP_MACH64LM		0x4C4D
#define PCI_CHIP_MACH64LN		0x4C4E
#define PCI_CHIP_MACH64LP		0x4C50
#define PCI_CHIP_MACH64LQ		0x4C51
#define PCI_CHIP_MACH64LR		0x4C52
#define PCI_CHIP_MACH64LS		0x4C53
#define PCI_CHIP_RADEON_LW		0x4C57
#define PCI_CHIP_RADEON_LX		0x4C58
#define PCI_CHIP_RADEON_LY		0x4C59
#define PCI_CHIP_RADEON_LZ		0x4C5A
#define PCI_CHIP_RV250_Ld		0x4C64
#define PCI_CHIP_RV250_Le		0x4C65
#define PCI_CHIP_RV250_Lf		0x4C66
#define PCI_CHIP_RV250_Lg		0x4C67
#define PCI_CHIP_RV250_Ln		0x4C6E
#define PCI_CHIP_RAGE128MF		0x4D46
#define PCI_CHIP_RAGE128ML		0x4D4C
#define PCI_CHIP_R300_ND		0x4E44
#define PCI_CHIP_R300_NE		0x4E45
#define PCI_CHIP_R300_NF		0x4E46
#define PCI_CHIP_R300_NG		0x4E47
#define PCI_CHIP_R350_NH                0x4E48  
#define PCI_CHIP_R350_NI                0x4E49  
#define PCI_CHIP_R360_NJ                0x4E4A  
#define PCI_CHIP_R350_NK                0x4E4B  
#define PCI_CHIP_RV350_NP               0x4E50
#define PCI_CHIP_RV350_NQ               0x4E51
#define PCI_CHIP_RV350_NR               0x4E52
#define PCI_CHIP_RV350_NS               0x4E53
#define PCI_CHIP_RV350_NT               0x4E54
#define PCI_CHIP_RV350_NV               0x4E56
#define PCI_CHIP_RAGE128PA		0x5041
#define PCI_CHIP_RAGE128PB		0x5042
#define PCI_CHIP_RAGE128PC		0x5043
#define PCI_CHIP_RAGE128PD		0x5044
#define PCI_CHIP_RAGE128PE		0x5045
#define PCI_CHIP_RAGE128PF		0x5046
#define PCI_CHIP_RAGE128PG		0x5047
#define PCI_CHIP_RAGE128PH		0x5048
#define PCI_CHIP_RAGE128PI		0x5049
#define PCI_CHIP_RAGE128PJ		0x504A
#define PCI_CHIP_RAGE128PK		0x504B
#define PCI_CHIP_RAGE128PL		0x504C
#define PCI_CHIP_RAGE128PM		0x504D
#define PCI_CHIP_RAGE128PN		0x504E
#define PCI_CHIP_RAGE128PO		0x504F
#define PCI_CHIP_RAGE128PP		0x5050
#define PCI_CHIP_RAGE128PQ		0x5051
#define PCI_CHIP_RAGE128PR		0x5052
#define PCI_CHIP_RAGE128PS		0x5053
#define PCI_CHIP_RAGE128PT		0x5054
#define PCI_CHIP_RAGE128PU		0x5055
#define PCI_CHIP_RAGE128PV		0x5056
#define PCI_CHIP_RAGE128PW		0x5057
#define PCI_CHIP_RAGE128PX		0x5058
#define PCI_CHIP_RADEON_QD		0x5144
#define PCI_CHIP_RADEON_QE		0x5145
#define PCI_CHIP_RADEON_QF		0x5146
#define PCI_CHIP_RADEON_QG		0x5147
#define PCI_CHIP_R200_QH		0x5148
#define PCI_CHIP_R200_QI		0x5149
#define PCI_CHIP_R200_QJ		0x514A
#define PCI_CHIP_R200_QK		0x514B
#define PCI_CHIP_R200_QL		0x514C
#define PCI_CHIP_R200_QM		0x514D
#define PCI_CHIP_R200_QN		0x514E
#define PCI_CHIP_R200_QO		0x514F
#define PCI_CHIP_RV200_QW		0x5157
#define PCI_CHIP_RV200_QX		0x5158
#define PCI_CHIP_RV100_QY		0x5159
#define PCI_CHIP_RV100_QZ		0x515A
#define PCI_CHIP_RAGE128RE		0x5245
#define PCI_CHIP_RAGE128RF		0x5246
#define PCI_CHIP_RAGE128RG		0x5247
#define PCI_CHIP_RAGE128RK		0x524B
#define PCI_CHIP_RAGE128RL		0x524C
#define PCI_CHIP_RAGE128SE		0x5345
#define PCI_CHIP_RAGE128SF		0x5346
#define PCI_CHIP_RAGE128SG		0x5347
#define PCI_CHIP_RAGE128SH		0x5348
#define PCI_CHIP_RAGE128SK		0x534B
#define PCI_CHIP_RAGE128SL		0x534C
#define PCI_CHIP_RAGE128SM		0x534D
#define PCI_CHIP_RAGE128SN		0x534E
#define PCI_CHIP_RAGE128TF		0x5446
#define PCI_CHIP_RAGE128TL		0x544C
#define PCI_CHIP_RAGE128TR		0x5452
#define PCI_CHIP_RAGE128TS		0x5453
#define PCI_CHIP_RAGE128TT		0x5454
#define PCI_CHIP_RAGE128TU		0x5455
#define PCI_CHIP_MACH64VT		0x5654
#define PCI_CHIP_MACH64VU		0x5655
#define PCI_CHIP_MACH64VV		0x5656
#define PCI_CHIP_RS300_5834		0x5834
#define PCI_CHIP_RS300_5835		0x5835
#define PCI_CHIP_RS300_5836		0x5836
#define PCI_CHIP_RS300_5837		0x5837
#define PCI_CHIP_RV280_5960		0x5960
#define PCI_CHIP_RV280_5961		0x5961
#define PCI_CHIP_RV280_5962		0x5962
#define PCI_CHIP_RV280_5964		0x5964
#define PCI_CHIP_RV280_5C61		0x5C61
#define PCI_CHIP_RV280_5C63		0x5C63

/* Avance Logic */
#define PCI_CHIP_ALG2064		0x2064
#define PCI_CHIP_ALG2301		0x2301
#define PCI_CHIP_ALG2501		0x2501

/* Tseng */
#define PCI_CHIP_ET4000_W32P_A		0x3202
#define PCI_CHIP_ET4000_W32P_B		0x3205
#define PCI_CHIP_ET4000_W32P_D		0x3206
#define PCI_CHIP_ET4000_W32P_C		0x3207
#define PCI_CHIP_ET6000			0x3208
#define PCI_CHIP_ET6300			0x4702

/* Weitek */
#define PCI_CHIP_P9000			0x9001
#define PCI_CHIP_P9100			0x9100

/* Digital */
#define PCI_CHIP_DC21050		0x0001
#define PCI_CHIP_DEC21030		0x0004
#define PCI_CHIP_TGA2			0x000D

/* Cirrus Logic */
#define PCI_CHIP_GD7548			0x0038
#define PCI_CHIP_GD7555			0x0040
#define PCI_CHIP_GD5430			0x00A0
#define PCI_CHIP_GD5434_4		0x00A4
#define PCI_CHIP_GD5434_8		0x00A8
#define PCI_CHIP_GD5436			0x00AC
#define PCI_CHIP_GD5446			0x00B8
#define PCI_CHIP_GD5480			0x00BC
#define PCI_CHIP_GD5462			0x00D0
#define PCI_CHIP_GD5464			0x00D4
#define PCI_CHIP_GD5464BD		0x00D5
#define PCI_CHIP_GD5465			0x00D6
#define PCI_CHIP_6729			0x1100
#define PCI_CHIP_6832			0x1110
#define PCI_CHIP_GD7542			0x1200
#define PCI_CHIP_GD7543			0x1202
#define PCI_CHIP_GD7541			0x1204

/* AMD */
#define PCI_CHIP_AMD761			0x700E

/* Trident */
#define PCI_CHIP_2100			0x2100
#define PCI_CHIP_8400			0x8400
#define PCI_CHIP_8420			0x8420
#define PCI_CHIP_8500			0x8500
#define PCI_CHIP_8520			0x8520
#define PCI_CHIP_8600			0x8600
#define PCI_CHIP_8620			0x8620
#define PCI_CHIP_8820			0x8820
#define PCI_CHIP_9320			0x9320
#define PCI_CHIP_9388			0x9388
#define PCI_CHIP_9397			0x9397
#define PCI_CHIP_939A			0x939A
#define PCI_CHIP_9420			0x9420
#define PCI_CHIP_9440			0x9440
#define PCI_CHIP_9520			0x9520
#define PCI_CHIP_9525			0x9525
#define PCI_CHIP_9540			0x9540
#define PCI_CHIP_9660			0x9660
#define PCI_CHIP_9750			0x9750
#define PCI_CHIP_9850			0x9850
#define PCI_CHIP_9880			0x9880
#define PCI_CHIP_9910			0x9910

/* ALI */
#define PCI_CHIP_M1435			0x1435

/* Matrox */
#define PCI_CHIP_MGA2085		0x0518
#define PCI_CHIP_MGA2064		0x0519
#define PCI_CHIP_MGA1064		0x051A
#define PCI_CHIP_MGA2164		0x051B
#define PCI_CHIP_MGA2164_AGP		0x051F
#define PCI_CHIP_MGAG200_PCI		0x0520
#define PCI_CHIP_MGAG200		0x0521
#define PCI_CHIP_MGAG400		0x0525
#define PCI_CHIP_MGAG550		0x2527
#define PCI_CHIP_IMPRESSION		0x0D10
#define PCI_CHIP_MGAG100_PCI		0x1000
#define PCI_CHIP_MGAG100		0x1001

#define PCI_CARD_G400_TH		0x2179
#define PCI_CARD_MILL_G200_SD		0xFF00
#define PCI_CARD_PROD_G100_SD		0xFF01
#define PCI_CARD_MYST_G200_SD		0xFF02
#define PCI_CARD_MILL_G200_SG		0xFF03
#define PCI_CARD_MARV_G200_SD		0xFF04

/* Chips & Tech */
#define PCI_CHIP_65545			0x00D8
#define PCI_CHIP_65548			0x00DC
#define PCI_CHIP_65550			0x00E0
#define PCI_CHIP_65554			0x00E4
#define PCI_CHIP_65555			0x00E5
#define PCI_CHIP_68554			0x00F4
#define PCI_CHIP_69000			0x00C0
#define PCI_CHIP_69030			0x0C30

/* Miro */
#define PCI_CHIP_ZR36050		0x5601

/* NEC */
#define PCI_CHIP_POWER_VR		0x0046

/* SiS */
#define PCI_CHIP_SG86C201		0x0001
#define PCI_CHIP_SG86C202		0x0002
#define PCI_CHIP_SG85C503		0x0008
#define PCI_CHIP_SIS5597		0x0200
/* Agregado por Carlos Duclos & Manuel Jander */
#define PCI_CHIP_SIS82C204		0x0204
#define PCI_CHIP_SG86C205		0x0205
#define PCI_CHIP_SG86C215		0x0215
#define PCI_CHIP_SG86C225		0x0225
#define PCI_CHIP_85C501			0x0406
#define PCI_CHIP_85C496			0x0496
#define PCI_CHIP_85C601			0x0601
#define PCI_CHIP_85C5107		0x5107
#define PCI_CHIP_85C5511		0x5511
#define PCI_CHIP_85C5513		0x5513
#define PCI_CHIP_SIS5571		0x5571
#define PCI_CHIP_SIS5597_2		0x5597
#define PCI_CHIP_SIS530			0x6306
#define PCI_CHIP_SIS6326		0x6326
#define PCI_CHIP_SIS7001		0x7001
#define PCI_CHIP_SIS300			0x0300
#define PCI_CHIP_SIS315H		0x0310
#define PCI_CHIP_SIS315PRO		0x0325
#define PCI_CHIP_SIS330			0x0330
#define PCI_CHIP_SIS630			0x6300
#define PCI_CHIP_SIS540			0x5300
#define PCI_CHIP_SIS550			0x5315 
#define PCI_CHIP_SIS650			0x6325 
#define PCI_CHIP_SIS730			0x7300

/* Hewlett-Packard */
#define PCI_CHIP_ELROY			0x1054
#define PCI_CHIP_ZX1_SBA		0x1229
#define PCI_CHIP_ZX1_IOC		0x122A
#define PCI_CHIP_ZX1_LBA		0x122E	/* a.k.a. Mercury */
#define PCI_CHIP_ZX1_AGP8		0x12B4	/* a.k.a. QuickSilver */

/* SGS */
#define PCI_CHIP_STG2000		0x0008
#define PCI_CHIP_STG1764		0x0009
#define PCI_CHIP_KYROII			0x0010

/* Texas Instruments */
#define PCI_CHIP_TI_PERMEDIA		0x3D04
#define PCI_CHIP_TI_PERMEDIA2		0x3D07

/* Oak */
#define PCI_CHIP_OTI107			0x0107

/* Number Nine */
#define PCI_CHIP_I128			0x2309
#define PCI_CHIP_I128_2			0x2339
#define PCI_CHIP_I128_T2R		0x493D
#define PCI_CHIP_I128_T2R4		0x5348

/* Sun */
#define PCI_CHIP_EBUS			0x1000
#define PCI_CHIP_HAPPY_MEAL		0x1001
#define PCI_CHIP_SIMBA			0x5000
#define PCI_CHIP_PSYCHO			0x8000
#define PCI_CHIP_SCHIZO			0x8001
#define PCI_CHIP_SABRE			0xA000
#define PCI_CHIP_HUMMINGBIRD		0xA001

/* BrookTree */
#define PCI_CHIP_BT848			0x0350
#define PCI_CHIP_BT849			0x0351

/* NVIDIA */
#define PCI_CHIP_NV1			0x0008
#define PCI_CHIP_DAC64			0x0009
#define PCI_CHIP_TNT			0x0020
#define PCI_CHIP_TNT2			0x0028
#define PCI_CHIP_UTNT2			0x0029
#define PCI_CHIP_VTNT2			0x002C
#define PCI_CHIP_UVTNT2			0x002D
#define PCI_CHIP_ITNT2			0x00A0
#define PCI_CHIP_GEFORCE_256		0x0100
#define PCI_CHIP_GEFORCE_DDR		0x0101
#define PCI_CHIP_QUADRO			0x0103
#define PCI_CHIP_GEFORCE2_MX		0x0110
#define PCI_CHIP_GEFORCE2_MX_100	0x0111
#define PCI_CHIP_GEFORCE2_GO		0x0112
#define PCI_CHIP_QUADRO2_MXR		0x0113
#define PCI_CHIP_GEFORCE2_GTS		0x0150
#define PCI_CHIP_GEFORCE2_TI		0x0151
#define PCI_CHIP_GEFORCE2_ULTRA		0x0152
#define PCI_CHIP_QUADRO2_PRO		0x0153
#define PCI_CHIP_GEFORCE4_MX_460	0x0170
#define PCI_CHIP_GEFORCE4_MX_440	0x0171
#define PCI_CHIP_GEFORCE4_MX_420	0x0172
#define PCI_CHIP_GEFORCE4_440_GO	0x0174
#define PCI_CHIP_GEFORCE4_420_GO	0x0175
#define PCI_CHIP_GEFORCE4_420_GO_M32	0x0176
#define PCI_CHIP_QUADRO4_500XGL		0x0178
#define PCI_CHIP_GEFORCE4_440_GO_M64	0x0179
#define PCI_CHIP_QUADRO4_200		0x017A
#define PCI_CHIP_QUADRO4_550XGL		0x017B
#define PCI_CHIP_QUADRO4_500_GOGL	0x017C
#define PCI_CHIP_IGEFORCE2		0x01A0
#define PCI_CHIP_GEFORCE3		0x0200
#define PCI_CHIP_GEFORCE3_TI_200	0x0201
#define PCI_CHIP_GEFORCE3_TI_500	0x0202
#define PCI_CHIP_QUADRO_DCC		0x0203
#define PCI_CHIP_GEFORCE4_TI_4600	0x0250
#define PCI_CHIP_GEFORCE4_TI_4400	0x0251
#define PCI_CHIP_GEFORCE4_TI_4200	0x0253
#define PCI_CHIP_QUADRO4_900XGL		0x0258
#define PCI_CHIP_QUADRO4_750XGL		0x0259
#define PCI_CHIP_QUADRO4_700XGL		0x025B

/* NVIDIA & SGS */
#define PCI_CHIP_RIVA128		0x0018

/* IMS */
#define PCI_CHIP_IMSTT128		0x9128
#define PCI_CHIP_IMSTT3D		0x9135

/* Alliance Semiconductor */
#define PCI_CHIP_AP6410			0x3210
#define PCI_CHIP_AP6422			0x6422
#define PCI_CHIP_AT24			0x6424
#define PCI_CHIP_AT3D			0x643D

/* 3dfx Interactive */
#define PCI_CHIP_VOODOO_GRAPHICS	0x0001
#define PCI_CHIP_VOODOO2		0x0002
#define PCI_CHIP_BANSHEE		0x0003
#define PCI_CHIP_VOODOO3		0x0005
#define PCI_CHIP_VOODOO5		0x0009

#define PCI_CARD_VOODOO3_2000		0x0036
#define PCI_CARD_VOODOO3_3000		0x003A

/* Rendition */
#define PCI_CHIP_V1000			0x0001
#define PCI_CHIP_V2x00			0x2000

/* 3Dlabs */
#define PCI_CHIP_300SX			0x0001
#define PCI_CHIP_500TX			0x0002
#define PCI_CHIP_DELTA			0x0003
#define PCI_CHIP_PERMEDIA		0x0004
#define PCI_CHIP_MX			0x0006
#define PCI_CHIP_PERMEDIA2		0x0007
#define PCI_CHIP_GAMMA			0x0008
#define PCI_CHIP_PERMEDIA2V		0x0009
#define PCI_CHIP_PERMEDIA3		0x000A
#define PCI_CHIP_PERMEDIA4		0x000C
#define PCI_CHIP_R4			0x000D
#define PCI_CHIP_GAMMA2			0x000E
#define PCI_CHIP_R4ALT			0x0011

/* S3 */
#define PCI_CHIP_PLATO			0x0551
#define PCI_CHIP_VIRGE			0x5631
#define PCI_CHIP_TRIO			0x8811
#define PCI_CHIP_AURORA64VP		0x8812
#define PCI_CHIP_TRIO64UVP		0x8814
#define PCI_CHIP_VIRGE_VX		0x883D
#define PCI_CHIP_868			0x8880
#define PCI_CHIP_928			0x88B0
#define PCI_CHIP_864_0			0x88C0
#define PCI_CHIP_864_1			0x88C1
#define PCI_CHIP_964_0			0x88D0
#define PCI_CHIP_964_1			0x88D1
#define PCI_CHIP_968			0x88F0
#define PCI_CHIP_TRIO64V2_DXGX		0x8901
#define PCI_CHIP_PLATO_PX		0x8902
#define PCI_CHIP_Trio3D			0x8904
#define PCI_CHIP_Trio3D_2X		0x8A13
#define PCI_CHIP_VIRGE_DXGX		0x8A01
#define PCI_CHIP_VIRGE_GX2		0x8A10
#define PCI_CHIP_SAVAGE3D		0x8A20
#define PCI_CHIP_SAVAGE3D_MV		0x8A21
#define PCI_CHIP_SAVAGE4		0x8A22
#define PCI_CHIP_VIRGE_MX		0x8C01
#define PCI_CHIP_VIRGE_MXPLUS		0x8C01
#define PCI_CHIP_VIRGE_MXP		0x8C03
#define PCI_CHIP_PROSAVAGE_PM		0x8A25
#define PCI_CHIP_PROSAVAGE_KM		0x8A26
#define PCI_CHIP_SAVAGE_MX_MV		0x8C10
#define PCI_CHIP_SAVAGE_MX		0x8C11
#define PCI_CHIP_SAVAGE_IX_MV		0x8C12
#define PCI_CHIP_SAVAGE_IX		0x8C13
#define PCI_CHIP_SAVAGE2000		0x9102

/* ARK Logic */
#define PCI_CHIP_1000PV			0xA091
#define PCI_CHIP_2000PV			0xA099
#define PCI_CHIP_2000MT			0xA0A1
#define PCI_CHIP_2000MI			0xA0A9

/* Tritech Microelectronics */
#define PCI_CHIP_TR25202		0xFC02

/* Neomagic */
#define PCI_CHIP_NM2070			0x0001
#define PCI_CHIP_NM2090			0x0002
#define PCI_CHIP_NM2093			0x0003
#define PCI_CHIP_NM2097			0x0083
#define PCI_CHIP_NM2160			0x0004
#define PCI_CHIP_NM2200			0x0005
#define PCI_CHIP_NM2230			0x0025
#define PCI_CHIP_NM2360			0x0006
#define PCI_CHIP_NM2380			0x0016

/* Intel */
#define PCI_CHIP_I815_BRIDGE		0x1130
#define PCI_CHIP_I815			0x1132
#define PCI_CHIP_82801_P2P		0x244E
#define PCI_CHIP_845_G_BRIDGE		0x2560
#define PCI_CHIP_845_G			0x2562
#define PCI_CHIP_I830_M_BRIDGE		0x3575
#define PCI_CHIP_I830_M			0x3577
#define PCI_CHIP_I810_BRIDGE		0x7120
#define PCI_CHIP_I810			0x7121
#define PCI_CHIP_I810_DC100_BRIDGE	0x7122
#define PCI_CHIP_I810_DC100		0x7123
#define PCI_CHIP_I810_E_BRIDGE		0x7124
#define PCI_CHIP_I810_E			0x7125
#define PCI_CHIP_I740_AGP		0x7800
#define PCI_CHIP_460GX_PXB		0x84CB
#define PCI_CHIP_460GX_SAC		0x84E0
#define PCI_CHIP_460GX_GXB_2		0x84E2	/* PCI function 2 */
#define PCI_CHIP_460GX_WXB		0x84E6
#define PCI_CHIP_460GX_GXB_1		0x84EA	/* PCI function 1 */

/* Silicon Motion Inc. */
#define PCI_CHIP_SMI910			0x0910
#define PCI_CHIP_SMI810			0x0810
#define PCI_CHIP_SMI820			0x0820
#define PCI_CHIP_SMI710			0x0710
#define PCI_CHIP_SMI712			0x0712
#define PCI_CHIP_SMI720			0x0720
#define PCI_CHIP_SMI731			0x0730

/* VMware */
#define PCI_CHIP_VMWARE0405		0x0405
#define PCI_CHIP_VMWARE0710		0x0710

#endif /* _XF86_PCIINFO_H */

--- NEW FILE: xf86Priv.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Priv.h,v 3.83 2004/01/27 01:31:45 dawes Exp $ */

/*
 * Copyright (c) 1997-2002 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 * This file contains declarations for private XFree86 functions and variables,
 * and definitions of private macros.
 *
 * "private" means not available to video drivers.
 */

#ifndef _XF86PRIV_H
#define _XF86PRIV_H

#include "xf86Privstr.h"
#include "propertyst.h"

/*
 * Parameters set ONLY from the command line options
 * The global state of these things is held in xf86InfoRec (when appropriate).
 */
extern const char *xf86ConfigFile;
extern Bool xf86AllowMouseOpenFail;
#ifdef XF86VIDMODE
extern Bool xf86VidModeDisabled;
extern Bool xf86VidModeAllowNonLocal; 
#endif 
#ifdef XF86MISC
extern Bool xf86MiscModInDevDisabled;
extern Bool xf86MiscModInDevAllowNonLocal;
#endif 
extern Bool xf86fpFlag;
extern Bool xf86coFlag;
extern Bool xf86sFlag;
extern Bool xf86bsEnableFlag;
extern Bool xf86bsDisableFlag;
extern Bool xf86silkenMouseDisableFlag;
extern char *xf86LayoutName;
extern char *xf86ScreenName;
extern char *xf86PointerName;
extern char *xf86KeyboardName;
#ifdef KEEPBPP
extern int xf86Bpp;
#endif
extern int xf86FbBpp;
extern int xf86Depth;
extern Pix24Flags xf86Pix24;
extern rgb xf86Weight;
extern Bool xf86FlipPixels;
extern Bool xf86BestRefresh;
extern Gamma xf86Gamma;
extern char *xf86ServerName;
extern Bool xf86ShowUnresolved;

/* Other parameters */

extern xf86InfoRec xf86Info;
extern const char *xf86InputDeviceList;
extern const char *xf86ModulePath;
extern MessageType xf86ModPathFrom;
extern const char *xf86LogFile;
extern MessageType xf86LogFileFrom;
extern Bool xf86LogFileWasOpened;
extern serverLayoutRec xf86ConfigLayout;
extern Pix24Flags xf86ConfigPix24;

extern unsigned short xf86MouseCflags[];
extern Bool xf86SupportedMouseTypes[];
extern int xf86NumMouseTypes;

#ifdef XFree86LOADER
extern DriverPtr *xf86DriverList;
extern ModuleInfoPtr *xf86ModuleInfoList;
extern int xf86NumModuleInfos;
#else
extern DriverPtr xf86DriverList[];
#endif
extern int xf86NumDrivers;
extern Bool xf86Resetting;
extern Bool xf86Initialising;
extern Bool xf86ProbeFailed;
extern int xf86NumScreens;
extern pciVideoPtr *xf86PciVideoInfo;
extern xf86CurrentAccessRec xf86CurrentAccess;
extern const char *xf86VisualNames[];
extern int xf86Verbose;                 /* verbosity level */
extern int xf86LogVerbose;		/* log file verbosity level */
extern Bool xf86ProbeOnly;
extern Bool xf86DoProbe;

extern RootWinPropPtr *xf86RegisteredPropertiesTable;

#ifndef DEFAULT_VERBOSE
#define DEFAULT_VERBOSE		0
#endif
#ifndef DEFAULT_LOG_VERBOSE
#define DEFAULT_LOG_VERBOSE	3
#endif
#ifndef DEFAULT_DPI
#define DEFAULT_DPI		75
#endif

#define DEFAULT_UNRESOLVED	TRUE
#define DEFAULT_BEST_REFRESH	FALSE

/* Function Prototypes */
#ifndef _NO_XF86_PROTOTYPES

/* xf86Beta.c */
extern void xf86CheckBeta(int extraDays, char *key);

/* xf86Bus.c */

void xf86BusProbe(void);
void xf86ChangeBusIndex(int oldIndex, int newIndex);
void xf86AccessInit(void);
void xf86AccessEnter(void);
void xf86AccessLeave(void);
void xf86EntityInit(void);
void xf86EntityEnter(void);
void xf86EntityLeave(void);
void xf86AccessLeaveState(void);

void xf86FindPrimaryDevice(void);
/* new RAC */
void xf86ResourceBrokerInit(void);
void xf86PostProbe(void);
void xf86ClearEntityListForScreen(int scrnIndex);
void xf86AddDevToEntity(int entityIndex, GDevPtr dev);
extern void xf86PostPreInit(void);
extern void xf86PostScreenInit(void);
extern memType getValidBIOSBase(PCITAG tag, int num);
extern int pciTestMultiDeviceCard(int bus, int dev, int func, PCITAG** pTag);

/* xf86Config.c */

Bool xf86PathIsAbsolute(const char *path);
Bool xf86PathIsSafe(const char *path);

/* xf86DefaultModes */

extern DisplayModeRec xf86DefaultModes [];

/* xf86DoScanPci.c */

void DoScanPci(int argc, char **argv, int i);

/* xf86DoProbe.c */
void DoProbeArgs(int argc, char **argv, int i);
void DoProbe(void);
void DoConfigure(void);

/* xf86Events.c */

void xf86PostKbdEvent(unsigned key);
void xf86PostMseEvent(DeviceIntPtr device, int buttons, int dx, int dy);
void xf86Wakeup(pointer blockData, int err, pointer pReadmask);
void xf86SigHandler(int signo);
#ifdef MEMDEBUG
void xf86SigMemDebug(int signo);
#endif
void xf86HandlePMEvents(int fd, pointer data);
extern int (*xf86PMGetEventFromOs)(int fd,pmEvent *events,int num);
extern pmWait (*xf86PMConfirmEventToOs)(int fd,pmEvent event);
void xf86GrabServerCallback(CallbackListPtr *, pointer, pointer);

/* xf86Helper.c */
void xf86LogInit(void);
void xf86CloseLog(void);

/* xf86Init.c */
Bool xf86LoadModules(char **list, pointer *optlist);
int xf86SetVerbosity(int verb);
int xf86SetLogVerbosity(int verb);

/* xf86Io.c */

void xf86KbdBell(int percent, DeviceIntPtr pKeyboard, pointer ctrl,
		 int unused);
void xf86KbdLeds(void);
void xf86UpdateKbdLeds(void);
void xf86KbdCtrl(DevicePtr pKeyboard, KeybdCtrl *ctrl); 
void xf86InitKBD(Bool init);  
int xf86KbdProc(DeviceIntPtr pKeyboard, int what);

/* xf86Kbd.c */ 

void xf86KbdGetMapping(KeySymsPtr pKeySyms, CARD8 *pModMap);

/* xf86Lock.c */

#ifdef USE_XF86_SERVERLOCK
void xf86UnlockServer(void);
#endif

/* xf86XKB.c */

void xf86InitXkb(void);

#endif /* _NO_XF86_PROTOTYPES */


#endif /* _XF86PRIV_H */

--- NEW FILE: xf86Privstr.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Privstr.h,v 1.41 2004/01/27 01:31:45 dawes Exp $ */

/*
 * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 * This file contains definitions of the private XFree86 data structures/types.
 * None of the data structures here should be used by video drivers.
 */ 

#ifndef _XF86PRIVSTR_H
#define _XF86PRIVSTR_H

#include "xf86Pci.h"
#include "xf86str.h"

/* PCI probe flags */

typedef enum {
    PCIProbe1		= 0,
    PCIProbe2,
    PCIForceConfig1,
    PCIForceConfig2,
    PCIForceNone,
    PCIOsConfig
} PciProbeType;

typedef enum {
    LogNone,
    LogFlush,
    LogSync
} Log;

typedef enum {
    SKNever,
    SKWhenNeeded,
    SKAlways
} SpecialKeysInDDX;

/*
 * xf86InfoRec contains global parameters which the video drivers never
 * need to access.  Global parameters which the video drivers do need
 * should be individual globals.
 */

typedef struct {

    /* keyboard part */
    DeviceIntPtr	pKeyboard;
    DeviceProc		kbdProc;		/* procedure for initializing */
    void		(* kbdEvents)(void);	/* proc for processing events */
    int			consoleFd;
    int			kbdFd;
    int			vtno;
    int			kbdType;		/* AT84 / AT101 */
    int			kbdRate;
    int			kbdDelay;
    int			bell_pitch;
    int			bell_duration;
    Bool		autoRepeat;
    unsigned long	leds;
    unsigned long	xleds;
    char *		vtinit;
    int			scanPrefix;		/* scancode-state */
    Bool		capsLock;
    Bool		numLock;
    Bool		scrollLock;
    Bool		modeSwitchLock;
    Bool		composeLock;
    Bool		vtSysreq;
    SpecialKeysInDDX	ddxSpecialKeys;
    Bool		ActionKeyBindingsSet;
#if defined(SVR4) && defined(i386)
    Bool		panix106;
#endif  /* SVR4 && i386 */
#if defined(__OpenBSD__) || defined(__NetBSD__)
    int                 wsKbdType;
#endif

    /* mouse part */
    DeviceIntPtr	pMouse;
#ifdef XINPUT
    pointer		mouseLocal;
#endif

    /* event handler part */
    int			lastEventTime;
    Bool		vtRequestsPending;
    Bool		inputPending;
    Bool		dontVTSwitch;
    Bool		dontZap;
    Bool		dontZoom;
    Bool		notrapSignals;	/* don't exit cleanly - die at fault */
    Bool		caughtSignal;

    /* graphics part */
    Bool		sharedMonitor;
    ScreenPtr		currentScreen;
#ifdef CSRG_BASED
    int			screenFd;	/* fd for memory mapped access to
					 * vga card */
    int			consType;	/* Which console driver? */
#endif

#ifdef XKB
    /* 
     * would like to use an XkbComponentNamesRec here but can't without
     * pulling in a bunch of header files. :-(
     */
    char *		xkbkeymap;
    char *		xkbkeycodes;
    char *		xkbtypes;
    char *		xkbcompat;
    char *		xkbsymbols;
    char *		xkbgeometry;
    Bool		xkbcomponents_specified;
    char *		xkbrules;
    char *		xkbmodel;
    char *		xkblayout;
    char *		xkbvariant;
    char *		xkboptions;
#endif

    /* Other things */
    Bool		allowMouseOpenFail;
    Bool		vidModeEnabled;		/* VidMode extension enabled */
    Bool		vidModeAllowNonLocal;	/* allow non-local VidMode
						 * connections */
    Bool		miscModInDevEnabled;	/* Allow input devices to be
						 * changed */
    Bool		miscModInDevAllowNonLocal;
    PciProbeType	pciFlags;
    Pix24Flags		pixmap24;
    MessageType		pix24From;
#if defined(i386) || defined(__i386__)
    Bool		pc98;
#endif
    Bool		pmFlag;
    Log			log;
    int			estimateSizesAggressively;
    Bool		kbdCustomKeycodes;
    Bool		disableRandR;
    MessageType		randRFrom;
    struct {
	Bool		disabled;		/* enable/disable deactivating
						 * grabs or closing the
						 * connection to the grabbing
						 * client */
	ClientPtr	override;		/* client that disabled
						 * grab deactivation.
						 */
	Bool		allowDeactivate;
	Bool		allowClosedown;
	ServerGrabInfoRec server;
    } grabInfo;
} xf86InfoRec, *xf86InfoPtr;

#ifdef DPMSExtension
/* Private info for DPMS */
typedef struct {
    CloseScreenProcPtr	CloseScreen;
    Bool		Enabled;
    int			Flags;
} DPMSRec, *DPMSPtr;
#endif

#ifdef XF86VIDMODE
/* Private info for Video Mode Extentsion */
typedef struct {
    DisplayModePtr	First;
    DisplayModePtr	Next;
    int			Flags;
    CloseScreenProcPtr	CloseScreen;
} VidModeRec, *VidModePtr;
#endif

/* Information for root window properties. */
typedef struct _RootWinProp {
    struct _RootWinProp *	next;
    char *			name;
    Atom			type;
    short			format;
    long			size;
    pointer			data;
} RootWinProp, *RootWinPropPtr;

/* private resource types */
#define ResNoAvoid  ResBios

/* ISC's cc can't handle ~ of UL constants, so explicitly type cast them. */
#define XLED1   ((unsigned long) 0x00000001)
#define XLED2   ((unsigned long) 0x00000002)
#define XLED3   ((unsigned long) 0x00000004)
#define XLED4	((unsigned long) 0x00000008)
#define XCAPS   ((unsigned long) 0x20000000)
#define XNUM    ((unsigned long) 0x40000000)
#define XSCR    ((unsigned long) 0x80000000)
#define XCOMP	((unsigned long) 0x00008000)

/* BSD console driver types (consType) */
#ifdef CSRG_BASED
#define PCCONS		   0
#define CODRV011	   1
#define CODRV01X	   2
#define SYSCONS		   8
#define PCVT		  16
#define WSCONS		  32
#endif

#endif /* _XF86PRIVSTR_H */

--- NEW FILE: xf86RandR.c ---
(This appears to be a binary file; contents omitted.)

--- NEW FILE: xf86Resources.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Resources.h,v 1.15 2003/08/24 17:36:55 dawes Exp $ */

/*
 * Copyright (c) 1999-2002 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

#ifndef _XF86_RESOURCES_H

#define _XF86_RESOURCES_H

#include "xf86str.h"

#define _END {ResEnd,0,0}

#define _VGA_EXCLUSIVE \
		{ResExcMemBlock | ResBios | ResBus, 0x000A0000, 0x000AFFFF},\
		{ResExcMemBlock | ResBios | ResBus, 0x000B0000, 0x000B7FFF},\
		{ResExcMemBlock | ResBios | ResBus, 0x000B8000, 0x000BFFFF},\
		{ResExcIoBlock  | ResBios | ResBus,     0x03B0,     0x03BB},\
		{ResExcIoBlock  | ResBios | ResBus,     0x03C0,     0x03DF}

#define _VGA_SHARED \
		{ResShrMemBlock | ResBios | ResBus, 0x000A0000, 0x000AFFFF},\
		{ResShrMemBlock | ResBios | ResBus, 0x000B0000, 0x000B7FFF},\
		{ResShrMemBlock | ResBios | ResBus, 0x000B8000, 0x000BFFFF},\
		{ResShrIoBlock  | ResBios | ResBus,     0x03B0,     0x03BB},\
		{ResShrIoBlock  | ResBios | ResBus,     0x03C0,     0x03DF}

#define _VGA_SHARED_MEM \
		{ResShrMemBlock | ResBios | ResBus, 0x000A0000, 0x000AFFFF},\
		{ResShrMemBlock | ResBios | ResBus, 0x000B0000, 0x000B7FFF},\
 		{ResShrMemBlock | ResBios | ResBus, 0x000B8000, 0x000BFFFF}

#define _VGA_SHARED_IO \
		{ResShrIoBlock  | ResBios | ResBus,     0x03B0,     0x03BB},\
		{ResShrIoBlock  | ResBios | ResBus,     0x03C0,     0x03DF}

/*
 * Exclusive unused VGA:  resources unneeded but cannot be disabled.
 * Like old Millennium.
 */
#define _VGA_EXCLUSIVE_UNUSED \
	{ResExcUusdMemBlock | ResBios | ResBus, 0x000A0000, 0x000AFFFF},\
	{ResExcUusdMemBlock | ResBios | ResBus, 0x000B0000, 0x000B7FFF},\
	{ResExcUusdMemBlock | ResBios | ResBus, 0x000B8000, 0x000BFFFF},\
	{ResExcUusdIoBlock  | ResBios | ResBus,     0x03B0,     0x03BB},\
	{ResExcUusdIoBlock  | ResBios | ResBus,     0x03C0,     0x03DF}

/*
 * Shared unused VGA:  resources unneeded but cannot be disabled
 * independently.  This is used to determine if a device needs RAC.
 */
#define _VGA_SHARED_UNUSED \
	{ResShrUusdMemBlock | ResBios | ResBus, 0x000A0000, 0x000AFFFF},\
	{ResShrUusdMemBlock | ResBios | ResBus, 0x000B0000, 0x000B7FFF},\
	{ResShrUusdMemBlock | ResBios | ResBus, 0x000B8000, 0x000BFFFF},\
	{ResShrUusdIoBlock  | ResBios | ResBus,     0x03B0,     0x03BB},\
	{ResShrUusdIoBlock  | ResBios | ResBus,     0x03C0,     0x03DF}

/*
 * Sparse versions of the above for those adapters that respond to all ISA
 * aliases of VGA ports.
 */
#define _VGA_EXCLUSIVE_SPARSE \
	{ResExcMemBlock | ResBios | ResBus, 0x000A0000, 0x000AFFFF},\
	{ResExcMemBlock | ResBios | ResBus, 0x000B0000, 0x000B7FFF},\
	{ResExcMemBlock | ResBios | ResBus, 0x000B8000, 0x000BFFFF},\
	{ResExcIoSparse | ResBios | ResBus,     0x03B0,     0x03F8},\
	{ResExcIoSparse | ResBios | ResBus,     0x03B8,     0x03FC},\
	{ResExcIoSparse | ResBios | ResBus,     0x03C0,     0x03E0}

#define _VGA_SHARED_SPARSE \
	{ResShrMemBlock | ResBios | ResBus, 0x000A0000, 0x000AFFFF},\
	{ResShrMemBlock | ResBios | ResBus, 0x000B0000, 0x000B7FFF},\
	{ResShrMemBlock | ResBios | ResBus, 0x000B8000, 0x000BFFFF},\
	{ResShrIoSparse | ResBios | ResBus,     0x03B0,     0x03F8},\
	{ResShrIoSparse | ResBios | ResBus,     0x03B8,     0x03FC},\
	{ResShrIoSparse | ResBios | ResBus,     0x03C0,     0x03E0}

#define _8514_EXCLUSIVE \
	{ResExcIoSparse | ResBios | ResBus, 0x02E8, 0x03F8}

#define _8514_SHARED \
	{ResShrIoSparse | ResBios | ResBus, 0x02E8, 0x03F8}

/* Predefined resources */
extern resRange resVgaExclusive[];
extern resRange resVgaShared[];
extern resRange resVgaIoShared[];
extern resRange resVgaMemShared[];
extern resRange resVgaUnusedExclusive[];
extern resRange resVgaUnusedShared[];
extern resRange resVgaSparseExclusive[];
extern resRange resVgaSparseShared[];
extern resRange res8514Exclusive[];
extern resRange res8514Shared[];

/* Less misleading aliases for xf86SetOperatingState() */
#define resVgaMem resVgaMemShared
#define resVgaIo  resVgaIoShared
#define resVga    resVgaShared

/* Old style names */
#define RES_EXCLUSIVE_VGA   resVgaExclusive
#define RES_SHARED_VGA      resVgaShared
#define RES_EXCLUSIVE_8514  res8514Exclusive
#define RES_SHARED_8514     res8514Shared

#define _PCI_AVOID_PC_STYLE \
	{ResExcIoSparse | ResBus, 0x0100, 0x0300},\
	{ResExcIoSparse | ResBus, 0x0200, 0x0200},\
        {ResExcMemBlock | ResBus, 0xA0000,0xFFFFF}

extern resRange PciAvoid[];

#define RES_UNDEFINED NULL
#endif

--- NEW FILE: xf86Versions.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Versions.c,v 1.2 2003/08/24 20:01:19 dawes Exp $ */
/*
 * Copyright (c) 2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

#include "xf86.h"
#include "xf86OSmouse.h"
#include "xf86OSKbd.h"

static CARD32 registeredVersions[NUM_BUILTIN_IFS];

CARD32
xf86GetBuiltinInterfaceVersion(BuiltinInterface iface, int flags)
{
    if (iface < 0 || iface >= NUM_BUILTIN_IFS) {
	xf86Msg(X_ERROR, "xf86GetBuiltinInterfaceVersion: Unexpected interface"
		"query: %d\n", iface);
	return 0;
    }

    if (registeredVersions[iface])
	return registeredVersions[iface];

    /* Most built-in interfaces are handled this way. */
    switch (iface) {
    case BUILTIN_IF_OSMOUSE:
	return OS_MOUSE_VERSION_CURRENT;
    case BUILTIN_IF_OSKBD:
	return OS_KBD_VERSION_CURRENT;
    default:
	xf86Msg(X_ERROR, "xf86GetBuiltinInterfaceVersion: internal error: "
		"interface %d not handled\n", iface);
	return 0;
    }
}

Bool
xf86RegisterBuiltinInterfaceVersion(BuiltinInterface iface, CARD32 version,
				    int flags)
{
    if (iface < 0 || iface >= NUM_BUILTIN_IFS) {
	xf86Msg(X_ERROR, "xf86RegisterBuiltinInterfaceVersion: "
		"unexpected interface number: %d\n", iface);
	return FALSE;
    }
    if (version == 0) {
	xf86Msg(X_ERROR, "xf86RegisterBuiltinInterfaceVersion: "
		"versions must be greater than zero\n");
	return FALSE;
    }
    registeredVersions[iface] = version;
    return TRUE;
}


--- NEW FILE: xf86VidMode.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86VidMode.c,v 1.17 2003/08/24 17:36:55 dawes Exp $ */
/*
 * Copyright (c) 1999-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 * This file contains the VidMode functions required by the extension.
 * These have been added to avoid the need for the higher level extension
 * code to access the private XFree86 data structures directly. Wherever
 * possible this code uses the functions in xf86Mode.c to do the work,
 * so that two version of code that do similar things don't have to be
 * maintained.
 */

#include <X11/X.h>
#include "os.h"
#include "xf86.h"
#include "xf86Priv.h"

#ifdef XF86VIDMODE
#include "vidmodeproc.h"
#include "xf86cmap.h"

static int VidModeGeneration = 0;
static int VidModeIndex = -1;
static int VidModeCount = 0;
static Bool VidModeClose(int i, ScreenPtr pScreen);

#define VMPTR(p) ((VidModePtr)(p)->devPrivates[VidModeIndex].ptr)

#endif

#ifdef DEBUG
# define DEBUG_P(x) ErrorF(x"\n");
#else
# define DEBUG_P(x) /**/
#endif

Bool
VidModeExtensionInit(ScreenPtr pScreen)
{
#ifdef XF86VIDMODE
    VidModePtr pVidMode;
    
    DEBUG_P("VidModeExtensionInit");

    if (!xf86GetVidModeEnabled()) {
	DEBUG_P("!xf86GetVidModeEnabled()");
	return FALSE;
    }

    if (serverGeneration != VidModeGeneration) {
	if ((VidModeIndex = AllocateScreenPrivateIndex()) < 0) {
	    DEBUG_P("AllocateScreenPrivateIndex() failed");
	    return FALSE;
	}
	VidModeGeneration = serverGeneration;
    }

    if (!(pScreen->devPrivates[VidModeIndex].ptr = xcalloc(sizeof(VidModeRec), 1))) {
	DEBUG_P("xcalloc failed");
	return FALSE;
    }

    pVidMode = VMPTR(pScreen);
    pVidMode->Flags = 0;
    pVidMode->Next = NULL;
    pVidMode->CloseScreen = pScreen->CloseScreen;
    pScreen->CloseScreen = VidModeClose;
    VidModeCount++;
    return TRUE;
#else
    DEBUG_P("no vidmode extension");
    return FALSE;
#endif
}


#ifdef XF86VIDMODE

static Bool
VidModeClose(int i, ScreenPtr pScreen)
{
    VidModePtr pVidMode = VMPTR(pScreen);

    DEBUG_P("VidModeClose");

    /* This shouldn't happen */
    if (!pVidMode)
	return FALSE;

    pScreen->CloseScreen = pVidMode->CloseScreen;

    if (--VidModeCount == 0) {
	if (pScreen->devPrivates[VidModeIndex].ptr)
	  xfree(pScreen->devPrivates[VidModeIndex].ptr);
	pScreen->devPrivates[VidModeIndex].ptr = NULL;
	VidModeIndex = -1;
    }
    return pScreen->CloseScreen(i, pScreen);
}

Bool
VidModeAvailable(int scrnIndex)
{
    ScrnInfoPtr pScrn;
    VidModePtr pVidMode;

    DEBUG_P("VidModeAvailable");

    if (VidModeIndex < 0) {
	DEBUG_P("VidModeIndex < 0");
	return FALSE;
    }
 
    pScrn = xf86Screens[scrnIndex];
    if (pScrn == NULL) {
	DEBUG_P("pScrn == NULL");
	return FALSE;
    }
    
    pVidMode = VMPTR(pScrn->pScreen);
    if (pVidMode)
	return TRUE;
    else {
	DEBUG_P("pVidMode == NULL");
	return FALSE;
    }
}

Bool
VidModeGetCurrentModeline(int scrnIndex, pointer *mode, int *dotClock)
{
    ScrnInfoPtr pScrn;

    DEBUG_P("VidModeGetCurrentModeline");

    if (!VidModeAvailable(scrnIndex))
	return FALSE;

    pScrn = xf86Screens[scrnIndex];
    *mode = (pointer)(pScrn->currentMode);
    *dotClock = pScrn->currentMode->Clock;

    return TRUE;
}

int
VidModeGetDotClock(int scrnIndex, int Clock)
{
    ScrnInfoPtr pScrn;

    DEBUG_P("VidModeGetDotClock");

    if (!VidModeAvailable(scrnIndex))
	return 0;

    pScrn = xf86Screens[scrnIndex];
    if ((pScrn->progClock) || (Clock > MAXCLOCKS))
	return Clock;
    else  
	return pScrn->clock[Clock];
}

int
VidModeGetNumOfClocks(int scrnIndex, Bool *progClock)
{
    ScrnInfoPtr pScrn;

    DEBUG_P("VidModeGetNumOfClocks");

    if (!VidModeAvailable(scrnIndex))
	return 0;

    pScrn = xf86Screens[scrnIndex];
    if (pScrn->progClock){
	*progClock = TRUE;
	return 0;
    } else {
	*progClock = FALSE;
	return pScrn->numClocks;
    }
}

Bool
VidModeGetClocks(int scrnIndex, int *Clocks)
{
    ScrnInfoPtr pScrn;
    int i;

    DEBUG_P("VidModeGetClocks");

    if (!VidModeAvailable(scrnIndex))
	return FALSE;

    pScrn = xf86Screens[scrnIndex];

    if (pScrn->progClock)
	return FALSE;

    for (i = 0;  i < pScrn->numClocks;  i++)
	*Clocks++ = pScrn->clock[i];

    return TRUE;
}


Bool
VidModeGetFirstModeline(int scrnIndex, pointer *mode, int *dotClock)
{
    ScrnInfoPtr pScrn;
    VidModePtr pVidMode;

    DEBUG_P("VidModeGetFirstModeline");

    if (!VidModeAvailable(scrnIndex))
	return FALSE;

    pScrn = xf86Screens[scrnIndex];
    pVidMode = VMPTR(pScrn->pScreen);
    pVidMode->First = pScrn->modes;
    pVidMode->Next =  pVidMode->First->next;

    if (pVidMode->First->status == MODE_OK) {
      *mode = (pointer)(pVidMode->First);
      *dotClock = VidModeGetDotClock(scrnIndex, pVidMode->First->Clock);
      return TRUE;
    }

    return VidModeGetNextModeline(scrnIndex, mode, dotClock);
}

Bool
VidModeGetNextModeline(int scrnIndex, pointer *mode, int *dotClock)
{
    ScrnInfoPtr pScrn;
    VidModePtr pVidMode;
    DisplayModePtr p;

    DEBUG_P("VidModeGetNextModeline");

    if (!VidModeAvailable(scrnIndex))
	return FALSE;

    pScrn = xf86Screens[scrnIndex];
    pVidMode = VMPTR(pScrn->pScreen);

    for (p = pVidMode->Next; p != NULL && p != pVidMode->First; p = p->next) {
	if (p->status == MODE_OK) {
	    pVidMode->Next = p->next;
	    *mode = (pointer)p;
	    *dotClock = VidModeGetDotClock(scrnIndex, p->Clock);
	    return TRUE;
	}
    }
    
    return FALSE;
}

Bool
VidModeDeleteModeline(int scrnIndex, pointer mode)
{
    ScrnInfoPtr pScrn;

    DEBUG_P("VidModeDeleteModeline");

    if ((mode == NULL) || (!VidModeAvailable(scrnIndex)))
	return FALSE;

    pScrn = xf86Screens[scrnIndex];
    xf86DeleteMode(&(pScrn->modes), (DisplayModePtr)mode);
    return TRUE;
}

Bool
VidModeZoomViewport(int scrnIndex, int zoom)
{
    ScrnInfoPtr pScrn;

    DEBUG_P("VidModeZoomViewPort");

    if (!VidModeAvailable(scrnIndex))
	return FALSE;

    pScrn = xf86Screens[scrnIndex];
    xf86ZoomViewport(pScrn->pScreen, zoom);
    return TRUE;
}

Bool
VidModeSetViewPort(int scrnIndex, int x, int y)
{
    ScrnInfoPtr pScrn;

    DEBUG_P("VidModeSetViewPort");

    if (!VidModeAvailable(scrnIndex))
	return FALSE;

    pScrn = xf86Screens[scrnIndex];
    pScrn->frameX0 = min( max(x, 0),
	                 pScrn->virtualX - pScrn->currentMode->HDisplay );
    pScrn->frameX1 = pScrn->frameX0 + pScrn->currentMode->HDisplay - 1;
    pScrn->frameY0 = min( max(y, 0),
	                 pScrn->virtualY - pScrn->currentMode->VDisplay );
    pScrn->frameY1 = pScrn->frameY0 + pScrn->currentMode->VDisplay - 1;
    if (pScrn->AdjustFrame != NULL)
	(pScrn->AdjustFrame)(scrnIndex, pScrn->frameX0, pScrn->frameY0, 0);

    return TRUE;
}

Bool
VidModeGetViewPort(int scrnIndex, int *x, int *y)
{
    ScrnInfoPtr pScrn;

    DEBUG_P("VidModeGetViewPort");

    if (!VidModeAvailable(scrnIndex))
	return FALSE;

    pScrn = xf86Screens[scrnIndex];
    *x = pScrn->frameX0;
    *y = pScrn->frameY0;
    return TRUE;
}

Bool
VidModeSwitchMode(int scrnIndex, pointer mode)
{
    ScrnInfoPtr pScrn;
    DisplayModePtr pTmpMode;
    Bool retval;

    DEBUG_P("VidModeSwitchMode");

    if (!VidModeAvailable(scrnIndex))
	return FALSE;

    pScrn = xf86Screens[scrnIndex];
    /* save in case we fail */
    pTmpMode = pScrn->currentMode;
    /* Force a mode switch */
    pScrn->currentMode = NULL;
    retval = xf86SwitchMode(pScrn->pScreen, mode);
    /* we failed: restore it */
    if (retval == FALSE)
	pScrn->currentMode = pTmpMode;
    return retval;
}

Bool
VidModeLockZoom(int scrnIndex, Bool lock)
{
    ScrnInfoPtr pScrn;

    DEBUG_P("VidModeLockZoom");

    if (!VidModeAvailable(scrnIndex))
	return FALSE;

    pScrn = xf86Screens[scrnIndex];

    if (xf86Info.dontZoom)
	return FALSE;

    xf86LockZoom(pScrn->pScreen, lock);
    return TRUE;
}

Bool
VidModeGetMonitor(int scrnIndex, pointer *monitor)
{
    ScrnInfoPtr pScrn;

    DEBUG_P("VidModeGetMonitor");

    if (!VidModeAvailable(scrnIndex))
	return FALSE;

    pScrn = xf86Screens[scrnIndex];
    *monitor = (pointer)(pScrn->monitor);

    return TRUE;
}

ModeStatus
VidModeCheckModeForMonitor(int scrnIndex, pointer mode)
{
    ScrnInfoPtr pScrn;

    DEBUG_P("VidModeCheckModeForMonitor");

    if ((mode == NULL) || (!VidModeAvailable(scrnIndex)))
	return MODE_ERROR;

    pScrn = xf86Screens[scrnIndex];

    return xf86CheckModeForMonitor((DisplayModePtr)mode, pScrn->monitor);
}

ModeStatus
VidModeCheckModeForDriver(int scrnIndex, pointer mode)
{
    ScrnInfoPtr pScrn;

    DEBUG_P("VidModeCheckModeForDriver");

    if ((mode == NULL) || (!VidModeAvailable(scrnIndex)))
	return MODE_ERROR;

    pScrn = xf86Screens[scrnIndex];

    return xf86CheckModeForDriver(pScrn, (DisplayModePtr)mode, 0);
}

void
VidModeSetCrtcForMode(int scrnIndex, pointer mode)
{
    ScrnInfoPtr pScrn;
    DisplayModePtr ScreenModes;
    
    DEBUG_P("VidModeSetCrtcForMode");

    if ((mode == NULL) || (!VidModeAvailable(scrnIndex)))
	return;

    /* Ugly hack so that the xf86Mode.c function can be used without change */
    pScrn = xf86Screens[scrnIndex];
    ScreenModes = pScrn->modes;
    pScrn->modes = (DisplayModePtr)mode;
    
    xf86SetCrtcForModes(pScrn, pScrn->adjustFlags);
    pScrn->modes = ScreenModes;
    return;
}

Bool
VidModeAddModeline(int scrnIndex, pointer mode)
{
    ScrnInfoPtr pScrn;
    
    DEBUG_P("VidModeAddModeline");

    if ((mode == NULL) || (!VidModeAvailable(scrnIndex)))
	return FALSE;

    pScrn = xf86Screens[scrnIndex];

    ((DisplayModePtr)mode)->name         = strdup(""); /* freed by deletemode */
    ((DisplayModePtr)mode)->status       = MODE_OK;
    ((DisplayModePtr)mode)->next         = pScrn->modes->next;
    ((DisplayModePtr)mode)->prev         = pScrn->modes;
    pScrn->modes->next                   = (DisplayModePtr)mode;
    if( ((DisplayModePtr)mode)->next != NULL )
      ((DisplayModePtr)mode)->next->prev   = (DisplayModePtr)mode;

    return TRUE;
}

int
VidModeGetNumOfModes(int scrnIndex)
{
    pointer mode = NULL;
    int dotClock= 0, nummodes = 0;
  
    DEBUG_P("VidModeGetNumOfModes");

    if (!VidModeGetFirstModeline(scrnIndex, &mode, &dotClock))
	return nummodes;

    do {
	nummodes++;
	if (!VidModeGetNextModeline(scrnIndex, &mode, &dotClock))
	    return nummodes;
    } while (TRUE);
}

Bool
VidModeSetGamma(int scrnIndex, float red, float green, float blue)
{
    ScrnInfoPtr pScrn;
    Gamma gamma;

    DEBUG_P("VidModeSetGamma");

    if (!VidModeAvailable(scrnIndex))
	return FALSE;

    pScrn = xf86Screens[scrnIndex];
    gamma.red = red;
    gamma.green = green;
    gamma.blue = blue;
    if (xf86ChangeGamma(pScrn->pScreen, gamma) != Success)
	return FALSE;
    else
	return TRUE;
}

Bool
VidModeGetGamma(int scrnIndex, float *red, float *green, float *blue)
{
    ScrnInfoPtr pScrn;

    DEBUG_P("VidModeGetGamma");

    if (!VidModeAvailable(scrnIndex))
	return FALSE;

    pScrn = xf86Screens[scrnIndex];
    *red = pScrn->gamma.red;
    *green = pScrn->gamma.green;
    *blue = pScrn->gamma.blue;
    return TRUE;
}

Bool
VidModeSetGammaRamp(int scrnIndex, int size, CARD16 *r, CARD16 *g, CARD16 *b)
{
    ScrnInfoPtr pScrn;

    if (!VidModeAvailable(scrnIndex))
        return FALSE;
 
    pScrn = xf86Screens[scrnIndex];
    xf86ChangeGammaRamp(pScrn->pScreen, size, r, g, b);
    return TRUE;
}

Bool
VidModeGetGammaRamp(int scrnIndex, int size, CARD16 *r, CARD16 *g, CARD16 *b)
{
    ScrnInfoPtr pScrn;

    if (!VidModeAvailable(scrnIndex))
        return FALSE;

    pScrn = xf86Screens[scrnIndex];
    xf86GetGammaRamp(pScrn->pScreen, size, r, g, b);
    return TRUE;
}

int
VidModeGetGammaRampSize(int scrnIndex)
{
    if (!VidModeAvailable(scrnIndex))
        return 0;

    return xf86GetGammaRampSize(xf86Screens[scrnIndex]->pScreen);
}

pointer
VidModeCreateMode(void)
{
    DisplayModePtr mode;
  
    mode = xalloc(sizeof(DisplayModeRec));
    if (mode != NULL) {
	mode->name          = "";
	mode->VScan         = 1;    /* divides refresh rate. default = 1 */
	mode->Private       = NULL;
	mode->next          = mode;
	mode->prev          = mode;
    }
    return mode;
}

void
VidModeCopyMode(pointer modefrom, pointer modeto)
{
  memcpy(modeto, modefrom, sizeof(DisplayModeRec));
}


int
VidModeGetModeValue(pointer mode, int valtyp)
{
  int ret = 0;
  
  switch (valtyp) {
    case VIDMODE_H_DISPLAY:
	ret = ((DisplayModePtr) mode)->HDisplay;
	break;
    case VIDMODE_H_SYNCSTART:
	ret = ((DisplayModePtr)mode)->HSyncStart;
	break;
    case VIDMODE_H_SYNCEND:
	ret = ((DisplayModePtr)mode)->HSyncEnd;
	break;
    case VIDMODE_H_TOTAL:
	ret = ((DisplayModePtr)mode)->HTotal;
	break;
    case VIDMODE_H_SKEW:
	ret = ((DisplayModePtr)mode)->HSkew;
	break;
    case VIDMODE_V_DISPLAY:
	ret = ((DisplayModePtr)mode)->VDisplay;
	break;
    case VIDMODE_V_SYNCSTART:
	ret = ((DisplayModePtr)mode)->VSyncStart;
	break;
    case VIDMODE_V_SYNCEND:
	ret = ((DisplayModePtr)mode)->VSyncEnd;
	break;
    case VIDMODE_V_TOTAL:
	ret = ((DisplayModePtr)mode)->VTotal;
	break;
    case VIDMODE_FLAGS:
	ret = ((DisplayModePtr)mode)->Flags;
	break;
    case VIDMODE_CLOCK:
	ret = ((DisplayModePtr)mode)->Clock;
	break;
  }
  return ret;
}

void
VidModeSetModeValue(pointer mode, int valtyp, int val)
{
  switch (valtyp) {
    case VIDMODE_H_DISPLAY:
	((DisplayModePtr)mode)->HDisplay = val;
	break;
    case VIDMODE_H_SYNCSTART:
	((DisplayModePtr)mode)->HSyncStart = val;
	break;
    case VIDMODE_H_SYNCEND:
	((DisplayModePtr)mode)->HSyncEnd = val;
	break;
    case VIDMODE_H_TOTAL:
	((DisplayModePtr)mode)->HTotal = val;
	break;
    case VIDMODE_H_SKEW:
	((DisplayModePtr)mode)->HSkew = val;
	break;
    case VIDMODE_V_DISPLAY:
	((DisplayModePtr)mode)->VDisplay = val;
	break;
    case VIDMODE_V_SYNCSTART:
	((DisplayModePtr)mode)->VSyncStart = val;
	break;
    case VIDMODE_V_SYNCEND:
	((DisplayModePtr)mode)->VSyncEnd = val;
	break;
    case VIDMODE_V_TOTAL:
	((DisplayModePtr)mode)->VTotal = val;
	break;
    case VIDMODE_FLAGS:
	((DisplayModePtr)mode)->Flags = val;
	break;
    case VIDMODE_CLOCK:
	((DisplayModePtr)mode)->Clock = val;
	break;
  }
  return;
}

vidMonitorValue
VidModeGetMonitorValue(pointer monitor, int valtyp, int indx)
{
  vidMonitorValue ret;
  
  switch (valtyp) {
    case VIDMODE_MON_VENDOR:
	ret.ptr = (((MonPtr)monitor)->vendor);
	break;
    case VIDMODE_MON_MODEL:
	ret.ptr = (((MonPtr)monitor)->model);
	break;
    case VIDMODE_MON_NHSYNC:
	ret.i = ((MonPtr)monitor)->nHsync;
	break;
    case VIDMODE_MON_NVREFRESH:
	ret.i = ((MonPtr)monitor)->nVrefresh;
	break;
    case VIDMODE_MON_HSYNC_LO:
	ret.f = (100.0 * ((MonPtr)monitor)->hsync[indx].lo);
	break;
    case VIDMODE_MON_HSYNC_HI:
	ret.f = (100.0 * ((MonPtr)monitor)->hsync[indx].hi);
	break;
    case VIDMODE_MON_VREFRESH_LO:
	ret.f = (100.0 * ((MonPtr)monitor)->vrefresh[indx].lo);
	break;
    case VIDMODE_MON_VREFRESH_HI:
	ret.f = (100.0 * ((MonPtr)monitor)->vrefresh[indx].hi);
	break;
  }
  return ret;
}


#endif /* XF86VIDMODE */

--- NEW FILE: xf86XKB.c ---
/* $XConsortium: xf86XKB.c /main/4 1996/02/04 09:28:04 kaleb $ */
/************************************************************
Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc.

Permission to use, copy, modify, and distribute this
software and its documentation for any purpose and without
fee is hereby granted, provided that the above copyright
notice appear in all copies and that both that copyright
notice and this permission notice appear in supporting
documentation, and that the name of Silicon Graphics not be 
used in advertising or publicity pertaining to distribution 
of the software without specific prior written permission.
Silicon Graphics makes no representation about the suitability 
of this software for any purpose. It is provided "as is"
without any express or implied warranty.

SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS 
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY 
AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL 
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, 
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE 
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
THE USE OR PERFORMANCE OF THIS SOFTWARE.

********************************************************/
/*
 * Copyright (c) 1994-2002 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86XKB.c,v 3.12 2003/08/24 17:36:55 dawes Exp $ */

#include <stdio.h>
#define	NEED_EVENTS 1
#include <X11/X.h>
#include <X11/Xproto.h>
#include <X11/keysym.h>
#include "inputstr.h"
#include "scrnintstr.h"
#include "windowstr.h"
#include <X11/extensions/XI.h>

#include "compiler.h"

#include "xf86.h"
#include "xf86Priv.h"
#define XF86_OS_PRIVS
#include "xf86_OSlib.h"

#include <X11/extensions/XKBsrv.h>

void
xf86InitXkb(void)
{
}

--- NEW FILE: xf86Xinput.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Xinput.c,v 3.70 2003/11/03 05:11:02 tsi Exp $ */
/*
 * Copyright 1995-1999 by Frederic Lepied, France. <Lepied at XFree86.org>
 *                                                                            
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is  hereby granted without fee, provided that
 * the  above copyright   notice appear  in   all  copies and  that both  that
 * copyright  notice   and   this  permission   notice  appear  in  supporting
 * documentation, and that   the  name of  Frederic   Lepied not  be  used  in
 * advertising or publicity pertaining to distribution of the software without
 * specific,  written      prior  permission.     Frederic  Lepied   makes  no
 * representations about the suitability of this software for any purpose.  It
 * is provided "as is" without express or implied warranty.                   
 *                                                                            
 * FREDERIC  LEPIED DISCLAIMS ALL   WARRANTIES WITH REGARD  TO  THIS SOFTWARE,
 * INCLUDING ALL IMPLIED   WARRANTIES OF MERCHANTABILITY  AND   FITNESS, IN NO
 * EVENT  SHALL FREDERIC  LEPIED BE   LIABLE   FOR ANY  SPECIAL, INDIRECT   OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
 * DATA  OR PROFITS, WHETHER  IN  AN ACTION OF  CONTRACT,  NEGLIGENCE OR OTHER
[...1464 lines suppressed...]
			   max_res);
#endif
}

/*
 * Set the valuator values to be in synch with dix/event.c
 * DefineInitialRootWindow().
 */
void
xf86InitValuatorDefaults(DeviceIntPtr dev, int axnum)
{
#ifdef XINPUT
    if (axnum == 0)
	dev->valuator->axisVal[0] = screenInfo.screens[0]->width / 2;
    else if (axnum == 1)
	dev->valuator->axisVal[1] = screenInfo.screens[0]->height / 2;
#endif
}

/* end of xf86Xinput.c */

--- NEW FILE: xf86Xinput.h ---
/* $XConsortium: xf86Xinput.h /main/11 1996/10/27 11:05:29 kaleb $ */
/*
 * Copyright 1995-1999 by Frederic Lepied, France. <Lepied at XFree86.org>
 *                                                                            
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is  hereby granted without fee, provided that
 * the  above copyright   notice appear  in   all  copies and  that both  that
 * copyright  notice   and   this  permission   notice  appear  in  supporting
 * documentation, and that   the  name of  Frederic   Lepied not  be  used  in
 * advertising or publicity pertaining to distribution of the software without
 * specific,  written      prior  permission.     Frederic  Lepied   makes  no
 * representations about the suitability of this software for any purpose.  It
 * is provided "as is" without express or implied warranty.                   
 *                                                                            
 * FREDERIC  LEPIED DISCLAIMS ALL   WARRANTIES WITH REGARD  TO  THIS SOFTWARE,
 * INCLUDING ALL IMPLIED   WARRANTIES OF MERCHANTABILITY  AND   FITNESS, IN NO
 * EVENT  SHALL FREDERIC  LEPIED BE   LIABLE   FOR ANY  SPECIAL, INDIRECT   OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
 * DATA  OR PROFITS, WHETHER  IN  AN ACTION OF  CONTRACT,  NEGLIGENCE OR OTHER
 * TORTIOUS  ACTION, ARISING    OUT OF OR   IN  CONNECTION  WITH THE USE    OR
 * PERFORMANCE OF THIS SOFTWARE.
 *
 */

/*
 * Copyright (c) 2000-2002 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86Xinput.h,v 3.36 2003/08/24 17:36:55 dawes Exp $ */

#ifndef _xf86Xinput_h
#define _xf86Xinput_h

#ifndef NEED_EVENTS
#define NEED_EVENTS
#endif
#include "xf86str.h"
#include "inputstr.h"
#ifdef XINPUT
#include <X11/extensions/XI.h>
#include <X11/extensions/XIproto.h>
#include "XIstubs.h"
#endif

/* Input device flags */
#define XI86_OPEN_ON_INIT       0x01 /* open the device at startup time */
#define XI86_CONFIGURED         0x02 /* the device has been configured */
#define XI86_ALWAYS_CORE	0x04 /* device always controls the pointer */
/* the device sends Xinput and core pointer events */
#define XI86_SEND_CORE_EVENTS	XI86_ALWAYS_CORE
/* if the device is the core pointer or is sending core events, and
 * SEND_DRAG_EVENTS is false, and a buttons is done, then no motion events
 * (mouse drag action) are sent. This is mainly to allow a touch screen to be
 * used with netscape and other browsers which do strange things if the mouse
 * moves between button down and button up. With a touch screen, this motion
 * is common due to the user's finger moving slightly.
 */
#define XI86_SEND_DRAG_EVENTS	0x08
#define XI86_CORE_POINTER	0x10 /* device is the core pointer */
#define XI86_CORE_KEYBOARD	0x20 /* device is the core keyboard */
#define XI86_POINTER_CAPABLE	0x40 /* capable of being a core pointer */
#define XI86_KEYBOARD_CAPABLE	0x80 /* capable of being a core keyboard */

#define XI_PRIVATE(dev) \
	(((LocalDevicePtr)((dev)->public.devicePrivate))->private)

#ifdef DBG
#undef DBG
#endif
#define DBG(lvl, f) {if ((lvl) <= xf86GetVerbosity()) f;}

#ifdef HAS_MOTION_HISTORY
#undef HAS_MOTION_HISTORY
#endif
#define HAS_MOTION_HISTORY(local) ((local)->dev->valuator && (local)->dev->valuator->numMotionEvents)

#ifdef XINPUT
/* This holds the input driver entry and module information. */
typedef struct _InputDriverRec {
    int			    driverVersion;
    char *		    driverName;
    void		    (*Identify)(int flags);
    struct _LocalDeviceRec *(*PreInit)(struct _InputDriverRec *drv,
				       IDevPtr dev, int flags);
    void		    (*UnInit)(struct _InputDriverRec *drv,
				      struct _LocalDeviceRec *pInfo,
				      int flags);
    pointer		    module;
    int			    refCount;
} InputDriverRec, *InputDriverPtr;
#endif

/* This is to input devices what the ScrnInfoRec is to screens. */

typedef struct _LocalDeviceRec {
    struct _LocalDeviceRec *next;
    char *		    name;
    int			    flags;
    
    Bool		    (*device_control)(DeviceIntPtr device, int what);
    void		    (*read_input)(struct _LocalDeviceRec *local);
    int			    (*control_proc)(struct _LocalDeviceRec *local,
					   xDeviceCtl *control);
    void		    (*close_proc)(struct _LocalDeviceRec *local);
    int			    (*switch_mode)(ClientPtr client, DeviceIntPtr dev,
					  int mode);
    Bool		    (*conversion_proc)(struct _LocalDeviceRec *local,
					      int first, int num, int v0,
					      int v1, int v2, int v3, int v4,
					      int v5, int *x, int *y);
    Bool		    (*reverse_conversion_proc)(
					struct _LocalDeviceRec *local,
					int x, int y, int *valuators);
    
    int			    fd;
    Atom		    atom;
    DeviceIntPtr	    dev;
    pointer		    private;
    int			    private_flags;
    pointer		    motion_history;
    ValuatorMotionProcPtr   motion_history_proc;
    unsigned int	    history_size;   /* only for configuration purpose */
    unsigned int	    first;
    unsigned int	    last;
    int			    old_x;
    int			    old_y;
    float		    dxremaind;
    float		    dyremaind;
    char *		    type_name;
    IntegerFeedbackPtr	    always_core_feedback;
    IDevPtr		    conf_idev;
    InputDriverPtr	    drv;
    pointer		    module;
    pointer		    options;
} LocalDeviceRec, *LocalDevicePtr, InputInfoRec, *InputInfoPtr;

typedef struct _DeviceAssocRec 
{
    char *		    config_section_name;
    LocalDevicePtr	    (*device_allocate)(void);
} DeviceAssocRec, *DeviceAssocPtr;

/* xf86Globals.c */
extern InputInfoPtr xf86InputDevs;

/* xf86Xinput.c */
int xf86IsCorePointer(DeviceIntPtr dev);
int xf86IsCoreKeyboard(DeviceIntPtr dev);
void xf86XInputSetSendCoreEvents(LocalDevicePtr local, Bool always);
#define xf86AlwaysCore(a,b) xf86XInputSetSendCoreEvents(a,b)

void InitExtInput(void);
Bool xf86eqInit(DevicePtr pKbd, DevicePtr pPtr);
void xf86eqEnqueue(struct _xEvent *event);
void xf86eqProcessInputEvents (void);
void xf86eqSwitchScreen(ScreenPtr pScreen, Bool fromDIX);
void xf86PostMotionEvent(DeviceIntPtr device, int is_absolute,
			 int first_valuator, int num_valuators, ...);
void xf86PostProximityEvent(DeviceIntPtr device, int is_in,
			    int first_valuator, int num_valuators, ...);
void xf86PostButtonEvent(DeviceIntPtr device, int is_absolute, int button,
		    	 int is_down, int first_valuator, int num_valuators,
			 ...);
void xf86PostKeyEvent(DeviceIntPtr device, unsigned int key_code, int is_down,
		      int is_absolute, int first_valuator, int num_valuators,
		      ...);
void xf86PostKeyboardEvent(DeviceIntPtr device, unsigned int key_code,
                           int is_down);
void xf86MotionHistoryAllocate(LocalDevicePtr local);
int xf86GetMotionEvents(DeviceIntPtr dev, xTimecoord *buff,
			unsigned long start, unsigned long stop,
			ScreenPtr pScreen);
void xf86XinputFinalizeInit(DeviceIntPtr dev);
Bool xf86CheckButton(int button, int down);
void xf86SwitchCoreDevice(LocalDevicePtr device, DeviceIntPtr core);
LocalDevicePtr xf86FirstLocalDevice(void);
int xf86ScaleAxis(int Cx, int Sxhigh, int Sxlow, int Rxhigh, int Rxlow);
void xf86XInputSetScreen(LocalDevicePtr local, int screen_number, int x, int y);
void xf86ProcessCommonOptions(InputInfoPtr pInfo, pointer options);
void xf86InitValuatorAxisStruct(DeviceIntPtr dev, int axnum, int minval,
				int maxval, int resolution, int min_res,
				int max_res);
void xf86InitValuatorDefaults(DeviceIntPtr dev, int axnum);
void xf86AddEnabledDevice(InputInfoPtr pInfo);
void xf86RemoveEnabledDevice(InputInfoPtr pInfo);

/* xf86Helper.c */
void xf86AddInputDriver(InputDriverPtr driver, pointer module, int flags);
void xf86DeleteInputDriver(int drvIndex);
InputInfoPtr xf86AllocateInput(InputDriverPtr drv, int flags);
void xf86DeleteInput(InputInfoPtr pInp, int flags);

/* xf86Option.c */
void xf86CollectInputOptions(InputInfoPtr pInfo, const char **defaultOpts,
			     pointer extraOpts);

#endif /* _xf86Xinput_h */

--- NEW FILE: xf86bigfont.c ---
/* $XFree86: xc/programs/Xserver/Xext/xf86bigfont.c,v 1.17 2003/10/28 23:08:43 tsi Exp $ */
/*
 * BIGFONT extension for sharing font metrics between clients (if possible)
 * and for transmitting font metrics to clients in a compressed form.
 *
 * Copyright (c) 1999-2000  Bruno Haible
 * Copyright (c) 1999-2000  The XFree86 Project, Inc.
 */

/* THIS IS NOT AN X CONSORTIUM STANDARD */

/*
 * Big fonts suffer from the following: All clients that have opened a
 * font can access the complete glyph metrics array (the XFontStruct member
 * `per_char') directly, without going through a macro. Moreover these
 * glyph metrics are ink metrics, i.e. are not redundant even for a
 * fixed-width font. For a Unicode font, the size of this array is 768 KB.
 *
 * Problems: 1. It eats a lot of memory in each client. 2. All this glyph
 * metrics data is piped through the socket when the font is opened.
 *
 * This extension addresses these two problems for local clients, by using
 * shared memory. It also addresses the second problem for non-local clients,
 * by compressing the data before transmit by a factor of nearly 6.
 *
 * If you use this extension, your OS ought to nicely support shared memory.
 * This means: Shared memory should be swappable to the swap, and the limits
 * should be high enough (SHMMNI at least 64, SHMMAX at least 768 KB,
 * SHMALL at least 48 MB). It is a plus if your OS allows shmat() calls
 * on segments that have already been marked "removed", because it permits
 * these segments to be cleaned up by the OS if the X server is killed with
 * signal SIGKILL.
 *
 * This extension is transparently exploited by Xlib (functions XQueryFont,
 * XLoadQueryFont).
 */

#include <sys/types.h>
#ifdef HAS_SHM
#if defined(linux) && (!defined(__GNU_LIBRARY__) || __GNU_LIBRARY__ < 2)
/* libc4 does not define __GNU_LIBRARY__, libc5 defines __GNU_LIBRARY__ as 1 */
/* Linux libc4 and libc5 only (because glibc doesn't include kernel headers):
   Linux 2.0.x and 2.2.x define SHMLBA as PAGE_SIZE, but forget to define
   PAGE_SIZE. It is defined in <asm/page.h>. */
#include <asm/page.h>
#endif
#ifdef SVR4
#include <sys/sysmacros.h>
#endif
#if defined(ISC) || defined(__CYGWIN__) || defined(SCO) || defined(SCO325)
#include <sys/param.h>
#include <sys/sysmacros.h>
#endif
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>
#endif

#include <X11/X.h>
#include <X11/Xproto.h>
#include "misc.h"
#include "os.h"
#include "dixstruct.h"
#include "gcstruct.h"
#include "dixfontstr.h"
#include "extnsionst.h"

#define _XF86BIGFONT_SERVER_
#include <X11/extensions/xf86bigfstr.h>

static void XF86BigfontResetProc(
    ExtensionEntry *	/* extEntry */
    );

static DISPATCH_PROC(ProcXF86BigfontDispatch);
static DISPATCH_PROC(ProcXF86BigfontQueryVersion);
static DISPATCH_PROC(ProcXF86BigfontQueryFont);
static DISPATCH_PROC(SProcXF86BigfontDispatch);
static DISPATCH_PROC(SProcXF86BigfontQueryVersion);
static DISPATCH_PROC(SProcXF86BigfontQueryFont);

#if 0
static unsigned char XF86BigfontReqCode;
#endif

#ifdef HAS_SHM

/* A random signature, transmitted to the clients so they can verify that the
   shared memory segment they are attaching to was really established by the
   X server they are talking to. */
static CARD32 signature;

/* Index for additional information stored in a FontRec's devPrivates array. */
static int FontShmdescIndex;

static unsigned int pagesize;

#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__CYGWIN__)

#include <sys/signal.h>

static Bool badSysCall = FALSE;

static void
SigSysHandler(
     int signo)
{
    badSysCall = TRUE;
}

static Bool
CheckForShmSyscall(void)
{
    void (*oldHandler)(int);
    int shmid = -1;

    /* If no SHM support in the kernel, the bad syscall will generate SIGSYS */
    oldHandler = signal(SIGSYS, SigSysHandler);

    badSysCall = FALSE;
    shmid = shmget(IPC_PRIVATE, 4096, IPC_CREAT);
    if (shmid != -1)
    {
        /* Successful allocation - clean up */
	shmctl(shmid, IPC_RMID, (struct shmid_ds *)NULL);
    }
    else
    {
        /* Allocation failed */
        badSysCall = TRUE;
    }
    signal(SIGSYS, oldHandler);
    return (!badSysCall);
}

#define MUST_CHECK_FOR_SHM_SYSCALL

#endif

#endif

void
XFree86BigfontExtensionInit()
{
#if 0
    ExtensionEntry* extEntry;

    if ((extEntry = AddExtension(XF86BIGFONTNAME,
				 XF86BigfontNumberEvents,
				 XF86BigfontNumberErrors,
				 ProcXF86BigfontDispatch,
				 SProcXF86BigfontDispatch,
				 XF86BigfontResetProc,
				 StandardMinorOpcode))) {
	XF86BigfontReqCode = (unsigned char) extEntry->base;
#else
    if (AddExtension(XF86BIGFONTNAME,
		     XF86BigfontNumberEvents,
		     XF86BigfontNumberErrors,
		     ProcXF86BigfontDispatch,
		     SProcXF86BigfontDispatch,
		     XF86BigfontResetProc,
		     StandardMinorOpcode)) {
#endif
#ifdef HAS_SHM
#ifdef MUST_CHECK_FOR_SHM_SYSCALL
	/*
	 * Note: Local-clients will not be optimized without shared memory
	 * support. Remote-client optimization does not depend on shared
	 * memory support.  Thus, the extension is still registered even
	 * when shared memory support is not functional.  
	 */
	if (!CheckForShmSyscall()) {
	    ErrorF(XF86BIGFONTNAME " extension local-client optimization disabled due to lack of shared memory support in the kernel\n");
	    return;
	}
#endif

	srand((unsigned int) time(NULL));
	signature = ((unsigned int) (65536.0/(RAND_MAX+1.0) * rand()) << 16)
	           + (unsigned int) (65536.0/(RAND_MAX+1.0) * rand());
	/* fprintf(stderr, "signature = 0x%08X\n", signature); */

	FontShmdescIndex = AllocateFontPrivateIndex();

#if !defined(CSRG_BASED) && !defined(__CYGWIN__)
	pagesize = SHMLBA;
#else
# ifdef _SC_PAGESIZE
	pagesize = sysconf(_SC_PAGESIZE);
# else
	pagesize = getpagesize();
# endif
#endif
#endif
    }
}


/* ========== Management of shared memory segments ========== */

#ifdef HAS_SHM

#ifdef __linux__
/* On Linux, shared memory marked as "removed" can still be attached.
   Nice feature, because the kernel will automatically free the associated
   storage when the server and all clients are gone. */
#define EARLY_REMOVE
#endif

typedef struct _ShmDesc {
    struct _ShmDesc *next;
    struct _ShmDesc **prev;
    int shmid;
    char *attach_addr;
} ShmDescRec, *ShmDescPtr;

static ShmDescPtr ShmList = (ShmDescPtr) NULL;

static ShmDescPtr
shmalloc(
    unsigned int size)
{
    ShmDescPtr pDesc;
    int shmid;
    char *addr;

#ifdef MUST_CHECK_FOR_SHM_SYSCALL
    if (pagesize == 0)
	return (ShmDescPtr) NULL;
#endif

    /* On some older Linux systems, the number of shared memory segments
       system-wide is 127. In Linux 2.4, it is 4095.
       Therefore there is a tradeoff to be made between allocating a
       shared memory segment on one hand, and allocating memory and piping
       the glyph metrics on the other hand. If the glyph metrics size is
       small, we prefer the traditional way. */
    if (size < 3500)
	return (ShmDescPtr) NULL;

    pDesc = (ShmDescRec *) xalloc(sizeof(ShmDescRec));
    if (!pDesc)
	return (ShmDescPtr) NULL;

    size = (size + pagesize-1) & -pagesize;
    shmid = shmget(IPC_PRIVATE, size, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);
    if (shmid == -1) {
	ErrorF(XF86BIGFONTNAME " extension: shmget() failed, size = %u, errno = %d\n",
	       size, errno);
	xfree(pDesc);
	return (ShmDescPtr) NULL;
    }

    if ((addr = shmat(shmid, 0, 0)) == (char *)-1) {
	ErrorF(XF86BIGFONTNAME " extension: shmat() failed, size = %u, errno = %d\n",
	       size, errno);
	shmctl(shmid, IPC_RMID, (void *) 0);
	xfree(pDesc);
	return (ShmDescPtr) NULL;
    }

#ifdef EARLY_REMOVE
    shmctl(shmid, IPC_RMID, (void *) 0);
#endif

    pDesc->shmid = shmid;
    pDesc->attach_addr = addr;
    if (ShmList) ShmList->prev = &pDesc->next;
    pDesc->next = ShmList;
    pDesc->prev = &ShmList;
    ShmList = pDesc;

    return pDesc;
}

static void
shmdealloc(
    ShmDescPtr pDesc)
{
#ifndef EARLY_REMOVE
    shmctl(pDesc->shmid, IPC_RMID, (void *) 0);
#endif
    shmdt(pDesc->attach_addr);

    if (pDesc->next) pDesc->next->prev = pDesc->prev;
    *pDesc->prev = pDesc->next;
    xfree(pDesc);
}

#endif

/* Called when a font is closed. */
void
XF86BigfontFreeFontShm(
    FontPtr pFont)
{
#ifdef HAS_SHM
    ShmDescPtr pDesc;

    /* If during shutdown of the server, XF86BigfontCleanup() has already
     * called shmdealloc() for all segments, we don't need to do it here.
     */
    if (!ShmList)
	return;

    pDesc = (ShmDescPtr) FontGetPrivate(pFont, FontShmdescIndex);
    if (pDesc)
	shmdealloc(pDesc);
#endif
}

/* Called upon fatal signal. */
void
XF86BigfontCleanup()
{
#ifdef HAS_SHM
    while (ShmList)
	shmdealloc(ShmList);
#endif
}

/* Called when a server generation dies. */
static void
XF86BigfontResetProc(
    ExtensionEntry* extEntry)
{
    /* This function is normally called from CloseDownExtensions(), called
     * from main(). It will be followed by a call to FreeAllResources(),
     * which will call XF86BigfontFreeFontShm() for each font. Thus it
     * appears that we do not need to do anything in this function. --
     * But I prefer to write robust code, and not keep shared memory lying
     * around when it's not needed any more. (Someone might close down the
     * extension without calling FreeAllResources()...)
     */
    XF86BigfontCleanup();
}


/* ========== Handling of extension specific requests ========== */

static int
ProcXF86BigfontQueryVersion(
    ClientPtr client)
{
    xXF86BigfontQueryVersionReply reply;

    REQUEST_SIZE_MATCH(xXF86BigfontQueryVersionReq);
    reply.type = X_Reply;
    reply.length = 0;
    reply.sequenceNumber = client->sequence;
    reply.majorVersion = XF86BIGFONT_MAJOR_VERSION;
    reply.minorVersion = XF86BIGFONT_MINOR_VERSION;
    reply.uid = geteuid();
    reply.gid = getegid();
#ifdef HAS_SHM
    reply.signature = signature;
#else
    reply.signature = 0; /* This is redundant. Avoids uninitialized memory. */
#endif
    reply.capabilities =
#ifdef HAS_SHM
	(LocalClient(client) && !client->swapped ? XF86Bigfont_CAP_LocalShm : 0)
#else
	0
#endif
	; /* may add more bits here in future versions */
    if (client->swapped) {
	char tmp;
	swaps(&reply.sequenceNumber, tmp);
	swapl(&reply.length, tmp);
	swaps(&reply.majorVersion, tmp);
	swaps(&reply.minorVersion, tmp);
	swapl(&reply.uid, tmp);
	swapl(&reply.gid, tmp);
	swapl(&reply.signature, tmp);
    }
    WriteToClient(client,
		  sizeof(xXF86BigfontQueryVersionReply), (char *)&reply);
    return client->noClientException;
}

static void
swapCharInfo(
    xCharInfo *pCI)
{
    char tmp;

    swaps(&pCI->leftSideBearing, tmp);
    swaps(&pCI->rightSideBearing, tmp);
    swaps(&pCI->characterWidth, tmp);
    swaps(&pCI->ascent, tmp);
    swaps(&pCI->descent, tmp);
    swaps(&pCI->attributes, tmp);
}

/* static CARD32 hashCI (xCharInfo *p); */
#define hashCI(p) \
	(CARD32)(((p->leftSideBearing << 27) + (p->leftSideBearing >> 5) + \
	          (p->rightSideBearing << 23) + (p->rightSideBearing >> 9) + \
	          (p->characterWidth << 16) + \
	          (p->ascent << 11) + (p->descent << 6)) ^ p->attributes)

static int
ProcXF86BigfontQueryFont(
    ClientPtr client)
{
    FontPtr pFont;
    REQUEST(xXF86BigfontQueryFontReq);
    CARD32 stuff_flags;
    xCharInfo* pmax;
    xCharInfo* pmin;
    int nCharInfos;
    int shmid;
#ifdef HAS_SHM
    ShmDescPtr pDesc;
#else
#define pDesc 0
#endif
    xCharInfo* pCI;
    CARD16* pIndex2UniqIndex;
    CARD16* pUniqIndex2Index;
    CARD32 nUniqCharInfos;

#if 0
    REQUEST_SIZE_MATCH(xXF86BigfontQueryFontReq);
#else
    switch (client->req_len) {
	case 2: /* client with version 1.0 libX11 */
	    stuff_flags = (LocalClient(client) && !client->swapped ? XF86Bigfont_FLAGS_Shm : 0);
	    break;
	case 3: /* client with version 1.1 libX11 */
	    stuff_flags = stuff->flags;
	    break;
	default:
	    return BadLength;
    }
#endif
    client->errorValue = stuff->id;		/* EITHER font or gc */
    pFont = (FontPtr)SecurityLookupIDByType(client, stuff->id, RT_FONT,
					    SecurityReadAccess);
    if (!pFont) {
	/* can't use VERIFY_GC because it might return BadGC */
	GC *pGC = (GC *) SecurityLookupIDByType(client, stuff->id, RT_GC,
						SecurityReadAccess);
        if (!pGC) {
	    client->errorValue = stuff->id;
            return BadFont;    /* procotol spec says only error is BadFont */
	}
	pFont = pGC->font;
    }

    pmax = FONTINKMAX(pFont);
    pmin = FONTINKMIN(pFont);
    nCharInfos =
       (pmax->rightSideBearing == pmin->rightSideBearing
        && pmax->leftSideBearing == pmin->leftSideBearing
        && pmax->descent == pmin->descent
        && pmax->ascent == pmin->ascent
        && pmax->characterWidth == pmin->characterWidth)
       ? 0 : N2dChars(pFont);
    shmid = -1;
    pCI = NULL;
    pIndex2UniqIndex = NULL;
    pUniqIndex2Index = NULL;
    nUniqCharInfos = 0;

    if (nCharInfos > 0) {
#ifdef HAS_SHM
	pDesc = (ShmDescPtr) FontGetPrivate(pFont, FontShmdescIndex);
	if (pDesc) {
	    pCI = (xCharInfo *) pDesc->attach_addr;
	    if (stuff_flags & XF86Bigfont_FLAGS_Shm)
		shmid = pDesc->shmid;
	} else {
	    if (stuff_flags & XF86Bigfont_FLAGS_Shm)
		pDesc = shmalloc(nCharInfos * sizeof(xCharInfo)
				 + sizeof(CARD32));
	    if (pDesc) {
		pCI = (xCharInfo *) pDesc->attach_addr;
		shmid = pDesc->shmid;
	    } else {
#endif
		pCI = (xCharInfo *)
		      ALLOCATE_LOCAL(nCharInfos * sizeof(xCharInfo));
		if (!pCI)
		    return BadAlloc;
#ifdef HAS_SHM
	    }
#endif
	    /* Fill nCharInfos starting at pCI. */
	    {
		xCharInfo* prCI = pCI;
		int ninfos = 0;
		int ncols = pFont->info.lastCol - pFont->info.firstCol + 1;
		int row;
		for (row = pFont->info.firstRow;
		     row <= pFont->info.lastRow && ninfos < nCharInfos;
		     row++) {
		    unsigned char chars[512];
		    xCharInfo* tmpCharInfos[256];
		    unsigned long count;
		    int col;
		    unsigned long i;
		    i = 0;
		    for (col = pFont->info.firstCol;
			 col <= pFont->info.lastCol;
			 col++) {
			chars[i++] = row;
			chars[i++] = col;
		    }
		    (*pFont->get_metrics) (pFont, ncols, chars, TwoD16Bit,
					   &count, tmpCharInfos);
		    for (i = 0; i < count && ninfos < nCharInfos; i++) {
			*prCI++ = *tmpCharInfos[i];
			ninfos++;
		    }
		}
	    }
#ifdef HAS_SHM
	    if (pDesc) {
		*(CARD32 *)(pCI + nCharInfos) = signature;
		if (!FontSetPrivate(pFont, FontShmdescIndex, pDesc)) {
		    shmdealloc(pDesc);
		    return BadAlloc;
		}
	    }
	}
#endif
	if (shmid == -1) {
	    /* Cannot use shared memory, so remove-duplicates the xCharInfos
	       using a temporary hash table. */
	    /* Note that CARD16 is suitable as index type, because
	       nCharInfos <= 0x10000. */
	    CARD32 hashModulus;
	    CARD16* pHash2UniqIndex;
	    CARD16* pUniqIndex2NextUniqIndex;
	    CARD32 NextIndex;
	    CARD32 NextUniqIndex;
	    CARD16* tmp;
	    CARD32 i, j;

	    hashModulus = 67;
	    if (hashModulus > nCharInfos+1)
		hashModulus = nCharInfos+1;

	    tmp = (CARD16*)
		  ALLOCATE_LOCAL((4*nCharInfos+1) * sizeof(CARD16));
	    if (!tmp) {
		if (!pDesc) DEALLOCATE_LOCAL(pCI);
		return BadAlloc;
	    }
	    pIndex2UniqIndex = tmp;
		/* nCharInfos elements */
	    pUniqIndex2Index = tmp + nCharInfos;
		/* max. nCharInfos elements */
	    pUniqIndex2NextUniqIndex = tmp + 2*nCharInfos;
		/* max. nCharInfos elements */
	    pHash2UniqIndex = tmp + 3*nCharInfos;
		/* hashModulus (<= nCharInfos+1) elements */

	    /* Note that we can use 0xffff as end-of-list indicator, because
	       even if nCharInfos = 0x10000, 0xffff can not occur as valid
	       entry before the last element has been inserted. And once the
	       last element has been inserted, we don't need the hash table
	       any more. */
	    for (j = 0; j < hashModulus; j++)
		pHash2UniqIndex[j] = (CARD16)(-1);

	    NextUniqIndex = 0;
	    for (NextIndex = 0; NextIndex < nCharInfos; NextIndex++) {
		xCharInfo* p = &pCI[NextIndex];
		CARD32 hashCode = hashCI(p) % hashModulus;
		for (i = pHash2UniqIndex[hashCode];
		     i != (CARD16)(-1);
		     i = pUniqIndex2NextUniqIndex[i]) {
		    j = pUniqIndex2Index[i];
		    if (pCI[j].leftSideBearing == p->leftSideBearing
			&& pCI[j].rightSideBearing == p->rightSideBearing
			&& pCI[j].characterWidth == p->characterWidth
			&& pCI[j].ascent == p->ascent
			&& pCI[j].descent == p->descent
			&& pCI[j].attributes == p->attributes)
			break;
		}
		if (i != (CARD16)(-1)) {
		    /* Found *p at Index j, UniqIndex i */
		    pIndex2UniqIndex[NextIndex] = i;
		} else {
		    /* Allocate a new entry in the Uniq table */
		    if (hashModulus <= 2*NextUniqIndex
			&& hashModulus < nCharInfos+1) {
			/* Time to increate hash table size */
			hashModulus = 2*hashModulus+1;
			if (hashModulus > nCharInfos+1)
			    hashModulus = nCharInfos+1;
			for (j = 0; j < hashModulus; j++)
			    pHash2UniqIndex[j] = (CARD16)(-1);
			for (i = 0; i < NextUniqIndex; i++)
			    pUniqIndex2NextUniqIndex[i] = (CARD16)(-1);
			for (i = 0; i < NextUniqIndex; i++) {
			    j = pUniqIndex2Index[i];
			    p = &pCI[j];
			    hashCode = hashCI(p) % hashModulus;
			    pUniqIndex2NextUniqIndex[i] = pHash2UniqIndex[hashCode];
			    pHash2UniqIndex[hashCode] = i;
			}
			p = &pCI[NextIndex];
			hashCode = hashCI(p) % hashModulus;
		    }
		    i = NextUniqIndex++;
		    pUniqIndex2NextUniqIndex[i] = pHash2UniqIndex[hashCode];
		    pHash2UniqIndex[hashCode] = i;
		    pUniqIndex2Index[i] = NextIndex;
		    pIndex2UniqIndex[NextIndex] = i;
		}
	    }
	    nUniqCharInfos = NextUniqIndex;
	    /* fprintf(stderr, "font metrics: nCharInfos = %d, nUniqCharInfos = %d, hashModulus = %d\n", nCharInfos, nUniqCharInfos, hashModulus); */
	}
    }

    {
	int nfontprops = pFont->info.nprops;
	int rlength =
	   sizeof(xXF86BigfontQueryFontReply)
	   + nfontprops * sizeof(xFontProp)
	   + (nCharInfos > 0 && shmid == -1
	      ? nUniqCharInfos * sizeof(xCharInfo)
	        + (nCharInfos+1)/2 * 2 * sizeof(CARD16)
	      : 0);
	xXF86BigfontQueryFontReply* reply =
	   (xXF86BigfontQueryFontReply *) ALLOCATE_LOCAL(rlength);
	char* p;
	if (!reply) {
	    if (nCharInfos > 0) {
		if (shmid == -1) DEALLOCATE_LOCAL(pIndex2UniqIndex);
		if (!pDesc) DEALLOCATE_LOCAL(pCI);
	    }
	    return BadAlloc;
	}
	reply->type = X_Reply;
	reply->length = (rlength - sizeof(xGenericReply)) >> 2;
	reply->sequenceNumber = client->sequence;
	reply->minBounds = pFont->info.ink_minbounds;
	reply->maxBounds = pFont->info.ink_maxbounds;
	reply->minCharOrByte2 = pFont->info.firstCol;
	reply->maxCharOrByte2 = pFont->info.lastCol;
	reply->defaultChar = pFont->info.defaultCh;
	reply->nFontProps = pFont->info.nprops;
	reply->drawDirection = pFont->info.drawDirection;
	reply->minByte1 = pFont->info.firstRow;
	reply->maxByte1 = pFont->info.lastRow;
	reply->allCharsExist = pFont->info.allExist;
	reply->fontAscent = pFont->info.fontAscent;
	reply->fontDescent = pFont->info.fontDescent;
	reply->nCharInfos = nCharInfos;
        reply->nUniqCharInfos = nUniqCharInfos;
	reply->shmid = shmid;
	reply->shmsegoffset = 0;
	if (client->swapped) {
	    char tmp;
	    swaps(&reply->sequenceNumber, tmp);
	    swapl(&reply->length, tmp);
	    swapCharInfo(&reply->minBounds);
	    swapCharInfo(&reply->maxBounds);
	    swaps(&reply->minCharOrByte2, tmp);
	    swaps(&reply->maxCharOrByte2, tmp);
	    swaps(&reply->defaultChar, tmp);
	    swaps(&reply->nFontProps, tmp);
	    swaps(&reply->fontAscent, tmp);
	    swaps(&reply->fontDescent, tmp);
	    swapl(&reply->nCharInfos, tmp);
	    swapl(&reply->nUniqCharInfos, tmp);
	    swapl(&reply->shmid, tmp);
	    swapl(&reply->shmsegoffset, tmp);
	}
	p = (char*) &reply[1];
	{
	    FontPropPtr pFP;
	    xFontProp* prFP;
	    int i;
	    for (i = 0, pFP = pFont->info.props, prFP = (xFontProp *) p;
		 i < nfontprops;
		 i++, pFP++, prFP++) {
		prFP->name = pFP->name;
		prFP->value = pFP->value;
		if (client->swapped) {
		    char tmp;
		    swapl(&prFP->name, tmp);
		    swapl(&prFP->value, tmp);
		}
	    }
	    p = (char*) prFP;
	}
	if (nCharInfos > 0 && shmid == -1) {
	    xCharInfo* pci;
	    CARD16* ps;
	    int i, j;
	    pci = (xCharInfo*) p;
	    for (i = 0; i < nUniqCharInfos; i++, pci++) {
		*pci = pCI[pUniqIndex2Index[i]];
		if (client->swapped)
		    swapCharInfo(pci);
	    }
	    ps = (CARD16*) pci;
	    for (j = 0; j < nCharInfos; j++, ps++) {
		*ps = pIndex2UniqIndex[j];
		if (client->swapped) {
		    char tmp;
		    swaps(ps, tmp);
		}
	    }
	}
	WriteToClient(client, rlength, (char *)reply);
	DEALLOCATE_LOCAL(reply);
	if (nCharInfos > 0) {
	    if (shmid == -1) DEALLOCATE_LOCAL(pIndex2UniqIndex);
	    if (!pDesc) DEALLOCATE_LOCAL(pCI);
	}
	return (client->noClientException);
    }
}

static int
ProcXF86BigfontDispatch(
    ClientPtr client)
{
    REQUEST(xReq);

    switch (stuff->data) {
	case X_XF86BigfontQueryVersion:
	    return ProcXF86BigfontQueryVersion(client);
	case X_XF86BigfontQueryFont:
	    return ProcXF86BigfontQueryFont(client);
	default:
	    return BadRequest;
    }
}

static int
SProcXF86BigfontQueryVersion(
    ClientPtr client)
{
    REQUEST(xXF86BigfontQueryVersionReq);
    char tmp;

    swaps(&stuff->length, tmp);
    return ProcXF86BigfontQueryVersion(client);
}

static int
SProcXF86BigfontQueryFont(
    ClientPtr client)
{
    REQUEST(xXF86BigfontQueryFontReq);
    char tmp;

    swaps(&stuff->length, tmp);
    REQUEST_SIZE_MATCH(xXF86BigfontQueryFontReq);
    swapl(&stuff->id, tmp);
    return ProcXF86BigfontQueryFont(client);
}

static int
SProcXF86BigfontDispatch(
    ClientPtr client)
{
    REQUEST(xReq);

    switch (stuff->data) {
	case X_XF86BigfontQueryVersion:
	    return SProcXF86BigfontQueryVersion(client);
	case X_XF86BigfontQueryFont:
	    return SProcXF86BigfontQueryFont(client);
	default:
	    return BadRequest;
    }
}

--- NEW FILE: xf86cmap.c ---
/* $XdotOrg: xc/programs/Xserver/hw/xfree86/common/xf86cmap.c,v 1.1.4.2 2004/02/16 20:19:59 alanc Exp $ */
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86cmap.c,v 1.25 2003/10/17 20:02:12 alanh Exp $ */
/*
 * Copyright (c) 1998-2001 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
[...1071 lines suppressed...]
	}
	red++; green++; blue++;
        entry++;
    }

    return Success;
}

int
xf86ChangeGamma(
   ScreenPtr pScreen,
   Gamma gamma
){
    ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];

    if(pScrn->ChangeGamma)
	return (*pScrn->ChangeGamma)(pScreen->myNum, gamma);

    return Success; /* Success? */
}

--- NEW FILE: xf86cmap.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86cmap.h,v 1.9 2003/10/17 20:02:12 alanh Exp $ */

/*
 * Copyright (c) 1998-2001 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

#ifndef _XF86CMAP_H
#define _XF86CMAP_H

#include "xf86str.h"
#include "colormapst.h"

#define CMAP_PALETTED_TRUECOLOR		0x0000001
#define CMAP_RELOAD_ON_MODE_SWITCH	0x0000002
#define CMAP_LOAD_EVEN_IF_OFFSCREEN	0x0000004

Bool xf86HandleColormaps(
    ScreenPtr pScreen,
    int maxCol,
    int sigRGBbits,
    xf86LoadPaletteProc *loadPalette,
    xf86SetOverscanProc *setOverscan,
    unsigned int flags
);

int
xf86ChangeGamma(
   ScreenPtr pScreen,
   Gamma newGamma
);

int
xf86ChangeGammaRamp(
   ScreenPtr pScreen,
   int size,
   unsigned short *red,
   unsigned short *green,
   unsigned short *blue
);

int xf86GetGammaRampSize(ScreenPtr pScreen);

int
xf86GetGammaRamp(
   ScreenPtr pScreen,
   int size,
   unsigned short *red,
   unsigned short *green,
   unsigned short *blue
);

#endif /* _XF86CMAP_H */


--- NEW FILE: xf86dga.c ---
/* $XFree86: xc/programs/Xserver/Xext/xf86dga.c,v 3.21 2000/06/30 19:06:54 keithp Exp $ */

/*

Copyright (c) 1995  Jon Tombs
Copyright (c) 1995, 1996, 1999  XFree86 Inc

*/

#define NEED_REPLIES
#define NEED_EVENTS
#include <X11/X.h>
#include <X11/Xproto.h>
#include "misc.h"
#include "dixstruct.h"
#include "extnsionst.h"
#include "colormapst.h"
#include "cursorstr.h"
#include "scrnintstr.h"
#include "servermd.h"
#define _XF86DGA_SERVER_
#include <X11/extensions/xf86dga.h>
#include <X11/extensions/xf86dgastr.h>
#include "swaprep.h"
#include "dgaproc.h"

#include "xf86dgaext.h"


static DISPATCH_PROC(ProcXF86DGADirectVideo);
static DISPATCH_PROC(ProcXF86DGAGetVidPage);
static DISPATCH_PROC(ProcXF86DGAGetVideoLL);
static DISPATCH_PROC(ProcXF86DGAGetViewPortSize);
static DISPATCH_PROC(ProcXF86DGASetVidPage);
static DISPATCH_PROC(ProcXF86DGASetViewPort);
static DISPATCH_PROC(ProcXF86DGAInstallColormap);
static DISPATCH_PROC(ProcXF86DGAQueryDirectVideo);
static DISPATCH_PROC(ProcXF86DGAViewPortChanged);


static int
ProcXF86DGAGetVideoLL(ClientPtr client)
{
    REQUEST(xXF86DGAGetVideoLLReq);
    xXF86DGAGetVideoLLReply rep;
    XDGAModeRec mode;
    int num, offset, flags;
    char *name;

    if (stuff->screen > screenInfo.numScreens)
	return BadValue;

    REQUEST_SIZE_MATCH(xXF86DGAGetVideoLLReq);
    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;

    if(!DGAAvailable(stuff->screen))
	return (DGAErrorBase + XF86DGANoDirectVideoMode);

    if(!(num = DGAGetOldDGAMode(stuff->screen)))
	return (DGAErrorBase + XF86DGANoDirectVideoMode);

    /* get the parameters for the mode that best matches */
    DGAGetModeInfo(stuff->screen, &mode, num);

    if(!DGAOpenFramebuffer(stuff->screen, &name, 
			(unsigned char**)(&rep.offset), 	
			(int*)(&rep.bank_size), &offset, &flags))
	return BadAlloc;

    rep.offset += mode.offset;
    rep.width = mode.bytesPerScanline / (mode.bitsPerPixel >> 3);
    rep.ram_size = rep.bank_size >> 10;

    WriteToClient(client, SIZEOF(xXF86DGAGetVideoLLReply), (char *)&rep);
    return (client->noClientException);
}

static int
ProcXF86DGADirectVideo(ClientPtr client)
{
    int num;
    PixmapPtr pix;
    XDGAModeRec mode;
    REQUEST(xXF86DGADirectVideoReq);

    if (stuff->screen > screenInfo.numScreens)
	return BadValue;

    REQUEST_SIZE_MATCH(xXF86DGADirectVideoReq);

    if (!DGAAvailable(stuff->screen)) 
	return DGAErrorBase + XF86DGANoDirectVideoMode;

    if (stuff->enable & XF86DGADirectGraphics) {
	if(!(num = DGAGetOldDGAMode(stuff->screen)))
	    return (DGAErrorBase + XF86DGANoDirectVideoMode);
    } else
	num = 0;

    if(Success != DGASetMode(stuff->screen, num, &mode, &pix))
	return (DGAErrorBase + XF86DGAScreenNotActive);

    DGASetInputMode (stuff->screen, 
		     (stuff->enable & XF86DGADirectKeyb) != 0,
		     (stuff->enable & XF86DGADirectMouse) != 0);

    return (client->noClientException);
}

static int
ProcXF86DGAGetViewPortSize(ClientPtr client)
{
    int num;
    XDGAModeRec mode;
    REQUEST(xXF86DGAGetViewPortSizeReq);
    xXF86DGAGetViewPortSizeReply rep;

    if (stuff->screen > screenInfo.numScreens)
	return BadValue;

    REQUEST_SIZE_MATCH(xXF86DGAGetViewPortSizeReq);
    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;

    if (!DGAAvailable(stuff->screen)) 
	return (DGAErrorBase + XF86DGANoDirectVideoMode);

    if(!(num = DGAGetOldDGAMode(stuff->screen)))
	return (DGAErrorBase + XF86DGANoDirectVideoMode);

    DGAGetModeInfo(stuff->screen, &mode, num);

    rep.width = mode.viewportWidth;
    rep.height = mode.viewportHeight;

    WriteToClient(client, SIZEOF(xXF86DGAGetViewPortSizeReply), (char *)&rep);
    return (client->noClientException);
}

static int
ProcXF86DGASetViewPort(ClientPtr client)
{
    REQUEST(xXF86DGASetViewPortReq);

    if (stuff->screen > screenInfo.numScreens)
	return BadValue;

    REQUEST_SIZE_MATCH(xXF86DGASetViewPortReq);

    if (!DGAActive(stuff->screen))
    {
	int num;
	PixmapPtr pix;
	XDGAModeRec mode;
	
	if(!(num = DGAGetOldDGAMode(stuff->screen)))
	    return (DGAErrorBase + XF86DGANoDirectVideoMode);
	if(Success != DGASetMode(stuff->screen, num, &mode, &pix))
	    return (DGAErrorBase + XF86DGAScreenNotActive);
    }

    if (DGASetViewport(stuff->screen, stuff->x, stuff->y, DGA_FLIP_RETRACE)
		!= Success)
	return DGAErrorBase + XF86DGADirectNotActivated;

    return (client->noClientException);
}

static int
ProcXF86DGAGetVidPage(ClientPtr client)
{
    REQUEST(xXF86DGAGetVidPageReq);
    xXF86DGAGetVidPageReply rep;

    if (stuff->screen > screenInfo.numScreens)
	return BadValue;

    REQUEST_SIZE_MATCH(xXF86DGAGetVidPageReq);
    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;
    rep.vpage = 0;  /* silently fail */

    WriteToClient(client, SIZEOF(xXF86DGAGetVidPageReply), (char *)&rep);
    return (client->noClientException);
}


static int
ProcXF86DGASetVidPage(ClientPtr client)
{
    REQUEST(xXF86DGASetVidPageReq);

    if (stuff->screen > screenInfo.numScreens)
	return BadValue;

    REQUEST_SIZE_MATCH(xXF86DGASetVidPageReq);

    /* silently fail */

    return (client->noClientException);
}


static int
ProcXF86DGAInstallColormap(ClientPtr client)
{
    ColormapPtr pcmp;
    REQUEST(xXF86DGAInstallColormapReq);

    REQUEST_SIZE_MATCH(xXF86DGAInstallColormapReq);

    if (!DGAActive(stuff->screen))
	return (DGAErrorBase + XF86DGADirectNotActivated);

    pcmp = (ColormapPtr  )LookupIDByType(stuff->id, RT_COLORMAP);
    if (pcmp) {
	DGAInstallCmap(pcmp);
        return (client->noClientException);
    } else {
        client->errorValue = stuff->id;
        return (BadColor);
    }
}

static int
ProcXF86DGAQueryDirectVideo(ClientPtr client)
{
    REQUEST(xXF86DGAQueryDirectVideoReq);
    xXF86DGAQueryDirectVideoReply rep;

    if (stuff->screen > screenInfo.numScreens)
	return BadValue;

    REQUEST_SIZE_MATCH(xXF86DGAQueryDirectVideoReq);
    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;
    rep.flags = 0;

    if (DGAAvailable(stuff->screen))
	rep.flags = XF86DGADirectPresent;

    WriteToClient(client, SIZEOF(xXF86DGAQueryDirectVideoReply), (char *)&rep);
    return (client->noClientException);
}

static int
ProcXF86DGAViewPortChanged(ClientPtr client)
{
    REQUEST(xXF86DGAViewPortChangedReq);
    xXF86DGAViewPortChangedReply rep;

    if (stuff->screen > screenInfo.numScreens)
	return BadValue;

    REQUEST_SIZE_MATCH(xXF86DGAViewPortChangedReq);

    if (!DGAActive(stuff->screen))
	return (DGAErrorBase + XF86DGADirectNotActivated);

    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;
    rep.result = 1;

    WriteToClient(client, SIZEOF(xXF86DGAViewPortChangedReply), (char *)&rep);
    return (client->noClientException);
}

int
ProcXF86DGADispatch(register ClientPtr client)
{
    REQUEST(xReq);

    switch (stuff->data)
    {
    case X_XF86DGAGetVideoLL:
	return ProcXF86DGAGetVideoLL(client);
    case X_XF86DGADirectVideo:
	return ProcXF86DGADirectVideo(client);
    case X_XF86DGAGetViewPortSize:
	return ProcXF86DGAGetViewPortSize(client);
    case X_XF86DGASetViewPort:
	return ProcXF86DGASetViewPort(client);
    case X_XF86DGAGetVidPage:
	return ProcXF86DGAGetVidPage(client);
    case X_XF86DGASetVidPage:
	return ProcXF86DGASetVidPage(client);
    case X_XF86DGAInstallColormap:
	return ProcXF86DGAInstallColormap(client);
    case X_XF86DGAQueryDirectVideo:
	return ProcXF86DGAQueryDirectVideo(client);
    case X_XF86DGAViewPortChanged:
	return ProcXF86DGAViewPortChanged(client);
    default:
	return BadRequest;
    }
}


--- NEW FILE: xf86dga2.c ---
/*
   Copyright (c) 1999 - The XFree86 Project Inc.

   Written by Mark Vojkovich
*/
/* $XFree86: xc/programs/Xserver/Xext/xf86dga2.c,v 1.17 2001/10/28 03:32:51 tsi Exp $ */


#define NEED_REPLIES
#define NEED_EVENTS
#include <X11/X.h>
#include <X11/Xproto.h>
#include "misc.h"
#include "dixstruct.h"
#include "dixevents.h"
#include "pixmapstr.h"
#include "extnsionst.h"
#include "colormapst.h"
#include "cursorstr.h"
#include "scrnintstr.h"
#include "servermd.h"
#define _XF86DGA_SERVER_
#include <X11/extensions/xf86dga.h>
#include <X11/extensions/xf86dgastr.h>
#include "swaprep.h"
#include "dgaproc.h"
#include "xf86dgaext.h"

#ifdef EXTMODULE
#include "xf86_ansic.h"
#else
#include <string.h>
#endif

static DISPATCH_PROC(ProcXDGADispatch);
static DISPATCH_PROC(SProcXDGADispatch);
static DISPATCH_PROC(ProcXDGAQueryVersion);
static DISPATCH_PROC(ProcXDGAQueryModes);
static DISPATCH_PROC(ProcXDGASetMode);
static DISPATCH_PROC(ProcXDGAOpenFramebuffer);
static DISPATCH_PROC(ProcXDGACloseFramebuffer);
static DISPATCH_PROC(ProcXDGASetViewport);
static DISPATCH_PROC(ProcXDGAInstallColormap);
static DISPATCH_PROC(ProcXDGASelectInput);
static DISPATCH_PROC(ProcXDGAFillRectangle);
static DISPATCH_PROC(ProcXDGACopyArea);
static DISPATCH_PROC(ProcXDGACopyTransparentArea);
static DISPATCH_PROC(ProcXDGAGetViewportStatus);
static DISPATCH_PROC(ProcXDGASync);
static DISPATCH_PROC(ProcXDGASetClientVersion);
static DISPATCH_PROC(ProcXDGAChangePixmapMode);
static DISPATCH_PROC(ProcXDGACreateColormap);

static void XDGAResetProc(ExtensionEntry *extEntry);

static void DGAClientStateChange (CallbackListPtr*, pointer, pointer);

static ClientPtr DGAClients[MAXSCREENS];

unsigned char DGAReqCode = 0;
int DGAErrorBase;
int DGAEventBase;

static int DGAGeneration = 0;
static int DGAClientPrivateIndex;
static int DGACallbackRefCount = 0;

/* This holds the client's version information */
typedef struct {
    int		major;
    int		minor;
} DGAPrivRec, *DGAPrivPtr;

#define DGAPRIV(c) ((c)->devPrivates[DGAClientPrivateIndex].ptr)

void
XFree86DGAExtensionInit(/*INITARGS*/)
{
    ExtensionEntry* extEntry;

    if ((extEntry = AddExtension(XF86DGANAME,
				XF86DGANumberEvents,
				XF86DGANumberErrors,
				ProcXDGADispatch,
				SProcXDGADispatch,
				XDGAResetProc,
				StandardMinorOpcode))) {
	int i;

	for(i = 0; i < MAXSCREENS; i++)
	     DGAClients[i] = NULL;

	DGAReqCode = (unsigned char)extEntry->base;
	DGAErrorBase = extEntry->errorBase;
	DGAEventBase = extEntry->eventBase;
	for (i = KeyPress; i <= MotionNotify; i++)
	    SetCriticalEvent (DGAEventBase + i);
    }

    /*
     * Allocate a client private index to hold the client's version
     * information.
     */
    if (DGAGeneration != serverGeneration) {
	DGAClientPrivateIndex = AllocateClientPrivateIndex();
	/*
	 * Allocate 0 length, and use the private to hold a pointer to
	 * our DGAPrivRec.
	 */
	if (!AllocateClientPrivate(DGAClientPrivateIndex, 0)) {
	    ErrorF("XFree86DGAExtensionInit: AllocateClientPrivate failed\n");
	    return;
	}
	DGAGeneration = serverGeneration;
    }
}



static void
XDGAResetProc (ExtensionEntry *extEntry)
{
   DeleteCallback (&ClientStateCallback, DGAClientStateChange, NULL);
   DGACallbackRefCount = 0;
}


static int
ProcXDGAQueryVersion(ClientPtr client)
{
    xXDGAQueryVersionReply rep;

    REQUEST_SIZE_MATCH(xXDGAQueryVersionReq);
    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;
    rep.majorVersion = XDGA_MAJOR_VERSION;
    rep.minorVersion = XDGA_MINOR_VERSION;

    WriteToClient(client, sizeof(xXDGAQueryVersionReply), (char *)&rep);
    return (client->noClientException);
}


static int
ProcXDGAOpenFramebuffer(ClientPtr client)
{
    REQUEST(xXDGAOpenFramebufferReq);
    xXDGAOpenFramebufferReply rep;
    char *deviceName;
    int nameSize;

    if (stuff->screen > screenInfo.numScreens)
        return BadValue;

    if (!DGAAvailable(stuff->screen)) 
        return DGAErrorBase + XF86DGANoDirectVideoMode;

    REQUEST_SIZE_MATCH(xXDGAOpenFramebufferReq);
    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;

    if(!DGAOpenFramebuffer(stuff->screen, &deviceName, 
			(unsigned char**)(&rep.mem1),
			(int*)&rep.size, (int*)&rep.offset, (int*)&rep.extra)) 
    {
	return BadAlloc;
    }

    nameSize = deviceName ? (strlen(deviceName) + 1) : 0;
    rep.length = (nameSize + 3) >> 2;

    WriteToClient(client, sizeof(xXDGAOpenFramebufferReply), (char *)&rep);
    if(rep.length)
	WriteToClient(client, nameSize, deviceName);

    return (client->noClientException);
}


static int
ProcXDGACloseFramebuffer(ClientPtr client)
{
    REQUEST(xXDGACloseFramebufferReq);

    if (stuff->screen > screenInfo.numScreens)
        return BadValue;

    if (!DGAAvailable(stuff->screen)) 
        return DGAErrorBase + XF86DGANoDirectVideoMode;

    REQUEST_SIZE_MATCH(xXDGACloseFramebufferReq);

    DGACloseFramebuffer(stuff->screen);

    return (client->noClientException);
}

static int
ProcXDGAQueryModes(ClientPtr client)
{
    int i, num, size;
    REQUEST(xXDGAQueryModesReq);
    xXDGAQueryModesReply rep;
    xXDGAModeInfo info;
    XDGAModePtr mode;

    if (stuff->screen > screenInfo.numScreens)
        return BadValue;

    REQUEST_SIZE_MATCH(xXDGAQueryModesReq);
    rep.type = X_Reply;
    rep.length = 0;
    rep.number = 0;
    rep.sequenceNumber = client->sequence;

    if (!DGAAvailable(stuff->screen)) {
	rep.number = 0;
	rep.length = 0;
	WriteToClient(client, sz_xXDGAQueryModesReply, (char*)&rep);
	return (client->noClientException);
    }

    if(!(num = DGAGetModes(stuff->screen))) {
	WriteToClient(client, sz_xXDGAQueryModesReply, (char*)&rep);
	return (client->noClientException);
    }

    if(!(mode = (XDGAModePtr)xalloc(num * sizeof(XDGAModeRec))))
	return BadAlloc;

    for(i = 0; i < num; i++)
	DGAGetModeInfo(stuff->screen, mode + i, i + 1);

    size = num * sz_xXDGAModeInfo;
    for(i = 0; i < num; i++)
	size += (strlen(mode[i].name) + 4) & ~3L;  /* plus NULL */

    rep.number = num;
    rep.length = size >> 2;

    WriteToClient(client, sz_xXDGAQueryModesReply, (char*)&rep);

    for(i = 0; i < num; i++) {
	size = strlen(mode[i].name) + 1;

	info.byte_order = mode[i].byteOrder;
	info.depth = mode[i].depth;
	info.num = mode[i].num;
	info.bpp = mode[i].bitsPerPixel;
	info.name_size = (size + 3) & ~3L;
	info.vsync_num = mode[i].VSync_num;
	info.vsync_den = mode[i].VSync_den;
	info.flags = mode[i].flags;
	info.image_width = mode[i].imageWidth;
	info.image_height = mode[i].imageHeight;
	info.pixmap_width = mode[i].pixmapWidth;
	info.pixmap_height = mode[i].pixmapHeight;
	info.bytes_per_scanline = mode[i].bytesPerScanline;
	info.red_mask = mode[i].red_mask;
	info.green_mask = mode[i].green_mask;
	info.blue_mask = mode[i].blue_mask;
	info.visual_class = mode[i].visualClass;
	info.viewport_width = mode[i].viewportWidth;
	info.viewport_height = mode[i].viewportHeight;
	info.viewport_xstep = mode[i].xViewportStep;
	info.viewport_ystep = mode[i].yViewportStep;
 	info.viewport_xmax = mode[i].maxViewportX;
	info.viewport_ymax = mode[i].maxViewportY;
	info.viewport_flags = mode[i].viewportFlags;
	info.reserved1 = mode[i].reserved1;
	info.reserved2 = mode[i].reserved2;
	
	WriteToClient(client, sz_xXDGAModeInfo, (char*)(&info));
	WriteToClient(client, size, mode[i].name);
    }

    xfree(mode);

    return (client->noClientException);
}


static void 
DGAClientStateChange (
    CallbackListPtr* pcbl,
    pointer nulldata,
    pointer calldata
){
    NewClientInfoRec* pci = (NewClientInfoRec*) calldata;
    ClientPtr client = NULL;
    int i;

    for(i = 0; i < screenInfo.numScreens; i++) {
	if(DGAClients[i] == pci->client) {
	   client = pci->client;
	   break;
	}
    }

    if(client && 
      ((client->clientState == ClientStateGone) ||
       (client->clientState == ClientStateRetained))) {
	XDGAModeRec mode;
	PixmapPtr pPix;

	DGAClients[i] = NULL;
	DGASelectInput(i, NULL, 0);
	DGASetMode(i, 0, &mode, &pPix);

	if(--DGACallbackRefCount == 0)
	    DeleteCallback(&ClientStateCallback, DGAClientStateChange, NULL);
    }
}

static int
ProcXDGASetMode(ClientPtr client)
{
    REQUEST(xXDGASetModeReq);
    xXDGASetModeReply rep;
    XDGAModeRec mode;
    xXDGAModeInfo info;
    PixmapPtr pPix;
    int size;

    if (stuff->screen > screenInfo.numScreens)
        return BadValue;

    REQUEST_SIZE_MATCH(xXDGASetModeReq);
    rep.type = X_Reply;
    rep.length = 0;
    rep.offset = 0;
    rep.flags = 0;
    rep.sequenceNumber = client->sequence;

    if (!DGAAvailable(stuff->screen)) 
        return DGAErrorBase + XF86DGANoDirectVideoMode;

    if(DGAClients[stuff->screen] && 
      (DGAClients[stuff->screen] != client))
        return DGAErrorBase + XF86DGANoDirectVideoMode;

    if(!stuff->mode) {
	if(DGAClients[stuff->screen]) {
	  if(--DGACallbackRefCount == 0)
	    DeleteCallback(&ClientStateCallback, DGAClientStateChange, NULL);
	}
	DGAClients[stuff->screen] = NULL;
	DGASelectInput(stuff->screen, NULL, 0);
	DGASetMode(stuff->screen, 0, &mode, &pPix);
	WriteToClient(client, sz_xXDGASetModeReply, (char*)&rep);
	return (client->noClientException);
    } 

    if(Success != DGASetMode(stuff->screen, stuff->mode, &mode, &pPix))
	return BadValue;

    if(!DGAClients[stuff->screen]) {
	if(DGACallbackRefCount++ == 0)
	   AddCallback (&ClientStateCallback, DGAClientStateChange, NULL);
    }

    DGAClients[stuff->screen] = client;

    if(pPix) {
	if(AddResource(stuff->pid, RT_PIXMAP, (pointer)(pPix))) {
	    pPix->drawable.id = (int)stuff->pid;
	    rep.flags = DGA_PIXMAP_AVAILABLE;
	}
    }

    size = strlen(mode.name) + 1;
   
    info.byte_order = mode.byteOrder;
    info.depth = mode.depth;
    info.num = mode.num;
    info.bpp = mode.bitsPerPixel;
    info.name_size = (size + 3) & ~3L;
    info.vsync_num = mode.VSync_num;
    info.vsync_den = mode.VSync_den;
    info.flags = mode.flags;
    info.image_width = mode.imageWidth;
    info.image_height = mode.imageHeight;
    info.pixmap_width = mode.pixmapWidth;
    info.pixmap_height = mode.pixmapHeight;
    info.bytes_per_scanline = mode.bytesPerScanline;
    info.red_mask = mode.red_mask;
    info.green_mask = mode.green_mask;
    info.blue_mask = mode.blue_mask;
    info.visual_class = mode.visualClass;
    info.viewport_width = mode.viewportWidth;
    info.viewport_height = mode.viewportHeight;
    info.viewport_xstep = mode.xViewportStep;
    info.viewport_ystep = mode.yViewportStep;
    info.viewport_xmax = mode.maxViewportX;
    info.viewport_ymax = mode.maxViewportY;
    info.viewport_flags = mode.viewportFlags;
    info.reserved1 = mode.reserved1;
    info.reserved2 = mode.reserved2;

    rep.length = (sz_xXDGAModeInfo + info.name_size) >> 2;

    WriteToClient(client, sz_xXDGASetModeReply, (char*)&rep);
    WriteToClient(client, sz_xXDGAModeInfo, (char*)(&info));
    WriteToClient(client, size, mode.name);

    return (client->noClientException);
}

static int
ProcXDGASetViewport(ClientPtr client)
{
    REQUEST(xXDGASetViewportReq);

    if (stuff->screen > screenInfo.numScreens)
        return BadValue;

    if(DGAClients[stuff->screen] != client)
        return DGAErrorBase + XF86DGADirectNotActivated;

    REQUEST_SIZE_MATCH(xXDGASetViewportReq);

    DGASetViewport(stuff->screen, stuff->x, stuff->y, stuff->flags);

    return (client->noClientException);
}

static int
ProcXDGAInstallColormap(ClientPtr client)
{
    ColormapPtr cmap;
    REQUEST(xXDGAInstallColormapReq);

    if (stuff->screen > screenInfo.numScreens)
        return BadValue;

    if(DGAClients[stuff->screen] != client)
        return DGAErrorBase + XF86DGADirectNotActivated;

    REQUEST_SIZE_MATCH(xXDGAInstallColormapReq);
   
    cmap = (ColormapPtr)LookupIDByType(stuff->cmap, RT_COLORMAP);
    if (cmap) {
        DGAInstallCmap(cmap);
        return (client->noClientException);
    } else {
        client->errorValue = stuff->cmap;
        return (BadColor);
    }

    return (client->noClientException);
}


static int
ProcXDGASelectInput(ClientPtr client)
{
    REQUEST(xXDGASelectInputReq);

    if (stuff->screen > screenInfo.numScreens)
        return BadValue;

    if(DGAClients[stuff->screen] != client)
        return DGAErrorBase + XF86DGADirectNotActivated;

    REQUEST_SIZE_MATCH(xXDGASelectInputReq);
   
    if(DGAClients[stuff->screen] == client)
	DGASelectInput(stuff->screen, client, stuff->mask);

    return (client->noClientException);
}


static int
ProcXDGAFillRectangle(ClientPtr client)
{
    REQUEST(xXDGAFillRectangleReq);

    if (stuff->screen > screenInfo.numScreens)
        return BadValue;

    if(DGAClients[stuff->screen] != client)
        return DGAErrorBase + XF86DGADirectNotActivated;

    REQUEST_SIZE_MATCH(xXDGAFillRectangleReq);
   
    if(Success != DGAFillRect(stuff->screen, stuff->x, stuff->y,
			stuff->width, stuff->height, stuff->color))
	return BadMatch;

    return (client->noClientException);
}

static int
ProcXDGACopyArea(ClientPtr client)
{
    REQUEST(xXDGACopyAreaReq);

    if (stuff->screen > screenInfo.numScreens)
        return BadValue;

    if(DGAClients[stuff->screen] != client)
        return DGAErrorBase + XF86DGADirectNotActivated;

    REQUEST_SIZE_MATCH(xXDGACopyAreaReq);
   
    if(Success != DGABlitRect(stuff->screen, stuff->srcx, stuff->srcy,
		stuff->width, stuff->height, stuff->dstx, stuff->dsty))
	return BadMatch;

    return (client->noClientException);
}


static int
ProcXDGACopyTransparentArea(ClientPtr client)
{
    REQUEST(xXDGACopyTransparentAreaReq);

    if (stuff->screen > screenInfo.numScreens)
        return BadValue;

    if(DGAClients[stuff->screen] != client)
        return DGAErrorBase + XF86DGADirectNotActivated;

    REQUEST_SIZE_MATCH(xXDGACopyTransparentAreaReq);
   
    if(Success != DGABlitTransRect(stuff->screen, stuff->srcx, stuff->srcy,
	stuff->width, stuff->height, stuff->dstx, stuff->dsty, stuff->key))
	return BadMatch;

    return (client->noClientException);
}


static int
ProcXDGAGetViewportStatus(ClientPtr client)
{
    REQUEST(xXDGAGetViewportStatusReq);
    xXDGAGetViewportStatusReply rep;

    if (stuff->screen > screenInfo.numScreens)
        return BadValue;

    if(DGAClients[stuff->screen] != client)
        return DGAErrorBase + XF86DGADirectNotActivated;

    REQUEST_SIZE_MATCH(xXDGAGetViewportStatusReq);
    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;

    rep.status = DGAGetViewportStatus(stuff->screen);

    WriteToClient(client, sizeof(xXDGAGetViewportStatusReply), (char *)&rep);
    return (client->noClientException);
}

static int
ProcXDGASync(ClientPtr client)
{
    REQUEST(xXDGASyncReq);
    xXDGASyncReply rep;

    if (stuff->screen > screenInfo.numScreens)
        return BadValue;

    if(DGAClients[stuff->screen] != client)
        return DGAErrorBase + XF86DGADirectNotActivated;

    REQUEST_SIZE_MATCH(xXDGASyncReq);
    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;

    DGASync(stuff->screen);

    WriteToClient(client, sizeof(xXDGASyncReply), (char *)&rep);
    return (client->noClientException);
}

static int
ProcXDGASetClientVersion(ClientPtr client)
{
    REQUEST(xXDGASetClientVersionReq);

    DGAPrivPtr pPriv;

    REQUEST_SIZE_MATCH(xXDGASetClientVersionReq);
    if ((pPriv = DGAPRIV(client)) == NULL) {
	pPriv = xalloc(sizeof(DGAPrivRec));
	/* XXX Need to look into freeing this */
	if (!pPriv)
	    return BadAlloc;
	DGAPRIV(client) = pPriv;
    }
    pPriv->major = stuff->major;
    pPriv->minor = stuff->minor;

    return (client->noClientException);
}

static int
ProcXDGAChangePixmapMode(ClientPtr client)
{
    REQUEST(xXDGAChangePixmapModeReq);
    xXDGAChangePixmapModeReply rep;
    int x, y;

    if (stuff->screen > screenInfo.numScreens)
        return BadValue;

    if(DGAClients[stuff->screen] != client)
        return DGAErrorBase + XF86DGADirectNotActivated;

    REQUEST_SIZE_MATCH(xXDGAChangePixmapModeReq);
    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;
	
    x = stuff->x;
    y = stuff->y;

    if(!DGAChangePixmapMode(stuff->screen, &x, &y, stuff->flags))
	return BadMatch;

    rep.x = x;
    rep.y = y;
    WriteToClient(client, sizeof(xXDGAChangePixmapModeReply), (char *)&rep);

    return (client->noClientException);
}


static int
ProcXDGACreateColormap(ClientPtr client)
{
    REQUEST(xXDGACreateColormapReq);
    int result;

    if (stuff->screen > screenInfo.numScreens)
        return BadValue;

    if(DGAClients[stuff->screen] != client)
        return DGAErrorBase + XF86DGADirectNotActivated;

    REQUEST_SIZE_MATCH(xXDGACreateColormapReq);

    if(!stuff->mode)
	return BadValue;
   
    result = DGACreateColormap(stuff->screen, client, stuff->id, 
				stuff->mode, stuff->alloc);
    if(result != Success)
	return result;

    return (client->noClientException);
}


static int
SProcXDGADispatch (ClientPtr client)
{
   return DGAErrorBase + XF86DGAClientNotLocal;
}

#if 0
#define DGA_REQ_DEBUG
#endif

#ifdef DGA_REQ_DEBUG
static char *dgaMinor[] = {
    "QueryVersion",
    "GetVideoLL",
    "DirectVideo",
    "GetViewPortSize",
    "SetViewPort",
    "GetVidPage",
    "SetVidPage",
    "InstallColormap",
    "QueryDirectVideo",
    "ViewPortChanged",
    "10",
    "11",
    "QueryModes",
    "SetMode",
    "SetViewport",
    "InstallColormap",
    "SelectInput",
    "FillRectangle",
    "CopyArea",
    "CopyTransparentArea",
    "GetViewportStatus",
    "Sync",
    "OpenFramebuffer",
    "CloseFramebuffer",
    "SetClientVersion",
    "ChangePixmapMode",
    "CreateColormap",
};
#endif

static int
ProcXDGADispatch (ClientPtr client)
{
    REQUEST(xReq);

    if (!LocalClient(client))
	return DGAErrorBase + XF86DGAClientNotLocal;

#ifdef DGA_REQ_DEBUG
    if (stuff->data <= X_XDGACreateColormap)
	fprintf (stderr, "    DGA %s\n", dgaMinor[stuff->data]);
#endif
    
    /* divert old protocol */
#if 1
    if( (stuff->data <= X_XF86DGAViewPortChanged) && 
	(stuff->data >= X_XF86DGAGetVideoLL)) 
	return ProcXF86DGADispatch(client);
#endif

    switch (stuff->data){
    case X_XDGAQueryVersion:
	return ProcXDGAQueryVersion(client);
    case X_XDGAQueryModes:
	return ProcXDGAQueryModes(client);
    case X_XDGASetMode:
	return ProcXDGASetMode(client);
    case X_XDGAOpenFramebuffer:
	return ProcXDGAOpenFramebuffer(client);
    case X_XDGACloseFramebuffer:
	return ProcXDGACloseFramebuffer(client);
    case X_XDGASetViewport:
	return ProcXDGASetViewport(client);
    case X_XDGAInstallColormap:
	return ProcXDGAInstallColormap(client);
    case X_XDGASelectInput:
	return ProcXDGASelectInput(client);
    case X_XDGAFillRectangle:
	return ProcXDGAFillRectangle(client);
    case X_XDGACopyArea:
	return ProcXDGACopyArea(client);
    case X_XDGACopyTransparentArea:
	return ProcXDGACopyTransparentArea(client);
    case X_XDGAGetViewportStatus:
	return ProcXDGAGetViewportStatus(client);
    case X_XDGASync:
	return ProcXDGASync(client);
    case X_XDGASetClientVersion:
	return ProcXDGASetClientVersion(client);
    case X_XDGAChangePixmapMode:
	return ProcXDGAChangePixmapMode(client);
    case X_XDGACreateColormap:
	return ProcXDGACreateColormap(client);
    default:
	return BadRequest;
    }
}

#ifdef EXTMODULE
void
XFree86DGARegister(INITARGS)
{
  XDGAEventBase = &DGAEventBase; 
}
#endif

--- NEW FILE: xf86dgaext.h ---
/* $XFree86$ */

#ifndef _XF86DGAEXT_H_
#define _XF86DGAEXT_H_

extern DISPATCH_PROC(ProcXF86DGADispatch);

#endif /* _XF86DGAEXT_H_ */

--- NEW FILE: xf86fbBus.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86fbBus.c,v 1.3 2003/08/24 17:36:55 dawes Exp $ */

/*
 * Copyright (c) 2000-2001 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 * This file contains the interfaces to the bus-specific code
 */

#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <X11/X.h>
#include "os.h"
#include "xf86.h"
#include "xf86Priv.h"
#include "xf86Resources.h"

#include "xf86Bus.h"

#define XF86_OS_PRIVS
#define NEED_OS_RAC_PROTOS
#include "xf86_OSproc.h"

#include "xf86RAC.h"

Bool fbSlotClaimed = FALSE;

int
xf86ClaimFbSlot(DriverPtr drvp, int chipset, GDevPtr dev, Bool active)
{
    EntityPtr p;
    int num;
    
    num = xf86AllocateEntity();
    p = xf86Entities[num];
    p->driver = drvp;
    p->chipset = 0;
    p->busType = BUS_NONE;
    p->active = active;
    p->inUse = FALSE;
    xf86AddDevToEntity(num, dev);
    p->access = xnfcalloc(1,sizeof(EntityAccessRec));
    p->access->fallback = &AccessNULL;
    p->access->pAccess = &AccessNULL;
    p->busAcc = NULL;

    fbSlotClaimed = TRUE;
    return num;
}

/*
 * Get the list of FB "slots" claimed by a screen
 */
int
xf86GetFbInfoForScreen(int scrnIndex)
{
    int num = 0;
    int i;
    EntityPtr p;
    
    for (i = 0; i < xf86Screens[scrnIndex]->numEntities; i++) {
	p = xf86Entities[xf86Screens[scrnIndex]->entityList[i]];
  	if (p->busType == BUS_NONE) {
  	    num++;
  	}
    }
    return num;
}

--- NEW FILE: xf86fbman.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86fbman.c,v 1.28 2003/11/03 05:11:03 tsi Exp $ */

/*
 * Copyright (c) 1998-2001 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
[...1404 lines suppressed...]
   offman = pScreen->devPrivates[xf86FBScreenIndex].ptr;

   extents = REGION_EXTENTS(pScreen, offman->InitialBoxes);
   w = extents->x2 - extents->x1;

   if(gran && ((gran > w) || (w % gran))) {
	/* we can't match the specified alignment with XY allocations */
	return NULL;
   }

   if(length <= w) { /* special case */
	h = 1;
	w = length;
   } else {
	h = (length + w - 1) / w;
   }

   return (*funcs->AllocateOffscreenArea)(
                pScreen, w, h, gran, moveCB, removeCB, privData);
}

--- NEW FILE: xf86fbman.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86fbman.h,v 1.14 2003/10/09 12:40:54 alanh Exp $ */

/*
 * Copyright (c) 1998-2001 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

#ifndef _XF86FBMAN_H
#define _XF86FBMAN_H


#include "scrnintstr.h"
#include "regionstr.h"


#define FAVOR_AREA_THEN_WIDTH		0
#define FAVOR_AREA_THEN_HEIGHT		1
#define FAVOR_WIDTH_THEN_AREA		2
#define FAVOR_HEIGHT_THEN_AREA		3

#define PRIORITY_LOW			0
#define PRIORITY_NORMAL			1
#define PRIORITY_EXTREME		2


typedef struct _FBArea {
   ScreenPtr    pScreen;
   BoxRec   	box;
   int 		granularity;
   void 	(*MoveAreaCallback)(struct _FBArea*, struct _FBArea*);
   void 	(*RemoveAreaCallback)(struct _FBArea*);
   DevUnion 	devPrivate;
} FBArea, *FBAreaPtr;

typedef struct _FBLinear {
   ScreenPtr    pScreen;
   int		size;
   int 		offset;
   int 		granularity;
   void 	(*MoveLinearCallback)(struct _FBLinear*, struct _FBLinear*);
   void 	(*RemoveLinearCallback)(struct _FBLinear*);
   DevUnion 	devPrivate;
} FBLinear, *FBLinearPtr;

typedef void (*FreeBoxCallbackProcPtr)(ScreenPtr, RegionPtr, pointer);
typedef void (*MoveAreaCallbackProcPtr)(FBAreaPtr, FBAreaPtr);
typedef void (*RemoveAreaCallbackProcPtr)(FBAreaPtr);

typedef void (*MoveLinearCallbackProcPtr)(FBLinearPtr, FBLinearPtr);
typedef void (*RemoveLinearCallbackProcPtr)(FBLinearPtr);


typedef struct {
    FBAreaPtr (*AllocateOffscreenArea)(
		ScreenPtr pScreen, 
		int w, int h,
		int granularity,
		MoveAreaCallbackProcPtr moveCB,
		RemoveAreaCallbackProcPtr removeCB,
		pointer privData);
    void      (*FreeOffscreenArea)(FBAreaPtr area);
    Bool      (*ResizeOffscreenArea)(FBAreaPtr area, int w, int h);
    Bool      (*QueryLargestOffscreenArea)(
		ScreenPtr pScreen,
		int *width, int *height,
		int granularity,
		int preferences,
		int priority);
    Bool      (*RegisterFreeBoxCallback)( 
		ScreenPtr pScreen,  
		FreeBoxCallbackProcPtr FreeBoxCallback,
		pointer devPriv);
/* linear functions */
    FBLinearPtr (*AllocateOffscreenLinear)(
		ScreenPtr pScreen, 
		int size,
		int granularity,
		MoveLinearCallbackProcPtr moveCB,
		RemoveLinearCallbackProcPtr removeCB,
		pointer privData);
    void      (*FreeOffscreenLinear)(FBLinearPtr area);
    Bool      (*ResizeOffscreenLinear)(FBLinearPtr area, int size);
    Bool      (*QueryLargestOffscreenLinear)(
		ScreenPtr pScreen,
		int *size,
		int granularity,
		int priority);
    Bool      (*PurgeOffscreenAreas) (ScreenPtr);
} FBManagerFuncs, *FBManagerFuncsPtr;


Bool xf86RegisterOffscreenManager(
    ScreenPtr pScreen, 
    FBManagerFuncsPtr funcs
);

Bool
xf86InitFBManagerRegion(
    ScreenPtr pScreen, 
    RegionPtr ScreenRegion
);

Bool
xf86InitFBManagerArea(
    ScreenPtr pScreen,
    int PixalArea,
    int Verbosity
);

Bool
xf86InitFBManager(
    ScreenPtr pScreen, 
    BoxPtr FullBox
);

Bool
xf86InitFBManagerLinear(
    ScreenPtr pScreen, 
    int offset,
    int size
);

Bool 
xf86FBManagerRunning(
    ScreenPtr pScreen
);

FBAreaPtr 
xf86AllocateOffscreenArea (
   ScreenPtr pScreen, 
   int w, int h,
   int granularity,
   MoveAreaCallbackProcPtr moveCB,
   RemoveAreaCallbackProcPtr removeCB,
   pointer privData
);

FBAreaPtr 
xf86AllocateLinearOffscreenArea (
   ScreenPtr pScreen, 
   int length,
   int granularity,
   MoveAreaCallbackProcPtr moveCB,
   RemoveAreaCallbackProcPtr removeCB,
   pointer privData
);

FBLinearPtr 
xf86AllocateOffscreenLinear (
   ScreenPtr pScreen, 
   int length,
   int granularity,
   MoveLinearCallbackProcPtr moveCB,
   RemoveLinearCallbackProcPtr removeCB,
   pointer privData
);

void xf86FreeOffscreenArea(FBAreaPtr area);
void xf86FreeOffscreenLinear(FBLinearPtr area);

Bool 
xf86ResizeOffscreenArea(
   FBAreaPtr resize,
   int w, int h
);

Bool 
xf86ResizeOffscreenLinear(
   FBLinearPtr resize,
   int size
);


Bool
xf86RegisterFreeBoxCallback(
    ScreenPtr pScreen,  
    FreeBoxCallbackProcPtr FreeBoxCallback,
    pointer devPriv
);

Bool
xf86PurgeUnlockedOffscreenAreas(
    ScreenPtr pScreen
);


Bool
xf86QueryLargestOffscreenArea(
    ScreenPtr pScreen,
    int *width, int *height,
    int granularity,
    int preferences,
    int priority
);

Bool
xf86QueryLargestOffscreenLinear(
    ScreenPtr pScreen,
    int *size,
    int granularity,
    int priority
);


#endif /* _XF86FBMAN_H */

--- NEW FILE: xf86isaBus.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86isaBus.c,v 3.6 2003/08/24 17:36:55 dawes Exp $ */
/*
 * Copyright (c) 1997-2000 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */


/*
 * This file contains the interfaces to the bus-specific code
 */

#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <X11/X.h>
#include "os.h"
#include "xf86.h"
#include "xf86Priv.h"
#include "xf86Resources.h"

#include "xf86Bus.h"

#define XF86_OS_PRIVS
#define NEED_OS_RAC_PROTOS
#include "xf86_OSproc.h"

#include "xf86RAC.h"

Bool isaSlotClaimed = FALSE;

/*
 * If the slot requested is already in use, return FALSE.
 * Otherwise, claim the slot for the screen requesting it.
 */

int
xf86ClaimIsaSlot(DriverPtr drvp, int chipset, GDevPtr dev, Bool active)
{
    EntityPtr p;
    BusAccPtr pbap = xf86BusAccInfo;
    int num;
    
    num = xf86AllocateEntity();
    p = xf86Entities[num];
    p->driver = drvp;
    p->chipset = chipset;
    p->busType = BUS_ISA;
    p->active = active;
    p->inUse = FALSE;
    xf86AddDevToEntity(num, dev);
    p->access = xnfcalloc(1,sizeof(EntityAccessRec));
    p->access->fallback = &AccessNULL;
    p->access->pAccess = &AccessNULL;
    p->busAcc = NULL;
    while (pbap) {
	if (pbap->type == BUS_ISA)
	    p->busAcc = pbap;
	pbap = pbap->next;
    }
    isaSlotClaimed = TRUE;
    return num;
}

/*
 * Get the list of ISA "slots" claimed by a screen
 *
 * Note: The ISA implementation here assumes that only one ISA "slot" type
 * can be claimed by any one screen.  That means a return value other than
 * 0 or 1 isn't useful.
 */
int
xf86GetIsaInfoForScreen(int scrnIndex)
{
    int num = 0;
    int i;
    EntityPtr p;
    
    for (i = 0; i < xf86Screens[scrnIndex]->numEntities; i++) {
	p = xf86Entities[xf86Screens[scrnIndex]->entityList[i]];
  	if (p->busType == BUS_ISA) {
  	    num++;
  	}
    }
    return num;
}

/*
 * Parse a BUS ID string, and return True if it is a ISA bus id.
 */

Bool
xf86ParseIsaBusString(const char *busID)
{
    /*
     * The format assumed to be "isa" or "isa:"
     */
    return (StringToBusType(busID,NULL) == BUS_ISA);
}


/*
 * xf86IsPrimaryIsa() -- return TRUE if primary device
 * is ISA.
 */
 
Bool
xf86IsPrimaryIsa(void)
{
    return ( primaryBus.type == BUS_ISA );
}

void
isaConvertRange2Host(resRange *pRange)
{
    return;
}

--- NEW FILE: xf86misc.c ---
/* $XFree86: xc/programs/Xserver/Xext/xf86misc.c,v 3.41 2003/11/17 22:20:27 dawes Exp $ */

/*
 * Copyright (c) 1995, 1996  The XFree86 Project, Inc
 */

/* THIS IS NOT AN X CONSORTIUM STANDARD */

#define NEED_REPLIES
#define NEED_EVENTS
#include <X11/X.h>
#include <X11/Xproto.h>
#include "misc.h"
#include "dixstruct.h"
#include "extnsionst.h"
#include "scrnintstr.h"
#include "inputstr.h"
#include "servermd.h"
#define _XF86MISC_SERVER_
#undef _XF86MISC_SAVER_COMPAT_
#include <X11/extensions/xf86mscstr.h>
#include "swaprep.h"
#include "xf86.h"
#include <X11/Xfuncproto.h>
#include "xf86miscproc.h"

#if 0
#include <X11/Xtrans.h>
#include "../os/osdep.h"
#include <X11/Xauth.h>
#ifndef USL
#ifndef Lynx
#include <sys/socket.h>
#else
#include <socket.h>
#endif
#endif /* USL */
#endif

#ifdef EXTMODULE
#include "xf86_ansic.h"
#endif

static int miscErrorBase;
static int MiscGeneration = 0;
static int MiscClientPrivateIndex;

/* This holds the client's version information */
typedef struct {
    int		major;
    int		minor;
} MiscPrivRec, *MiscPrivPtr;

#define MPRIV(c) ((c)->devPrivates[MiscClientPrivateIndex].ptr)

static void XF86MiscResetProc(
    ExtensionEntry* /* extEntry */
);

static void
ClientVersion(ClientPtr client, int *major, int *minor)
{
    MiscPrivPtr pPriv;

    pPriv = MPRIV(client);
    if (!pPriv) {
	if (major) *major = 0;
	if (minor) *minor = 0;
	return;
    }
    
    if (major) *major = pPriv->major;
    if (minor) *minor = pPriv->minor;
}

static DISPATCH_PROC(ProcXF86MiscDispatch);
static DISPATCH_PROC(ProcXF86MiscQueryVersion);
static DISPATCH_PROC(ProcXF86MiscGetKbdSettings);
static DISPATCH_PROC(ProcXF86MiscGetMouseSettings);
static DISPATCH_PROC(ProcXF86MiscSetKbdSettings);
static DISPATCH_PROC(ProcXF86MiscSetMouseSettings);
static DISPATCH_PROC(ProcXF86MiscSetGrabKeysState);
static DISPATCH_PROC(ProcXF86MiscSetClientVersion);
static DISPATCH_PROC(ProcXF86MiscGetFilePaths);
static DISPATCH_PROC(ProcXF86MiscPassMessage);
#ifdef _XF86MISC_SAVER_COMPAT_
static DISPATCH_PROC(ProcXF86MiscGetSaver);
static DISPATCH_PROC(ProcXF86MiscSetSaver);
#endif
static DISPATCH_PROC(SProcXF86MiscDispatch);
static DISPATCH_PROC(SProcXF86MiscQueryVersion);
static DISPATCH_PROC(SProcXF86MiscGetKbdSettings);
static DISPATCH_PROC(SProcXF86MiscGetMouseSettings);
static DISPATCH_PROC(SProcXF86MiscSetKbdSettings);
static DISPATCH_PROC(SProcXF86MiscSetMouseSettings);
static DISPATCH_PROC(SProcXF86MiscSetGrabKeysState);
static DISPATCH_PROC(SProcXF86MiscSetClientVersion);
static DISPATCH_PROC(SProcXF86MiscGetFilePaths);
static DISPATCH_PROC(SProcXF86MiscPassMessage);
#ifdef _XF86MISC_SAVER_COMPAT_
static DISPATCH_PROC(SProcXF86MiscGetSaver);
static DISPATCH_PROC(SProcXF86MiscSetSaver);
#endif

#if 0
static unsigned char XF86MiscReqCode = 0;
#endif

#ifdef DEBUG
# define DEBUG_P(x) ErrorF(x"\n");
#else
# define DEBUG_P(x) /**/
#endif

#define MISCERR(x)	(miscErrorBase + x)

void
XFree86MiscExtensionInit(void)
{
    ExtensionEntry* extEntry;

    DEBUG_P("XFree86MiscExtensionInit");

    if (!xf86GetModInDevEnabled())
	return;

    /*
     * Allocate a client private index to hold the client's version
     * information.
     */
    if (MiscGeneration != serverGeneration) {
	MiscClientPrivateIndex = AllocateClientPrivateIndex();
	/*
	 * Allocate 0 length, and use the private to hold a pointer to our
	 * MiscPrivRec.
	 */
	if (!AllocateClientPrivate(MiscClientPrivateIndex, 0)) {
	    ErrorF("XFree86MiscExtensionInit: "
		   "AllocateClientPrivate failed\n");
	    return;
	}
	MiscGeneration = serverGeneration;
    }
    
    if (
	(extEntry = AddExtension(XF86MISCNAME,
				XF86MiscNumberEvents,
				XF86MiscNumberErrors,
				ProcXF86MiscDispatch,
				SProcXF86MiscDispatch,
				XF86MiscResetProc,
				StandardMinorOpcode))) {
#if 0
	XF86MiscReqCode = (unsigned char)extEntry->base;
#endif
	miscErrorBase = extEntry->errorBase;
    }
}

/*ARGSUSED*/
static void
XF86MiscResetProc (extEntry)
    ExtensionEntry* extEntry;
{
}

static int
ProcXF86MiscQueryVersion(client)
    register ClientPtr client;
{
    xXF86MiscQueryVersionReply rep;
    register int n;

    DEBUG_P("XF86MiscQueryVersion");

    REQUEST_SIZE_MATCH(xXF86MiscQueryVersionReq);
    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;
    rep.majorVersion = XF86MISC_MAJOR_VERSION;
    rep.minorVersion = XF86MISC_MINOR_VERSION;
    if (client->swapped) {
    	swaps(&rep.sequenceNumber, n);
    	swapl(&rep.length, n);
    	swaps(&rep.majorVersion, n);
    	swaps(&rep.minorVersion, n);
    }
    WriteToClient(client, sizeof(xXF86MiscQueryVersionReply), (char *)&rep);
    return (client->noClientException);
}

#ifdef _XF86MISC_SAVER_COMPAT_
/* THESE HAVE NOT BEEN CONVERTED TO THE NEW DESIGN */

/*
 * This will go away, but remains for now for compatibility with older
 * clients.
 */
static int
ProcXF86MiscSetSaver(client)
    register ClientPtr client;
{
    REQUEST(xXF86MiscSetSaverReq);
    ScrnInfoPtr vptr;

    if (stuff->screen > screenInfo.numScreens)
	return BadValue;

    vptr = (ScrnInfoPtr) screenInfo.screens[stuff->screen]->devPrivates[xf86ScreenIndex].ptr;

    REQUEST_SIZE_MATCH(xXF86MiscSetSaverReq);

    if (stuff->suspendTime < 0)
	return BadValue;
    if (stuff->offTime < 0)
	return BadValue;

    return (client->noClientException);
}

/*
 * This will go away, but remains for now for compatibility with older
 * clients.
 */
static int
ProcXF86MiscGetSaver(client)
    register ClientPtr client;
{
    REQUEST(xXF86MiscGetSaverReq);
    xXF86MiscGetSaverReply rep;
    register int n;
    ScrnInfoPtr vptr;

    if (stuff->screen > screenInfo.numScreens)
	return BadValue;

    vptr = (ScrnInfoPtr) screenInfo.screens[stuff->screen]->devPrivates[xf86ScreenIndex].ptr;

    REQUEST_SIZE_MATCH(xXF86MiscGetSaverReq);
    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;
    rep.suspendTime = 0;
    rep.offTime = 0;
    
    if (client->swapped) {
    	swaps(&rep.sequenceNumber, n);
    	swapl(&rep.length, n);
    	swapl(&rep.suspendTime, n);
    	swapl(&rep.offTime, n);
    }
    WriteToClient(client, SIZEOF(xXF86MiscGetSaverReply), (char *)&rep);
    return (client->noClientException);
}

#endif /* _XF86MISC_SAVER_COMPAT_ */

static int
ProcXF86MiscGetMouseSettings(client)
    register ClientPtr client;
{
    xXF86MiscGetMouseSettingsReply rep;
    char *devname;
    pointer mouse;
    register int n;

    DEBUG_P("XF86MiscGetMouseSettings");

    REQUEST_SIZE_MATCH(xXF86MiscGetMouseSettingsReq);
    rep.type = X_Reply;
    rep.sequenceNumber = client->sequence;

    if (!MiscExtGetMouseSettings(&mouse, &devname))
	return BadValue;

    rep.mousetype =	  MiscExtGetMouseValue(mouse, MISC_MSE_PROTO);
    rep.baudrate =	  MiscExtGetMouseValue(mouse, MISC_MSE_BAUDRATE);
    rep.samplerate =	  MiscExtGetMouseValue(mouse, MISC_MSE_SAMPLERATE);
    rep.resolution =	  MiscExtGetMouseValue(mouse, MISC_MSE_RESOLUTION);
    rep.buttons =	  MiscExtGetMouseValue(mouse, MISC_MSE_BUTTONS);
    rep.emulate3buttons = MiscExtGetMouseValue(mouse, MISC_MSE_EM3BUTTONS);
    rep.emulate3timeout = MiscExtGetMouseValue(mouse, MISC_MSE_EM3TIMEOUT);
    rep.chordmiddle =	  MiscExtGetMouseValue(mouse, MISC_MSE_CHORDMIDDLE);
    rep.flags =		  MiscExtGetMouseValue(mouse, MISC_MSE_FLAGS);
    rep.devnamelen = (devname? strlen(devname): 0);
    rep.length = (sizeof(xXF86MiscGetMouseSettingsReply) -
		  sizeof(xGenericReply) + ((rep.devnamelen+3) & ~3)) >> 2;
    
    if (client->swapped) {
    	swaps(&rep.sequenceNumber, n);
    	swapl(&rep.length, n);
    	swapl(&rep.mousetype, n);
    	swapl(&rep.baudrate, n);
    	swapl(&rep.samplerate, n);
    	swapl(&rep.resolution, n);
    	swapl(&rep.buttons, n);
    	swapl(&rep.emulate3buttons, n);
    	swapl(&rep.emulate3timeout, n);
    	swapl(&rep.chordmiddle, n);
    	swapl(&rep.flags, n);
    }
    WriteToClient(client, SIZEOF(xXF86MiscGetMouseSettingsReply), (char *)&rep);
    MiscExtDestroyStruct(mouse, MISC_POINTER);
    
    if (rep.devnamelen)
        WriteToClient(client, rep.devnamelen, devname);
    return (client->noClientException);
}

static int
ProcXF86MiscGetKbdSettings(client)
    register ClientPtr client;
{
    xXF86MiscGetKbdSettingsReply rep;
    pointer kbd;
    register int n;

    DEBUG_P("XF86MiscGetKbdSettings");

    REQUEST_SIZE_MATCH(xXF86MiscGetKbdSettingsReq);
    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;
    if (!MiscExtGetKbdSettings(&kbd))
	return BadValue;

    rep.kbdtype =	MiscExtGetKbdValue(kbd, MISC_KBD_TYPE);
    rep.rate =		MiscExtGetKbdValue(kbd, MISC_KBD_RATE);
    rep.delay =		MiscExtGetKbdValue(kbd, MISC_KBD_DELAY);
    rep.servnumlock =	MiscExtGetKbdValue(kbd, MISC_KBD_SERVNUMLOCK);
    if (client->swapped) {
    	swaps(&rep.sequenceNumber, n);
    	swapl(&rep.length, n);
    	swapl(&rep.kbdtype, n);
    	swapl(&rep.rate, n);
    	swapl(&rep.delay, n);
    }
    WriteToClient(client, SIZEOF(xXF86MiscGetKbdSettingsReply), (char *)&rep);
    return (client->noClientException);
}

static int
ProcXF86MiscSetMouseSettings(client)
    register ClientPtr client;
{
    MiscExtReturn ret;
    pointer mouse;
    char *devname = NULL;
    int major, minor;
    
    REQUEST(xXF86MiscSetMouseSettingsReq);

    DEBUG_P("XF86MiscSetMouseSettings");

    REQUEST_AT_LEAST_SIZE(xXF86MiscSetMouseSettingsReq);

    ClientVersion(client, &major, &minor);
    
    if (xf86GetVerbosity() > 1) {
	ErrorF("SetMouseSettings - type: %d brate: %d srate: %d chdmid: %d\n",
		(int)stuff->mousetype, (int)stuff->baudrate,
		(int)stuff->samplerate, stuff->chordmiddle);
	ErrorF("                   em3but: %d em3tim: %d res: %d flags: %ld\n",
		stuff->emulate3buttons, (int)stuff->emulate3timeout,
		(int)stuff->resolution, (unsigned long)stuff->flags);
    }

    if ((mouse = MiscExtCreateStruct(MISC_POINTER)) == (pointer) 0)
	return BadAlloc;

    MiscExtSetMouseValue(mouse, MISC_MSE_PROTO,		stuff->mousetype);
    MiscExtSetMouseValue(mouse, MISC_MSE_BAUDRATE,	stuff->baudrate);
    MiscExtSetMouseValue(mouse, MISC_MSE_SAMPLERATE,	stuff->samplerate);
    MiscExtSetMouseValue(mouse, MISC_MSE_RESOLUTION,	stuff->resolution);
    MiscExtSetMouseValue(mouse, MISC_MSE_BUTTONS,	stuff->buttons);
    MiscExtSetMouseValue(mouse, MISC_MSE_EM3BUTTONS,	stuff->emulate3buttons);
    MiscExtSetMouseValue(mouse, MISC_MSE_EM3TIMEOUT,	stuff->emulate3timeout);
    MiscExtSetMouseValue(mouse, MISC_MSE_CHORDMIDDLE,	stuff->chordmiddle);
    MiscExtSetMouseValue(mouse, MISC_MSE_FLAGS,		stuff->flags);
    
    if ((major > 0 || minor > 5) && stuff->devnamelen) {
	int size = sizeof(xXF86MiscSetMouseSettingsReq) + stuff->devnamelen;
	size = (size + 3) >> 2;
	if (client->req_len < size)
	    return BadLength;
	if (stuff->devnamelen) {
	    if (!(devname = xalloc(stuff->devnamelen)))
		return BadAlloc;
	    strncpy(devname,(char*)(&stuff[1]),stuff->devnamelen);
	    if (xf86GetVerbosity() > 1)
		ErrorF("SetMouseSettings - device: %s\n",devname);
	    MiscExtSetMouseDevice(mouse, devname);
	}
    }

    ret = MiscExtApply(mouse, MISC_POINTER);

    if (devname)
	xfree(devname);
    
    switch ((ret)) {
        case MISC_RET_SUCCESS:      break;
	case MISC_RET_BADVAL:       return BadValue;
	case MISC_RET_BADMSEPROTO:  return MISCERR(XF86MiscBadMouseProtocol);
	case MISC_RET_BADBAUDRATE:  return MISCERR(XF86MiscBadMouseBaudRate);
	case MISC_RET_BADFLAGS:     return MISCERR(XF86MiscBadMouseFlags);
        case MISC_RET_BADCOMBO:     return MISCERR(XF86MiscBadMouseCombo);
        case MISC_RET_NOMODULE:     return MISCERR(XF86MiscNoModule);
        default:
	    ErrorF("Unexpected return from MiscExtApply(POINTER) = %d\n", ret);
	    return BadImplementation;
    }

    if (xf86GetVerbosity() > 1)
	ErrorF("SetMouseSettings - Succeeded\n");
    return (client->noClientException);
}

static int
ProcXF86MiscSetKbdSettings(client)
    register ClientPtr client;
{
    MiscExtReturn ret;
    pointer kbd;
    REQUEST(xXF86MiscSetKbdSettingsReq);

    DEBUG_P("XF86MiscSetKbdSettings");

    REQUEST_SIZE_MATCH(xXF86MiscSetKbdSettingsReq);

    if (xf86GetVerbosity() > 1)
	ErrorF("SetKbdSettings - type: %d rate: %d delay: %d snumlk: %d\n",
		(int)stuff->kbdtype, (int)stuff->rate,
		(int)stuff->delay, stuff->servnumlock);

    if ((kbd = MiscExtCreateStruct(MISC_KEYBOARD)) == (pointer) 0)
	return BadAlloc;

    MiscExtSetKbdValue(kbd, MISC_KBD_TYPE,		stuff->kbdtype);
    MiscExtSetKbdValue(kbd, MISC_KBD_RATE,		stuff->rate);
    MiscExtSetKbdValue(kbd, MISC_KBD_DELAY,		stuff->delay);
    MiscExtSetKbdValue(kbd, MISC_KBD_SERVNUMLOCK,	stuff->servnumlock);

    switch ((ret = MiscExtApply(kbd, MISC_KEYBOARD))) {
	case MISC_RET_SUCCESS:      break;
	case MISC_RET_BADVAL:       return BadValue;
	case MISC_RET_BADKBDTYPE:   return MISCERR(XF86MiscBadKbdType);
	default:
	    ErrorF("Unexpected return from MiscExtApply(KEYBOARD) = %d\n", ret);
	    return BadImplementation;
    }

    if (xf86GetVerbosity() > 1)
	ErrorF("SetKbdSettings - Succeeded\n");
    return (client->noClientException);
}

static int
ProcXF86MiscSetGrabKeysState(client)
    register ClientPtr client;
{
    int n, status;
    xXF86MiscSetGrabKeysStateReply rep;
    REQUEST(xXF86MiscSetGrabKeysStateReq);

    DEBUG_P("XF86MiscSetGrabKeysState");

    REQUEST_SIZE_MATCH(xXF86MiscSetGrabKeysStateReq);

    if ((status = MiscExtSetGrabKeysState(client, stuff->enable)) == 0) {
	if (xf86GetVerbosity() > 1)
	    ErrorF("SetGrabKeysState - %s\n",
		   stuff->enable ? "enabled" : "disabled");
    }

    rep.type = X_Reply;
    rep.length = 0;
    rep.sequenceNumber = client->sequence;
    rep.status = status;
    if (client->swapped) {
    	swaps(&rep.sequenceNumber, n);
    	swapl(&rep.length, n);
    	swapl(&rep.status, n);
    }
    WriteToClient(client, SIZEOF(xXF86MiscSetGrabKeysStateReply), (char *)&rep);

    return (client->noClientException);
}

static int
ProcXF86MiscSetClientVersion(ClientPtr client)
{
    REQUEST(xXF86MiscSetClientVersionReq);

    MiscPrivPtr pPriv;

    DEBUG_P("XF86MiscSetClientVersion");

    REQUEST_SIZE_MATCH(xXF86MiscSetClientVersionReq);

    if ((pPriv = MPRIV(client)) == NULL) {
	pPriv = xalloc(sizeof(MiscPrivRec));
	if (!pPriv)
	    return BadAlloc;
	MPRIV(client) = pPriv;
    }
    ErrorF("SetClientVersion: %i %i\n",stuff->major,stuff->minor);
    pPriv->major = stuff->major;
    pPriv->minor = stuff->minor;
    
    return (client->noClientException);
}

static int
ProcXF86MiscGetFilePaths(client)
    register ClientPtr client;
{
    xXF86MiscGetFilePathsReply rep;
    const char *configfile;
    const char *modulepath;
    const char *logfile;
    register int n;

    DEBUG_P("XF86MiscGetFilePaths");

    REQUEST_SIZE_MATCH(xXF86MiscGetFilePathsReq);
    rep.type = X_Reply;
    rep.sequenceNumber = client->sequence;

    if (!MiscExtGetFilePaths(&configfile, &modulepath, &logfile))
	return BadValue;

    rep.configlen = (configfile? strlen(configfile): 0);
    rep.modulelen = (modulepath? strlen(modulepath): 0);
    rep.loglen = (logfile? strlen(logfile): 0);
    rep.length = (SIZEOF(xXF86MiscGetFilePathsReply) - SIZEOF(xGenericReply) +
		  ((rep.configlen + 3) & ~3) +
		  ((rep.modulelen + 3) & ~3) +
		  ((rep.loglen + 3) & ~3) ) >> 2;
    
    if (client->swapped) {
    	swaps(&rep.sequenceNumber, n);
    	swapl(&rep.length, n);
    	swaps(&rep.configlen, n);
    	swaps(&rep.modulelen, n);
    	swaps(&rep.loglen, n);
    }
    WriteToClient(client, SIZEOF(xXF86MiscGetFilePathsReply), (char *)&rep);
    
    if (rep.configlen)
        WriteToClient(client, rep.configlen, (char *)configfile);
    if (rep.modulelen)
        WriteToClient(client, rep.modulelen, (char *)modulepath);
    if (rep.loglen)
        WriteToClient(client, rep.loglen, (char *)logfile);

    return (client->noClientException);
}

static int
ProcXF86MiscPassMessage(client)
    register ClientPtr client;
{
    xXF86MiscPassMessageReply rep;
    char *msgtype, *msgval, *retstr;
    int retval, size;
    register int n;

    REQUEST(xXF86MiscPassMessageReq);

    DEBUG_P("XF86MiscPassMessage");

    REQUEST_AT_LEAST_SIZE(xXF86MiscPassMessageReq);
    size = (sizeof(xXF86MiscPassMessageReq) + 3) >> 2;
    size+= (stuff->typelen + 3) >> 2;
    size+= (stuff->vallen  + 3) >> 2;
    if (client->req_len < size)
	return BadLength;
    if (stuff->typelen) {
	if (!(msgtype = xalloc(stuff->typelen)))
	    return BadAlloc;
	strncpy(msgtype,(char*)(&stuff[1]),stuff->typelen);
    } else return BadValue;
    if (stuff->vallen) {
	if (!(msgval = xalloc(stuff->vallen)))
	    return BadAlloc;
	strncpy(msgval,(char*)(&stuff[1] + ((stuff->typelen + 3) & ~3)),
			stuff->vallen);
    } else return BadValue;

    if ((retval= MiscExtPassMessage(stuff->screen,msgtype,msgval,&retstr)) != 0)
	return retval;

    rep.type = X_Reply;
    rep.sequenceNumber = client->sequence;
    rep.mesglen = (retstr? strlen(retstr): 0);
    rep.length = (SIZEOF(xXF86MiscPassMessageReply) - SIZEOF(xGenericReply) +
		  ((rep.mesglen + 3) & ~3)) >> 2;
    
    if (client->swapped) {
    	swaps(&rep.sequenceNumber, n);
    	swapl(&rep.length, n);
    	swaps(&rep.mesglen, n);
    }
    WriteToClient(client, SIZEOF(xXF86MiscPassMessageReply), (char *)&rep);
    
    if (rep.mesglen)
        WriteToClient(client, rep.mesglen, (char *)retstr);

    return (client->noClientException);
}

static int
ProcXF86MiscDispatch (client)
    register ClientPtr	client;
{
    REQUEST(xReq);
    switch (stuff->data)
    {
    case X_XF86MiscQueryVersion:
	return ProcXF86MiscQueryVersion(client);
#ifdef _XF86MISC_SAVER_COMPAT_
    case X_XF86MiscGetSaver:
	return ProcXF86MiscGetSaver(client);
    case X_XF86MiscSetSaver:
	return ProcXF86MiscSetSaver(client);
#endif
    case X_XF86MiscGetMouseSettings:
	return ProcXF86MiscGetMouseSettings(client);
    case X_XF86MiscGetKbdSettings:
	return ProcXF86MiscGetKbdSettings(client);
    case X_XF86MiscSetClientVersion:
		return ProcXF86MiscSetClientVersion(client);
    case X_XF86MiscGetFilePaths:
	return ProcXF86MiscGetFilePaths(client);
    case X_XF86MiscPassMessage:
	return ProcXF86MiscPassMessage(client);
    default:
	if (!xf86GetModInDevEnabled())
	    return miscErrorBase + XF86MiscModInDevDisabled;
	if (xf86GetModInDevAllowNonLocal() || LocalClient (client)) {
	    switch (stuff->data) {
	        case X_XF86MiscSetMouseSettings:
		    return ProcXF86MiscSetMouseSettings(client);
	        case X_XF86MiscSetKbdSettings:
		    return ProcXF86MiscSetKbdSettings(client);
		case X_XF86MiscSetGrabKeysState:
		    return ProcXF86MiscSetGrabKeysState(client);
	        default:
		    return BadRequest;
	    }
	} else
	    return miscErrorBase + XF86MiscModInDevClientNotLocal;
    }
}

static int
SProcXF86MiscQueryVersion(client)
    register ClientPtr	client;
{
    register int n;
    REQUEST(xXF86MiscQueryVersionReq);
    swaps(&stuff->length, n);
    return ProcXF86MiscQueryVersion(client);
}

#ifdef _XF86MISC_SAVER_COMPAT_
static int
SProcXF86MiscGetSaver(client)
    ClientPtr client;
{
    register int n;
    REQUEST(xXF86MiscGetSaverReq);
    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xXF86MiscGetSaverReq);
    swaps(&stuff->screen, n);
    return ProcXF86MiscGetSaver(client);
}

static int
SProcXF86MiscSetSaver(client)
    ClientPtr client;
{
    register int n;
    REQUEST(xXF86MiscSetSaverReq);
    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xXF86MiscSetSaverReq);
    swaps(&stuff->screen, n);
    swapl(&stuff->suspendTime, n);
    swapl(&stuff->offTime, n);
    return ProcXF86MiscSetSaver(client);
}
#endif /* _XF86MISC_SAVER_COMPAT_ */

static int
SProcXF86MiscGetMouseSettings(client)
    ClientPtr client;
{
    register int n;
    REQUEST(xXF86MiscGetMouseSettingsReq);
    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xXF86MiscGetMouseSettingsReq);
    return ProcXF86MiscGetMouseSettings(client);
}

static int
SProcXF86MiscGetKbdSettings(client)
    ClientPtr client;
{
    register int n;
    REQUEST(xXF86MiscGetKbdSettingsReq);
    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xXF86MiscGetKbdSettingsReq);
    return ProcXF86MiscGetKbdSettings(client);
}

static int
SProcXF86MiscSetMouseSettings(client)
    ClientPtr client;
{
    register int n;
    REQUEST(xXF86MiscSetMouseSettingsReq);
    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xXF86MiscSetMouseSettingsReq);
    swapl(&stuff->mousetype, n);
    swapl(&stuff->baudrate, n);
    swapl(&stuff->samplerate, n);
    swapl(&stuff->resolution, n);
    swapl(&stuff->buttons, n);
    swapl(&stuff->emulate3timeout, n);
    swapl(&stuff->flags, n);
    return ProcXF86MiscSetMouseSettings(client);
}

static int
SProcXF86MiscSetKbdSettings(client)
    ClientPtr client;
{
    register int n;
    REQUEST(xXF86MiscSetKbdSettingsReq);
    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xXF86MiscSetKbdSettingsReq);
    swapl(&stuff->kbdtype, n);
    swapl(&stuff->rate, n);
    swapl(&stuff->delay, n);
    return ProcXF86MiscSetKbdSettings(client);
}

static int
SProcXF86MiscSetGrabKeysState(client)
    ClientPtr client;
{
    register int n;
    REQUEST(xXF86MiscSetGrabKeysStateReq);
    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xXF86MiscSetGrabKeysStateReq);
    swaps(&stuff->enable, n);
    return ProcXF86MiscSetGrabKeysState(client);
}

static int
SProcXF86MiscSetClientVersion(ClientPtr client)
{
    register int n;
    REQUEST(xXF86MiscSetClientVersionReq);
    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xXF86MiscSetClientVersionReq);
    swaps(&stuff->major, n);
    swaps(&stuff->minor, n);
    return ProcXF86MiscSetClientVersion(client);
}

static int
SProcXF86MiscGetFilePaths(client)
    ClientPtr client;
{
    register int n;
    REQUEST(xXF86MiscGetFilePathsReq);
    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xXF86MiscGetFilePathsReq);
    return ProcXF86MiscGetFilePaths(client);
}

static int
SProcXF86MiscPassMessage(client)
    ClientPtr client;
{
    register int n;
    REQUEST(xXF86MiscPassMessageReq);
    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xXF86MiscPassMessageReq);
    return ProcXF86MiscPassMessage(client);
}

static int
SProcXF86MiscDispatch (client)
    register ClientPtr	client;
{
    REQUEST(xReq);
    switch (stuff->data)
    {
    case X_XF86MiscQueryVersion:
	return SProcXF86MiscQueryVersion(client);
#ifdef _XF86MISC_SAVER_COMPAT_
    case X_XF86MiscGetSaver:
	return SProcXF86MiscGetSaver(client);
    case X_XF86MiscSetSaver:
	return SProcXF86MiscSetSaver(client);
#endif
    case X_XF86MiscGetMouseSettings:
	return SProcXF86MiscGetMouseSettings(client);
    case X_XF86MiscGetKbdSettings:
	return SProcXF86MiscGetKbdSettings(client);
    case X_XF86MiscSetClientVersion:
	return SProcXF86MiscSetClientVersion(client);
    case X_XF86MiscGetFilePaths:
	return SProcXF86MiscGetFilePaths(client);
    case X_XF86MiscPassMessage:
	return SProcXF86MiscPassMessage(client);
    default:
	if (!xf86GetModInDevEnabled())
	    return miscErrorBase + XF86MiscModInDevDisabled;
	if (xf86GetModInDevAllowNonLocal() || LocalClient (client)) {
	    switch (stuff->data) {
	        case X_XF86MiscSetMouseSettings:
		    return SProcXF86MiscSetMouseSettings(client);
	        case X_XF86MiscSetKbdSettings:
		    return SProcXF86MiscSetKbdSettings(client);
	        case X_XF86MiscSetGrabKeysState:
		    return SProcXF86MiscSetGrabKeysState(client);
	        default:
		    return BadRequest;
	    }
	} else
	    return miscErrorBase + XF86MiscModInDevClientNotLocal;
    }
}


--- NEW FILE: xf86miscproc.h ---
/* $XFree86: xc/programs/Xserver/Xext/xf86miscproc.h,v 1.5 2002/11/20 04:04:58 dawes Exp $ */

/* Prototypes for Pointer/Keyboard functions that the DDX must provide */

#ifndef _XF86MISCPROC_H_
#define _XF86MISCPROC_H_

typedef enum {
    MISC_MSE_PROTO,
    MISC_MSE_BAUDRATE,
    MISC_MSE_SAMPLERATE,
    MISC_MSE_RESOLUTION,
    MISC_MSE_BUTTONS,
    MISC_MSE_EM3BUTTONS,
    MISC_MSE_EM3TIMEOUT,
    MISC_MSE_CHORDMIDDLE,
    MISC_MSE_FLAGS
} MiscExtMseValType;

typedef enum {
    MISC_KBD_TYPE,
    MISC_KBD_RATE,
    MISC_KBD_DELAY,
    MISC_KBD_SERVNUMLOCK
} MiscExtKbdValType;

typedef enum {
    MISC_RET_SUCCESS,
    MISC_RET_BADVAL,
    MISC_RET_BADMSEPROTO,
    MISC_RET_BADBAUDRATE,
    MISC_RET_BADFLAGS,
    MISC_RET_BADCOMBO,
    MISC_RET_BADKBDTYPE,
    MISC_RET_NOMODULE
} MiscExtReturn;

typedef enum {
    MISC_POINTER,
    MISC_KEYBOARD
} MiscExtStructType;

#define MISC_MSEFLAG_CLEARDTR	1
#define MISC_MSEFLAG_CLEARRTS	2
#define MISC_MSEFLAG_REOPEN	128

void XFree86MiscExtensionInit(void);

Bool MiscExtGetMouseSettings(pointer *mouse, char **devname);
int  MiscExtGetMouseValue(pointer mouse, MiscExtMseValType valtype);
Bool MiscExtSetMouseValue(pointer mouse, MiscExtMseValType valtype, int value);
Bool MiscExtGetKbdSettings(pointer *kbd);
int  MiscExtGetKbdValue(pointer kbd, MiscExtKbdValType valtype);
Bool MiscExtSetKbdValue(pointer kbd, MiscExtKbdValType valtype, int value);
int MiscExtSetGrabKeysState(ClientPtr client, int enable);
pointer MiscExtCreateStruct(MiscExtStructType mse_or_kbd);
void    MiscExtDestroyStruct(pointer structure, MiscExtStructType mse_or_kbd);
MiscExtReturn MiscExtApply(pointer structure, MiscExtStructType mse_or_kbd);
Bool MiscExtSetMouseDevice(pointer mouse, char* device);
Bool MiscExtGetFilePaths(const char **configfile, const char **modulepath,
			 const char **logfile);
int  MiscExtPassMessage(int scrn, const char *msgtype, const char *msgval,
			  char **retstr);

#endif


--- NEW FILE: xf86noBus.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86noBus.c,v 1.2 2003/08/24 17:36:55 dawes Exp $ */

/*
 * Copyright (c) 2000-2002 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 * This file contains the interfaces to the bus-specific code
 */

#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <X11/X.h>
#include "os.h"
#include "xf86.h"
#include "xf86Priv.h"
#include "xf86Resources.h"

#include "xf86Bus.h"

#define XF86_OS_PRIVS
#define NEED_OS_RAC_PROTOS
#include "xf86_OSproc.h"

#include "xf86RAC.h"

int
xf86ClaimNoSlot(DriverPtr drvp, int chipset, GDevPtr dev, Bool active)
{
    EntityPtr p;
    int num;
    
    num = xf86AllocateEntity();
    p = xf86Entities[num];
    p->driver = drvp;
    p->chipset = 0;
    p->busType = BUS_NONE;
    p->active = active;
    p->inUse = FALSE;
    xf86AddDevToEntity(num, dev);
    p->access = xnfcalloc(1,sizeof(EntityAccessRec));
    p->access->fallback = &AccessNULL;
    p->access->pAccess = &AccessNULL;
    p->busAcc = NULL;

    return num;
}

--- NEW FILE: xf86pciBus.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86pciBus.c,v 3.77 2003/11/03 05:11:03 tsi Exp $ */
/*
 * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
[...3518 lines suppressed...]
#ifdef INCLUDE_DEPRECATED
void
xf86EnablePciBusMaster(pciVideoPtr pPci, Bool enable)
{
    CARD32 temp;
    PCITAG tag;

    if (!pPci) return;

    tag = pciTag(pPci->bus, pPci->device, pPci->func);
    temp = pciReadLong(tag, PCI_CMD_STAT_REG);
    if (enable) {
	updateAccessInfoStatusControlInfo(tag, temp | PCI_CMD_MASTER_ENABLE);
	pciWriteLong(tag, PCI_CMD_STAT_REG, temp | PCI_CMD_MASTER_ENABLE);
    } else {
	updateAccessInfoStatusControlInfo(tag, temp & ~PCI_CMD_MASTER_ENABLE);
	pciWriteLong(tag, PCI_CMD_STAT_REG, temp & ~PCI_CMD_MASTER_ENABLE);
    }
}
#endif /* INCLUDE_DEPRECATED */

--- NEW FILE: xf86pciBus.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86pciBus.h,v 3.10 2003/08/24 17:36:56 dawes Exp $ */

/*
 * Copyright (c) 1999-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

#ifndef _XF86_PCI_BUS_H
#define _XF86_PCI_BUS_H

#define PCITAG_SPECIAL pciTag(0xFF,0xFF,0xFF)

typedef struct {
    CARD32 command;
    CARD32 base[6];
    CARD32 biosBase;
} pciSave, *pciSavePtr;

typedef struct {
    PCITAG tag;
    CARD32 ctrl;
} pciArg;

typedef struct {
    int busnum;
    int devnum;
    int funcnum;
    pciArg arg;
    xf86AccessRec ioAccess;
    xf86AccessRec io_memAccess;
    xf86AccessRec memAccess;
    pciSave save;
    pciSave restore;
    Bool ctrl;
} pciAccRec, *pciAccPtr;

typedef union {
    CARD16 control;
} pciBridgesSave, *pciBridgesSavePtr;

typedef struct pciBusRec {
    int brbus, brdev, brfunc;	/* ID of the bridge to this bus */
    int primary, secondary, subordinate;
    int subclass;		/* bridge type */
    int interface;
    resPtr preferred_io;	/* I/O range */
    resPtr preferred_mem;	/* non-prefetchable memory range */
    resPtr preferred_pmem;	/* prefetchable memory range */
    resPtr io;			/* for subtractive PCI-PCI bridges */
    resPtr mem;
    resPtr pmem;
    int brcontrol;		/* bridge_control byte */
    struct pciBusRec *next;
} PciBusRec, *PciBusPtr;

void xf86PciProbe(void);
void ValidatePci(void);
resList GetImplicitPciResources(int entityIndex);
void initPciState(void);
void initPciBusState(void);
void DisablePciAccess(void);
void DisablePciBusAccess(void);
void PciStateEnter(void);
void PciBusStateEnter(void);
void PciStateLeave(void);
void PciBusStateLeave(void);
resPtr ResourceBrokerInitPci(resPtr *osRes);
void pciConvertRange2Host(int entityIndex, resRange *pRange);
void isaConvertRange2Host(resRange *pRange);

extern pciAccPtr * xf86PciAccInfo;

#endif /* _XF86_PCI_BUS_H */

--- NEW FILE: xf86sbusBus.c ---
/*
 * SBUS bus-specific code.
 *
 * Copyright (C) 2000 Jakub Jelinek (jakub at redhat.com)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * JAKUB JELINEK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86sbusBus.c,v 3.6 2001/03/03 22:16:35 tsi Exp $ */

#include <ctype.h>
#include <stdio.h>
#include <unistd.h>
#include <X11/X.h>
#include "os.h"
#include "xf86.h"
#include "xf86Priv.h"
#include "xf86_OSlib.h"
#include "xf86Resources.h"
#include "xf86cmap.h"

#include "xf86Bus.h"

#include "xf86sbusBus.h"
#include "xf86Sbus.h"

Bool sbusSlotClaimed = FALSE;

static int xf86nSbusInfo;

static void
CheckSbusDevice(const char *device, int fbNum)
{
    int fd, i;
    struct fbgattr fbattr;
    sbusDevicePtr psdp;

    fd = open(device, O_RDONLY, 0);
    if (fd < 0)
	return;
    memset(&fbattr, 0, sizeof(fbattr));
    if (ioctl(fd, FBIOGATTR, &fbattr) < 0) {
	if (ioctl(fd, FBIOGTYPE, &fbattr.fbtype) < 0) {
	    close(fd);
	    return;
	}
    }
    close(fd);
    for (i = 0; sbusDeviceTable[i].devId; i++)
	if (sbusDeviceTable[i].fbType == fbattr.fbtype.fb_type)
	    break;
    if (! sbusDeviceTable[i].devId)
	return;
    xf86SbusInfo = xnfrealloc(xf86SbusInfo, sizeof(psdp) * (++xf86nSbusInfo + 1));
    xf86SbusInfo[xf86nSbusInfo] = NULL;
    xf86SbusInfo[xf86nSbusInfo - 1] = psdp = xnfcalloc(sizeof (sbusDevice), 1);
    psdp->devId = sbusDeviceTable[i].devId;
    psdp->fbNum = fbNum;
    psdp->device = xnfstrdup(device);
    psdp->width = fbattr.fbtype.fb_width;
    psdp->height = fbattr.fbtype.fb_height;
    psdp->fd = -1;
}

void
xf86SbusProbe(void)
{
    int i, useProm = 0;
    char fbDevName[32];
    sbusDevicePtr psdp, *psdpp;

    xf86SbusInfo = xalloc(sizeof(psdp));
    *xf86SbusInfo = NULL;
    for (i = 0; i < 32; i++) {
	sprintf(fbDevName, "/dev/fb%d", i);
	CheckSbusDevice(fbDevName, i);
    }
    if (sparcPromInit() >= 0) {
	useProm = 1;
	sparcPromAssignNodes();
    }
    for (psdpp = xf86SbusInfo; (psdp = *psdpp); psdpp++) {
	for (i = 0; sbusDeviceTable[i].devId; i++)
	    if (sbusDeviceTable[i].devId == psdp->devId)
		psdp->descr = sbusDeviceTable[i].descr;
	/*
	 * If we can use PROM information and found the PROM node for this
	 * device, we can tell more about the card.
	 */
	if (useProm && psdp->node.node) {
	    char *prop, *promPath;
	    int len, chiprev, vmsize;

	    switch (psdp->devId) {
	    case SBUS_DEVICE_MGX:
		prop = sparcPromGetProperty(&psdp->node, "fb_size", &len);
		if (prop && len == 4 && *(int *)prop == 0x400000)
		    psdp->descr = "Quantum 3D MGXplus with 4M VRAM";
		break;
	    case SBUS_DEVICE_CG6:
		chiprev = 0;
		vmsize = 0;
		prop = sparcPromGetProperty(&psdp->node, "chiprev", &len);
		if (prop && len == 4)
		    chiprev = *(int *)prop;
		prop = sparcPromGetProperty(&psdp->node, "vmsize", &len);
		if (prop && len == 4)
		    vmsize = *(int *)prop;
		switch (chiprev) {
		case 1:
		case 2:
		case 3:
		case 4:
		    psdp->descr = "Sun Double width GX"; break;
		case 5:
		case 6:
		case 7:
		case 8:
		case 9:
		    psdp->descr = "Sun Single width GX"; break;
		case 11:
		    switch (vmsize) {
		    case 2:
			psdp->descr = "Sun Turbo GX with 1M VSIMM"; break;
		    case 4:
			psdp->descr = "Sun Turbo GX Plus"; break;
		    default:
			psdp->descr = "Sun Turbo GX"; break;
		    }
		}
		break;
	    case SBUS_DEVICE_CG14:
		prop = sparcPromGetProperty(&psdp->node, "reg", &len);
		vmsize = 0;
		if (prop && !(len % 12) && len > 0)
		    vmsize = *(int *)(prop + len - 4);
		switch (vmsize) {
		case 0x400000:
		    psdp->descr = "Sun SX with 4M VSIMM"; break;
		case 0x800000:
		    psdp->descr = "Sun SX with 8M VSIMM"; break;
		}
		break;
	    case SBUS_DEVICE_LEO:
		prop = sparcPromGetProperty(&psdp->node, "model", &len);
		if (prop && len > 0 && !strstr(prop, "501-2503"))
		    psdp->descr = "Sun Turbo ZX";
		break;
	    case SBUS_DEVICE_TCX:
		if (sparcPromGetBool(&psdp->node, "tcx-8-bit"))
		    psdp->descr = "Sun TCX (8bit)";
		else
		    psdp->descr = "Sun TCX (S24)";
		break;
	    case SBUS_DEVICE_FFB:
		prop = sparcPromGetProperty(&psdp->node, "name", &len);
		chiprev = 0;
		prop = sparcPromGetProperty(&psdp->node, "board_type", &len);
		if (prop && len == 4)
		    chiprev = *(int *)prop;
		if (strstr (prop, "afb")) {
		    if (chiprev == 3)
			psdp->descr = "Sun|Elite3D-M6 Horizontal";
		} else {
		    switch (chiprev) {
		    case 0x08:
			psdp->descr = "Sun FFB 67MHz Creator"; break;
		    case 0x0b:
			psdp->descr = "Sun FFB 67MHz Creator 3D"; break;
		    case 0x1b:
			psdp->descr = "Sun FFB 75MHz Creator 3D"; break;
		    case 0x20:
		    case 0x28:
			psdp->descr = "Sun FFB2 Vertical Creator"; break;
		    case 0x23:
		    case 0x2b:
			psdp->descr = "Sun FFB2 Vertical Creator 3D"; break;
		    case 0x30:
			psdp->descr = "Sun FFB2+ Vertical Creator"; break;
		    case 0x33:
			psdp->descr = "Sun FFB2+ Vertical Creator 3D"; break;
		    case 0x40:
		    case 0x48:
			psdp->descr = "Sun FFB2 Horizontal Creator"; break;
		    case 0x43:
		    case 0x4b:
			psdp->descr = "Sun FFB2 Horizontal Creator 3D"; break;
		    }
		}
		break;
	    }

	    xf86Msg(X_PROBED, "SBUS:(0x%08x) %s", psdp->node.node, psdp->descr);
	    promPath = sparcPromNode2Pathname (&psdp->node);
	    if (promPath) {
		xf86ErrorF(" at %s", promPath);
		xfree(promPath);
	    }
	} else
	    xf86Msg(X_PROBED, "SBUS: %s", psdp->descr);
	xf86ErrorF("\n");
    }
    if (useProm)
	sparcPromClose();
}

/*
 * Parse a BUS ID string, and return the SBUS bus parameters if it was
 * in the correct format for a SBUS bus id.
 */

Bool
xf86ParseSbusBusString(const char *busID, int *fbNum)
{
    /*
     * The format is assumed to be one of:
     * "fbN", e.g. "fb1", which means the device corresponding to /dev/fbN
     * "nameN", e.g. "cgsix0", which means Nth instance of card NAME
     * "/prompath", e.g. "/sbus at 0,10001000/cgsix at 3,0" which is PROM pathname
     * to the device.
     */

    const char *id;
    int i, len;

    if (StringToBusType(busID, &id) != BUS_SBUS)
	return FALSE;

    if (*id != '/') {
	if (!strncmp (id, "fb", 2)) {
	    if (!isdigit(id[2]))
		return FALSE;
	    *fbNum = atoi(id + 2);
	    return TRUE;
	} else {
	    sbusDevicePtr *psdpp;
	    int devId;

	    for (i = 0, len = 0; sbusDeviceTable[i].devId; i++) {
		len = strlen(sbusDeviceTable[i].promName);
		if (!strncmp (sbusDeviceTable[i].promName, id, len)
		    && isdigit(id[len]))
		    break;
	    }
	    devId = sbusDeviceTable[i].devId;
	    if (!devId) return FALSE;
	    i = atoi(id + len);
	    for (psdpp = xf86SbusInfo; *psdpp; ++psdpp) {
		if ((*psdpp)->devId != devId)
		    continue;
		if (!i) {
		    *fbNum = (*psdpp)->fbNum;
		    return TRUE;
		}
		i--;
	    }
	}
	return FALSE;
    }

    if (sparcPromInit() >= 0) {
	i = sparcPromPathname2Node(id);
	sparcPromClose();
	if (i) {
	    sbusDevicePtr *psdpp;
	    for (psdpp = xf86SbusInfo; *psdpp; ++psdpp) {
		if ((*psdpp)->node.node == i) {
		    *fbNum = (*psdpp)->fbNum;
		    return TRUE;
		}
	    }
	}
    }
    return FALSE;
}

/*
 * Compare a BUS ID string with a SBUS bus id.  Return TRUE if they match.
 */

Bool
xf86CompareSbusBusString(const char *busID, int fbNum)
{
    int iFbNum;

    if (xf86ParseSbusBusString(busID, &iFbNum)) {
	return fbNum == iFbNum;
    } else {
	return FALSE;
    }
}

/*
 * Check if the slot requested is free.  If it is already in use, return FALSE.
 */

Bool
xf86CheckSbusSlot(int fbNum)
{
    int i;
    EntityPtr p;

    for (i = 0; i < xf86NumEntities; i++) {
	p = xf86Entities[i];
	/* Check if this SBUS slot is taken */
	if (p->busType == BUS_SBUS && p->sbusBusId.fbNum == fbNum)
	    return FALSE;
    }

    return TRUE;
}

/*
 * If the slot requested is already in use, return -1.
 * Otherwise, claim the slot for the screen requesting it.
 */

int
xf86ClaimSbusSlot(sbusDevicePtr psdp, DriverPtr drvp,
		  GDevPtr dev, Bool active)
{
    EntityPtr p = NULL;

    int num;

    if (xf86CheckSbusSlot(psdp->fbNum)) {
        num = xf86AllocateEntity();
        p = xf86Entities[num];
        p->driver = drvp;
        p->chipset = -1;
        p->busType = BUS_SBUS;
        xf86AddDevToEntity(num, dev);
        p->sbusBusId.fbNum = psdp->fbNum;
        p->active = active;
        p->inUse = FALSE;
        /* Here we initialize the access structure */
        p->access = xnfcalloc(1,sizeof(EntityAccessRec));
	p->access->fallback = &AccessNULL;
        p->access->pAccess = &AccessNULL;
	sbusSlotClaimed = TRUE;
	return num;
    } else
	return -1;
}

int
xf86MatchSbusInstances(const char *driverName, int sbusDevId, 
		       GDevPtr *devList, int numDevs, DriverPtr drvp,
		       int **foundEntities)
{
    int i,j;
    sbusDevicePtr psdp, *psdpp;
    int numClaimedInstances = 0;
    int allocatedInstances = 0;
    int numFound = 0;
    GDevPtr devBus = NULL;
    GDevPtr dev = NULL;
    int *retEntities = NULL;
    int useProm = 0;

    struct Inst {
	sbusDevicePtr	sbus;
	GDevPtr		dev;
	Bool		claimed;  /* BusID matches with a device section */
    } *instances = NULL;

    *foundEntities = NULL;
    for (psdpp = xf86SbusInfo, psdp = *psdpp; psdp; psdp = *++psdpp) {
	if (psdp->devId != sbusDevId)
	    continue;
	if (psdp->fd == -2)
	    continue;
	++allocatedInstances;
	instances = xnfrealloc(instances,
			       allocatedInstances * sizeof(struct Inst));
	instances[allocatedInstances - 1].sbus = psdp;
	instances[allocatedInstances - 1].dev = NULL;
	instances[allocatedInstances - 1].claimed = FALSE;
	numFound++;
    }

    /*
     * This may be debatable, but if no SBUS devices with a matching vendor
     * type is found, return zero now.  It is probably not desirable to
     * allow the config file to override this.
     */
    if (allocatedInstances <= 0) {
	xfree(instances);
	return 0;
    }

    if (xf86DoProbe) {
	xfree(instances);
	return numFound;
    }

    if (sparcPromInit() >= 0)
	useProm = 1;

    if (xf86DoConfigure && xf86DoConfigurePass1) {
	GDevPtr pGDev;
	int actualcards = 0;
	for (i = 0; i < allocatedInstances; i++) {
	    actualcards++;
	    pGDev = xf86AddBusDeviceToConfigure(drvp->driverName, BUS_SBUS,
						instances[i].sbus, -1);
	    if (pGDev) {
		/*
		 * XF86Match???Instances() treat chipID and chipRev as
		 * overrides, so clobber them here.
		 */
		pGDev->chipID = pGDev->chipRev = -1;
	    }
	}
	xfree(instances);
	if (useProm)
	    sparcPromClose();
	return actualcards;
    }

#ifdef DEBUG
    ErrorF("%s instances found: %d\n", driverName, allocatedInstances);
#endif

    for (i = 0; i < allocatedInstances; i++) {
	char *promPath = NULL;

	psdp = instances[i].sbus;
	devBus = NULL;
	dev = NULL;
	if (useProm && psdp->node.node)
	    promPath = sparcPromNode2Pathname(&psdp->node);

	for (j = 0; j < numDevs; j++) {
	    if (devList[j]->busID && *devList[j]->busID) {
		if (xf86CompareSbusBusString(devList[j]->busID, psdp->fbNum)) {
		    if (devBus)
			xf86MsgVerb(X_WARNING,0,
			    "%s: More than one matching Device section for "
			    "instance (BusID: %s) found: %s\n",
			    driverName,devList[j]->identifier,
			    devList[j]->busID);
		    else
			devBus = devList[j];
		} 
	    } else {
		if (!dev && !devBus) {
		    if (promPath)
			xf86Msg(X_PROBED, "Assigning device section with no busID to SBUS:%s\n",
				promPath);
		    else
			xf86Msg(X_PROBED, "Assigning device section with no busID to SBUS:fb%d\n",
				psdp->fbNum);
		    dev = devList[j];
		} else
		    xf86MsgVerb(X_WARNING, 0,
			    "%s: More than one matching Device section "
			    "found: %s\n", driverName, devList[j]->identifier);
	    }
	}
	if (devBus) dev = devBus;  /* busID preferred */ 
	if (!dev && psdp->fd != -2) {
	    if (promPath) {
		xf86MsgVerb(X_WARNING, 0, "%s: No matching Device section "
			    "for instance (BusID SBUS:%s) found\n",
			    driverName, promPath);
	    } else
		xf86MsgVerb(X_WARNING, 0, "%s: No matching Device section "
			    "for instance (BusID SBUS:fb%d) found\n",
			    driverName, psdp->fbNum);
	} else if (dev) {
	    numClaimedInstances++;
	    instances[i].claimed = TRUE;
	    instances[i].dev = dev;
	}
	if (promPath)
	    xfree(promPath);
    }

#ifdef DEBUG
    ErrorF("%s instances found: %d\n", driverName, numClaimedInstances);
#endif

    /*
     * Of the claimed instances, check that another driver hasn't already
     * claimed its slot.
     */
    numFound = 0;
    for (i = 0; i < allocatedInstances && numClaimedInstances > 0; i++) {
	if (!instances[i].claimed)
	    continue;
	psdp = instances[i].sbus;
	if (!xf86CheckSbusSlot(psdp->fbNum))
	    continue;

#ifdef DEBUG
	ErrorF("%s: card at fb%d %08x is claimed by a Device section\n",
	       driverName, psdp->fbNum, psdp->node.node);
#endif
	
	/* Allocate an entry in the lists to be returned */
	numFound++;
	retEntities = xnfrealloc(retEntities, numFound * sizeof(int));
	retEntities[numFound - 1]
	    = xf86ClaimSbusSlot(psdp, drvp, instances[i].dev,instances[i].dev->active ?
				TRUE : FALSE);
    }
    xfree(instances);
    if (numFound > 0) {
	*foundEntities = retEntities;
    }

    if (useProm)
	sparcPromClose();

    return numFound;
}

/*
 * xf86GetSbusInfoForEntity() -- Get the sbusDevicePtr of entity.
 */
sbusDevicePtr
xf86GetSbusInfoForEntity(int entityIndex)
{
    sbusDevicePtr *psdpp;
    EntityPtr p = xf86Entities[entityIndex];

    if (entityIndex >= xf86NumEntities
	|| p->busType != BUS_SBUS) return NULL;

    for (psdpp = xf86SbusInfo; *psdpp != NULL; psdpp++) {
	if (p->sbusBusId.fbNum == (*psdpp)->fbNum)
	    return (*psdpp);
    }
    return NULL;
}

int
xf86GetEntityForSbusInfo(sbusDevicePtr psdp)
{
    int i;

    for (i = 0; i < xf86NumEntities; i++) {
	EntityPtr p = xf86Entities[i];
	if (p->busType != BUS_SBUS) continue;

	if (p->sbusBusId.fbNum == psdp->fbNum)
	    return i;
    }
    return -1;
}

void
xf86SbusUseBuiltinMode(ScrnInfoPtr pScrn, sbusDevicePtr psdp)
{
    DisplayModePtr mode;

    mode = xnfcalloc(sizeof(DisplayModeRec), 1);
    mode->name = "current";
    mode->next = mode;
    mode->prev = mode;
    mode->type = M_T_BUILTIN;
    mode->Clock = 100000000;
    mode->HDisplay = psdp->width;
    mode->HSyncStart = psdp->width;
    mode->HSyncEnd = psdp->width;
    mode->HTotal = psdp->width;
    mode->VDisplay = psdp->height;
    mode->VSyncStart = psdp->height;
    mode->VSyncEnd = psdp->height;
    mode->VTotal = psdp->height;
    mode->SynthClock = mode->Clock;
    mode->CrtcHDisplay = mode->HDisplay;
    mode->CrtcHSyncStart = mode->HSyncStart;
    mode->CrtcHSyncEnd = mode->HSyncEnd;
    mode->CrtcHTotal = mode->HTotal;
    mode->CrtcVDisplay = mode->VDisplay;
    mode->CrtcVSyncStart = mode->VSyncStart;
    mode->CrtcVSyncEnd = mode->VSyncEnd;
    mode->CrtcVTotal = mode->VTotal;
    mode->CrtcHAdjusted = FALSE;
    mode->CrtcVAdjusted = FALSE;
    pScrn->modes = mode;
    pScrn->virtualX = psdp->width;
    pScrn->virtualY = psdp->height;
}

static int sbusPaletteIndex = -1;
static unsigned long sbusPaletteGeneration = 0;
typedef struct _sbusCmap {
    sbusDevicePtr psdp;
    CloseScreenProcPtr CloseScreen;
    Bool origCmapValid;
    unsigned char origRed[16];
    unsigned char origGreen[16];
    unsigned char origBlue[16];
} sbusCmapRec, *sbusCmapPtr;

#define SBUSCMAPPTR(pScreen) ((sbusCmapPtr)((pScreen)->devPrivates[sbusPaletteIndex].ptr))

static void
xf86SbusCmapLoadPalette(ScrnInfoPtr pScrn, int numColors, int *indices,
			LOCO *colors, VisualPtr pVisual)
{
    int i, index;
    sbusCmapPtr cmap;
    struct fbcmap fbcmap;
    unsigned char *data = ALLOCATE_LOCAL(numColors*3);
                             
    cmap = SBUSCMAPPTR(pScrn->pScreen);
    if (!cmap) return;
    fbcmap.count = 0;
    fbcmap.index = indices[0];
    fbcmap.red = data;
    fbcmap.green = data + numColors;
    fbcmap.blue = fbcmap.green + numColors;
    for (i = 0; i < numColors; i++) {
	index = indices[i];
	if (fbcmap.count && index != fbcmap.index + fbcmap.count) {
	    ioctl (cmap->psdp->fd, FBIOPUTCMAP, &fbcmap);
	    fbcmap.count = 0;
	    fbcmap.index = index;
	}
	fbcmap.red[fbcmap.count] = colors[index].red;
	fbcmap.green[fbcmap.count] = colors[index].green;
	fbcmap.blue[fbcmap.count++] = colors[index].blue;
    }
    ioctl (cmap->psdp->fd, FBIOPUTCMAP, &fbcmap);
    DEALLOCATE_LOCAL(data);
}

static Bool
xf86SbusCmapCloseScreen(int i, ScreenPtr pScreen)
{
    sbusCmapPtr cmap;
    struct fbcmap fbcmap;
                         
    cmap = SBUSCMAPPTR(pScreen);
    if (cmap->origCmapValid) {
	fbcmap.index = 0;
	fbcmap.count = 16;
	fbcmap.red = cmap->origRed;
	fbcmap.green = cmap->origGreen;
	fbcmap.blue = cmap->origBlue;
	ioctl (cmap->psdp->fd, FBIOPUTCMAP, &fbcmap);
    }
    pScreen->CloseScreen = cmap->CloseScreen;
    xfree (cmap);
    return (*pScreen->CloseScreen) (i, pScreen);
}    

Bool
xf86SbusHandleColormaps(ScreenPtr pScreen, sbusDevicePtr psdp)
{
    sbusCmapPtr cmap;
    struct fbcmap fbcmap;
    unsigned char data[2];

    if(sbusPaletteGeneration != serverGeneration) {
	if((sbusPaletteIndex = AllocateScreenPrivateIndex()) < 0)
	    return FALSE;
	sbusPaletteGeneration = serverGeneration;
    }
    cmap = xnfcalloc(1, sizeof(sbusCmapRec));
    pScreen->devPrivates[sbusPaletteIndex].ptr = cmap;
    cmap->psdp = psdp;
    fbcmap.index = 0;
    fbcmap.count = 16;
    fbcmap.red = cmap->origRed;
    fbcmap.green = cmap->origGreen;
    fbcmap.blue = cmap->origBlue;
    if (ioctl (psdp->fd, FBIOGETCMAP, &fbcmap) >= 0)
	cmap->origCmapValid = TRUE;
    fbcmap.index = 0;
    fbcmap.count = 2;
    fbcmap.red = data;
    fbcmap.green = data;
    fbcmap.blue = data;
    if (pScreen->whitePixel == 0) {
	data[0] = 255;
	data[1] = 0;
    } else {
	data[0] = 0;
	data[1] = 255;
    }
    ioctl (psdp->fd, FBIOPUTCMAP, &fbcmap);
    cmap->CloseScreen = pScreen->CloseScreen;
    pScreen->CloseScreen = xf86SbusCmapCloseScreen;
    return xf86HandleColormaps(pScreen, 256, 8,
			       xf86SbusCmapLoadPalette, NULL, 0);
}

--- NEW FILE: xf86sbusBus.h ---
/*
 * SBUS bus-specific declarations
 *
 * Copyright (C) 2000 Jakub Jelinek (jakub at redhat.com)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * JAKUB JELINEK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86sbusBus.h,v 3.4 2001/10/28 03:33:19 tsi Exp $ */

#ifndef _XF86_SBUSBUS_H
#define _XF86_SBUSBUS_H

#include "xf86str.h"

#define SBUS_DEVICE_BW2		0x0001
#define SBUS_DEVICE_CG2		0x0002
#define SBUS_DEVICE_CG3		0x0003
#define SBUS_DEVICE_CG4		0x0004
#define SBUS_DEVICE_CG6		0x0005
#define SBUS_DEVICE_CG8		0x0006
#define SBUS_DEVICE_CG12	0x0007
#define SBUS_DEVICE_CG14	0x0008
#define SBUS_DEVICE_LEO		0x0009
#define SBUS_DEVICE_TCX		0x000a
#define SBUS_DEVICE_FFB		0x000b
#define SBUS_DEVICE_GT		0x000c
#define SBUS_DEVICE_MGX		0x000d

typedef struct sbus_prom_node {
    int			node;
    /* Because of misdesigned openpromio */
    int			cookie[2];
} sbusPromNode, *sbusPromNodePtr;

typedef struct sbus_device {
    int			devId;
    int			fbNum;
    int			fd;
    int			width, height;
    sbusPromNode	node;
    char		*descr;
    char		*device;
} sbusDevice, *sbusDevicePtr;

extern struct sbus_devtable {
    int devId;
    int fbType;
    char *promName;
    char *descr;
} sbusDeviceTable[];

void xf86SbusProbe(void);
extern sbusDevicePtr *xf86SbusInfo;

int xf86MatchSbusInstances(const char *driverName, int sbusDevId, 
			   GDevPtr *devList, int numDevs, DriverPtr drvp,
			   int **foundEntities);
sbusDevicePtr xf86GetSbusInfoForEntity(int entityIndex);
int xf86GetEntityForSbusInfo(sbusDevicePtr psdp);
void xf86SbusUseBuiltinMode(ScrnInfoPtr pScrn, sbusDevicePtr psdp);
pointer xf86MapSbusMem(sbusDevicePtr psdp, unsigned long offset,
		       unsigned long size);
void xf86UnmapSbusMem(sbusDevicePtr psdp, pointer addr, unsigned long size);
void xf86SbusHideOsHwCursor(sbusDevicePtr psdp);
void xf86SbusSetOsHwCursorCmap(sbusDevicePtr psdp, int bg, int fg);
Bool xf86SbusHandleColormaps(ScreenPtr pScreen, sbusDevicePtr psdp);

extern int promRootNode;

int promGetSibling(int node);
int promGetChild(int node);
char * promGetProperty(const char *prop, int *lenp);
int promGetBool(const char *prop);

int sparcPromInit(void);
void sparcPromClose(void);
char * sparcPromGetProperty(sbusPromNodePtr pnode, const char *prop, int *lenp);
int sparcPromGetBool(sbusPromNodePtr pnode, const char *prop);
void sparcPromAssignNodes(void);
char * sparcPromNode2Pathname(sbusPromNodePtr pnode);
int sparcPromPathname2Node(const char *pathName);

#endif /* _XF86_SBUSBUS_H */

--- NEW FILE: xf86str.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86str.h,v 1.97 2003/10/30 17:36:56 tsi Exp $ */

/*
 * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
[...1033 lines suppressed...]
typedef enum {
    BUILTIN_IF_OSMOUSE = 0,
    BUILTIN_IF_OSKBD = 1,
    NUM_BUILTIN_IFS
} BuiltinInterface;

/*
 * These are intentionally the same as the module version macros.
 * It is possible to register a module as providing a specific interface,
 * in which case the module's version is used.  This feature isn't
 * really ready for use yet though.
 */

#define BUILTIN_INTERFACE_VERSION_NUMERIC(maj, min, patch) \
	((((maj) & 0xFF) << 24) | (((min) & 0xFF) << 16) | (patch & 0xFFFF))
#define GET_BUILTIN_INTERFACE_MAJOR_VERSION(vers)	(((vers) >> 24) & 0xFF)
#define GET_BUILTIN_INTERFACE_MINOR_VERSION(vers)	(((vers) >> 16) & 0xFF)
#define GET_BUILTIN_INTERFACE_PATCH_VERSION(vers)	((vers) & 0xFFFF)

#endif /* _XF86STR_H */

--- NEW FILE: xf86vmode.c ---
/* $XFree86: xc/programs/Xserver/Xext/xf86vmode.c,v 3.58 2003/11/06 18:37:57 tsi Exp $ */

/*

Copyright 1995  Kaleb S. KEITHLEY

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
[...2161 lines suppressed...]
		return SProcXF86VidModeModModeLine(client);
	    case X_XF86VidModeSwitchMode:
		return SProcXF86VidModeSwitchMode(client);
	    case X_XF86VidModeSwitchToMode:
		return SProcXF86VidModeSwitchToMode(client);
	    case X_XF86VidModeLockModeSwitch:
		return SProcXF86VidModeLockModeSwitch(client);
	    case X_XF86VidModeSetViewPort:
		return SProcXF86VidModeSetViewPort(client);
	    case X_XF86VidModeSetGamma:
		return SProcXF86VidModeSetGamma(client);
	    case X_XF86VidModeSetGammaRamp:
		return SProcXF86VidModeSetGammaRamp(client);
	    default:
		return BadRequest;
	    }
	} else
	    return VidModeErrorBase + XF86VidModeClientNotLocal;
    }
}

--- NEW FILE: xf86xv.c ---
/*
 * XFree86 Xv DDX written by Mark Vojkovich (markv at valinux.com)
 */
/*
 * Copyright (c) 1998-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
[...2007 lines suppressed...]
	    i = w;
	    while (i >= 4) {
		Dst[0] = Src[0];
		Dst[1] = Src[1];
		Dst[2] = Src[2];
		Dst[3] = Src[3];
		Dst += 4;  Src += 4;  i -= 4;
	    }
	    if (!i) break;
	    Dst[0] = Src[0];
	    if (i == 1) break;
	    Dst[1] = Src[1];
	    if (i == 2) break;
	    Dst[2] = Src[2];
	} while (0);

	src = (const CARD8 *)src + srcPitch;
	dst = (CARD8 *)dst + dstPitch;
    }
}

--- NEW FILE: xf86xv.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86xv.h,v 1.25 2003/08/24 17:36:56 dawes Exp $ */

/*
 * Copyright (c) 1998-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

#ifndef _XF86XV_H_
#define _XF86XV_H_

#include "xvdix.h"
#include "xf86str.h"

#define VIDEO_NO_CLIPPING			0x00000001
#define VIDEO_INVERT_CLIPLIST			0x00000002
#define VIDEO_OVERLAID_IMAGES			0x00000004
#define VIDEO_OVERLAID_STILLS			0x00000008
#define VIDEO_CLIP_TO_VIEWPORT			0x00000010

typedef struct {
  int id;
  int type;
  int byte_order;
  unsigned char guid[16];               
  int bits_per_pixel;
  int format;
  int num_planes;

  /* for RGB formats only */
  int depth;
  unsigned int red_mask;       
  unsigned int green_mask;   
  unsigned int blue_mask;   

  /* for YUV formats only */
  unsigned int y_sample_bits;
  unsigned int u_sample_bits;
  unsigned int v_sample_bits;   
  unsigned int horz_y_period;
  unsigned int horz_u_period;
  unsigned int horz_v_period;
  unsigned int vert_y_period;
  unsigned int vert_u_period;
  unsigned int vert_v_period;
  char component_order[32];
  int scanline_order;
} XF86ImageRec, *XF86ImagePtr; 


typedef struct {
  ScrnInfoPtr pScrn;
  int id;
  unsigned short width, height;
  int *pitches; /* bytes */
  int *offsets; /* in bytes from start of framebuffer */
  DevUnion devPrivate;  
} XF86SurfaceRec, *XF86SurfacePtr;


typedef int (* PutVideoFuncPtr)( ScrnInfoPtr pScrn, 
	short vid_x, short vid_y, short drw_x, short drw_y,
	short vid_w, short vid_h, short drw_w, short drw_h,
	RegionPtr clipBoxes, pointer data );
typedef int (* PutStillFuncPtr)( ScrnInfoPtr pScrn, 
	short vid_x, short vid_y, short drw_x, short drw_y,
	short vid_w, short vid_h, short drw_w, short drw_h,
	RegionPtr clipBoxes, pointer data );
typedef int (* GetVideoFuncPtr)( ScrnInfoPtr pScrn, 
	short vid_x, short vid_y, short drw_x, short drw_y,
	short vid_w, short vid_h, short drw_w, short drw_h,
	RegionPtr clipBoxes, pointer data );
typedef int (* GetStillFuncPtr)( ScrnInfoPtr pScrn, 
	short vid_x, short vid_y, short drw_x, short drw_y,
	short vid_w, short vid_h, short drw_w, short drw_h,
	RegionPtr clipBoxes, pointer data );
typedef void (* StopVideoFuncPtr)(ScrnInfoPtr pScrn, pointer data, Bool Exit);
typedef int (* SetPortAttributeFuncPtr)(ScrnInfoPtr pScrn, Atom attribute,
	INT32 value, pointer data);
typedef int (* GetPortAttributeFuncPtr)(ScrnInfoPtr pScrn, Atom attribute,
	INT32 *value, pointer data);
typedef void (* QueryBestSizeFuncPtr)(ScrnInfoPtr pScrn, Bool motion,
	short vid_w, short vid_h, short drw_w, short drw_h, 
	unsigned int *p_w, unsigned int *p_h, pointer data);
typedef int (* PutImageFuncPtr)( ScrnInfoPtr pScrn, 
	short src_x, short src_y, short drw_x, short drw_y,
	short src_w, short src_h, short drw_w, short drw_h,
	int image, unsigned char* buf, short width, short height, Bool Sync,
	RegionPtr clipBoxes, pointer data );
typedef int (* ReputImageFuncPtr)( ScrnInfoPtr pScrn, short drw_x, short drw_y,
        RegionPtr clipBoxes, pointer data );
typedef int (*QueryImageAttributesFuncPtr)(ScrnInfoPtr pScrn, 
	int image, unsigned short *width, unsigned short *height, 
	int *pitches, int *offsets);

typedef enum {
    XV_OFF,
    XV_PENDING,
    XV_ON
} XvStatus;

/*** this is what the driver needs to fill out ***/

typedef struct {
  int id;
  char *name;
  unsigned short width, height;
  XvRationalRec rate;
} XF86VideoEncodingRec, *XF86VideoEncodingPtr;

typedef struct {
  char 	depth;  
  short class;
} XF86VideoFormatRec, *XF86VideoFormatPtr;

typedef struct {
  int   flags;
  int   min_value;
  int   max_value;
  char  *name;
} XF86AttributeRec, *XF86AttributePtr;

typedef struct {
  unsigned int type; 
  int flags;
  char *name;
  int nEncodings;
  XF86VideoEncodingPtr pEncodings;  
  int nFormats;
  XF86VideoFormatPtr pFormats;  
  int nPorts;
  DevUnion *pPortPrivates;
  int nAttributes;
  XF86AttributePtr pAttributes;
  int nImages;
  XF86ImagePtr pImages;
  PutVideoFuncPtr PutVideo;
  PutStillFuncPtr PutStill;
  GetVideoFuncPtr GetVideo;
  GetStillFuncPtr GetStill;
  StopVideoFuncPtr StopVideo;
  SetPortAttributeFuncPtr SetPortAttribute;
  GetPortAttributeFuncPtr GetPortAttribute;
  QueryBestSizeFuncPtr QueryBestSize;
  PutImageFuncPtr PutImage;
  ReputImageFuncPtr ReputImage;
  QueryImageAttributesFuncPtr QueryImageAttributes;
} XF86VideoAdaptorRec, *XF86VideoAdaptorPtr;

typedef struct {
  XF86ImagePtr image;
  int flags;
  int (*alloc_surface)(ScrnInfoPtr pScrn,
		  int id,
		  unsigned short width, 	
		  unsigned short height,
		  XF86SurfacePtr surface);
  int (*free_surface)(XF86SurfacePtr surface);
  int (*display) (XF86SurfacePtr surface,
		  short vid_x, short vid_y, 
		  short drw_x, short drw_y,
		  short vid_w, short vid_h, 
		  short drw_w, short drw_h,
		  RegionPtr clipBoxes);
  int (*stop)    (XF86SurfacePtr surface);
  int (*getAttribute) (ScrnInfoPtr pScrn, Atom attr, INT32 *value);
  int (*setAttribute) (ScrnInfoPtr pScrn, Atom attr, INT32 value);
  int max_width;
  int max_height;
  int num_attributes;
  XF86AttributePtr attributes;
} XF86OffscreenImageRec, *XF86OffscreenImagePtr;

Bool
xf86XVScreenInit(
   ScreenPtr pScreen, 
   XF86VideoAdaptorPtr 	*Adaptors,
   int num
);

typedef int (* xf86XVInitGenericAdaptorPtr)(ScrnInfoPtr pScrn,
	XF86VideoAdaptorPtr **Adaptors);

int
xf86XVRegisterGenericAdaptorDriver(
    xf86XVInitGenericAdaptorPtr InitFunc
);

int
xf86XVListGenericAdaptors(
    ScrnInfoPtr          pScrn,
    XF86VideoAdaptorPtr  **Adaptors
);

Bool 
xf86XVRegisterOffscreenImages(
   ScreenPtr pScreen,
   XF86OffscreenImagePtr images,
   int num
);

XF86OffscreenImagePtr
xf86XVQueryOffscreenImages(
   ScreenPtr pScreen,
   int *num
);
   
XF86VideoAdaptorPtr xf86XVAllocateVideoAdaptorRec(ScrnInfoPtr pScrn);

void xf86XVFreeVideoAdaptorRec(XF86VideoAdaptorPtr ptr);

void
xf86XVFillKeyHelper (ScreenPtr pScreen, CARD32 key, RegionPtr clipboxes);

Bool
xf86XVClipVideoHelper(
    BoxPtr dst,
    INT32 *xa,
    INT32 *xb,
    INT32 *ya,
    INT32 *yb,
    RegionPtr reg,
    INT32 width,
    INT32 height
);

void
xf86XVCopyYUV12ToPacked(
    const void *srcy,
    const void *srcv,
    const void *srcu,
    void *dst,
    int srcPitchy,
    int srcPitchuv,
    int dstPitch,
    int h,
    int w
);

void
xf86XVCopyPacked(
    const void *src,
    void *dst,
    int srcPitch,
    int dstPitch,
    int h,
    int w
);

#endif  /* _XF86XV_H_ */

--- NEW FILE: xf86xvmc.c ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86xvmc.c,v 1.6 2003/10/08 22:31:59 mvojkovi Exp $ */

/*
 * Copyright (c) 2001-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

#include "misc.h"
#include "xf86.h"
#include "xf86_OSproc.h"

#include <X11/X.h>
#include <X11/Xproto.h>
#include "scrnintstr.h"
#include "resource.h"
#include "dixstruct.h"

#ifdef XFree86LOADER
#include "xvmodproc.h"
#endif

#include "xf86xvpriv.h"
#include "xf86xvmc.h"

#ifdef XFree86LOADER
int (*XvMCScreenInitProc)(ScreenPtr, int, XvMCAdaptorPtr) = NULL;
#else
int (*XvMCScreenInitProc)(ScreenPtr, int, XvMCAdaptorPtr) = XvMCScreenInit;
#endif


typedef struct {
  CloseScreenProcPtr CloseScreen; 
  int num_adaptors;
  XF86MCAdaptorPtr *adaptors;
  XvMCAdaptorPtr dixinfo;
} xf86XvMCScreenRec, *xf86XvMCScreenPtr;

static unsigned long XF86XvMCGeneration = 0;
static int XF86XvMCScreenIndex = -1;

#define XF86XVMC_GET_PRIVATE(pScreen) \
   (xf86XvMCScreenPtr)((pScreen)->devPrivates[XF86XvMCScreenIndex].ptr)


static int 
xf86XvMCCreateContext (
  XvPortPtr pPort,
  XvMCContextPtr pContext,
  int *num_priv,
  CARD32 **priv
)
{
    xf86XvMCScreenPtr pScreenPriv = XF86XVMC_GET_PRIVATE(pContext->pScreen);
    ScrnInfoPtr pScrn = xf86Screens[pContext->pScreen->myNum];

    pContext->port_priv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr);

    return (*pScreenPriv->adaptors[pContext->adapt_num]->CreateContext)(
		pScrn, pContext, num_priv, priv);
}

static void 
xf86XvMCDestroyContext ( XvMCContextPtr pContext)
{
    xf86XvMCScreenPtr pScreenPriv = XF86XVMC_GET_PRIVATE(pContext->pScreen);
    ScrnInfoPtr pScrn = xf86Screens[pContext->pScreen->myNum];

    (*pScreenPriv->adaptors[pContext->adapt_num]->DestroyContext)(
                				pScrn, pContext);
}

static int 
xf86XvMCCreateSurface (
  XvMCSurfacePtr pSurface,
  int *num_priv,
  CARD32 **priv
)
{
    XvMCContextPtr pContext = pSurface->context;
    xf86XvMCScreenPtr pScreenPriv = XF86XVMC_GET_PRIVATE(pContext->pScreen);
    ScrnInfoPtr pScrn = xf86Screens[pContext->pScreen->myNum];

    return (*pScreenPriv->adaptors[pContext->adapt_num]->CreateSurface)(
                pScrn, pSurface, num_priv, priv);
}

static void 
xf86XvMCDestroySurface (XvMCSurfacePtr pSurface)
{
    XvMCContextPtr pContext = pSurface->context;
    xf86XvMCScreenPtr pScreenPriv = XF86XVMC_GET_PRIVATE(pContext->pScreen);
    ScrnInfoPtr pScrn = xf86Screens[pContext->pScreen->myNum];

    (*pScreenPriv->adaptors[pContext->adapt_num]->DestroySurface)(
                                                pScrn, pSurface);
}

static int 
xf86XvMCCreateSubpicture (
  XvMCSubpicturePtr pSubpicture,
  int *num_priv,
  CARD32 **priv
)
{
    XvMCContextPtr pContext = pSubpicture->context;
    xf86XvMCScreenPtr pScreenPriv = XF86XVMC_GET_PRIVATE(pContext->pScreen);
    ScrnInfoPtr pScrn = xf86Screens[pContext->pScreen->myNum];

    return (*pScreenPriv->adaptors[pContext->adapt_num]->CreateSubpicture)(
                                  pScrn, pSubpicture, num_priv, priv);
}

static void
xf86XvMCDestroySubpicture (XvMCSubpicturePtr pSubpicture)
{
    XvMCContextPtr pContext = pSubpicture->context;
    xf86XvMCScreenPtr pScreenPriv = XF86XVMC_GET_PRIVATE(pContext->pScreen);
    ScrnInfoPtr pScrn = xf86Screens[pContext->pScreen->myNum];

    (*pScreenPriv->adaptors[pContext->adapt_num]->DestroySubpicture)(
                                                pScrn, pSubpicture);
}


static Bool
xf86XvMCCloseScreen (int i, ScreenPtr pScreen)
{
    xf86XvMCScreenPtr pScreenPriv = XF86XVMC_GET_PRIVATE(pScreen);

    pScreen->CloseScreen = pScreenPriv->CloseScreen;

    xfree(pScreenPriv->dixinfo);
    xfree(pScreenPriv);

    return (*pScreen->CloseScreen)(i, pScreen);
}

Bool xf86XvMCScreenInit(
   ScreenPtr pScreen, 
   int num_adaptors,
   XF86MCAdaptorPtr *adaptors
)
{
   XvMCAdaptorPtr pAdapt;
   xf86XvMCScreenPtr pScreenPriv;
   XvScreenPtr pxvs = 
	(XvScreenPtr)(pScreen->devPrivates[XF86XvScreenIndex].ptr);

   int i, j;

   if(!XvMCScreenInitProc) return FALSE;

   if(XF86XvMCGeneration != serverGeneration) {
	if((XF86XvMCScreenIndex = AllocateScreenPrivateIndex()) < 0)
	   return FALSE;
	XF86XvMCGeneration = serverGeneration;
   }

   if(!(pAdapt = xalloc(sizeof(XvMCAdaptorRec) * num_adaptors)))
	return FALSE;

   if(!(pScreenPriv = xalloc(sizeof(xf86XvMCScreenRec)))) {
	xfree(pAdapt);
	return FALSE;
   }

   pScreen->devPrivates[XF86XvMCScreenIndex].ptr = (pointer)pScreenPriv; 

   pScreenPriv->CloseScreen = pScreen->CloseScreen;
   pScreen->CloseScreen = xf86XvMCCloseScreen;

   pScreenPriv->num_adaptors = num_adaptors;
   pScreenPriv->adaptors = adaptors;
   pScreenPriv->dixinfo = pAdapt;

   for(i = 0; i < num_adaptors; i++) {
	pAdapt[i].xv_adaptor = NULL;
	for(j = 0; j < pxvs->nAdaptors; j++) {
	   if(!strcmp((*adaptors)->name, pxvs->pAdaptors[j].name)) {
		pAdapt[i].xv_adaptor = &(pxvs->pAdaptors[j]); 
		break;
	   }
	}
	if(!pAdapt[i].xv_adaptor) {
	    /* no adaptor by that name */
	    xfree(pAdapt);
	    return FALSE;
	}
	pAdapt[i].num_surfaces = (*adaptors)->num_surfaces;
	pAdapt[i].surfaces = (XvMCSurfaceInfoPtr*)((*adaptors)->surfaces);
	pAdapt[i].num_subpictures = (*adaptors)->num_subpictures;
	pAdapt[i].subpictures = (XvImagePtr*)((*adaptors)->subpictures);
	pAdapt[i].CreateContext = xf86XvMCCreateContext;
	pAdapt[i].DestroyContext = xf86XvMCDestroyContext;
	pAdapt[i].CreateSurface = xf86XvMCCreateSurface;
	pAdapt[i].DestroySurface = xf86XvMCDestroySurface;
	pAdapt[i].CreateSubpicture = xf86XvMCCreateSubpicture;
	pAdapt[i].DestroySubpicture = xf86XvMCDestroySubpicture;
	adaptors++;
   }

   if(Success != (*XvMCScreenInitProc)(pScreen, num_adaptors, pAdapt))
	return FALSE;

   return TRUE;
}

XF86MCAdaptorPtr xf86XvMCCreateAdaptorRec (void)
{
   return xcalloc(1, sizeof(XF86MCAdaptorRec));
}

void xf86XvMCDestroyAdaptorRec(XF86MCAdaptorPtr adaptor)
{
   xfree(adaptor);
}

--- NEW FILE: xf86xvmc.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86xvmc.h,v 1.7 2003/10/08 22:31:59 mvojkovi Exp $ */

/*
 * Copyright (c) 2001 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

#ifndef _XF86XVMC_H
#define _XF86XVMC_H

#include "xvmcext.h"
#include "xf86xv.h"

typedef struct {
  int num_xvimages;
  int *xvimage_ids;  /* reference the subpictures in the XF86MCAdaptorRec */
} XF86MCImageIDList; 

typedef struct {
  int surface_type_id;  /* Driver generated.  Must be unique on the port */
  int chroma_format;
  int color_description;  /* no longer used */
  unsigned short max_width;       
  unsigned short max_height;   
  unsigned short subpicture_max_width;
  unsigned short subpicture_max_height;
  int mc_type;         
  int flags;
  XF86MCImageIDList *compatible_subpictures; /* can be null, if none */
} XF86MCSurfaceInfoRec, *XF86MCSurfaceInfoPtr;


/*
   xf86XvMCCreateContextProc 

   DIX will fill everything out in the context except the driver_priv.
   The port_priv holds the private data specified for the port when
   Xv was initialized by the driver.
   The driver may store whatever it wants in driver_priv and edit
   the width, height and flags.  If the driver wants to return something
   to the client it can allocate space in priv and specify the number
   of 32 bit words in num_priv.  This must be dynamically allocated
   space because DIX will free it after it passes it to the client.
*/
   

typedef int (*xf86XvMCCreateContextProcPtr) (
  ScrnInfoPtr pScrn,
  XvMCContextPtr context,
  int *num_priv,
  CARD32 **priv 
);

typedef void (*xf86XvMCDestroyContextProcPtr) (
  ScrnInfoPtr pScrn,
  XvMCContextPtr context
);

/*
   xf86XvMCCreateSurfaceProc 

   DIX will fill everything out in the surface except the driver_priv.
   The driver may store whatever it wants in driver_priv.  The driver
   may pass data back to the client in the same manner as the
   xf86XvMCCreateContextProc.
*/


typedef int (*xf86XvMCCreateSurfaceProcPtr) (
  ScrnInfoPtr pScrn,
  XvMCSurfacePtr surface,
  int *num_priv,
  CARD32 **priv
);

typedef void (*xf86XvMCDestroySurfaceProcPtr) (
  ScrnInfoPtr pScrn,
  XvMCSurfacePtr surface
);

/*
   xf86XvMCCreateSubpictureProc 

   DIX will fill everything out in the subpicture except the driver_priv,
   num_palette_entries, entry_bytes and component_order.  The driver may
   store whatever it wants in driver_priv and edit the width and height.
   If it is a paletted subpicture the driver needs to fill out the
   num_palette_entries, entry_bytes and component_order.  These are
   not communicated to the client until the time the surface is
   created.

   The driver may pass data back to the client in the same manner as the
   xf86XvMCCreateContextProc.
*/


typedef int (*xf86XvMCCreateSubpictureProcPtr) (
  ScrnInfoPtr pScrn,
  XvMCSubpicturePtr subpicture,
  int *num_priv,
  CARD32 **priv
);

typedef void (*xf86XvMCDestroySubpictureProcPtr) (
  ScrnInfoPtr pScrn,
  XvMCSubpicturePtr subpicture
);


typedef struct {
  char *name;
  int num_surfaces;
  XF86MCSurfaceInfoPtr *surfaces;
  int num_subpictures;
  XF86ImagePtr *subpictures;
  xf86XvMCCreateContextProcPtr 		CreateContext; 
  xf86XvMCDestroyContextProcPtr		DestroyContext; 
  xf86XvMCCreateSurfaceProcPtr 		CreateSurface; 
  xf86XvMCDestroySurfaceProcPtr		DestroySurface; 
  xf86XvMCCreateSubpictureProcPtr	CreateSubpicture; 
  xf86XvMCDestroySubpictureProcPtr	DestroySubpicture; 
} XF86MCAdaptorRec, *XF86MCAdaptorPtr;

/* 
   xf86XvMCScreenInit 

   Unlike Xv, the adaptor data is not copied from this structure.
   This structure's data is used so it must stick around for the
   life of the server.  Note that it's an array of pointers not
   an array of structures.
*/

Bool xf86XvMCScreenInit(
  ScreenPtr pScreen, 
  int num_adaptors,
  XF86MCAdaptorPtr *adaptors
);

XF86MCAdaptorPtr xf86XvMCCreateAdaptorRec (void);
void xf86XvMCDestroyAdaptorRec(XF86MCAdaptorPtr adaptor);

#endif /* _XF86XVMC_H */

--- NEW FILE: xf86xvpriv.h ---
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86xvpriv.h,v 1.2 2003/08/24 17:36:56 dawes Exp $ */

/*
 * Copyright (c) 2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

#ifndef _XF86XVPRIV_H_
#define _XF86XVPRIV_H_

#include "xf86xv.h"

/*** These are DDX layer privates ***/

extern int XF86XvScreenIndex;

typedef struct {
   DestroyWindowProcPtr		DestroyWindow;
   ClipNotifyProcPtr		ClipNotify;
   WindowExposuresProcPtr	WindowExposures;
   void                         (*AdjustFrame)(int, int, int, int);
   Bool                         (*EnterVT)(int, int);
   void                         (*LeaveVT)(int, int);
   GCPtr			videoGC;
} XF86XVScreenRec, *XF86XVScreenPtr;

typedef struct {
  int flags;  
  PutVideoFuncPtr PutVideo;
  PutStillFuncPtr PutStill;
  GetVideoFuncPtr GetVideo;
  GetStillFuncPtr GetStill;
  StopVideoFuncPtr StopVideo;
  SetPortAttributeFuncPtr SetPortAttribute;
  GetPortAttributeFuncPtr GetPortAttribute;
  QueryBestSizeFuncPtr QueryBestSize;
  PutImageFuncPtr PutImage;
  ReputImageFuncPtr ReputImage;
  QueryImageAttributesFuncPtr QueryImageAttributes;
} XvAdaptorRecPrivate, *XvAdaptorRecPrivatePtr;

typedef struct {
   ScrnInfoPtr pScrn;
   DrawablePtr pDraw;
   unsigned char type;
   unsigned int subWindowMode;
   DDXPointRec clipOrg;
   RegionPtr clientClip;
   RegionPtr pCompositeClip;
   Bool FreeCompositeClip;
   XvAdaptorRecPrivatePtr AdaptorRec;
   XvStatus isOn;
   Bool moved;
   int vid_x, vid_y, vid_w, vid_h;
   int drw_x, drw_y, drw_w, drw_h;
   DevUnion DevPriv;
} XvPortRecPrivate, *XvPortRecPrivatePtr;

typedef struct _XF86XVWindowRec{
   XvPortRecPrivatePtr PortRec;
   struct _XF86XVWindowRec *next;
} XF86XVWindowRec, *XF86XVWindowPtr;

#endif  /* _XF86XVPRIV_H_ */

--- NEW FILE: xisb.c ---
/*
 * Copyright (c) 1997  Metro Link Incorporated
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
 * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * Except as contained in this notice, the name of the Metro Link shall not be
 * used in advertising or otherwise to promote the sale, use or other dealings
 * in this Software without prior written authorization from Metro Link.
 *
 */
/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xisb.c,v 1.5 2000/11/06 19:24:07 dawes Exp $ */

/*
	X Input Serial Buffer routines for use in any XInput driver that accesses
	a serial device.
*/


/*****************************************************************************
 *	Standard Headers
 ****************************************************************************/

#ifdef __UNIXOS2__
#define I_NEED_OS2_H
#endif

#include <misc.h>
#include <xf86.h>
#include <xf86Version.h>
#include <xf86_OSproc.h>
#include <xf86_OSlib.h>
#include <xf86Xinput.h>
#include "xisb.h"

/*****************************************************************************
 *	Local Headers
 ****************************************************************************/

/*****************************************************************************
 *	Variables without includable headers
 ****************************************************************************/

/*****************************************************************************
 *	Local Variables
 ****************************************************************************/

/*****************************************************************************
 *	Function Definitions
 ****************************************************************************/

XISBuffer *
XisbNew (int fd, xf86ssize_t size)
{
	XISBuffer *b;

	b = xalloc (sizeof (XISBuffer));
	if (!b)
		return (NULL);
	b->buf = xalloc ((sizeof (unsigned char) * size));
	if (!b->buf)
	{
		xfree (b);
		return (NULL);
	}

	b->fd = fd;
	b->trace = 0;
	b->block_duration = 0;
	b->current = 1;	/* force it to be past the end to trigger initial read */
	b->end = 0;
	b->buffer_size = size;
	return (b);
}

void
XisbFree (XISBuffer *b)
{
	xfree (b->buf);
	xfree (b);
}

int
XisbRead (XISBuffer *b)
{
	int ret;

	if (b->current >= b->end)
	{
		if (b->block_duration >= 0)
		{
			if (xf86WaitForInput (b->fd, b->block_duration) < 1)
				return (-1);
		}
		else
		{
			/*
			 * automatically clear it so if XisbRead is called in a loop
			 * the next call will make sure there is data with select and
			 * thus prevent a blocking read
			 */
			b->block_duration = 0;
		}
		
		ret = xf86ReadSerial (b->fd, b->buf, b->buffer_size);
		switch (ret)
		{
			case 0:
				return (-1); /* timeout */
			case -1:
				return (-2); /* error */
			default:
				b->end = ret;
				b->current = 0;
				break;
		}
	}
	if (b->trace)
		ErrorF ("read 0x%02x (%c)\n", b->buf[b->current], 
			isprint(b->buf[b->current])?b->buf[b->current]:'.');

	return (b->buf[b->current++]);
}

/* the only purpose of this function is to provide output tracing */
xf86ssize_t
XisbWrite (XISBuffer *b, unsigned char *msg, xf86ssize_t len)
{
    if (b->trace)
    {
        int i = 0;
        for (i = 0; i < len; i++)
            ErrorF ("\t\twrote 0x%02x (%c)\n", msg[i], msg[i]);
    }
    return (xf86WriteSerial (b->fd, msg, len));
}

/* turn tracing of this buffer on (1) or off (0) */
void
XisbTrace (XISBuffer *b, int trace)
{
	b->trace = trace;
}

/*
 * specify a block_duration of -1 when you know the buffer's fd is ready to
 * read. After a read, it is automatically set to 0 so that the next read
 * will use check to select for data and prevent a block.
 * It is the caller's responsibility to set the block_duration to -1 if it
 * knows that there is data to read (because the main select loop triggered
 * the read) and want's to avoid the unnecessary overhead of the select call
 *
 * a zero or positive block duration will cause the select to block for the
 * give duration in usecs.
 */

void
XisbBlockDuration (XISBuffer *b, int block_duration)
{
	b->block_duration = block_duration;
}

--- NEW FILE: xisb.h ---
/*
 * Copyright (c) 1997  Metro Link Incorporated
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
 * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * Except as contained in this notice, the name of the Metro Link shall not be
 * used in advertising or otherwise to promote the sale, use or other dealings
 * in this Software without prior written authorization from Metro Link.
 *
 */
/* $XFree86$ */

#ifndef	_xisb_H_
#define _xisb_H_

/******************************************************************************
 *		Definitions
 *									structs, typedefs, #defines, enums
 *****************************************************************************/

typedef struct _XISBuffer
{
	int fd;
	int trace;
	int block_duration;
	xf86ssize_t current;	/* bytes read */
	xf86ssize_t end;
	xf86ssize_t buffer_size;
	unsigned char *buf;
} XISBuffer;

/******************************************************************************
 *		Declarations
 *								variables:	use xisb_LOC in front
 *											of globals.
 *											put locals in the .c file.
 *****************************************************************************/
XISBuffer * XisbNew (int fd, xf86ssize_t size);
void XisbFree (XISBuffer *b);
int XisbRead (XISBuffer *b);
xf86ssize_t XisbWrite (XISBuffer *b, unsigned char *msg, xf86ssize_t len);
void XisbTrace (XISBuffer *b, int trace);
void XisbBlockDuration (XISBuffer *b, int block_duration);

/*
 *	DO NOT PUT ANYTHING AFTER THIS ENDIF
 */
#endif




More information about the xserver-commit mailing list