/*
X11 video driver for the Conexant 23415 MPEG encoder/decoder On-Screen Display
using the ivtvfb framebuffer driver.

Copyright (C) 2004 Matthias Badaire
Copyright (C) 2004-2007 John P. Harvey <john.p.harvey@btinternet.com>
Copyright (C) 2006-2007 Ian Armstrong <ian@iarmst.demon.co.uk>

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, FIT-
NESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
XFREE86 PROJECT 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 XFree86 Project 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 XFree86 Project.
*/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>

#include "ivtv_compat.h"
#include "ivtv_hw.h"
#include "ivtv.h"

/* all drivers need this */
#include "xf86.h"
#include "xf86_OSproc.h"

/* pci stuff */
#include "xf86PciInfo.h"
#include "xf86Pci.h"

#include "xf86cmap.h"

#include "globals.h"
#ifdef HAVE_XEXTPROTO_71
# include <X11/extensions/dpmsconst.h>
#else
# define DPMS_SERVER
# include <X11/extensions/dpms.h>
#endif

#if IVTVDEBUG
# define TRACE_ENTER(str)	ErrorF("ivtv_hw: " str " %d\n",pScrn->scrnIndex)
#else
# define TRACE_ENTER(str)
#endif

/* -------------------------------------------------------------------- */
/* some helpers for printing debug informations                         */

#if IVTVDEBUG
static void
print_ivtv_mode(char *txt, struct fb_var_screeninfo *var)
{
    ErrorF("ivtv %s mode:\t%d   %d %d %d %d   %d %d %d %d   %d %d:%d:%d\n",
	txt, var->pixclock,
	var->xres, var->right_margin, var->hsync_len, var->left_margin,
	var->yres, var->lower_margin, var->vsync_len, var->upper_margin,
	var->bits_per_pixel,
	var->red.length, var->green.length, var->blue.length);
}

static void
print_xfree_mode(char *txt, DisplayModePtr mode)
{
    ErrorF("xfree %s mode:\t%d   %d %d %d %d   %d %d %d %d\n",
	txt, mode->Clock,
	mode->HDisplay, mode->HSyncStart, mode->HSyncEnd, mode->HTotal,
	mode->VDisplay, mode->VSyncStart, mode->VSyncEnd, mode->VTotal);
}
#endif

/* -------------------------------------------------------------------- */
/* Convert timings between the XFree and the Frame Buffer Device        */

static void
xfree2ivtv_fblayout(ScrnInfoPtr pScrn, struct fb_var_screeninfo *var)
{
    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);

    var->xres_virtual = devPtr->shadow_width / (pScrn->bitsPerPixel / 8);
    var->yres_virtual = devPtr->shadow_height;
    var->bits_per_pixel = pScrn->bitsPerPixel;
    var->red.length = pScrn->weight.red;
    var->green.length = pScrn->weight.green;
    var->blue.length = pScrn->weight.blue;
}

static void
xfree2ivtv_timing(DisplayModePtr mode, struct fb_var_screeninfo *var)
{
    var->xres = mode->HDisplay;
    var->yres = mode->VDisplay;
    if (var->xres_virtual < var->xres)
	var->xres_virtual = var->xres;
    if (var->yres_virtual < var->yres)
	var->yres_virtual = var->yres;
    var->xoffset = var->yoffset = 0;
    var->pixclock = mode->Clock ? 1000000000 / mode->Clock : 0;
    var->right_margin = mode->HSyncStart - mode->HDisplay;
    var->hsync_len = mode->HSyncEnd - mode->HSyncStart;
    var->left_margin = mode->HTotal - mode->HSyncEnd;
    var->lower_margin = mode->VSyncStart - mode->VDisplay;
    var->vsync_len = mode->VSyncEnd - mode->VSyncStart;
    var->upper_margin = mode->VTotal - mode->VSyncEnd;
    var->sync = 0;
    if (mode->Flags & V_INTERLACE)
	var->vmode = FB_VMODE_INTERLACED;
    else
	var->vmode = FB_VMODE_NONINTERLACED;
}

