#!/bin/sh
UNSUPPORTED=1
LEGACY=0
#CARDS="$(lspci -n|gawk '{sub("Class","")} $2 == "0300:" {print$3}')"
CARDS="$(lspci -n|perl -e 'while(<>){(push(@cards,$_)) if (s/^.+?\s*0300\:\s+(.+?)\s+.*$/$1/)} print join(" ",@cards);')"
for card in $CARDS; do
 VENDOR=${card%:*}
 DEVICE=${card#*:}
 case $VENDOR in
  1002)
   case $DEVICE in
    #strings /usr/lib/xorg/modules/drivers/fglrx_drv.so|awk '/^0x....$/{print tolower($1)}'|sed s/0x//|sort -u|tr '\n' '|'|sed 's/|$//'
    3150|3152|3e50|4144|4146|4148|4149|4150|4151|4152|4153|4155|4a48|4a49|4a4a|4a4b|4a4c|4a4e|4a4f|4a50|4a54|4b48|4b49|4b4a|4b4b|4b4c|4e44|4e45|4e46|4e48|4e49|4e4a|4e50|4e51|4e52|4e56|5460|5461|5462|5548|5549|554a|554b|554c|554d|554e|554f|564f|5652|5653|5657|5854|5874|5954|5955|5974|5975|5a41|5a42|5a43|5a61|5a62|5a63|5b60|5b62|5b63|5b66|5d48|5d4a|5d4c|5d4d|5d4f|5d52|5d57|5e4a|5e4b|5e4c|5e4d|5e4f|7100|7101|7102|7108|7109|710a|710b|710c|7140|7141|7142|7143|7145|7146|7147|7149|714a|714b|714c|714d|714e|714f|7151|715e|715f|7180|7181|7183|7186|7187|7188|718a|718b|718c|718d|718f|7193|7196|719f|71c0|71c1|71c2|71c3|71c5|71c6|71c7|71cd|71ce|71d5|71d6|71de|7200|7210|7211|7240|7243|7244|7245|7246|7247|7248|7249|724a|724b|724c|724d|724e|724f|7280|7281|7283|7284|7287|7288|7289|728b|7290|7291|7293|7297|791e|791f|793f|7941|7942|796c|796d|796e|796f|9400|9401|9402|9403|9405|94c0|94c1|94c3|94c4|94c5|94c6|94c7|94c8|94c9|94cb|94cc|9500|9501|9504|9505|9507|9580|9581|9583|9586|9587|9588|9589|958a|958b|958e|95c0|95c4|95c5|95c7|9610|9611|9612|9613) UNSUPPORTED=0 ;;
    4242|4966|4967|4c64|4c66|4c67|5148|514c|514d|5960|5961|5962|5964|5965|5c61|5c63) UNSUPPORTED=0;LEGACY=1 ;;
    5834|5835|728c|7834|7835) UNSUPPORTED=0;LEGACY=2 ;;
    3151|3154|3e54|4147|4154|4a4d|4e47|4e4b|4e54|5464|5550|5551|5554|5555|564a|564b|5b64|5b65|5d49|5d50|5d51|5e48|7103|7104|7105|7106|710e|710f|7144|7152|7153|719b|71c4|71d2|71d4|71da|728c) UNSUPPORTED=0;LEGACY=3 ;;
    *) UNSUPPORTED=1 ;;
   esac
   ;;
 esac
done
if [ ! -f /etc/kanotix-version ]; then
 echo Error: No KANOTIX found. Do not ask for support! >&2
fi
if [ ! -f /etc/debian_version ]; then
 echo Error: No Debian compatible system found. Do not ask for support! >&2
 exit 100
fi
if [ "$UNSUPPORTED" = "1" ]; then
 echo Error: No ATI RADEON/FIREGL adapter found. >&2
 exit 3
fi
if [ -e /etc/X11/XF86Config-4 -a -z "`grep -s -e radeon -e fglrx -e ati -e vesa -e fbdev /etc/X11/XF86Config-4|grep Driver`" ]; then
 echo Error: Bad /etc/X11/XF86Config-4 file. >&2
 exit 4
fi
if [ -e /etc/X11/xorg.conf -a -z "`grep -s -e radeon -e fglrx -e ati -e vesa -e fbdev /etc/X11/xorg.conf|grep Driver`" ]; then
 echo Error: Bad /etc/X11/xorg.conf file. >&2
 exit 5
fi
if [ "$(id -u)" != 0 ]; then
 echo Error: You must be root to run this script! >&2
 exit 6
fi
LAPTOP=""
[ "$(find /proc/acpi/battery/ -mindepth 1 -type d 2>/dev/null)" ] && LAPTOP="yes"
[ -d /KNOPPIX -o -d /KANOTIX ] && INSTALLED="no" || INSTALLED="yes"
if [ -f /etc/default/distro ]; then
 . /etc/default/distro
 [ "$FLL_DISTRO_MODE" = "live" ] && INSTALLED="no"