static void
ivtv2xfree_timing(struct fb_var_screeninfo *var, DisplayModePtr mode)
{
    mode->Clock = var->pixclock ? 1000000000 / var->pixclock : 28000000;
    mode->HDisplay = var->xres;
    mode->HSyncStart = mode->HDisplay + var->right_margin;
    mode->HSyncEnd = mode->HSyncStart + var->hsync_len;
    mode->HTotal = mode->HSyncEnd + var->left_margin;
    mode->VDisplay = var->yres;
    mode->VSyncStart = mode->VDisplay + var->lower_margin;
    mode->VSyncEnd = mode->VSyncStart + var->vsync_len;
    mode->VTotal = mode->VSyncEnd + var->upper_margin;
    mode->Flags = 0;
    mode->Flags |= var->sync & FB_SYNC_HOR_HIGH_ACT ? V_PHSYNC : V_NHSYNC;
    mode->Flags |= var->sync & FB_SYNC_VERT_HIGH_ACT ? V_PVSYNC : V_NVSYNC;
    mode->Flags |= var->sync & FB_SYNC_COMP_HIGH_ACT ? V_PCSYNC : V_NCSYNC;
    if ((var->vmode & FB_VMODE_MASK) == FB_VMODE_INTERLACED)
	mode->Flags |= V_INTERLACE;
    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;
}

/* -------------------------------------------------------------------- */
/* open correct framebuffer device                                      */

static int
ivtv_open(int scrnIndex, char *dev, char **namep, IVTVDevPtr devPtr)
{
    struct fb_fix_screeninfo fix;
    int fbufId = 255;
    int yuvId;
    char *devid;
    int fd;

    /* try argument (from XF86Config) first */
    if (dev) {
	fd = open(dev, O_RDWR, 0);
    } else {
	/* second: environment variable */
	dev = getenv("FRAMEBUFFER");
	if ((NULL == dev) || ((fd = open(dev, O_RDWR, 0)) == -1)) {
	    /* last try: default device */
	    dev = "/dev/fb0";
	    fd = open(dev, O_RDWR, 0);
	}
    }

    if (fd == -1) {
	xf86DrvMsg(scrnIndex, X_ERROR, "ivtv_open: Open \"%s\" failed (%s)\n",
		    dev, strerror(errno));
	return -1;
    }

    if (-1 == ioctl(fd, FBIOGET_FSCREENINFO, (void *)(&fix))) {
	xf86DrvMsg(scrnIndex, X_ERROR,
	    "ivtv_open: FBIOGET_FSCREENINFO failed (%s)\n", strerror(errno));
	if (namep)
	    *namep = NULL;
	return -1;
    }

    if (namep) {
	*namep = xnfalloc(16);
	strncpy(*namep, fix.id, 16);
    }

    if (fd == -1 || devPtr == NULL)
	return fd;

    devid = dev + 7;

    if (*devid == '/')
	devid++;
    sscanf(devid, "%d", &fbufId);

    devPtr->legacy_dma = 1;
    devPtr->legacy_fb_api = 0;
    devPtr->legacy_api = 1;
    devPtr->dma_write = 0;
    devPtr->yuvDevNum = -1;

    xf86DrvMsg(scrnIndex, X_PROBED, "Framebuffer id from dev %s is %d\n",
	    dev, fbufId);

    for (yuvId = 48; yuvId < 64 && devPtr->yuvDevName == NULL; yuvId++) {
	char yuvDev[20] = "/dev/video";
	char yuvDevFull[20];
	char yuvDevFull1[20];
	int yuvFd;
	struct v4l2_capability vcap;

	sprintf(yuvDevFull, "%s%d", yuvDev, yuvId);
	yuvFd = open(yuvDevFull, O_RDONLY);

	if (yuvFd == -1 && errno == ENODEV) {
	    sprintf(yuvDevFull1, "%s%d", yuvDev, yuvId - 48);
	    yuvFd = open(yuvDevFull1, O_RDONLY);
	    if (yuvFd == -1) {
		xf86DrvMsg(scrnIndex, X_ERROR,
			"ivtv_open: Unable to open yuv device '%s'\n",
			yuvDevFull);
	    }
	} else if (yuvFd == -1 && errno == EACCES) {
		/* Device exists, but we weren't allowed to open it */
		xf86DrvMsg(scrnIndex, X_ERROR,
		    "ivtv_open: Unable to open yuv device '%s'. "
                    "Check device permissions.\n", yuvDevFull);
	}

	if (yuvFd == -1)
		continue;

	memset(&vcap, 0, sizeof(vcap));
	if (ioctl(yuvFd, VIDIOC_QUERYCAP, &vcap) < 0) {
	    xf86DrvMsg(scrnIndex, X_ERROR,
		    "ivtv_open: Can't query driver version so not adding Xv"
		    "support on %s\n", yuvDevFull);
	    close(yuvFd);
	    continue;
	}
	xf86DrvMsg(scrnIndex, X_INFO,
		"IVTV driver version %d.%d.%d\n",
		vcap.version >> 16,
		(vcap.version >> 8) & 0xFF, vcap.version & 0xFF);
	if (vcap.version > 0x010400) {
	    xf86DrvMsg(scrnIndex, X_INFO, "Using new API with dma write() support\n");
	    devPtr->dma_write = 1;
	    devPtr->legacy_api = 0;
	    devPtr->legacy_dma = 0;
	} else if (vcap.version >= 0x010000) {
	    xf86DrvMsg(scrnIndex, X_INFO, "Using new API\n");
	    devPtr->dma_write = 0;
	    devPtr->legacy_api = 0;
	    devPtr->legacy_dma = 0;
	} else {
	    xf86DrvMsg(scrnIndex, X_INFO, "Using legacy API\n");
	}

	if (devPtr->legacy_api) {
	    int yuvFbId = -1;
	    int ret = ioctl(yuvFd, IVTV_IOC_GET_FB, &yuvFbId);

	    if (ret != -1 && yuvFbId == fbufId) {
		struct ivtvfb_ioctl_state_info fbstate;

		if (vcap.version < 0x306) {
		    xf86DrvMsg(scrnIndex, X_ERROR,
			    "Version of ivtv is too old to support Xv\n");
		    break;
		} else if (vcap.version >= 0xA00) {
		    devPtr->legacy_dma = 0;
		    xf86DrvMsg(scrnIndex, X_INFO,
			    "Using new osd dma\n");
		} else {
		    xf86DrvMsg(scrnIndex, X_INFO,
			    "Using old osd dma\n");
		}
		devPtr->yuvDevName = strdup(yuvDevFull);
		devPtr->yuvDevNum = yuvId;
		xf86DrvMsg(scrnIndex, X_INFO,
			"Linked framebuffer 'dev/fb%d' to yuv device '%s'\n",
			yuvFbId, yuvDevFull);

		ioctl(fd, IVTVFB_IOCTL_GET_STATE, &fbstate);
		fbstate.status &= ~(IVTVFB_STATUS_GLOBAL_ALPHA | IVTVFB_STATUS_LOCAL_ALPHA);
		fbstate.status |= IVTVFB_STATUS_ENABLED;
		ioctl(fd, IVTVFB_IOCTL_SET_STATE, &fbstate);
	    }
	} else {
	    struct v4l2_framebuffer fbuf;

	    ioctl(yuvFd, VIDIOC_G_FBUF, &fbuf);
	    if (fix.smem_start == (unsigned long)fbuf.base) {
		devPtr->yuvDevName = strdup(yuvDevFull);
		devPtr->yuvDevNum = yuvId;
		xf86DrvMsg(scrnIndex, X_INFO,
			"Linked framebuffer 'dev/fb%d' to yuv device '%s'\n",
			fbufId, yuvDevFull);
		fbuf.flags &= ~(V4L2_FBUF_FLAG_GLOBAL_ALPHA | V4L2_FBUF_FLAG_LOCAL_ALPHA);
		fbuf.flags |= V4L2_FBUF_FLAG_OVERLAY;
		ioctl(yuvFd, VIDIOC_S_FBUF, &fbuf);
		ioctl(fd, FBIOBLANK, VESA_NO_BLANKING);
	    }
	}
	close(yuvFd);
    }

    if (devPtr->yuvDevName == NULL) {
	xf86DrvMsg(scrnIndex, X_ERROR,
		"Unable to match framebuffer '%s' with yuv device\n", dev);
    }
    return fd;
}