fi
if [ "$INSTALLED" = "yes" ]; then
 if [ -n "$DISPLAY" ]; then
  echo Error: Can\`t be run within X! Use a text console \(ALT-CTRL-F1\) >&2
  exit 7
 fi
else
 if grep -q -e unionfs -e aufs /proc/mounts; then
  echo Unionfs found. >&2
 else
  echo Activating Unionfs now. >&2
  UNIONFS=unionfs
  modinfo aufs >/dev/null 2>&1 && UNIONFS=aufs
  AUFSOPT=""
  [ "$UNIONFS" = "aufs" ] && AUFSOPT="udba=reval,"
  mkdir -p /tmp/union
  UNION=/KNOPPIX
  [ -d /KANOTIX ] && UNION=/KANOTIX
  [ -d "$FLL_MOUNTPOINT" ] && UNION="$FLL_MOUNTPOINT"
  mount -t $UNIONFS -o ${AUFSOPT}dirs=/tmp/union/:$UNION none $UNION/ >/dev/null 2>&1
 fi
fi
 X_CONF=XF86Config-4
cd /usr/src
KVER=$(uname -r)
KV=$(uname -r|cut -d. -f1-2)

RMML=0
VER_FORCE=""
PRINT_VER=0
NO_X_KILL=0
PATCH=0
COMPOSITE=1

while getopts pcrv:yzh opt; do
 case $opt in
  p) PRINT_VER=1
     ;;
  c) COMPOSITE=0
     ;;
  r) RMML=1
     ;;
  v) VER_FORCE="$OPTARG"
     ;;
  y) PATCH=1
     ;;
  z) NO_X_KILL=1
     ;;
  \?|h) echo "Usage $0 [options] " >&2
        echo "optional options are:" >&2
	echo " -c      Disable Composite extension" >&2
        echo " -r      Remove ModeLines" >&2
        echo " -v VER  Force use of specific driver version. Example: -v 8.29.6" >&2
        echo " -p      Print driver version to be installed and quit" >&2
        echo " -y      Force patching. Special purpose only!" >&2
        echo " -z      No X kill/restart. Special purpose only!" >&2
        echo " -h      Show this help" >&2
        exit 6
        ;;
 esac
done

# check for pipe usage
[ "$0" = "sh" -o "$0" = "bash" ] && NO_X_KILL=1

# most DX8 cards
VER_LEGACY_1=8.28.8

# rest of DX8 cards
VER_LEGACY_2=8.29.6

# FireGL cards
VER_LEGACY_3=8.40.4

VER=7-11
#VER=8.42.3
#VER=8.41.7
#VER=8.40.4
# Google Earth does not run with 8.40.4
#VER=8.39.4
# first release 8.39.4 showed "AMD Testing use only" in down right corner ;)
#VER=8.38.7
#VER=8.38.6
#VER=8.37.6
#VER=8.36.5
# No modeline support for Xorg 7.2 - disabled
#VER=8.35.5
#VER=8.34.8
#VER=8.33.6
# 8.33.6 used 85 hz on 75 hz max setting with modelines
# 8.33.6 and newer required for Xorg 7.2
#VER=8.32.5
# 8.32.5 supports Xorg 7.2 RC2
#VER=8.31.5
#VER=8.30.3
# 8.30.3 does not work with 71c1|71d4|71d5
#VER=8.29.6
#VER=8.28.8
#VER=8.27.10
# 8.27.10 and newer required for Xorg 7.1
#VER=8.26.18
#VER=8.25.18
#VER=8.24.8
#VER=8.23.7
#VER=8.22.5

[ "$LEGACY" = "1" ] && VER=$VER_LEGACY_1
[ "$LEGACY" = "2" ] && VER=$VER_LEGACY_2
[ "$LEGACY" = "3" ] && VER=$VER_LEGACY_3

[ -n "$VER_FORCE" ] && VER=$VER_FORCE

X -version 2>&1|grep -q -e "X Window System Version 7.1" && case $VER in 8.22.5|8.23.7|8.24.8|8.25.18|8.26.18)
 echo Error: No Xorg 7.1 support in $VER >&2
 exit 8
 ;;
esac
X -version 2>&1|grep -q -e "X Window System Version 7.2" -e "X Window System Version 1.3" -e "X Server 1.4" && case $VER in 8.22.5|8.23.7|8.24.8|8.25.18|8.26.18|8.27.10|8.28.8|8.29.6|8.30.3|8.31.5|8.32.5)
 echo Error: No Xorg 7.2 support in $VER >&2
 case $VER in
  8.28.8|8.29.6|8.32.5)
   if [ "$PATCH" = "1" ]; then
    echo Warning: Only incomplete patch possible \(2d only\) >&2
   else
    echo Error: Only incomplete patch possible \(2d only\), use -y option to try >&2
    exit 9
   fi
   ;;
  *)
   exit 10
   ;;
 esac
esac
if X -version 2>&1|grep -q -e "X Window System Version 1.3" -e "X Server 1.4"; then
 case $VER in
  8.33.6|8.34.8|8.35.5|8.36.5)
   echo Error: No Xorg 1.3 support in $VER >&2
   PATCH=1
   ;;
  8.37.6|8.38.6|8.38.7|8.39.4|8.40.4|8.41.7|8.42.3|7-11) # supports Xorg 1.3
   ;;
  *)
   if [ "$PATCH" = "0" ]; then
    echo Error: Unknown status of Xorg 1.3 support for this release, use -y to force. >&2
    exit 11
   fi
   ;;
 esac
fi

[ "$PATCH" = "1" ] && echo Warning: Patching driver to support any Xorg release >&2
#if [ "$VER" = "8.39.4" ]; then
# PATCH=1
# echo Warning: Brutally patching driver to disable logo >&2
#fi

if [ "$PRINT_VER" = "1" ]; then
 echo $VER
 exit
fi

CPU=$(uname -m)
if [ "$CPU" = "x86_64" ]; then
 ARCH="amd64"
else
 ARCH="i386"
fi

CPU="x86.x86_64" # since 8.31.5
if [ "$VER" = "8.22.5" -o "$VER" = "8.23.7" ]; then 
 if [ "$ARCH" = "i386" ]; then
  CPU="i386"
 else
  CPU="x86_64"
 fi
fi
case $VER in 
 8.24.8|8.25.18|8.26.18|8.27.10|8.28.8|8.29.6|8.30.3) CPU="x86" ;;
esac

X_CONF=XF86Config-4
if which Xorg >/dev/null; then
 X=_6_8_0-
 [ -e /etc/X11/xorg.conf ] && X_CONF=xorg.conf
fi 

unset X86
[ "$ARCH" = "amd64" ] && X86=64
unset BIT
[ "$ARCH" = "amd64" ] && BIT="64bit/"

case $VER in
 8.22.5|8.23.7|8.24.8|8.25.18|8.26.18|8.27.10) DRIVER=ati-driver-installer-$VER-$CPU.run ;;
 8.24.8|8.25.18|8.26.18|8.27.10|8.28.8|8.29.6|8.30.3) DRIVER=ati-driver-installer-$VER.run ;;
 *) DRIVER=ati-driver-installer-$VER-$CPU.run ;;
esac

if ! [ -e $DRIVER ]; then
 wget --referer=ati.com -Nc http://www2.ati.com/drivers/linux/${BIT}${DRIVER}
fi

GL=/usr/X11R6/lib/libGL.so.1.2

[ -x /usr/share/ati/fglrx-uninstall.sh ] && /usr/share/ati/fglrx-uninstall.sh
dpkg --purge fglrx${X86}-4-3-0 >/dev/null 2>&1
dpkg --purge fglrx${X86}-6-8-0 >/dev/null 2>&1
dpkg --purge fglrx-glc22 >/dev/null 2>&1
dpkg --purge fglrx >/dev/null 2>&1
for package in $(dpkg-divert --list|grep "diversion of $GL"|cut -f7 -d' '|grep -v -e fglrx-driver -e xorg-driver-fglrx); do 
 dpkg-divert --package $package --remove $GL
done

if [ -e $GL.1st ]; then
 rm -f $GL
 mv $GL.1st $GL
fi

unset UP

# Ubuntu universe workaround
[ -r /etc/lsb-release ] && . /etc/lsb-release
if [ "$DISTRIB_ID" = "Ubuntu" ]; then
 if ! grep -Eq "^[[:space:]]*deb[[:space:]]+.*universe$" /etc/apt/sources.list; then
  grep -Eq "deb[[:space:]]+.*universe$" /etc/apt/sources.list && sed -i 's/^#\s*\(deb\s.*universe\)$/\1/' /etc/apt/sources.list
 fi
fi

if ! [ -x /usr/bin/module-assistant ]; then
 apt-get update && UP=1
 apt-get install --allow-unauthenticated --yes module-assistant
fi

if ! [ -d /usr/share/build-essential ]; then
 [ -z "$UP" ] && apt-get update
 apt-get install --allow-unauthenticated --yes build-essential
fi

if ! [ -x /usr/bin/fakeroot ]; then
 [ -z "$UP" ] && apt-get update
 apt-get install --allow-unauthenticated --yes fakeroot
fi

if ! [ -x /usr/bin/dh_testdir ]; then
 [ -z "$UP" ] && apt-get update
 apt-get install --allow-unauthenticated --yes debhelper
fi

if ! [ -x /bin/bzip2 ]; then
 [ -z "$UP" ] && apt-get update
 apt-get install --allow-unauthenticated --yes bzip2
fi

if ! [ -f /usr/lib/libstdc++.so.5 ]; then
 [ -z "$UP" ] && apt-get update
 apt-get install --allow-unauthenticated --yes libstdc++5
fi

if [ "$(uname -m)" = "x86_64" -a ! -d /usr/share/doc/ia32-libs ]; then
 [ -z "$UP" ] && apt-get update
 apt-get install --allow-unauthenticated --yes ia32-libs
fi

if [ "$(uname -m)" = "x86_64" ] && ! [ -f /emul/ia32-linux/usr/lib/libXcursor.so.1 -o -f /usr/lib32/libXcursor.so.1 ]; then
 [ -z "$UP" ] && apt-get update
 apt-get install --allow-unauthenticated --yes ia32-libs-gtk
fi

if ! [ -x /usr/bin/module-assistant ]; then
 echo "Error: module-assistant missing." >&2
 [ -r /etc/lsb-release ] && . /etc/lsb-release
 [ "$DISTRIB_ID" = "Ubuntu" ] && echo "Hint: Enable universe repository in /etc/apt/sources.list." >&2
 exit 1
fi

if [ -f /etc/modutils/1alsa ]; then
 mv /lib/modules/extra/alsa /lib/modules/$(uname -r)/
 rm -f /etc/modutils/1alsa
 depmod -a
fi

rm -rf fglrx-install /tmp/fglrx*
rm -f /tmp/xorg-driver-fglrx* fglrx* xorg-driver-fglrx*
rm -f /etc/fglrxrc /etc/fglrxprofiles.csv

# Ubuntu workaround
[ -f /etc/default/linux-restricted-modules-common ] && perl -pi -e 's/^(DISABLED_MODULES)=.*/\1="fglrx"/' /etc/default/linux-restricted-modules-common
[ -x /sbin/lrm-manager ] && /sbin/lrm-manager

DISTRIB_ID=Debian
DISTRIB_CODENAME=etch
X -version 2>&1|grep -q -e "X Window System Version 6.9" -e "X Window System Version 7.0" && DISTRIB_CODENAME=sid
if [ -d /usr/lib/xorg/modules ]; then
 DISTRIB_ID=Ubuntu
 DISTRIB_CODENAME=dapper
fi
X -version 2>&1|grep -q -e "X Window System Version 7.1" -e "X Window System Version 7.2" -e "X Window System Version 1.3" -e "X Server 1.4" && [ "$VER" != "8.27.10" ] && DISTRIB_CODENAME=edgy

# Debian (and Ubuntu)
[ -f /etc/debian_version -a ! -f /etc/kanotix-version ] && m-a -i prepare

# Kanotix fallback
[ -f /etc/kanotix-version -a "$(readlink -e /lib/modules/$(uname -r)/build)" = "" ] && m-a -i prepare

#LC_ALL= LC_CTYPE= LC_MESSAGES= LANG= sh $DRIVER --buildpkg $DISTRIB_ID/$DISTRIB_CODENAME || (
LC_ALL= LC_CTYPE= LC_MESSAGES= LANG= sh $DRIVER --extract fglrx-install || (
 rm -f $DRIVER
 echo $DRIVER could not build Debian packages and has been deleted. >&2
 echo Please restart the script to try again. >&2
 exit 2
) || exit

cd fglrx-install
[ "$VER" = "8.22.5" -o "$VER" = "8.23.7" ] && perl -pi -e 's/(XVERSIONMAX := )(\$\(basename \$\(XVERSION\)\).99)/${1}1:${2}/' packages/Debian/debian/rules
[ "$KV" = "2.6" ] && [ "$VER" = "8.22.5" -o "$VER" = "8.23.7" -o "$VER" = "8.24.8" ] && if [ "$(uname -r|grep -E '2.6.16|2.6.17')" != "" ]; then
 patch common/lib/modules/fglrx/build_mod/firegl_public.c <<EOT
Index: firegl_public.c
@@ -361,13 +361,15 @@
 } firegl_drm_stub_info_t;
 static firegl_drm_stub_info_t firegl_stub_info;
 
-#if LINUX_VERSION_CODE < 0x020400
+#if LINUX_VERSION_CODE > 0x02060F
 struct firegl_drm_stub_info_t *firegl_stub_pointer = NULL;
 #define inter_module_put(x)
 #define inter_module_unregister(x)
 #define inter_module_get_request(x,y)   firegl_stub_pointer
 #define inter_module_register(x,y,z)    do { firegl_stub_pointer = z; } while (0)
+#endif
 /* This is a kludge for backward compatibility that is only useful in DRM(stub_open) */
+#if LINUX_VERSION_CODE < 0x020400
 #define fops_put(fops)      MOD_DEC_USE_COUNT
 #define fops_get(fops)      (fops); MOD_INC_USE_COUNT
 #endif // LINUX_VERSION_CODE < 0x020400
@@ -2353,7 +2353,7 @@
 
 int ATI_API_CALL __ke_no_iommu(void)
 {
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,1)
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,1) && LINUX_VERSION_CODE < KERNEL_VERSION(2,6,16)
 #ifdef CONFIG_GART_IOMMU
     return no_iommu;
 #else /* !CONFIG_GART_IOMMU */
EOT
 patch common/lib/modules/fglrx/build_mod/2.6.x/Makefile <<EOT
Index: Makefile
@@ -1,4 +1,4 @@
-GCC_VER_MAJ      = \$(shell \$(CC) --version | head -n 1 | sed -e 's/[^0-9. ]//g;s/^ *//;s/^\(.\)\..*\$\$/\1/')
+GCC_VER_MAJ      = \$(shell \$(CC) -dumpversion | cut -f1 -d.)
 
 obj-m           += fglrx.o
 fglrx-libs      += libfglrx_ip.a.GCC\$(GCC_VER_MAJ)
@@ -24,36 +24,18 @@
 # on first call from remote location we get into this path
 # whilst on second call all is managed by the embedding kernel makefile
 
-KVER            = \$(shell uname -r)
-# KVER            = 2.6.0-0.test1.1.26custom
-
-ifeq (1,1)
-KDIR            = /lib/modules/\$(KVER)/build
-else
-KDIR            = /usr/src/linux-\$(KVER)
-endif
-PWD             = \$(shell pwd)
 
 fglrx-cfiles    = \${fglrx-c-objs:.o=.c}
 
 # default:: kmod_build
 
 kmod_build:: \$(fglrx-libs) \$(fglrx-cfiles) \$(fglrx-hdrs) \$(drm-hdrs)
-	\$(MAKE) -C \$(KDIR) SUBDIRS=\$(PWD) modules
-
-%.c:
-	@ln -s ../\$@
-
-%.h:
-	@ln -s ../\$@
-
-%.GCC\$(GCC_VER_MAJ):
-	@ln -s ../\$@
+	\$(MAKE) -C \$(KDIR) SUBDIRS=\$(CURDIR) modules
 
 # distclean:: clean
 
 clean::
-	rm -f *.c *.h *.o *.ko *.GCC* .??*
+	rm -f *.o *.ko .*.cmd
 
 endif
 
EOT
fi
[ "$KV" = "2.6" ] && [ "$VER" = "8.27.10" -o "$VER" = "8.28.8" ] && if [ "$(uname -r|grep -E '2.6.18|2.6.19|2.6.20|2.6.21|2.6.22')" != "" ]; then
 patch common/lib/modules/fglrx/build_mod/firegl_public.c <<EOT
Index: firegl_public.c
@@ -23,6 +23,9 @@

 // ============================================================
 #include <linux/version.h>
+#ifndef UTS_RELEASE
+#include <linux/utsrelease.h>
+#endif
 #ifdef MODVERSIONS
 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,71)
 #include <linux/modversions.h>
@@ -208,6 +211,10 @@ _syscall3( int, modify_ldt, int, func, v
 #define preempt_enable()
 #endif

+#ifndef VM_SHM
+#define VM_SHM (0)
+#endif
+
 // ============================================================
 /* globals */

EOT
fi
case $VER in 8.22.5|8.23.7|8.24.8|8.25.18|8.26.18|8.27.10|8.28.8|8.29.6|8.30.3|8.31.5|8.32.5|8.33.6)
 [ "$KV" = "2.6" ] && if [ "$(uname -r|grep -E '2.6.20|2.6.21|2.6.22')" != "" -a ! -f  packages/Fedora/ati-drivers-2.6.20.patch -a ! -f packages/Fedora/firegl_public.c.patch ]; then
 # http://mlau.at/fglrx-833-2620-fixes.patch
 patch common/lib/modules/fglrx/build_mod/firegl_public.c <<'EOT'
Index: firegl_public.c
@@ -194,6 +194,82 @@
 int errno;
 #endif // __ia64__
 
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,19)
+#if defined(__i386__)
+
+#define __syscall_return(type, res) \
+do { \
+	if ((unsigned long)(res) >= (unsigned long)(-MAX_ERRNO)) { \
+		errno = -(res); \
+		res = -1; \
+	} \
+	return (type) (res); \
+} while (0)
+
+#define _syscall2(type,name,type1,arg1,type2,arg2) \
+type name(type1 arg1,type2 arg2) \
+{ \
+long __res; \
+__asm__ volatile ("push %%ebx ; movl %2,%%ebx ; int $0x80 ; pop %%ebx" \
+	: "=a" (__res) \
+	: "0" (__NR_##name),"ri" ((long)(arg1)),"c" ((long)(arg2)) \
+	: "memory"); \
+__syscall_return(type,__res); \
+}
+
+#define _syscall3(type,name,type1,arg1,type2,arg2,type3,arg3) \
+type name(type1 arg1,type2 arg2,type3 arg3) \
+{ \
+long __res; \
+__asm__ volatile ("push %%ebx ; movl %2,%%ebx ; int $0x80 ; pop %%ebx" \
+	: "=a" (__res) \
+	: "0" (__NR_##name),"ri" ((long)(arg1)),"c" ((long)(arg2)), \
+		  "d" ((long)(arg3)) : "memory"); \
+__syscall_return(type,__res); \
+}
+
+#elif defined(__x86_64__)
+#define __syscall_clobber "r11","rcx","memory"
+
+#define __syscall_return(type, res) \
+do { \
+	if ((unsigned long)(res) >= (unsigned long)(-MAX_ERRNO)) { \
+		errno = -(res); \
+		res = -1; \
+	} \
+	return (type) (res); \
+} while (0)
+
+#define __syscall "syscall"
+
+#define _syscall2(type,name,type1,arg1,type2,arg2) \
+type name(type1 arg1,type2 arg2) \
+{ \
+long __res; \
+__asm__ volatile (__syscall \
+	: "=a" (__res) \
+	: "0" (__NR_##name),"D" ((long)(arg1)),"S" ((long)(arg2)) : __syscall_clobber ); \
+__syscall_return(type,__res); \
+}
+
+#define _syscall3(type,name,type1,arg1,type2,arg2,type3,arg3) \
+type name(type1 arg1,type2 arg2,type3 arg3) \
+{ \
+long __res; \
+__asm__ volatile (__syscall \
+	: "=a" (__res) \
+	: "0" (__NR_##name),"D" ((long)(arg1)),"S" ((long)(arg2)), \
+		  "d" ((long)(arg3)) : __syscall_clobber); \
+__syscall_return(type,__res); \
+}
+
+#else
+
+#error "please fix the fglrx syscall mess"
+
+#endif	/* __i386__ */
+#endif	/* 2.6.19 */
+
 // int mlock(const void *addr, size_t len);
 _syscall2(int, mlock, const void *, addr, size_t, len )
 // int munlock(const void *addr, size_t len);
@@ -2561,11 +2637,23 @@ void ATI_API_CALL __ke_free_irq(unsigned
 #else
 static void ATI_API_CALL (*irq_handler_func)(int, void*, void*); /* function pointer variable */
 
+#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19)
 static irqreturn_t ke_irq_handler_wrap(int irq, void *arg1, struct pt_regs *regs)
 {
     irq_handler_func(irq, arg1, regs);
     return IRQ_HANDLED;
 }
+#else
+static irqreturn_t ke_irq_handler_wrap(int irq, void *arg1)
+{
+    irq_handler_func(irq, arg1, get_irq_regs());
+    return IRQ_HANDLED;
+}
+#endif
+
+#ifndef SA_SHIRQ
+#define SA_SHIRQ IRQF_SHARED
+#endif
 
 int ATI_API_CALL __ke_request_irq(unsigned int irq, 
     void (*ATI_API_CALL handler)(int, void *, void *),
EOT
 fi
esac
[ "$KV" = "2.6" ] && if [ "$(uname -r|grep -E '2.6.20|2.6.21|2.6.22')" != "" -a -f packages/Fedora/ati-drivers-2.6.20.patch ]; then
 patch -p0 < packages/Fedora/ati-drivers-2.6.20.patch
fi
[ "$KV" = "2.6" ] && if [ "$(uname -r|grep -E '2.6.20|2.6.21|2.6.22')" != "" -a -f packages/Fedora/firegl_public.c.patch ]; then
 patch common/lib/modules/fglrx/build_mod/firegl_public.c packages/Fedora/firegl_public.c.patch
fi
case $VER in 8.22.5|8.23.7|8.24.8|8.25.18|8.26.18|8.27.10|8.28.8|8.29.6|8.30.3|8.31.5|8.32.5|8.33.6|8.34.8|8.35.5|8.36.5|8.37.6|8.38.6|8.38.7)
 [ "$KV" = "2.6" ] && if [ "$(uname -r|grep -E '2.6.22')" != "" -a "$(uname -m)" = "x86_64" ]; then
 patch common/lib/modules/fglrx/build_mod/firegl_public.c <<'EOT'
--- common/lib/modules/fglrx/build_mod/firegl_public.c	2007-02-20 13:23:07.000000000 -0500
+++ common/lib/modules/fglrx/build_mod/firegl_public.c	2007-05-15 16:55:34.000000000 -0400
@@ -145,11 +145,11 @@
 #endif
 
 #ifdef __x86_64__
-#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,12)
-#include "linux/ioctl32.h"
-#else
-#include "asm/ioctl32.h"
-#endif
+//#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,12)
+//#include "linux/ioctl32.h"
+//#else
+//#include "asm/ioctl32.h"
+//#endif
 
 #ifdef __x86_64__
 #include "asm/compat.h"
EOT
 fi
esac
case $VER in 
 8.22.5|8.23.7|8.24.8|8.25.18|8.26.18|8.27.10|8.30.3|8.31.5|8.32.5|8.33.6|8.34.8|8.35.5|8.36.5|8.37.6|8.38.6|8.38.7) ;;
 8.28.8|8.29.6) [ "$KV" = "2.6" ] && if [ "$(uname -r|grep -E '2.6.23|2.6.24')" != "" ]; then
   #http://mlau.at/files/fglrx-828-2624rc-fixes.patch
   cd common/lib/modules/fglrx/build_mod
   patch -p0 <<'EOT'
crude patch to get the fglrx-8.28 kernel module to compile against
2.6.24-rc4/5.	Use at your own risk!  -- mlau

fglrx-828-2624rc-fixes.patch

--- drm.h~	2007-12-11 17:56:24.000000000 +0100
+++ drm.h	2007-12-11 17:56:24.000000000 +0100
@@ -38,7 +38,6 @@
 #define _DRM_H_
 
 #if defined(__linux__)
-#include <linux/config.h>
 #include <asm/ioctl.h>		/* For _IO* macros */
 #define DRM_IOCTL_NR(n)		_IOC_NR(n)
 #define DRM_IOC_VOID		_IOC_NONE
--- drmP.h~	2007-12-11 17:56:42.000000000 +0100
+++ drmP.h	2007-12-11 17:56:42.000000000 +0100
@@ -42,7 +42,6 @@
  * can build the DRM (part of PI DRI). 4/21/2000 S + B */
 #include <asm/current.h>
 #endif /* __alpha__ */
-#include <linux/config.h>
 #include <linux/module.h>
 #include <linux/kernel.h>
 #include <linux/miscdevice.h>
--- firegl_public.c.8288	2007-12-11 18:10:37.000000000 +0100
+++ firegl_public.c	2007-12-11 18:09:04.000000000 +0100
@@ -86,7 +86,6 @@
 #include <asm/unistd.h> /* for installing the patch wrapper */
 #include <linux/module.h>
 
-#include <linux/config.h>
 #include <linux/kernel.h>
 #include <linux/fs.h>
 #include <linux/proc_fs.h>
@@ -151,6 +150,10 @@
 #endif
 #endif
 
+#ifndef UTS_RELEASE
+#include <linux/utsrelease.h>
+#endif
+
 #include <linux/kmod.h>
 #include "firegl_public.h"
 
@@ -176,6 +179,83 @@
 int errno;
 #endif // __ia64__
 
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,19)
+#if defined(__i386__)
+
+#define __syscall_return(type, res) \
+do { \
+	if ((unsigned long)(res) >= (unsigned long)(-MAX_ERRNO)) { \
+		errno = -(res); \
+		res = -1; \
+	} \
+	return (type) (res); \
+} while (0)
+
+#define _syscall2(type,name,type1,arg1,type2,arg2) \
+type name(type1 arg1,type2 arg2) \
+{ \
+long __res; \
+__asm__ volatile ("push %%ebx ; movl %2,%%ebx ; int $0x80 ; pop %%ebx" \
+	: "=a" (__res) \
+	: "0" (__NR_##name),"ri" ((long)(arg1)),"c" ((long)(arg2)) \
+	: "memory"); \
+__syscall_return(type,__res); \
+}
+
+#define _syscall3(type,name,type1,arg1,type2,arg2,type3,arg3) \
+type name(type1 arg1,type2 arg2,type3 arg3) \
+{ \
+long __res; \
+__asm__ volatile ("push %%ebx ; movl %2,%%ebx ; int $0x80 ; pop %%ebx" \
+	: "=a" (__res) \
+	: "0" (__NR_##name),"ri" ((long)(arg1)),"c" ((long)(arg2)), \
+		  "d" ((long)(arg3)) : "memory"); \
+__syscall_return(type,__res); \
+}
+
+#elif defined(__x86_64__)
+#define __syscall_clobber "r11","rcx","memory"
+
+#define __syscall_return(type, res) \
+do { \
+	if ((unsigned long)(res) >= (unsigned long)(-MAX_ERRNO)) { \
+		errno = -(res); \
+		res = -1; \
+	} \
+	return (type) (res); \
+} while (0)
+
+#define __syscall "syscall"
+
+#define _syscall2(type,name,type1,arg1,type2,arg2) \
+type name(type1 arg1,type2 arg2) \
+{ \
+long __res; \
+__asm__ volatile (__syscall \
+	: "=a" (__res) \
+	: "0" (__NR_##name),"D" ((long)(arg1)),"S" ((long)(arg2)) : __syscall_clobber ); \
+__syscall_return(type,__res); \
+}
+
+#define _syscall3(type,name,type1,arg1,type2,arg2,type3,arg3) \
+type name(type1 arg1,type2 arg2,type3 arg3) \
+{ \
+long __res; \
+__asm__ volatile (__syscall \
+	: "=a" (__res) \
+	: "0" (__NR_##name),"D" ((long)(arg1)),"S" ((long)(arg2)), \
+		  "d" ((long)(arg3)) : __syscall_clobber); \
+__syscall_return(type,__res); \
+}
+
+#else
+
+#error "please fix the fglrx syscall mess"
+
+#endif	/* __i386__ */
+#endif	/* 2.6.19 */
+
+
 // int mlock(const void *addr, size_t len);
 _syscall2(int, mlock, const void *, addr, size_t, len )
 // int munlock(const void *addr, size_t len);
@@ -208,6 +288,57 @@ _syscall3( int, modify_ldt, int, func, v
 #define preempt_enable()
 #endif
 
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,22)
+#if defined(__i386__)
+#define ptep_test_and_clear_dirty(vma, addr, ptep) ({                  \
+       int __ret = 0;                                                  \
+       if (pte_dirty(*(ptep)))                                         \
+               __ret = test_and_clear_bit(_PAGE_BIT_DIRTY,             \
+                                               &(ptep)->pte_low);      \
+       if (__ret)                                                      \
+               pte_update((vma)->vm_mm, addr, ptep);                   \
+       __ret;                                                          \
+})
+
+static inline int pte_read(pte_t pte)	{ return (pte).pte_low & _PAGE_USER; }
+static inline int pte_user(pte_t pte)	{ return (pte).pte_low & _PAGE_USER; }
+#ifdef CONFIG_X86_PAE
+/*
+ * Is the pte executable?
+ */
+static inline int pte_x(pte_t pte)
+{
+        return !(pte_val(pte) & _PAGE_NX);
+}
+
+/*
+ * All present user-pages with !NX bit are user-executable:
+ */
+static inline int pte_exec(pte_t pte)
+{
+        return pte_user(pte) && pte_x(pte);
+}
+#else
+static inline int pte_exec(pte_t pte)
+{
+        return pte_user(pte);
+}
+#endif	/* PAE */
+
+#elif defined(__x86_64__)
+static inline int ptep_test_and_clear_dirty(struct vm_area_struct *vma,
+					unsigned long addr, pte_t *ptep)
+{
+	if (!pte_dirty(*ptep))
+		return 0;
+	return test_and_clear_bit(_PAGE_BIT_DIRTY, &ptep->pte);
+}
+static inline int pte_read(pte_t pte)	{ return pte_val(pte) & _PAGE_USER; }
+static inline int pte_exec(pte_t pte)	{ return !(pte_val(pte) & _PAGE_NX); }
+#endif
+#endif
+
+
 // ============================================================
 /* globals */
 
@@ -1743,7 +1874,7 @@ int ATI_API_CALL __ke_check_pci(int busn
 {
     struct pci_dev* pci_dev;
 
-    pci_dev = pci_find_slot(busnum, PCI_DEVFN(devnum, funcnum));
+    pci_dev = pci_get_slot(busnum, PCI_DEVFN(devnum, funcnum));
     if (!pci_dev)
         return 0;
 
@@ -1772,7 +1903,7 @@ int ATI_API_CALL __ke_pci_get_irq(__ke_p
 
 __ke_pci_dev_t* ATI_API_CALL __ke_pci_find_device (unsigned int vendor, unsigned int dev, __ke_pci_dev_t* from)
 {
-	return (__ke_pci_dev_t*)pci_find_device( vendor, dev, (struct pci_dev *)(void *)from );
+	return (__ke_pci_dev_t*)pci_get_device( vendor, dev, (struct pci_dev *)(void *)from );
 }
 
 void* ATI_API_CALL __ke_malloc(__ke_size_t size)
@@ -2031,7 +2162,7 @@ void ATI_API_CALL __ke_put_vm_page_table
 #ifndef ptep_clear_flush_dirty
 #define ptep_clear_flush_dirty(__vma, __address, __ptep) \
 ({							 \
-    int __dirty = ptep_test_and_clear_dirty(__ptep);	 \
+    int __dirty = ptep_test_and_clear_dirty(__vma, __address, __ptep);	 \
     if (__dirty)					 \
         flush_tlb_page(__vma, __address);		 \
     __dirty;						 \
@@ -2379,7 +2510,7 @@ int ATI_API_CALL __ke_pci_write_config_d
 
 __ke_pci_dev_t* ATI_API_CALL __ke_pci_find_slot(__ke_u32 bus, __ke_u32 slot)
 {
-    return (__ke_pci_dev_t*)pci_find_slot(bus, slot);
+    return (__ke_pci_dev_t*)pci_get_slot(bus, slot);
 }
 
 __ke_u8 ATI_API_CALL __ke_pci_get_busnr(__ke_pci_dev_t* pcidev)
@@ -2482,6 +2613,10 @@ static irqreturn_t ke_irq_handler_wrap(i
     return IRQ_HANDLED;
 }
 
+#ifndef SA_SHIRQ
+#define SA_SHIRQ IRQF_SHARED
+#endif
+
 int ATI_API_CALL __ke_request_irq(unsigned int irq, 
     void (*ATI_API_CALL handler)(int, void *, void *),
     const char *dev_name, void *dev_id)
@@ -3172,13 +3307,13 @@ int ATI_API_CALL __ke_vm_map(struct file
                 __KE_DEBUG(REMAP_PAGE_RANGE_STR " failed\n");
                 return -EAGAIN;
             }
-            vma->vm_flags |= VM_SHM | VM_RESERVED; /* Don't swap */
+            vma->vm_flags |= VM_RESERVED; /* Don't swap */
             vma->vm_ops = &vm_ops;
             }
 			break;
 
         case __KE_SHM:
-            vma->vm_flags |= VM_SHM | VM_RESERVED; /* Don't swap */
+            vma->vm_flags |= VM_RESERVED; /* Don't swap */
             vma->vm_ops = &vm_shm_ops;
             break;
 
@@ -3187,26 +3322,26 @@ int ATI_API_CALL __ke_vm_map(struct file
             pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
 
 #if LINUX_VERSION_CODE <= 0x02040e /* KERNEL_VERSION(2,4,14) */
-            vma->vm_flags |= VM_LOCKED | VM_SHM; /* Don't swap */
+            vma->vm_flags |= VM_LOCKED; /* Don't swap */
 #else
             vma->vm_flags |= VM_RESERVED;
 #endif
 
-            //vma->vm_flags |=  VM_SHM | VM_LOCKED; /* DDDDDDDDDDon't swap */
+            //vma->vm_flags |= VM_LOCKED; /* DDDDDDDDDDon't swap */
             //vma->vm_mm->locked_vm += pages; /* Kernel tracks aqmount of locked pages */
             vma->vm_ops = &vm_pcie_ops;
             break;
 
         case __KE_CTX:
             pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
-            vma->vm_flags |= VM_LOCKED | VM_SHM | VM_RESERVED; /* Don't swap */
+            vma->vm_flags |= VM_LOCKED | VM_RESERVED; /* Don't swap */
             vma->vm_mm->locked_vm += pages; /* Kernel tracks aqmount of locked pages */
             vma->vm_ops = &vm_ctx_ops;
             break;
 
         case __KE_PCI_BQS:
             pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
-            vma->vm_flags |= VM_LOCKED | VM_SHM | VM_RESERVED; /* Don't swap */
+            vma->vm_flags |= VM_LOCKED | VM_RESERVED; /* Don't swap */
             vma->vm_mm->locked_vm += pages; /* Kernel tracks aqmount of locked pages */
             vma->vm_ops = &vm_pci_bq_ops;
             break;
@@ -3222,7 +3357,7 @@ int ATI_API_CALL __ke_vm_map(struct file
                  * with sorting out the real physical pages and mappings
                  * in our page fault handler
                  */
-                vma->vm_flags |= VM_SHM | VM_RESERVED; /* Don't swap */
+                vma->vm_flags |= VM_RESERVED; /* Don't swap */
                 vma->vm_ops = &vm_cant_ops;
             }
 #else
@@ -3235,11 +3370,7 @@ int ATI_API_CALL __ke_vm_map(struct file
                     __KE_DEBUG(REMAP_PAGE_RANGE_STR " failed\n");
                     return -EAGAIN;
                 }
-#ifdef __x86_64__
-                vma->vm_flags |= VM_RESERVED;
-#else
-                vma->vm_flags |= VM_SHM | VM_RESERVED; /* Don't swap */
-#endif
+                vma->vm_flags |= VM_RESERVED; /* Don't swap */
                 vma->vm_ops = &vm_ops;
             }
 #endif
@@ -3254,7 +3385,7 @@ int ATI_API_CALL __ke_vm_map(struct file
                  * with sorting out the real physical pages and mappings
                  * in our page fault handler
                  */
-                vma->vm_flags |= VM_SHM | VM_RESERVED; /* Don't swap */
+                vma->vm_flags |= VM_RESERVED; /* Don't swap */
                 vma->vm_ops = &vm_cant_agp_bq_ops;
             }
             // else
@@ -3267,11 +3398,7 @@ int ATI_API_CALL __ke_vm_map(struct file
                     __KE_DEBUG(REMAP_PAGE_RANGE_STR " failed\n");
                     return -EAGAIN;
                 }
-#ifdef __x86_64__
-                vma->vm_flags |= VM_RESERVED;
-#else
-                vma->vm_flags |= VM_SHM | VM_RESERVED; /* Don't swap */
-#endif
+                vma->vm_flags |= VM_RESERVED; /* Don't swap */
                 vma->vm_ops = &vm_agp_bq_ops;
             }
 #endif
@@ -3279,7 +3406,7 @@ int ATI_API_CALL __ke_vm_map(struct file
 #endif /* __AGP__BUILTIN__ */
 
         case __KE_KMAP:
-		    vma->vm_flags |= VM_SHM | VM_RESERVED;
+		    vma->vm_flags |= VM_RESERVED;
             vma->vm_ops = &vm_kmap_ops;
             if (readonly && (vma->vm_flags & VM_WRITE))
             {

EOT
   cd -
  fi
  ;;
 8.39.4) [ "$KV" = "2.6" ] && if [ "$(uname -r|grep -E '2.6.23|2.6.24')" != "" ]; then
   #http://mlau.at/files/fglrx-839-2624rc-fixes.patch
   patch common/lib/modules/fglrx/build_mod/firegl_public.c <<'EOT'
crude patch to get fglrx-8.39 to compile against 2.6.23/2.6.24-rc4/5.
Use at your own risk!	-- mlau

--- firegl_public.c.orig	2007-07-20 22:51:46.000000000 +0200
+++ firegl_public.c	2007-12-11 18:35:16.000000000 +0100
@@ -214,6 +214,56 @@
 #define preempt_enable()
 #endif
 
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,22)
+#if defined(__i386__)
+#define ptep_test_and_clear_dirty(vma, addr, ptep) ({                  \
+       int __ret = 0;                                                  \
+       if (pte_dirty(*(ptep)))                                         \
+               __ret = test_and_clear_bit(_PAGE_BIT_DIRTY,             \
+                                               &(ptep)->pte_low);      \
+       if (__ret)                                                      \
+               pte_update((vma)->vm_mm, addr, ptep);                   \
+       __ret;                                                          \
+})
+
+static inline int pte_read(pte_t pte)	{ return (pte).pte_low & _PAGE_USER; }
+static inline int pte_user(pte_t pte)	{ return (pte).pte_low & _PAGE_USER; }
+#ifdef CONFIG_X86_PAE
+/*
+ * Is the pte executable?
+ */
+static inline int pte_x(pte_t pte)
+{
+        return !(pte_val(pte) & _PAGE_NX);
+}
+ 
+/*
+ * All present user-pages with !NX bit are user-executable:
+ */
+static inline int pte_exec(pte_t pte)
+{
+        return pte_user(pte) && pte_x(pte);
+}
+#else
+static inline int pte_exec(pte_t pte)
+{
+        return pte_user(pte);
+}
+#endif	/* PAE */
+
+#elif defined(__x86_64__)
+static inline int ptep_test_and_clear_dirty(struct vm_area_struct *vma,
+					unsigned long addr, pte_t *ptep)
+{
+	if (!pte_dirty(*ptep))
+		return 0;
+	return test_and_clear_bit(_PAGE_BIT_DIRTY, &ptep->pte);
+}
+static inline int pte_read(pte_t pte)	{ return pte_val(pte) & _PAGE_USER; }
+static inline int pte_exec(pte_t pte)	{ return !(pte_val(pte) & _PAGE_NX); }
+#endif
+#endif
+
 // ============================================================
 /* globals */
 
@@ -1831,7 +1881,7 @@ int ATI_API_CALL __ke_check_pci(int busn
 {
     struct pci_dev* pci_dev;
 
-    pci_dev = pci_find_slot(busnum, PCI_DEVFN(devnum, funcnum));
+    pci_dev = pci_get_slot(busnum, PCI_DEVFN(devnum, funcnum));
     if (!pci_dev)
         return 0;
 
@@ -1860,7 +1910,7 @@ int ATI_API_CALL __ke_pci_get_irq(__ke_p
 
 __ke_pci_dev_t* ATI_API_CALL __ke_pci_find_device (unsigned int vendor, unsigned int dev, __ke_pci_dev_t* from)
 {
-	return (__ke_pci_dev_t*)pci_find_device( vendor, dev, (struct pci_dev *)(void *)from );
+	return (__ke_pci_dev_t*)pci_get_device( vendor, dev, (struct pci_dev *)(void *)from );
 }
 
 void* ATI_API_CALL __ke_malloc(__ke_size_t size)
@@ -2333,7 +2383,7 @@ void ATI_API_CALL __ke_put_vm_page_table
 #ifndef ptep_clear_flush_dirty
 #define ptep_clear_flush_dirty(__vma, __address, __ptep) \
 ({							 \
-    int __dirty = ptep_test_and_clear_dirty(__ptep);	 \
+    int __dirty = ptep_test_and_clear_dirty(__vma, __address, __ptep);	 \
     if (__dirty)					 \
         flush_tlb_page(__vma, __address);		 \
     __dirty;						 \
@@ -2693,7 +2743,7 @@ int ATI_API_CALL __ke_pci_write_config_d
 
 __ke_pci_dev_t* ATI_API_CALL __ke_pci_find_slot(__ke_u32 bus, __ke_u32 slot)
 {
-    return (__ke_pci_dev_t*)pci_find_slot(bus, slot);
+    return (__ke_pci_dev_t*)pci_get_slot(bus, slot);
 }
 
 __ke_u8 ATI_API_CALL __ke_pci_get_busnr(__ke_pci_dev_t* pcidev)
@@ -2773,6 +2823,10 @@ void ATI_API_CALL __ke_disable_irq(int i
     disable_irq( irq );
 }
 
+#ifndef SA_SHIRQ
+#define SA_SHIRQ IRQF_SHARED
+#endif
+
 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,71)
 int ATI_API_CALL __ke_request_irq(unsigned int irq, 
     void (*ATI_API_CALL handler)(int, void *, void *),
@@ -5277,7 +5331,7 @@ unsigned int ATI_API_CALL KAS_Spinlock_R
 /** \brief Type definition of the structure describing Slab Cache object */
 typedef struct tag_kasSlabCache_t
 {
-    kmem_cache_t* cache;        /* OS slab cache object */
+    struct kmem_cache *cache;	/* OS slab cache object */
     spinlock_t lock;            /* OS spinlock object protecting the cache */
     unsigned int routine_type;  /* Type of routine the cache might be accessed from */
     char name[14];              /* Cache object name (kernel 2.4 restricts its length to 19 chars) */
@@ -5323,7 +5377,7 @@ unsigned int ATI_API_CALL KAS_SlabCache_
     DBG_TRACE("creating slab object '%s'", slabcache_obj->name);
 
     if ((slabcache_obj->cache =
-            kmem_cache_create(slabcache_obj->name, iEntrySize, 0, 0, NULL, NULL)))
+            kmem_cache_create(slabcache_obj->name, iEntrySize, 0, 0, NULL)))
     {
         ret = 1;
     }

EOT
  fi
  ;;
 8.40.4|8.41.7|8.42.3) [ "$KV" = "2.6" ] && if [ "$(uname -r|grep -E '2.6.23|2.6.24')" != "" ]; then
   #http://mlau.at/files/fglrx-842-2623.patch
   patch common/lib/modules/fglrx/build_mod/firegl_public.c <<'EOT'
crude patch to make 8.42 compile against 2.6.23+.
The x64 version probably doesn't work.

Better get the patch from the ati-drivers sabayon overlay ;-)

--- firegl_public.c.orig	2007-10-23 19:31:26.000000000 +0200
+++ firegl_public.c	2007-10-23 19:32:07.000000000 +0200
@@ -217,6 +217,56 @@
 #define preempt_enable()
 #endif
 
+#if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,22)
+#if defined(__i386__)
+#define ptep_test_and_clear_dirty(vma, addr, ptep) ({                  \
+       int __ret = 0;                                                  \
+       if (pte_dirty(*(ptep)))                                         \
+               __ret = test_and_clear_bit(_PAGE_BIT_DIRTY,             \
+                                               &(ptep)->pte_low);      \
+       if (__ret)                                                      \
+               pte_update((vma)->vm_mm, addr, ptep);                   \
+       __ret;                                                          \
+})
+
+static inline int pte_read(pte_t pte)	{ return (pte).pte_low & _PAGE_USER; }
+static inline int pte_user(pte_t pte)	{ return (pte).pte_low & _PAGE_USER; }
+#ifdef CONFIG_X86_PAE
+/*
+ * Is the pte executable?
+ */
+static inline int pte_x(pte_t pte)
+{
+        return !(pte_val(pte) & _PAGE_NX);
+}
+ 
+/*
+ * All present user-pages with !NX bit are user-executable:
+ */
+static inline int pte_exec(pte_t pte)
+{
+        return pte_user(pte) && pte_x(pte);
+}
+#else
+static inline int pte_exec(pte_t pte)
+{
+        return pte_user(pte);
+}
+#endif	/* PAE */
+
+#elif defined(__x86_64__)
+static inline int ptep_test_and_clear_dirty(struct vm_area_struct *vma,
+					unsigned long addr, pte_t *ptep)
+{
+	if (!pte_dirty(*ptep))
+		return 0;
+	return test_and_clear_bit(_PAGE_BIT_DIRTY, &ptep->pte);
+}
+static inline int pte_read(pte_t pte)	{ return pte_val(pte) & _PAGE_USER; }
+static inline int pte_exec(pte_t pte)	{ return !(pte_val(pte) & _PAGE_NX); }
+#endif
+#endif
+
 // ============================================================
 /* globals */
 
@@ -2489,7 +2539,7 @@ void ATI_API_CALL __ke_put_vm_page_table
 #ifndef ptep_clear_flush_dirty
 #define ptep_clear_flush_dirty(__vma, __address, __ptep) \
 ({							 \
-    int __dirty = ptep_test_and_clear_dirty(__ptep);	 \
+    int __dirty = ptep_test_and_clear_dirty(__vma, __address, __ptep);	 \
     if (__dirty)					 \
         flush_tlb_page(__vma, __address);		 \
     __dirty;						 \
@@ -2936,7 +2986,7 @@ int ATI_API_CALL __ke_request_irq(unsign
 {
     return request_irq(irq,
         (void(*)(int, void *, struct pt_regs *))handler,
-        SA_SHIRQ, dev_name, dev_id);
+        IRQF_SHARED, dev_name, dev_id);
 }
 
 void ATI_API_CALL __ke_free_irq(unsigned int irq, void *dev_id)
@@ -2959,7 +3009,7 @@ int ATI_API_CALL __ke_request_irq(unsign
     irq_handler_func = handler;
     return request_irq(irq,
         ke_irq_handler_wrap,
-        SA_SHIRQ, dev_name, dev_id);
+        IRQF_SHARED, dev_name, dev_id);
 }
 
 void ATI_API_CALL __ke_free_irq(unsigned int irq, void *dev_id)
@@ -5436,7 +5486,7 @@ unsigned int ATI_API_CALL KAS_Spinlock_R
 /** \brief Type definition of the structure describing Slab Cache object */
 typedef struct tag_kasSlabCache_t
 {
-    kmem_cache_t* cache;        /* OS slab cache object */
+    struct kmem_cache *cache;	/* OS slab cache object */
     spinlock_t lock;            /* OS spinlock object protecting the cache */
     unsigned int routine_type;  /* Type of routine the cache might be accessed from */
     char name[14];              /* Cache object name (kernel 2.4 restricts its length to 19 chars) */
@@ -5482,7 +5532,7 @@ unsigned int ATI_API_CALL KAS_SlabCache_
     DBG_TRACE("creating slab object '%s'", slabcache_obj->name);
 
     if ((slabcache_obj->cache =
-            kmem_cache_create(slabcache_obj->name, iEntrySize, 0, 0, NULL, NULL)))
+            kmem_cache_create(slabcache_obj->name, iEntrySize, 0, 0, NULL)))
     {
         ret = 1;
     }

EOT
  fi
  ;;
esac

[ "$VER" = "8.42.3" ] && patch -p1 <<'EOT'
diff -Nru ati-8.42.3.orig/packages/Debian/ati-packager.sh ati-8.42.3/packages/Debian/ati-packager.sh
--- ati-8.42.3.orig/packages/Debian/ati-packager.sh	2007-10-22 18:30:02.000000000 +0200
+++ ati-8.42.3/packages/Debian/ati-packager.sh	2007-10-11 23:22:35.000000000 +0200
@@ -95,6 +95,11 @@
     cp -f -R ${InstallerRootDir}/arch/${ARCH_DIR}/* ${TmpDrvFilesDir}
     cp -f -R ${InstallerRootDir}/common/* ${TmpDrvFilesDir}
 
+    if [ "$ARCH" = "amd64" ]; then
+        cp -f -R ${InstallerRootDir}/arch/x86/usr/X11R6/lib \
+                ${TmpDrvFilesDir}/usr/X11R6/
+    fi
+
     # Merge package files from the appropriate directories
     chmod -R u+w ${AbsDistroDir}
 	cp -f -R ${AbsDistroDir}/dists/${X_NAME} ${TmpDrvFilesDir}/debian
diff -Nru ati-8.42.3.orig/packages/Ubuntu/ati-packager.sh ati-8.42.3/packages/Ubuntu/ati-packager.sh
--- ati-8.42.3.orig/packages/Ubuntu/ati-packager.sh	2007-10-22 18:30:02.000000000 +0200
+++ ati-8.42.3/packages/Ubuntu/ati-packager.sh	2007-10-11 23:22:35.000000000 +0200
@@ -69,7 +69,7 @@
         dapper|6.06) X_DIR=x690; X_NAME=dapper;;
         edgy|6.10)   X_DIR=x710; X_NAME=edgy;;
         feisty|7.04) X_DIR=x710; X_NAME=feisty;;
-        gutsy|7.10) X_DIR=x710; X_NAME=gutsy;;
+        gutsy|7.10)  X_DIR=x710; X_NAME=gutsy;;
         *) echo "Error: invalid package name passed to --buildpkg" ; exit 1 ;;
     esac
 
@@ -97,6 +97,11 @@
     cp -f -R ${InstallerRootDir}/arch/${ARCH_DIR}/* ${TmpDrvFilesDir}
     cp -f -R ${InstallerRootDir}/common/* ${TmpDrvFilesDir}
 
+    if [ "$ARCH" = "amd64" ]; then
+        cp -f -R ${InstallerRootDir}/arch/x86/usr/X11R6/lib \
+		${TmpDrvFilesDir}/usr/X11R6/
+    fi
+
     # Merge package files from the appropriate directories
 	chmod -R u+w ${AbsDistroDir}
 	cp -f -R ${AbsDistroDir}/dists/${X_NAME} ${TmpDrvFilesDir}/debian

EOT

if X -version 2>&1|grep -q -e "X Window System Version 7.1" -e "X Window System Version 7.2" -e "X Window System Version 1.3" -e "X Server 1.4" && [ "$VER" = "8.27.10" ]; then
 perl -pi -e 's#(dapper|6.06\) X_DIR=)x690(; X_NAME=dapper;;)#${1}x710${2}#' packages/Ubuntu/ati-packager.sh
 [ -d x710/usr/X11R6/bin ] || cp -r x690/usr/X11R6/bin/ x710/usr/X11R6/
fi
# Ubuntu Edgy fix
[ "$(readlink /bin/sh)" = "dash" ] && sed -i 's/==/=/;s/pushd/cd/;s/popd//;s/echo\s\+-e/printf "%b\n"/' packages/Ubuntu/ati-packager.sh
# Kernel 2.6.19 fix
case $VER in 
 8.22.5|8.23.7|8.24.8|8.25.18|8.26.18|8.27.10|8.28.8|8.29.6|8.30.3|8.31.5|8.32.5)
  if [ ! -f /lib/modules/$(uname -r)/build/include/linux/config.h -a -f /lib/modules/$(uname -r)/build/include/linux/autoconf.h ]; then
   sed -i s/config.h/autoconf.h/ common/lib/modules/fglrx/build_mod/firegl_public.c \
                                 common/lib/modules/fglrx/build_mod/drm.h \
				 common/lib/modules/fglrx/build_mod/drmP.h
  fi ;;
esac

[ "$PATCH" = "1" ] && case $VER in
 8.28.8)
  # only 2d working
  sed -i 's/\xe8\x10\xc8\xfe\xff\x85\xc0\x7f\x31/\xe8\x10\xc8\xfe\xff\x85\xc0\x90\x90/' x710/usr/X11R6/lib/modules/drivers/fglrx_drv.so
  sed -i 's/\xe8\xa2\xec\xfe\xff\x85\xc0\x7f\x23/\xe8\xa2\xec\xfe\xff\x85\xc0\x90\x90/' x710_64a/usr/X11R6/lib64/modules/drivers/fglrx_drv.so
  ;;
 8.29.6)
  # only 2d working
  sed -i 's/\xe8\x20\xff\xfd\xff\x85\xc0\x7f\x31/\xe8\x20\xff\xfd\xff\x85\xc0\x90\x90/' x710/usr/X11R6/lib/modules/drivers/fglrx_drv.so
  sed -i 's/\xe8\xb2\xe9\xfd\xff\x85\xc0\x7f\x23/\xe8\xb2\xe9\xfd\xff\x85\xc0\x90\x90/' x710_64a/usr/X11R6/lib64/modules/drivers/fglrx_drv.so
  ;;
 8.32.5)
  # only 2d working
  sed -i 's/\xe8\x28\x01\xfe\xff\x85\xc0\x7f\x31/\xe8\x28\x01\xfe\xff\x85\xc0\x90\x90/' x710/usr/X11R6/lib/modules/drivers/fglrx_drv.so
  sed -i 's/\xe8\x22\xe3\xfd\xff\x85\xc0\x7f\x23/\xe8\x22\xe3\xfd\xff\x85\xc0\x90\x90/' x710_64a/usr/X11R6/lib64/modules/drivers/fglrx_drv.so
  ;;
 8.33.6)
  sed -i 's/\xe8\x28\xff\xfd\xff\x85\xc0\x7f\x31/\xe8\x28\xff\xfd\xff\x85\xc0\x90\x90/' x710/usr/X11R6/lib/modules/drivers/fglrx_drv.so
  sed -i 's/\xe8\x8a\xe1\xfd\xff\x85\xc0\x7f\x23/\xe8\x8a\xe1\xfd\xff\x85\xc0\x90\x90/' x710_64a/usr/X11R6/lib64/modules/drivers/fglrx_drv.so
  sed -i 's/\x0f\x88\x6c\x09\x00\x00/\x90\xe9\x6c\x09\x00\x00/' x710/usr/X11R6/lib/modules/drivers/fglrx_drv.so
  sed -i 's/\x0f\x88\x3f\x08\x00\x00/\x90\xe9\x3f\x08\x00\x00/' x710_64a/usr/X11R6/lib64/modules/drivers/fglrx_drv.so
  ;;
 8.34.8)
  sed -i 's/\xe8\xe0\xf9\xfd\xff\x85\xc0\x7f\x31/\xe8\xe0\xf9\xfd\xff\x85\xc0\x90\x90/' x710/usr/X11R6/lib/modules/drivers/fglrx_drv.so
  sed -i 's/\xe8\xa2\xdc\xfd\xff\x85\xc0\x7f\x23/\xe8\xa2\xdc\xfd\xff\x85\xc0\x90\x90/' x710_64a/usr/X11R6/lib64/modules/drivers/fglrx_drv.so
  sed -i 's/\x0f\x88\x3c\x09\x00\x00/\x90\xe9\x3c\x09\x00\x00/' x710/usr/X11R6/lib/modules/drivers/fglrx_drv.so
  sed -i 's/\x0f\x88\x3b\x08\x00\x00/\x90\xe9\x3b\x08\x00\x00/' x710_64a/usr/X11R6/lib64/modules/drivers/fglrx_drv.so
  ;;
 8.35.5)
  sed -i 's/\xe8\xb4\xf4\xfd\xff\x85\xc0\x7f\x31/\xe8\xb4\xf4\xfd\xff\x85\xc0\x90\x90/' x710/usr/X11R6/lib/modules/drivers/fglrx_drv.so
  sed -i 's/\xe8\x4a\xd9\xfd\xff\x85\xc0\x7f\x23/\xe8\x4a\xd9\xfd\xff\x85\xc0\x90\x90/' x710_64a/usr/X11R6/lib64/modules/drivers/fglrx_drv.so
  sed -i 's/\x0f\x88\x3c\x09\x00\x00/\x90\xe9\x3c\x09\x00\x00/' x710/usr/X11R6/lib/modules/drivers/fglrx_drv.so
  sed -i 's/\x0f\x88\x3b\x08\x00\x00/\x90\xe9\x3b\x08\x00\x00/' x710_64a/usr/X11R6/lib64/modules/drivers/fglrx_drv.so
  ;;
 8.36.5)
  sed -i 's/\xe8\xec\x4f\xfe\xff\x85\xc0\x7f\x31/\xe8\xec\x4f\xfe\xff\x85\xc0\x90\x90/' x710/usr/X11R6/lib/modules/drivers/fglrx_drv.so
  sed -i 's/\xe8\xaa\x72\xfe\xff\x85\xc0\x7f\x23/\xe8\xaa\x72\xfe\xff\x85\xc0\x90\x90/' x710_64a/usr/X11R6/lib64/modules/drivers/fglrx_drv.so
  sed -i 's/\x0f\x88\x3c\x09\x00\x00/\x90\xe9\x3c\x09\x00\x00/' x710/usr/X11R6/lib/modules/drivers/fglrx_drv.so
  sed -i 's/\x0f\x88\x3b\x08\x00\x00/\x90\xe9\x3b\x08\x00\x00/' x710_64a/usr/X11R6/lib64/modules/drivers/fglrx_drv.so
  ;;
 8.39.4|8.40.4)
  DRIVER=x710/usr/X11R6/lib/modules/drivers/fglrx_drv.so
  for x in $(objdump -d $DRIVER|awk '/call/&&/Logo/{print "\\x"$2"\\x"$3"\\x"$4"\\x"$5"\\x"$6}'); do
   sed -i "s/$x/\x90\x90\x90\x90\x90/g" $DRIVER
  done
  DRIVER=x710_64a/usr/X11R6/lib64/modules/drivers/fglrx_drv.so
  for x in $(objdump -d $DRIVER|awk '/call/&&/Logo/{print "\\x"$2"\\x"$3"\\x"$4"\\x"$5"\\x"$6}'); do
   sed -i "s/$x/\x90\x90\x90\x90\x90/g" $DRIVER
  done
  ;;
esac

# install on sid even when xorg-server-core conflicts with fglrx-driver
if [ "$DISTRIB_ID" = "Ubuntu" ]; then
 grep -A 14 "Package: xserver-xorg-core" /var/lib/dpkg/status|grep -q "^Conflicts:.*fglrx-driver.*" && perl -pi -e 's/Provides: fglrx-driver\n//' packages/Ubuntu/dists/$DISTRIB_CODENAME/control.template
fi

# X Server 1.4 hack
if X -version 2>&1|grep -q -e "X Server 1.4"; then
 export XVERSION=1.4
 export XTYPE=X.Org
fi

perl -pi -e 's|^#(\s*dh_install.*modules/dri.*)|\1|' packages/Debian/dists/*/rules packages/Ubuntu/dists/*/rules 2>/dev/null

perl -pi -e 's/(LD_PRELOAD= dh_shlibdeps).*/\1||true/' packages/Debian/dists/*/rules packages/Ubuntu/dists/*/rules 2>/dev/null

LC_ALL= LC_CTYPE= LC_MESSAGES= LANG= bash ati-installer.sh $VER --buildpkg $DISTRIB_ID/$DISTRIB_CODENAME
cd ..
rm -rf fglrx-install

rm -f /lib/modules/$(uname -r)/kernel/drivers/char/drm/fglrx.*o
rm -f /lib/modules/$(uname -r)/misc/fglrx.*o
rm -f /lib/modules/$(uname -r)/volatile/fglrx.*o
rm -f fglrx-installer_$VER-1_$ARCH.changes
rm -rf /usr/src/modules/fglrx
OLD_FGLRX=$(COLUMNS=200 dpkg -l|cut -f3 -d' '|grep fglrx)
[ -n "$OLD_FGLRX" ] && dpkg --purge $OLD_FGLRX
OLD_FGLRX=$(COLUMNS=200 dpkg -l|cut -f3 -d' '|grep fglrx)
# use hack only if needed to fix packageing error
if [ -n "$OLD_FGLRX" ]; then
 rm -f /usr/lib/fglrx/libGL.so.1.xlibmesa
 dpkg --purge $OLD_FGLRX
fi

if [ -d /usr/lib/opengl ]; then
 rm -rf /usr/lib/opengl
 ldconfig
fi

CC=gcc-$(perl -pe '($_)=/gcc.[Vv]ersion\s(4\.\d|3\.\d|2\.\d+)/;' /proc/version)
if [ -e /usr/bin/$CC ]; then
 CC=/usr/bin/$CC
else
 unset CC
fi

# ati version hack
case $VER in
 7-11) VER=8.433;;
esac

# bad hack
[ -n "$CC" ] && mount --bind $CC /usr/bin/gcc

# unfreeze
FROZEN=0
[ -f /etc/frozen-rc.d ] && FROZEN=1
[ -x /usr/sbin/unfreeze-rc.d ] && /usr/sbin/unfreeze-rc.d

if [ "$DISTRIB_ID" = "Ubuntu" ]; then
 dpkg -i xorg-driver-fglrx_$VER-1_$ARCH.deb
 ls fglrx-control_$VER-1_$ARCH.deb >/dev/null 2>&1 && dpkg -i fglrx-control_$VER-1_$ARCH.deb
 ls fglrx-amdcccle_$VER-1_$ARCH.deb >/dev/null 2>&1 && dpkg -i fglrx-amdcccle_$VER-1_$ARCH.deb
 dpkg -i fglrx-kernel-source_$VER-1_$ARCH.deb
 CC=$CC m-a build fglrx-kernel-source
 m-a install fglrx-kernel-source
else
 dpkg -i fglrx-driver_$VER-1_$ARCH.deb
 ls fglrx-control*_$VER-1_$ARCH.deb >/dev/null 2>&1 && dpkg -i fglrx-control*_$VER-1_$ARCH.deb
 ls fglrx-amdcccle_$VER-1_$ARCH.deb >/dev/null 2>&1 && dpkg -i fglrx-amdcccle_$VER-1_$ARCH.deb
 dpkg -i fglrx-kernel-src_$VER-1_$ARCH.deb
 CC=$CC m-a build fglrx-kernel-src
 m-a install fglrx-kernel-src
fi

# restore freeze state
[ "$FROZEN" = "1" -a -x /usr/sbin/freeze-rc.d ] && /usr/sbin/freeze-rc.d

depmod -a

# bad hack off
[ -n "$CC" ] && umount $CC

rm -rf /usr/src/modules/fglrx
rm -rf fglrx-install
rm -f /tmp/fglrx* /tmp/xorg-driver-fglrx* fglrx* xorg-driver-fglrx*

dpkg --purge fglrx-kernel-src fglrx-kernel-source >/dev/null 2>&1

if ! [ "$NO_X_KILL" = "1" ]; then
 if [ "$INSTALLED" = "yes" ]; then
  DM=$(cat /etc/X11/default-display-manager 2>/dev/null)
  DM=$(basename $DM 2>/dev/null)
  if [ -z "$DM" ]; then
   if [ -x /etc/init.d/kdm ]; then
    /etc/init.d/kdm stop
   elif [ -x /etc/init.d/gdm ]; then
    /etc/init.d/gdm stop
   elif [ -x /etc/init.d/xdm ]; then
    /etc/init.d/xdm stop
   fi
  else
   [ -x /etc/init.d/$DM ] && /etc/init.d/$DM stop
  fi
 fi
fi
killall -9 Xgl >/dev/null 2>&1
rmmod radeon drm >/dev/null 2>&1
rmmod fglrx >/dev/null 2>&1
#rmmod agpgart >/dev/null 2>&1
perl -pi -e 's/^[\s]*radeon/#radeon/' /etc/modules
perl -pi -e 's/^[\s]*fglrx/#fglrx/' /etc/modules

if ! [ -e /etc/X11/$X_CONF.1st ]; then
 cp /etc/X11/$X_CONF /etc/X11/$X_CONF.1st
fi

#fglrxconfig
perl -p -e 's/^[\s]*Load\s*"GLcore"/#\tLoad  "GLcore"/;
            s/^[\s]*#*[\s]*Load\s*"dri"/\tLoad  "dri"/;
            s/^[\s]*#*[\s]*Load\s*"glx"/\tLoad  "glx"/;
            s/^[\s]*#*[\s]*Option\s*"Composite".*/#\tOption\t"Composite"\t"1"/;
            s/^[\s]*Driver\s*"radeon"/\tDriver      "fglrx"/g;
	    s/^[\s]*Driver\s*"radeonhd"/\tDriver      "fglrx"/g;
            s/^[\s]*Driver\s*"fbdev"/\tDriver      "fglrx"/g;
            s/^[\s]*Driver\s*"vesa"/\tDriver      "fglrx"/g;
            s/^[\s]*Driver\s*"ati"/\tDriver      "fglrx"/g;
            s/DefaultColorDepth.*/DefaultColorDepth 24/;
	    s/DefaultDepth.*/DefaultDepth 24/;
            s/^[\s]*Option\s*"sw_cursor"/\t#Option     "sw_cursor"/;
            s/^([\s]*Load\s*"extmod")/#\1\n\tSubSection  "extmod"\n\t  Option  "omit xfree86-dga"\n\tEndSubSection/;
            s/^.*UseInternalAGPGART.*\n?//g;
            s/^.*VideoOverlay.*\n?//g;
            s/^.*OpenGLOverlay.*\n?//g;
            s/^.*MonitorLayout.*\n?//g;
            s/^([\s]*Driver\s*"fglrx")/\1\n\tOption      "UseInternalAGPGART" "yes"\n\tOption      "VideoOverlay" "on"\n\tOption      "OpenGLOverlay" "off"\n\tOption      "MonitorLayout" "AUTO, AUTO"/g' \
            < /etc/X11/$X_CONF.1st > /etc/X11/$X_CONF
lsmod|grep -q agpgart && perl -pi -e 's/^([\s]*Option\s*"UseInternalAGPGART").*/\1 "no"/g' /etc/X11/$X_CONF
[ "$CPU" = "x86_64" ] && perl -pi -e 's/^([\s]*Option\s*"UseInternalAGPGART").*/\1 "no"/g' /etc/X11/$X_CONF
[ "$LAPTOP" ] && perl -pi -e 's/^([\s]*Option\s*"MonitorLayout").*/\1 "LVDS, AUTO"/g' /etc/X11/$X_CONF
case $VER in 8.16.20|8.18.6|8.18.8|8.19.10|8.20.8|8.21.7|8.30.3|8.31.5|8.33.6|8.34.8|8.35.5|8.36.5|8.37.6|8.38.6|8.38.7|8.39.4|8.40.4|8.41.7|8.42.3|8.433) RMML=1 ;; esac
[ "$RMML" = "1" ] && perl -pi -e 's/^.*Mode.ine.*\n?//g' /etc/X11/$X_CONF
# Ubuntu Edgy workaround (Composite 1 is default there!)
if which Xorg >/dev/null; then
 if ! grep -q Extensions /etc/X11/$X_CONF; then
  printf "%b\n" '\nSection "Extensions"' >> /etc/X11/$X_CONF
  printf "%b\n" '\tOption\t"Composite"\t"1"' >> /etc/X11/$X_CONF
  printf "%b\n" '#\tOption\t"RENDER"\t"1"' >> /etc/X11/$X_CONF
  echo 'EndSection' >> /etc/X11/$X_CONF
 fi
 case $VER in 8.22.5|8.23.7|8.24.8|8.25.18|8.26.18|8.27.10|8.28.8|8.29.6|8.30.3|8.31.5|8.32.5|8.33.6|8.34.8|8.35.5|8.36.5|8.37.6|8.38.6|8.38.7|8.39.4|8.40.4|8.41.7)
  perl -pi -e 's/^[\s]*#*[\s]*Option\s*"Composite".*/\tOption\t"Composite"\t"0"/' /etc/X11/$X_CONF
  # fully disable AIGLX seems to help sometimes
  perl -pi -e 's/^[\s]*#*[\s]*Option\s*"AIGLX".*//;s/(^[\s]*Section\s*"ServerLayout".*)/\1\n\tOption\t"AIGLX"\t"0"/' /etc/X11/$X_CONF
  ;;
 *)
  perl -pi -e 's/^[\s]*#*[\s]*Option\s*"Composite".*/\tOption\t"Composite"\t"1"/' /etc/X11/$X_CONF
  perl -pi -e 's/^[\s]*#*[\s]*Option\s*"AIGLX".*//' /etc/X11/$X_CONF
  ;;
 esac
 # disable composite if -c option used
 if [ "$COMPOSITE" = "0" ]; then
  perl -pi -e 's/^[\s]*#*[\s]*Option\s*"Composite".*/\tOption\t"Composite"\t"0"/' /etc/X11/$X_CONF
  perl -pi -e 's/^[\s]*#*[\s]*Option\s*"AIGLX".*//;s/(^[\s]*Section\s*"ServerLayout".*)/\1\n\tOption\t"AIGLX"\t"0"/' /etc/X11/$X_CONF
 fi
fi
# added for 3.14.6 and above
if ! grep -q "/dev/shm tmpfs" /proc/mounts; then
 perl -pi -e 's|\n?$|\n|' /etc/fstab
 perl -pi -e 's|.*tmpfs.*[\n]*||' /etc/fstab
 echo tmpfs /dev/shm tmpfs defaults 0 0 >> /etc/fstab
 mount /dev/shm
fi
sync

# X Server 1.4 workaround
case $VER in 
 8.41.7|8.40.4|8.39.4|8.38.7|8.38.6|8.37.6|8.36.5|8.35.5|8.34.8|8.33.6|8.32.5|8.31.5|8.30.3|8.29.6|8.28.8|8.27.10|8.26.18|8.25.18|8.24.8|8.23.7|8.22.5) 
 if X -version 2>&1|grep -q -e "X Server 1.4"; then
  DDM=$(cat /etc/X11/default-display-manager 2>/dev/null|sed 's|.*/||')
  if [ -z "$DDM" ]; then
   for DDM in kdm gdm xdm; do
    [ -x /etc/init.d/$DDM ] && break
   done
  fi
  case $DDM in
   gdm)
    if ! grep -q [[]server-Standard[]] /etc/gdm/gdm.conf; then
     echo Warning: Using X Server 1.4 GDM workaround ! >&2
     echo [server-Standard] >> /etc/gdm/gdm.conf
     echo command=/usr/bin/X -audit 0 -ignoreABI >> /etc/gdm/gdm.conf
    fi
    ;;
   kdm)
    for k in 3 4; do
     if [ -f /etc/kde$k/kdm/kdmrc ] && ! grep -qe -ignoreABI /etc/kde$k/kdm/kdmrc; then
      echo "Warning: Using X Server 1.4 KDM (KDE$k) workaround !" >&2
      sed -i 's|^\(\s*ServerCmd=.*\)|\1 -ignoreABI|' /etc/kde$k/kdm/kdmrc
     fi
    done
    ;;
   xdm)
    if ! grep -qe -ignoreABI /etc/X11/xdm/Xservers; then
     echo Warning: Using X Server 1.4 XDM workaround ! >&2
     sed -i 's|^\(\s*:.*\)|\1 -ignoreABI|' /etc/X11/xdm/Xservers
    fi
    ;;
  esac
 fi
 ;;
esac

if ! [ "$NO_X_KILL" = "1" ]; then
 if [ "$INSTALLED" = "yes" ]; then
  if [ -z "$DM" ]; then
   if [ -x /etc/init.d/kdm ]; then
    /etc/init.d/kdm start
   elif [ -x /etc/init.d/gdm ]; then
    /etc/init.d/gdm start
   elif [ -x /etc/init.d/xdm ]; then
    /etc/init.d/xdm start
   fi
  else
   [ -x /etc/init.d/$DM ] && /etc/init.d/$DM start
  fi
 else
  if [ -x /etc/init.d/xsession ]; then
   nohup sh -c "/etc/init.d/xsession stop; sleep 5; rmmod radeon drm fglrx 2>/dev/null; /etc/init.d/xsession start"
  else
   nohup sh -c "/etc/init.d/kdm stop; sleep 5; rmmod radeon drm fglrx 2>/dev/null; /etc/init.d/kdm start"
  fi
 fi
fi