/* -------------------------------------------------------------------- */

Bool
#if XSERVER_LIBPCIACCESS
ivtvHWProbe(struct pci_device *PciInfo, char *device, char **namep)
#else
ivtvHWProbe(pciVideoPtr pPci, char *device, char **namep)
#endif
{
    int fd;
    Bool retVal = TRUE;
    struct fb_fix_screeninfo fix;

    fd = ivtv_open(-1, device, namep, NULL);

    if (-1 == fd)
	return FALSE;

    if (-1 == ioctl(fd, FBIOGET_FSCREENINFO, (void *)(&fix))) {
	*namep = NULL;
	xf86DrvMsg(0, X_ERROR, "Probe: FBIOGET_FSCREENINFO failed (%s)\n",
		    strerror(errno));
	return FALSE;
    }
    if (strcmp("cx23415 TV out", fix.id)) {
	if (strcmp("iTVC15 TV out", fix.id)) {
	    xf86DrvMsg(0, X_ERROR, "Probe: Unsupported card '%s'\n", fix.id);
	    retVal = FALSE;
	}
    }
    close(fd);
    return retVal;
}

Bool
#if XSERVER_LIBPCIACCESS
ivtvHWInit(ScrnInfoPtr pScrn, struct pci_device *PciInfo, char *device)
#else
ivtvHWInit(ScrnInfoPtr pScrn, pciVideoPtr pPci, char *device)
#endif
{
    TRACE_ENTER("Init");

    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);
    devPtr->fd_yuv = -1;
    devPtr->yuvDevName = NULL;

    /* open device */
    devPtr->fd = ivtv_open(pScrn->scrnIndex, device, NULL, devPtr);

    if (-1 == devPtr->fd) {
	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
	    "Init: Failed to open framebuffer device, consult warnings"
	    " and/or errors above for possible reasons\n"
	    "\t(you may have to look at the server log to see"
	    " warnings)\n");
	return FALSE;
    }

    /* get current fb device settings */
    if (-1 == ioctl(devPtr->fd, FBIOGET_FSCREENINFO, (void *)(&devPtr->fix))) {
	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
	    "Init: FBIOGET_FSCREENINFO failed (%s)\n", strerror(errno));
	return FALSE;
    }
    if (-1 == ioctl(devPtr->fd, FBIOGET_VSCREENINFO, (void *)(&devPtr->var))) {
	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
	    "Init: FBIOGET_VSCREENINFO failed (%s)\n", strerror(errno));
	return FALSE;
    }

    /* we can use the current settings as "buildin mode" */
    ivtv2xfree_timing(&devPtr->var, &devPtr->buildin);
    devPtr->buildin.name = "current";
    devPtr->buildin.next = &devPtr->buildin;
    devPtr->buildin.prev = &devPtr->buildin;
    devPtr->buildin.type |= M_T_BUILTIN;

    return TRUE;
}

char *
ivtvHWGetName(ScrnInfoPtr pScrn)
{
    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);

    return devPtr->fix.id;
}

int
ivtvHWGetDepth(ScrnInfoPtr pScrn, int *fbbpp)
{
    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);

    if (fbbpp)
	*fbbpp = devPtr->var.bits_per_pixel;

    if (devPtr->fix.visual == FB_VISUAL_TRUECOLOR ||
	devPtr->fix.visual == FB_VISUAL_DIRECTCOLOR)
	return devPtr->var.red.length + devPtr->var.green.length +
	    devPtr->var.blue.length;

    return devPtr->var.bits_per_pixel;
}

int
ivtvHWGetType(ScrnInfoPtr pScrn)
{
    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);

    return devPtr->fix.type;
}

int
ivtvHWGetVidmem(ScrnInfoPtr pScrn)
{
    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);

    return devPtr->fix.smem_len;
}

void
ivtvHWSetVideoModes(ScrnInfoPtr pScrn)
{
    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);
    int virtX = pScrn->display->virtualX;
    int virtY = pScrn->display->virtualY;
    struct fb_var_screeninfo var;
    char **modename;
    DisplayModePtr mode, this, last = NULL;

    TRACE_ENTER("VerifyModes");
    if (NULL == pScrn->display->modes)
	return;

    for (modename = pScrn->display->modes; *modename != NULL; modename++) {
	for (mode = pScrn->monitor->Modes; mode != NULL; mode = mode->next)
	    if (0 == strcmp(mode->name, *modename))
		break;
	if (NULL == mode) {
	    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
		"\tmode \"%s\" not found\n", *modename);
	    continue;
	}
	memset(&var, 0, sizeof(var));
	xfree2ivtv_timing(mode, &var);
	xfree2ivtv_fblayout(pScrn, &devPtr->var);
	var.xres_virtual = virtX;
	var.yres_virtual = virtY;
	var.bits_per_pixel = pScrn->bitsPerPixel;
	var.red.length = pScrn->weight.red;
	var.green.length = pScrn->weight.green;
	var.blue.length = pScrn->weight.blue;

	var.activate = FB_ACTIVATE_TEST;
	if (var.xres_virtual < var.xres)
	    var.xres_virtual = var.xres;
	if (var.yres_virtual < var.yres)
	    var.yres_virtual = var.yres;
	if (-1 == ioctl(devPtr->fd, FBIOPUT_VSCREENINFO, (void *)(&var))) {
	    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
		"\tmode \"%s\" test failed\n", *modename);
	    continue;
	}
	xf86DrvMsg(pScrn->scrnIndex, X_INFO, "\tmode \"%s\" ok\n", *modename);
	if (virtX < var.xres)
	    virtX = var.xres;
	if (virtY < var.yres)
	    virtY = var.yres;
	if (NULL == pScrn->modes) {
	    pScrn->modes = xnfalloc(sizeof(DisplayModeRec));
	    this = pScrn->modes;
	    memcpy(this, mode, sizeof(DisplayModeRec));
	    this->next = this;
	    this->prev = this;
	} else {
	    this = xnfalloc(sizeof(DisplayModeRec));
	    memcpy(this, mode, sizeof(DisplayModeRec));
	    this->next = pScrn->modes;
	    this->prev = last;
	    last->next = this;
	    pScrn->modes->prev = this;
	}
	last = this;
    }
    pScrn->virtualX = virtX;
    pScrn->virtualY = virtY;
}

void
ivtvHWUseBuildinMode(ScrnInfoPtr pScrn)
{
    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);

    TRACE_ENTER("UseBuildinMode");
    pScrn->modes = &devPtr->buildin;
    pScrn->virtualX = pScrn->display->virtualX;
    pScrn->virtualY = pScrn->display->virtualY;
    if (pScrn->virtualX < devPtr->buildin.HDisplay)
	pScrn->virtualX = devPtr->buildin.HDisplay;
    if (pScrn->virtualY < devPtr->buildin.VDisplay)
	pScrn->virtualY = devPtr->buildin.VDisplay;
}

/* -------------------------------------------------------------------- */

#ifdef IVTVDEVHW_BYTE_SWAP
void *
ivtvHWMapVidmem(ScrnInfoPtr pScrn)
{
    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);
    long page_mask = ~(getpagesize() - 1);

    TRACE_ENTER("MapVidmem");
    if (NULL == devPtr->fbmem) {
	devPtr->fboff = (unsigned long)devPtr->fix.smem_start & ~page_mask;
	devPtr->fbmem_len =
	    (devPtr->fboff + devPtr->fix.smem_len + ~page_mask) & page_mask;
	devPtr->fbmem =
	    mmap(NULL, devPtr->fbmem_len, PROT_READ | PROT_WRITE, MAP_SHARED,
	    devPtr->fd, 0);
	if (-1 == (long)devPtr->fbmem) {
	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		"MapVidmem: mmap failed (%s)\n", strerror(errno));
	    devPtr->fbmem = NULL;
	} else {
	    /* Perhaps we'd better add fboff to fbmem and return 0 in
	     * ivtvHWLinearOffset()? Of course we then need to mask
	     * fPtr->fbmem with page_mask in ivtvHWUnmapVidmem() as
	     * well. [geert] */
	}
    }
    pScrn->memPhysBase =
	(unsigned long)devPtr->fix.smem_start & (unsigned long)(page_mask);
    pScrn->fbOffset =
	(unsigned long)devPtr->fix.smem_start & (unsigned long)(~page_mask);
    return devPtr->fbmem;
}

Bool
ivtvHWUnmapVidmem(ScrnInfoPtr pScrn)
{
    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);

    TRACE_ENTER("UnmapVidmem");
    if (NULL != devPtr->fbmem) {
	if (-1 == munmap(devPtr->fbmem, devPtr->fbmem_len))
	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		"UnmapVidmem: munmap failed (%s)\n", strerror(errno));
	devPtr->fbmem = NULL;
    }
    return TRUE;
}
#endif /* IVTVDEVHW_BYTE_SWAP */

/* -------------------------------------------------------------------- */

Bool
ivtvHWModeInit(ScrnInfoPtr pScrn, DisplayModePtr mode)
{
    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);

    TRACE_ENTER("ModeInit");
    xfree2ivtv_timing(mode, &devPtr->var);
    xfree2ivtv_fblayout(pScrn, &devPtr->var);
#if IVTVDEBUG
    print_xfree_mode("init", mode);
    print_ivtv_mode("init", &devPtr->var);
#endif
    pScrn->vtSema = TRUE;

    /* set */
    if (0 != ioctl(devPtr->fd, FBIOPUT_VSCREENINFO, (void *)(&devPtr->var))) {
	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
	    "ModeInit: FBIOPUT_VSCREENINFO failed (%s)\n", strerror(errno));
	return FALSE;
    }
    /* read back */
    if (0 != ioctl(devPtr->fd, FBIOGET_FSCREENINFO, (void *)(&devPtr->fix))) {
	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
	    "ModeInit: FBIOGET_FSCREENINFO failed (%s)\n", strerror(errno));
	return FALSE;
    }
    if (0 != ioctl(devPtr->fd, FBIOGET_VSCREENINFO, (void *)(&devPtr->var))) {
	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
	    "ModeInit: FBIOGET_VSCREENINFO failed (%s)\n", strerror(errno));
	return FALSE;
    }
    return TRUE;
}

/* -------------------------------------------------------------------- */
/* video mode save/restore                                              */

/* TODO: colormap */
void
ivtvHWSave(ScrnInfoPtr pScrn)
{
    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);

    TRACE_ENTER("Save");
    if (0 != ioctl(devPtr->fd, FBIOGET_VSCREENINFO,
	    (void *)(&devPtr->saved_var)))
	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		   "Save: FBIOGET_VSCREENINFO failed (%s)\n", strerror(errno));
}

void
ivtvHWRestore(ScrnInfoPtr pScrn)
{
    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);

    TRACE_ENTER("Restore");
    if (0 != ioctl(devPtr->fd, FBIOPUT_VSCREENINFO,
	    (void *)(&devPtr->saved_var)))
	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		    "Restore: FBIOPUT_VSCREENINFO failed (%s)\n",
		    strerror(errno));
}

/* -------------------------------------------------------------------- */
/* callback for xf86HandleColormaps                                     */

void
ivtvHWLoadPalette(ScrnInfoPtr pScrn, int numColors, int *indices,
    LOCO * colors, VisualPtr pVisual)
{
    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);
    struct fb_cmap cmap;
    unsigned short red, green, blue;
    int i;

    TRACE_ENTER("Load Palette");
    cmap.len = 1;
    cmap.red = &red;
    cmap.green = &green;
    cmap.blue = &blue;
    cmap.transp = NULL;
    for (i = 0; i < numColors; i++) {
	cmap.start = indices[i];
	red = (colors[indices[i]].red << 8) | colors[indices[i]].red;
	green = (colors[indices[i]].green << 8) | colors[indices[i]].green;
	blue = (colors[indices[i]].blue << 8) | colors[indices[i]].blue;
	if (-1 == ioctl(devPtr->fd, FBIOPUTCMAP, (void *)&cmap))
	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		"LoadPalette: FBIOPUTCMAP failed (%s)\n", strerror(errno));
    }
}

/* -------------------------------------------------------------------- */
/* these can be hooked directly into ScrnInfoRec                        */

int
ivtvHWValidMode(int scrnIndex, DisplayModePtr mode, Bool verbose, int flags)
{
    ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);
    struct fb_var_screeninfo var;

    TRACE_ENTER("ValidMode");
    memcpy(&var, &devPtr->var, sizeof(var));
    xfree2ivtv_timing(mode, &var);
    xfree2ivtv_fblayout(pScrn, &devPtr->var);
    var.activate = FB_ACTIVATE_TEST;
    if (0 != ioctl(devPtr->fd, FBIOPUT_VSCREENINFO, (void *)(&devPtr->var))) {
	xf86DrvMsg(scrnIndex, X_ERROR,
	    "ValidMode: FBIOPUT_VSCREENINFO failed (%s)\n", strerror(errno));
	return MODE_BAD;
    }
    return MODE_OK;
}

Bool
ivtvHWSwitchMode(int scrnIndex, DisplayModePtr mode, int flags)
{
    ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);

    TRACE_ENTER("SwitchMode");
    xfree2ivtv_timing(mode, &devPtr->var);
    xfree2ivtv_fblayout(pScrn, &devPtr->var);
    if (0 != ioctl(devPtr->fd, FBIOPUT_VSCREENINFO, (void *)(&devPtr->var))) {
	xf86DrvMsg(scrnIndex, X_ERROR,
	    "SwitchMode: FBIOPUT_VSCREENINFO failed (%s)\n", strerror(errno));
	return FALSE;
    }
    return TRUE;
}

void
ivtvHWAdjustFrame(int scrnIndex, int x, int y, int flags)
{
    ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);

    devPtr->var.xoffset = x;
    devPtr->var.yoffset = y;
    if (-1 == ioctl(devPtr->fd, FBIOPAN_DISPLAY, (void *)&devPtr->var)) {
	xf86DrvMsgVerb(scrnIndex, 5, X_WARNING,
	    "AdjustFrame: FBIOPAN_DISPLAY failed (%s)\n", strerror(errno));
    }
}

Bool
ivtvHWEnterVT(int scrnIndex, int flags)
{
    ScrnInfoPtr pScrn = xf86Screens[scrnIndex];

    TRACE_ENTER("EnterVT");
    if (!ivtvHWModeInit(pScrn, pScrn->currentMode))
	return FALSE;
    ivtvHWAdjustFrame(scrnIndex, pScrn->frameX0, pScrn->frameY0, 0);
    return TRUE;
}

void
ivtvHWLeaveVT(int scrnIndex, int flags)
{
    ScrnInfoPtr pScrn = xf86Screens[scrnIndex];

    TRACE_ENTER("LeaveVT");
    ivtvHWRestore(pScrn);
}

void
ivtvHWDPMSSet(ScrnInfoPtr pScrn, int mode, int flags)
{
    unsigned long fbmode;

    if (!pScrn->vtSema)
	return;

    switch (mode) {
    case DPMSModeOn:
	fbmode = 0;
	break;
    case DPMSModeStandby:
	fbmode = 2;
	break;
    case DPMSModeSuspend:
	fbmode = 3;
	break;
    case DPMSModeOff:
	fbmode = 4;
	break;
    default:
	return;
    }

#ifdef USE_BLANK
    if (-1 == ioctl(IVTVDEVHWPTR(pScrn)->fd, FBIOBLANK, (void *)fbmode))
	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
	    "DPMSSet: FBIOBLANK (%s) failed\n", strerror(errno));
#endif
}

Bool
ivtvHWSaveScreen(ScreenPtr pScreen, int mode)
{
    ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
    unsigned long unblank;

    if (!pScrn->vtSema)
	return TRUE;

    unblank = xf86IsUnblank(mode);

#ifdef USE_BLANK
    if (-1 == ioctl(IVTVDEVHWPTR(pScrn)->fd, FBIOBLANK, (void *)(1 - unblank))) {
	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		"SaveScreen: FBIOBLANK (%s) failed\n", strerror(errno));
	return FALSE;
    }
#endif
    return TRUE;
}

#define MAX_RETRY_DMA 11
char *lastScreen = NULL;

Bool
ivtvHWSendDMA(ScrnInfoPtr pScrn, void *ptr, int x1, int x2, int y1, int y2)
{
    int totalScreenSize = 0, secondOffset = 0;
    int fb_api;

    IVTVDevPtr devPtr = IVTVDEVPTR(pScrn);

    struct ivtvfb_dma_frame args;
    int cpt = MAX_RETRY_DMA;

    int startOffset =
	((y1) * devPtr->shadow_width) + (x1 * pScrn->bitsPerPixel / 8);
    int endOffset =
	((y2 - 1) * devPtr->shadow_width) + (x2 * pScrn->bitsPerPixel / 8);

    /* If possible, use write() */
    if (devPtr->dma_write) {
	lseek(devPtr->fd, startOffset, SEEK_SET);
	if (write(devPtr->fd, ptr + startOffset, endOffset - startOffset) < 0)
	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		       "SendDMA: fb write() failed (%s)\n", strerror(errno));
	return TRUE;
    }

    totalScreenSize = devPtr->shadow_width * devPtr->shadow_height;

    if (pScrn->bitsPerPixel != 32) {
	/* Must align start & end addresses */
	startOffset &= ~3;

	if (endOffset & 3) {
	    endOffset = (endOffset + 4) & ~3;

	    /* If end of buffer, alignment not critical */
	    if (endOffset > totalScreenSize)
		endOffset = totalScreenSize;
	}
    }

    unsigned long totalData = endOffset - startOffset;

    /* Older versions of ivtv have to DMA a fixed block size */
    if (devPtr->legacy_dma) {
	if (totalData > 64 * 1024 * 4) {
	    /* This is a bigger lump so send in 2 bits */
	    totalData /= 2;
	    totalData = (totalData + 65535) & ~65535;
	    secondOffset = endOffset - totalData;
	} else {
	    totalData = (totalData + 65535) & ~65535;
	    if ((startOffset + totalData) > totalScreenSize) {
		startOffset -= (startOffset + totalData) - totalScreenSize;
	    }
	}
    }

    args.source = ((char *)ptr + startOffset);
    args.dest_offset = startOffset;
    args.count = totalData;

    /* Both ioctls accept the same argument list */
    fb_api =
	devPtr->legacy_fb_api ? IVTVFB_IOCTL_PREP_FRAME : IVTVFB_IOC_DMA_FRAME;

    while (cpt--) {
	if (0 == ioctl(devPtr->fd, fb_api, (void *)(&args)))
	    break;

	if (errno == EINVAL && !devPtr->legacy_fb_api) {
	    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Switching to legacy fb api\n");
	    fb_api = IVTVFB_IOCTL_PREP_FRAME;
	    devPtr->legacy_fb_api = 1;
	}
    }

    if (secondOffset) {
	args.source = ((char *)ptr + secondOffset);
	args.dest_offset = secondOffset;
	args.count = totalData;

	while (cpt--) {
	    if (0 == ioctl(devPtr->fd, fb_api, (void *)(&args)))
		break;
	}
    }

    return TRUE;
}
