wsfb_driver.c revision e686e132
1/*
2 * Copyright © 2001-2012 Matthieu Herrb
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 *    - Redistributions of source code must retain the above copyright
10 *      notice, this list of conditions and the following disclaimer.
11 *    - Redistributions in binary form must reproduce the above
12 *      copyright notice, this list of conditions and the following
13 *      disclaimer in the documentation and/or other materials provided
14 *      with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
19 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
20 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
22 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
28 *
29 */
30
31/*
32 * Based on fbdev.c written by:
33 *
34 * Authors:  Alan Hourihane, <alanh@fairlite.demon.co.uk>
35 *	     Michel Dänzer, <michdaen@iiic.ethz.ch>
36 */
37
38#ifdef HAVE_CONFIG_H
39#include "config.h"
40#endif
41
42#include <errno.h>
43#include <fcntl.h>
44#include <unistd.h>
45#include <sys/ioctl.h>
46#include <sys/types.h>
47#include <sys/mman.h>
48#include <sys/time.h>
49#include <errno.h>
50#include <dev/wscons/wsconsio.h>
51
52/* All drivers need this. */
53#include "xf86.h"
54#include "xf86_OSproc.h"
55#include "xf86_OSlib.h"
56
57#include "mipointer.h"
58#include "micmap.h"
59#include "colormapst.h"
60#include "xf86cmap.h"
61#include "shadow.h"
62#include "dgaproc.h"
63
64/* For visuals */
65#include "fb.h"
66
67#if GET_ABI_MAJOR(ABI_VIDEODRV_VERSION) < 6
68#include "xf86Resources.h"
69#include "xf86RAC.h"
70#endif
71
72#ifdef XvExtension
73#include "xf86xv.h"
74#endif
75
76#include "wsfb.h"
77
78/* #include "wsconsio.h" */
79
80#include <sys/mman.h>
81
82#ifdef X_PRIVSEP
83extern int priv_open_device(const char *);
84#else
85#define priv_open_device(n)    open(n,O_RDWR|O_NONBLOCK|O_EXCL)
86#endif
87
88#if defined(__NetBSD__)
89#define WSFB_DEFAULT_DEV "/dev/ttyE0"
90#else
91#define WSFB_DEFAULT_DEV "/dev/ttyC0"
92#endif
93
94#if GET_ABI_MAJOR(ABI_VIDEODRV_VERSION) > 6
95#define xf86LoaderReqSymLists(...) do {} while (0)
96#define LoaderRefSymLists(...) do {} while (0)
97#define xf86LoaderReqSymbols(...) do {} while (0)
98#endif
99
100#define DEBUG 0
101
102#if DEBUG
103# define TRACE_ENTER(str)       ErrorF("wsfb: " str " %d\n",pScrn->scrnIndex)
104# define TRACE_EXIT(str)        ErrorF("wsfb: " str " done\n")
105# define TRACE(str)             ErrorF("wsfb trace: " str "\n")
106#else
107# define TRACE_ENTER(str)
108# define TRACE_EXIT(str)
109# define TRACE(str)
110#endif
111
112/* Prototypes */
113static pointer WsfbSetup(pointer, pointer, int *, int *);
114static Bool WsfbGetRec(ScrnInfoPtr);
115static void WsfbFreeRec(ScrnInfoPtr);
116static const OptionInfoRec * WsfbAvailableOptions(int, int);
117static void WsfbIdentify(int);
118static Bool WsfbProbe(DriverPtr, int);
119static Bool WsfbPreInit(ScrnInfoPtr, int);
120static Bool WsfbScreenInit(SCREEN_INIT_ARGS_DECL);
121static Bool WsfbCloseScreen(CLOSE_SCREEN_ARGS_DECL);
122static void *WsfbWindowLinear(ScreenPtr, CARD32, CARD32, int, CARD32 *,
123			      void *);
124static void WsfbPointerMoved(SCRN_ARG_TYPE, int, int);
125static Bool WsfbEnterVT(VT_FUNC_ARGS_DECL);
126static void WsfbLeaveVT(VT_FUNC_ARGS_DECL);
127static Bool WsfbSwitchMode(SWITCH_MODE_ARGS_DECL);
128static int WsfbValidMode(SCRN_ARG_TYPE, DisplayModePtr, Bool, int);
129static void WsfbLoadPalette(ScrnInfoPtr, int, int *, LOCO *, VisualPtr);
130static Bool WsfbSaveScreen(ScreenPtr, int);
131static void WsfbSave(ScrnInfoPtr);
132static void WsfbRestore(ScrnInfoPtr);
133
134/* DGA stuff */
135#ifdef XFreeXDGA
136static Bool WsfbDGAOpenFramebuffer(ScrnInfoPtr, char **, unsigned char **,
137				   int *, int *, int *);
138static Bool WsfbDGASetMode(ScrnInfoPtr, DGAModePtr);
139static void WsfbDGASetViewport(ScrnInfoPtr, int, int, int);
140static Bool WsfbDGAInit(ScrnInfoPtr, ScreenPtr);
141#endif
142
143static void WsfbShadowUpdateSwap32(ScreenPtr, shadowBufPtr);
144static void WsfbShadowUpdateSplit(ScreenPtr, shadowBufPtr);
145
146static Bool WsfbDriverFunc(ScrnInfoPtr, xorgDriverFuncOp, pointer);
147
148/* Helper functions */
149static int wsfb_open(const char *);
150static pointer wsfb_mmap(size_t, off_t, int);
151
152enum { WSFB_ROTATE_NONE = 0,
153       WSFB_ROTATE_CCW = 90,
154       WSFB_ROTATE_UD = 180,
155       WSFB_ROTATE_CW = 270
156};
157
158/*
159 * This is intentionally screen-independent.
160 * It indicates the binding choice made in the first PreInit.
161 */
162static int pix24bpp = 0;
163
164#define WSFB_VERSION 		4000
165#define WSFB_NAME		"wsfb"
166#define WSFB_DRIVER_NAME	"wsfb"
167
168_X_EXPORT DriverRec WSFB = {
169	WSFB_VERSION,
170	WSFB_DRIVER_NAME,
171	WsfbIdentify,
172	WsfbProbe,
173	WsfbAvailableOptions,
174	NULL,
175	0,
176	WsfbDriverFunc
177};
178
179/* Supported "chipsets" */
180static SymTabRec WsfbChipsets[] = {
181	{ 0, "wsfb" },
182	{ -1, NULL }
183};
184
185/* Supported options */
186typedef enum {
187	OPTION_SHADOW_FB,
188	OPTION_ROTATE,
189	OPTION_HW_CURSOR,
190	OPTION_SW_CURSOR
191} WsfbOpts;
192
193static const OptionInfoRec WsfbOptions[] = {
194	{ OPTION_SHADOW_FB, "ShadowFB", OPTV_BOOLEAN, {0}, FALSE},
195	{ OPTION_ROTATE, "Rotate", OPTV_STRING, {0}, FALSE},
196	{ OPTION_HW_CURSOR, "HWCursor", OPTV_BOOLEAN, {1}, FALSE},
197	{ -1, NULL, OPTV_NONE, {0}, FALSE}
198};
199
200#if GET_ABI_MAJOR(ABI_VIDEODRV_VERSION) <= 6
201/* Symbols needed from other modules */
202static const char *fbSymbols[] = {
203	"fbPictureInit",
204	"fbScreenInit",
205	NULL
206};
207static const char *shadowSymbols[] = {
208	"shadowAdd",
209	"shadowSetup",
210	"shadowUpdatePacked",
211	"shadowUpdatePackedWeak",
212	"shadowUpdateRotatePacked",
213	"shadowUpdateRotatePackedWeak",
214	NULL
215};
216
217static const char *ramdacSymbols[] = {
218	"xf86CreateCursorInfoRec",
219	"xf86DestroyCursorInfoRec",
220	"xf86InitCursor",
221	NULL
222};
223#endif
224
225static XF86ModuleVersionInfo WsfbVersRec = {
226	"wsfb",
227	MODULEVENDORSTRING,
228	MODINFOSTRING1,
229	MODINFOSTRING2,
230	XORG_VERSION_CURRENT,
231	PACKAGE_VERSION_MAJOR,
232	PACKAGE_VERSION_MINOR,
233	PACKAGE_VERSION_PATCHLEVEL,
234	ABI_CLASS_VIDEODRV,
235	ABI_VIDEODRV_VERSION,
236	NULL,
237	{0, 0, 0, 0}
238};
239
240_X_EXPORT XF86ModuleData wsfbModuleData = { &WsfbVersRec, WsfbSetup, NULL };
241
242static pointer
243WsfbSetup(pointer module, pointer opts, int *errmaj, int *errmin)
244{
245	static Bool setupDone = FALSE;
246
247#if !(defined __NetBSD__ || defined __OpenBSD__)
248	/* Check that we're being loaded on a OpenBSD or NetBSD system. */
249	if (errmaj)
250		*errmaj = LDR_BADOS;
251	if (errmin)
252		*errmin = 0;
253	return NULL;
254#endif
255	if (!setupDone) {
256		setupDone = TRUE;
257		xf86AddDriver(&WSFB, module, HaveDriverFuncs);
258		LoaderRefSymLists(fbSymbols, shadowSymbols, ramdacSymbols,
259		    NULL);
260		return (pointer)1;
261	} else {
262		if (errmaj != NULL)
263			*errmaj = LDR_ONCEONLY;
264		return NULL;
265	}
266}
267
268static Bool
269WsfbGetRec(ScrnInfoPtr pScrn)
270{
271
272	if (pScrn->driverPrivate != NULL)
273		return TRUE;
274
275	pScrn->driverPrivate = xnfcalloc(sizeof(WsfbRec), 1);
276	return TRUE;
277}
278
279static void
280WsfbFreeRec(ScrnInfoPtr pScrn)
281{
282
283	if (pScrn->driverPrivate == NULL)
284		return;
285	free(pScrn->driverPrivate);
286	pScrn->driverPrivate = NULL;
287}
288
289static const OptionInfoRec *
290WsfbAvailableOptions(int chipid, int busid)
291{
292	return WsfbOptions;
293}
294
295static void
296WsfbIdentify(int flags)
297{
298	xf86PrintChipsets(WSFB_NAME, "driver for wsdisplay framebuffer",
299			  WsfbChipsets);
300}
301
302/* Open the framebuffer device. */
303static int
304wsfb_open(const char *dev)
305{
306	int fd = -1;
307
308	/* Try argument from xorg.conf first. */
309	if (dev == NULL || ((fd = priv_open_device(dev)) == -1)) {
310		/* Second: environment variable. */
311		dev = getenv("XDEVICE");
312		if (dev == NULL || ((fd = priv_open_device(dev)) == -1)) {
313			/* Last try: default device. */
314			dev = WSFB_DEFAULT_DEV;
315			if ((fd = priv_open_device(dev)) == -1) {
316				return -1;
317			}
318		}
319	}
320	return fd;
321}
322
323/* Map the framebuffer's memory. */
324static pointer
325wsfb_mmap(size_t len, off_t off, int fd)
326{
327	int pagemask, mapsize;
328	caddr_t addr;
329	pointer mapaddr;
330
331	pagemask = getpagesize() - 1;
332	mapsize = ((int) len + pagemask) & ~pagemask;
333	addr = 0;
334
335	/*
336	 * Try and make it private first, that way once we get it, an
337	 * interloper, e.g. another server, can't get this frame buffer,
338	 * and if another server already has it, this one won't.
339	 */
340	mapaddr = (pointer) mmap(addr, mapsize,
341				 PROT_READ | PROT_WRITE, MAP_SHARED,
342				 fd, off);
343	if (mapaddr == MAP_FAILED) {
344		mapaddr = NULL;
345	}
346#if DEBUG
347	ErrorF("mmap returns: addr %p len 0x%x\n", mapaddr, mapsize);
348#endif
349	return mapaddr;
350}
351
352static Bool
353WsfbProbe(DriverPtr drv, int flags)
354{
355	int i, fd, entity;
356       	GDevPtr *devSections;
357	int numDevSections;
358	const char *dev;
359	Bool foundScreen = FALSE;
360
361	TRACE("probe start");
362
363	/* For now, just bail out for PROBE_DETECT. */
364	if (flags & PROBE_DETECT)
365		return FALSE;
366
367	if ((numDevSections = xf86MatchDevice(WSFB_DRIVER_NAME,
368					      &devSections)) <= 0)
369		return FALSE;
370
371	/* Do not attach if the modesetting driver is active */
372	if (fbSlotClaimed == TRUE) {
373		DriverPtr fbSlotDrv = xf86GetEntityInfo(0)->driver;
374		if (strcmp(fbSlotDrv->driverName, "modesetting") == 0)
375			return FALSE;
376	}
377
378	for (i = 0; i < numDevSections; i++) {
379		ScrnInfoPtr pScrn = NULL;
380
381		dev = xf86FindOptionValue(devSections[i]->options, "device");
382		if ((fd = wsfb_open(dev)) >= 0) {
383			entity = xf86ClaimFbSlot(drv, 0, devSections[i], TRUE);
384			pScrn = xf86ConfigFbEntity(NULL,0,entity,
385						   NULL,NULL,NULL,NULL);
386			if (pScrn != NULL) {
387				foundScreen = TRUE;
388				pScrn->driverVersion = WSFB_VERSION;
389				pScrn->driverName = WSFB_DRIVER_NAME;
390				pScrn->name = WSFB_NAME;
391				pScrn->Probe = WsfbProbe;
392				pScrn->PreInit = WsfbPreInit;
393				pScrn->ScreenInit = WsfbScreenInit;
394				pScrn->SwitchMode = WsfbSwitchMode;
395				pScrn->AdjustFrame = NULL;
396				pScrn->EnterVT = WsfbEnterVT;
397				pScrn->LeaveVT = WsfbLeaveVT;
398				pScrn->ValidMode = WsfbValidMode;
399
400				xf86DrvMsg(pScrn->scrnIndex, X_INFO,
401				    "using %s\n", dev != NULL ? dev :
402				    "default device");
403			}
404		}
405	}
406	free(devSections);
407	TRACE("probe done");
408	return foundScreen;
409}
410
411static Bool
412WsfbPreInit(ScrnInfoPtr pScrn, int flags)
413{
414	WsfbPtr fPtr;
415	int default_depth, bitsperpixel, wstype;
416	const char *dev, *s;
417	char *mod = NULL;
418	const char *reqSym = NULL;
419	Gamma zeros = {0.0, 0.0, 0.0};
420	DisplayModePtr mode;
421	MessageType from;
422
423	if (flags & PROBE_DETECT) return FALSE;
424
425	TRACE_ENTER("PreInit");
426
427	if (pScrn->numEntities != 1) return FALSE;
428
429	pScrn->monitor = pScrn->confScreen->monitor;
430
431	WsfbGetRec(pScrn);
432	fPtr = WSFBPTR(pScrn);
433
434	fPtr->pEnt = xf86GetEntityInfo(pScrn->entityList[0]);
435
436#if GET_ABI_MAJOR(ABI_VIDEODRV_VERSION) < 6
437	pScrn->racMemFlags = RAC_FB | RAC_COLORMAP | RAC_CURSOR | RAC_VIEWPORT;
438	pScrn->racIoFlags = pScrn->racMemFlags;
439#endif
440
441	dev = xf86FindOptionValue(fPtr->pEnt->device->options, "device");
442	fPtr->fd = wsfb_open(dev);
443	if (fPtr->fd == -1) {
444		return FALSE;
445	}
446
447	if (ioctl(fPtr->fd, WSDISPLAYIO_GET_FBINFO, &fPtr->fbi) != 0) {
448		struct wsdisplay_fbinfo info;
449		struct wsdisplayio_fbinfo *fbi = &fPtr->fbi;
450		int lb;
451
452		xf86Msg(X_WARNING, "ioctl(WSDISPLAYIO_GET_FBINFO) failed, " \
453			"falling back to old method\n");
454		if (ioctl(fPtr->fd, WSDISPLAYIO_GINFO, &info) == -1) {
455			xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
456				   "ioctl WSDISPLAY_GINFO: %s\n",
457				   strerror(errno));
458			return FALSE;
459		}
460		if (ioctl(fPtr->fd, WSDISPLAYIO_GTYPE, &wstype) == -1) {
461			xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
462				   "ioctl WSDISPLAY_GTYPE: %s\n",
463				   strerror(errno));
464			return FALSE;
465		}
466		if (ioctl(fPtr->fd, WSDISPLAYIO_LINEBYTES, &lb) == -1) {
467			xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
468				   "ioctl WSDISPLAYIO_LINEBYTES: %s\n",
469				   strerror(errno));
470			return FALSE;
471		}
472		/* ok, fake up a new style fbinfo */
473		fbi->fbi_width = info.width;
474		fbi->fbi_height = info.height;
475		fbi->fbi_stride = lb;
476		fbi->fbi_bitsperpixel = info.depth;
477		if (info.depth > 16) {
478			fbi->fbi_pixeltype = WSFB_RGB;
479			if (wstype == WSDISPLAY_TYPE_SUN24 ||
480			    wstype == WSDISPLAY_TYPE_SUNCG12 ||
481			    wstype == WSDISPLAY_TYPE_SUNCG14 ||
482			    wstype == WSDISPLAY_TYPE_SUNTCX ||
483			    wstype == WSDISPLAY_TYPE_SUNFFB ||
484			    wstype == WSDISPLAY_TYPE_XVR1000 ||
485			    wstype == WSDISPLAY_TYPE_VC4) {
486				fbi->fbi_subtype.fbi_rgbmasks.red_offset = 0;
487				fbi->fbi_subtype.fbi_rgbmasks.red_size = 8;
488				fbi->fbi_subtype.fbi_rgbmasks.green_offset = 8;
489				fbi->fbi_subtype.fbi_rgbmasks.green_size = 8;
490				fbi->fbi_subtype.fbi_rgbmasks.blue_offset = 16;
491				fbi->fbi_subtype.fbi_rgbmasks.blue_size = 8;
492			} else {
493				fbi->fbi_subtype.fbi_rgbmasks.red_offset = 16;
494				fbi->fbi_subtype.fbi_rgbmasks.red_size = 8;
495				fbi->fbi_subtype.fbi_rgbmasks.green_offset = 8;
496				fbi->fbi_subtype.fbi_rgbmasks.green_size = 8;
497				fbi->fbi_subtype.fbi_rgbmasks.blue_offset = 0;
498				fbi->fbi_subtype.fbi_rgbmasks.blue_size = 8;
499			}
500			fbi->fbi_subtype.fbi_rgbmasks.alpha_offset = 0;
501			fbi->fbi_subtype.fbi_rgbmasks.alpha_size = 0;
502		} else if (info.depth <= 8) {
503			fbi->fbi_pixeltype = WSFB_CI;
504			fbi->fbi_subtype.fbi_cmapinfo.cmap_entries = info.cmsize;
505		}
506		fbi->fbi_flags = 0;
507		fbi->fbi_fbsize = lb * info.height;
508		fbi->fbi_fboffset = 0;
509
510	}
511	xf86Msg(X_INFO, "fboffset %x\n", fPtr->fbi.fbi_fboffset);
512	/*
513	 * Allocate room for saving the colormap.
514	 */
515	if (fPtr->fbi.fbi_pixeltype == WSFB_CI &&
516	    fPtr->fbi.fbi_subtype.fbi_cmapinfo.cmap_entries > 0) {
517		fPtr->saved_cmap.red =
518		    (unsigned char *)malloc(fPtr->fbi.fbi_subtype.fbi_cmapinfo.cmap_entries);
519		if (fPtr->saved_cmap.red == NULL) {
520			xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
521			    "Cannot malloc %d bytes\n",
522			    fPtr->fbi.fbi_subtype.fbi_cmapinfo.cmap_entries);
523			return FALSE;
524		}
525		fPtr->saved_cmap.green =
526		    (unsigned char *)malloc(fPtr->fbi.fbi_subtype.fbi_cmapinfo.cmap_entries);
527		if (fPtr->saved_cmap.green == NULL) {
528			xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
529			    "Cannot malloc %d bytes\n",
530			    fPtr->fbi.fbi_subtype.fbi_cmapinfo.cmap_entries);
531			free(fPtr->saved_cmap.red);
532			return FALSE;
533		}
534		fPtr->saved_cmap.blue =
535		    (unsigned char *)malloc(fPtr->fbi.fbi_subtype.fbi_cmapinfo.cmap_entries);
536		if (fPtr->saved_cmap.blue == NULL) {
537			xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
538			    "Cannot malloc %d bytes\n",
539			    fPtr->fbi.fbi_subtype.fbi_cmapinfo.cmap_entries);
540			free(fPtr->saved_cmap.red);
541			free(fPtr->saved_cmap.green);
542			return FALSE;
543		}
544	}
545
546	/* Handle depth */
547	default_depth = fPtr->fbi.fbi_bitsperpixel <= 24 ? fPtr->fbi.fbi_bitsperpixel : 24;
548	bitsperpixel = fPtr->fbi.fbi_bitsperpixel == 15 ? 16 : fPtr->fbi.fbi_bitsperpixel;
549#if defined(__NetBSD__) && defined(WSDISPLAY_TYPE_LUNA)
550	if (wstype == WSDISPLAY_TYPE_LUNA) {
551		/*
552		 * XXX
553		 * LUNA's color framebuffers support 4bpp or 8bpp
554		 * but they have multiple 1bpp VRAM planes like ancient VGA.
555		 * For now, Xorg server supports only the first one plane
556		 * as 1bpp monochrome server.
557		 *
558		 * Note OpenBSD/luna88k workarounds this by switching depth
559		 * and palette settings by WSDISPLAYIO_SETGFXMODE ioctl.
560		 */
561		default_depth = 1;
562		bitsperpixel = 1;
563	}
564#endif
565	if (!xf86SetDepthBpp(pScrn, default_depth, default_depth,
566		bitsperpixel,
567		bitsperpixel >= 24 ? Support24bppFb|Support32bppFb : 0))
568		return FALSE;
569
570	/* Check consistency. */
571	if (pScrn->bitsPerPixel != bitsperpixel) {
572		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
573		    "specified depth (%d) or bpp (%d) doesn't match "
574		    "framebuffer depth (%d)\n", pScrn->depth,
575		    pScrn->bitsPerPixel, bitsperpixel);
576		return FALSE;
577	}
578	xf86PrintDepthBpp(pScrn);
579
580	/* Get the depth24 pixmap format. */
581	if (pScrn->depth == 24 && pix24bpp == 0)
582		pix24bpp = xf86GetBppFromDepth(pScrn, 24);
583
584	/* Handle options. */
585	xf86CollectOptions(pScrn, NULL);
586	fPtr->Options = (OptionInfoRec *)malloc(sizeof(WsfbOptions));
587	if (fPtr->Options == NULL)
588		return FALSE;
589	memcpy(fPtr->Options, WsfbOptions, sizeof(WsfbOptions));
590	xf86ProcessOptions(pScrn->scrnIndex, fPtr->pEnt->device->options,
591			   fPtr->Options);
592
593	/* Use shadow framebuffer by default, on depth >= 8 */
594	xf86Msg(X_INFO, "fbi_flags: %x\n", fPtr->fbi.fbi_flags);
595	if ((pScrn->depth >= 8) &&
596	   ((fPtr->fbi.fbi_flags & WSFB_VRAM_IS_RAM) == 0)) {
597		fPtr->shadowFB = xf86ReturnOptValBool(fPtr->Options,
598						      OPTION_SHADOW_FB, TRUE);
599	} else
600		if (xf86ReturnOptValBool(fPtr->Options,
601					 OPTION_SHADOW_FB, FALSE)) {
602			xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
603				   "Shadow FB option ignored on depth < 8");
604		}
605	if (fPtr->fbi.fbi_flags & WSFB_VRAM_IS_SPLIT) {
606		if (!fPtr->shadowFB) {
607			xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
608				   "Shadow FB forced on for split framebuffer");
609			fPtr->shadowFB = TRUE;
610		}
611	}
612	/* Rotation */
613	fPtr->rotate = WSFB_ROTATE_NONE;
614	if ((s = xf86GetOptValString(fPtr->Options, OPTION_ROTATE))) {
615		if (pScrn->depth >= 8) {
616			if (!xf86NameCmp(s, "CW")) {
617				fPtr->shadowFB = TRUE;
618				fPtr->rotate = WSFB_ROTATE_CW;
619				xf86DrvMsg(pScrn->scrnIndex, X_CONFIG,
620				    "Rotating screen clockwise\n");
621			} else if (!xf86NameCmp(s, "CCW")) {
622				fPtr->shadowFB = TRUE;
623				fPtr->rotate = WSFB_ROTATE_CCW;
624				xf86DrvMsg(pScrn->scrnIndex, X_CONFIG,
625				    "Rotating screen counter clockwise\n");
626			} else if (!xf86NameCmp(s, "UD")) {
627				fPtr->shadowFB = TRUE;
628				fPtr->rotate = WSFB_ROTATE_UD;
629				xf86DrvMsg(pScrn->scrnIndex, X_CONFIG,
630				    "Rotating screen upside down\n");
631			} else {
632				xf86DrvMsg(pScrn->scrnIndex, X_CONFIG,
633				    "\"%s\" is not a valid value for Option "
634				    "\"Rotate\"\n", s);
635				xf86DrvMsg(pScrn->scrnIndex, X_INFO,
636				    "Valid options are \"CW\", \"CCW\","
637				    " or \"UD\"\n");
638			}
639		} else {
640			xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
641			    "Option \"Rotate\" ignored on depth < 8");
642		}
643	}
644
645
646	fPtr->useSwap32 = FALSE;
647	/* Color weight */
648	if (fPtr->fbi.fbi_pixeltype == WSFB_RGB) {
649		rgb zeros = { 0, 0, 0 }, masks;
650
651		if (fPtr->fbi.fbi_subtype.fbi_rgbmasks.red_size > 0) {
652			uint32_t msk;
653
654			/*
655			 * see if we need to byte-swap pixels
656			 * XXX this requires a shadow FB and is incompatible
657			 * (for now ) with rotation
658			 */
659			if ((fPtr->fbi.fbi_bitsperpixel == 32) &&
660			    (fPtr->fbi.fbi_subtype.fbi_rgbmasks.blue_offset == 24) &&
661			    (fPtr->rotate == WSFB_ROTATE_NONE) &&
662			    (fPtr->shadowFB == TRUE)) {
663			    	/*
664			    	 * looks like BGRA - set the swap flag and flip
665			    	 * the offsets
666			    	 */
667			    	xf86Msg(X_INFO, "endian-flipped RGB framebuffer "
668			    			"detected, using WsfbShadowUpdateSwap32()\n");
669			    	fPtr->fbi.fbi_subtype.fbi_rgbmasks.blue_offset = 0;
670			    	fPtr->fbi.fbi_subtype.fbi_rgbmasks.green_offset = 8;
671			    	fPtr->fbi.fbi_subtype.fbi_rgbmasks.red_offset = 16;
672			    	fPtr->fbi.fbi_subtype.fbi_rgbmasks.alpha_offset = 24;
673				fPtr->useSwap32 = TRUE;
674			}
675
676			msk = 0xffffffff;
677			msk = msk << fPtr->fbi.fbi_subtype.fbi_rgbmasks.red_size;
678			msk = ~msk;
679			masks.red = msk << fPtr->fbi.fbi_subtype.fbi_rgbmasks.red_offset;
680
681			msk = 0xffffffff;
682			msk = msk << fPtr->fbi.fbi_subtype.fbi_rgbmasks.green_size;
683			msk = ~msk;
684			masks.green = msk << fPtr->fbi.fbi_subtype.fbi_rgbmasks.green_offset;
685
686			msk = 0xffffffff;
687			msk = msk << fPtr->fbi.fbi_subtype.fbi_rgbmasks.blue_size;
688			msk = ~msk;
689			masks.blue = msk << fPtr->fbi.fbi_subtype.fbi_rgbmasks.blue_offset;
690			xf86Msg(X_INFO, "masks generated: %08lx %08lx %08lx\n",
691			    (unsigned long)masks.red,
692			    (unsigned long)masks.green,
693			    (unsigned long)masks.blue);
694		} else {
695			masks.red = 0;
696			masks.green = 0;
697			masks.blue = 0;
698		}
699
700		if (!xf86SetWeight(pScrn, zeros, masks))
701			return FALSE;
702	}
703
704	/* Visual init */
705	if (!xf86SetDefaultVisual(pScrn, -1))
706		return FALSE;
707
708	/* We don't currently support DirectColor at > 8bpp . */
709	if (pScrn->depth > 8 && pScrn->defaultVisual != TrueColor) {
710		xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Given default visual"
711			   " (%s) is not supported at depth %d\n",
712			   xf86GetVisualName(pScrn->defaultVisual),
713			   pScrn->depth);
714		return FALSE;
715	}
716
717	xf86SetGamma(pScrn,zeros);
718
719	pScrn->progClock = TRUE;
720	pScrn->rgbBits   = (pScrn->depth >= 8) ? 8 : pScrn->depth;
721	pScrn->chipset   = "wsfb";
722	pScrn->videoRam  = fPtr->fbi.fbi_fbsize;
723
724	xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Vidmem: %dk\n",
725		   pScrn->videoRam/1024);
726
727	/* Fake video mode struct. */
728	mode = (DisplayModePtr)malloc(sizeof(DisplayModeRec));
729	mode->prev = mode;
730	mode->next = mode;
731	mode->name = "wsfb current mode";
732	mode->status = MODE_OK;
733	mode->type = M_T_BUILTIN;
734	mode->Clock = 0;
735	mode->HDisplay = fPtr->fbi.fbi_width;
736	mode->HSyncStart = 0;
737	mode->HSyncEnd = 0;
738	mode->HTotal = 0;
739	mode->HSkew = 0;
740	mode->VDisplay = fPtr->fbi.fbi_height;
741	mode->VSyncStart = 0;
742	mode->VSyncEnd = 0;
743	mode->VTotal = 0;
744	mode->VScan = 0;
745	mode->Flags = 0;
746	if (pScrn->modes != NULL) {
747		xf86DrvMsg(pScrn->scrnIndex, X_INFO,
748		   "Ignoring mode specification from screen section\n");
749	}
750	pScrn->currentMode = pScrn->modes = mode;
751	pScrn->virtualX = fPtr->fbi.fbi_width;
752	pScrn->virtualY = fPtr->fbi.fbi_height;
753	pScrn->displayWidth = pScrn->virtualX;
754
755	/* Set the display resolution. */
756	xf86SetDpi(pScrn, 0, 0);
757
758	from = X_DEFAULT;
759	fPtr->HWCursor = TRUE;
760	if (xf86GetOptValBool(fPtr->Options, OPTION_HW_CURSOR, &fPtr->HWCursor))
761		from = X_CONFIG;
762	if (xf86ReturnOptValBool(fPtr->Options, OPTION_SW_CURSOR, FALSE)) {
763		from = X_CONFIG;
764		fPtr->HWCursor = FALSE;
765	}
766	xf86DrvMsg(pScrn->scrnIndex, from, "Using %s cursor\n",
767		fPtr->HWCursor ? "HW" : "SW");
768
769	/* Load bpp-specific modules. */
770	switch(pScrn->bitsPerPixel) {
771	case 1:
772	case 4:
773	default:
774		mod = "fb";
775		break;
776	}
777
778
779	/* Load shadow if needed. */
780	if (fPtr->shadowFB) {
781		xf86DrvMsg(pScrn->scrnIndex, X_CONFIG,
782			   "Using \"Shadow Framebuffer\"\n");
783		if (xf86LoadSubModule(pScrn, "shadow") == NULL) {
784			WsfbFreeRec(pScrn);
785			return FALSE;
786		}
787	}
788
789	if (mod && xf86LoadSubModule(pScrn, mod) == NULL) {
790		WsfbFreeRec(pScrn);
791		return FALSE;
792	}
793
794	if (xf86LoadSubModule(pScrn, "ramdac") == NULL) {
795		WsfbFreeRec(pScrn);
796		return FALSE;
797        }
798
799	if (mod) {
800		if (reqSym) {
801			xf86LoaderReqSymbols(reqSym, NULL);
802		} else {
803			xf86LoaderReqSymLists(fbSymbols, NULL);
804		}
805	}
806	TRACE_EXIT("PreInit");
807	return TRUE;
808}
809
810static Bool
811WsfbCreateScreenResources(ScreenPtr pScreen)
812{
813	ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
814	WsfbPtr fPtr = WSFBPTR(pScrn);
815	PixmapPtr pPixmap;
816	Bool ret;
817	void (*shadowproc)(ScreenPtr, shadowBufPtr);
818
819	pScreen->CreateScreenResources = fPtr->CreateScreenResources;
820	ret = pScreen->CreateScreenResources(pScreen);
821	pScreen->CreateScreenResources = WsfbCreateScreenResources;
822
823	if (!ret)
824		return FALSE;
825
826	pPixmap = pScreen->GetScreenPixmap(pScreen);
827	if (fPtr->fbi.fbi_flags & WSFB_VRAM_IS_SPLIT) {
828		shadowproc = WsfbShadowUpdateSplit;
829	} else if (fPtr->useSwap32) {
830		shadowproc = WsfbShadowUpdateSwap32;
831	} else if (fPtr->rotate) {
832		shadowproc = shadowUpdateRotatePacked;
833	} else
834		shadowproc = shadowUpdatePacked;
835
836	if (!shadowAdd(pScreen, pPixmap, shadowproc,
837		WsfbWindowLinear, fPtr->rotate, NULL)) {
838		return FALSE;
839	}
840	return TRUE;
841}
842
843
844static Bool
845WsfbShadowInit(ScreenPtr pScreen)
846{
847	ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
848	WsfbPtr fPtr = WSFBPTR(pScrn);
849
850	if (!shadowSetup(pScreen))
851		return FALSE;
852	fPtr->CreateScreenResources = pScreen->CreateScreenResources;
853	pScreen->CreateScreenResources = WsfbCreateScreenResources;
854
855	return TRUE;
856}
857
858static Bool
859WsfbScreenInit(SCREEN_INIT_ARGS_DECL)
860{
861	ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
862	WsfbPtr fPtr = WSFBPTR(pScrn);
863	VisualPtr visual;
864	int ret, flags, ncolors;
865	int wsmode = WSDISPLAYIO_MODE_DUMBFB;
866	int wstype;
867	size_t len;
868
869	TRACE_ENTER("WsfbScreenInit");
870#if DEBUG
871	ErrorF("\tbitsPerPixel=%d, depth=%d, defaultVisual=%s\n"
872	       "\tmask: %x,%x,%x, offset: %u,%u,%u\n",
873	       pScrn->bitsPerPixel,
874	       pScrn->depth,
875	       xf86GetVisualName(pScrn->defaultVisual),
876	       pScrn->mask.red,pScrn->mask.green,pScrn->mask.blue,
877	       pScrn->offset.red,pScrn->offset.green,pScrn->offset.blue);
878#endif
879	switch (fPtr->fbi.fbi_bitsperpixel) {
880	case 1:
881	case 4:
882	case 8:
883		len = fPtr->fbi.fbi_stride * fPtr->fbi.fbi_height;
884		break;
885	case 15:
886	case 16:
887		if (fPtr->fbi.fbi_stride == fPtr->fbi.fbi_width) {
888			xf86Msg(X_ERROR, "Bogus stride == width in 16bit colour\n");
889			len = fPtr->fbi.fbi_width * fPtr->fbi.fbi_height * sizeof(short);
890		} else {
891			len = fPtr->fbi.fbi_stride * fPtr->fbi.fbi_height;
892		}
893		break;
894	case 24:
895		if (fPtr->fbi.fbi_stride == fPtr->fbi.fbi_width) {
896			xf86Msg(X_ERROR, "Bogus stride == width in 24bit colour\n");
897			len = fPtr->fbi.fbi_width * fPtr->fbi.fbi_height * 3;
898		} else {
899			len = fPtr->fbi.fbi_stride * fPtr->fbi.fbi_height;
900		}
901		break;
902	case 32:
903		if (fPtr->fbi.fbi_stride == fPtr->fbi.fbi_width) {
904			xf86Msg(X_ERROR, "Bogus stride == width in 32bit colour\n");
905			len = fPtr->fbi.fbi_width * fPtr->fbi.fbi_height * sizeof(int);
906		} else {
907			len = fPtr->fbi.fbi_stride * fPtr->fbi.fbi_height;
908		}
909		break;
910	default:
911		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
912			   "unsupported depth %d\n", fPtr->fbi.fbi_bitsperpixel);
913		return FALSE;
914	}
915	/* Switch to graphics mode - required before mmap. */
916	if (ioctl(fPtr->fd, WSDISPLAYIO_SMODE, &wsmode) == -1) {
917		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
918			   "ioctl WSDISPLAYIO_SMODE: %s\n",
919			   strerror(errno));
920		return FALSE;
921	}
922	/* Get wsdisplay type to handle quirks */
923	if (ioctl(fPtr->fd, WSDISPLAYIO_GTYPE, &wstype) == -1) {
924		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
925			   "ioctl WSDISPLAY_GTYPE: %s\n",
926			   strerror(errno));
927		return FALSE;
928	}
929	len = max(len, fPtr->fbi.fbi_fbsize);
930	fPtr->fbmem = wsfb_mmap(len, 0, fPtr->fd);
931
932	if (fPtr->fbmem == NULL) {
933		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
934			   "wsfb_mmap: %s\n", strerror(errno));
935		return FALSE;
936	}
937	fPtr->fbmem_len = len;
938
939	WsfbSave(pScrn);
940	pScrn->vtSema = TRUE;
941
942	/* MI layer */
943	miClearVisualTypes();
944	if (pScrn->bitsPerPixel > 8) {
945		if (!miSetVisualTypes(pScrn->depth, TrueColorMask,
946				      pScrn->rgbBits, TrueColor))
947			return FALSE;
948	} else {
949		if (!miSetVisualTypes(pScrn->depth,
950				      miGetDefaultVisualMask(pScrn->depth),
951				      pScrn->rgbBits, pScrn->defaultVisual))
952			return FALSE;
953	}
954	if (!miSetPixmapDepths())
955		return FALSE;
956
957	if (fPtr->rotate == WSFB_ROTATE_CW
958	    || fPtr->rotate == WSFB_ROTATE_CCW) {
959		int tmp = pScrn->virtualX;
960		pScrn->virtualX = pScrn->displayWidth = pScrn->virtualY;
961		pScrn->virtualY = tmp;
962	}
963	if (fPtr->rotate && !fPtr->PointerMoved) {
964		fPtr->PointerMoved = pScrn->PointerMoved;
965		pScrn->PointerMoved = WsfbPointerMoved;
966	}
967
968	fPtr->fbstart = fPtr->fbmem + fPtr->fbi.fbi_fboffset;
969#ifdef	WSDISPLAY_TYPE_LUNA
970	if (wstype == WSDISPLAY_TYPE_LUNA) {
971		/*
972		 * XXX
973		 * LUNA's FB seems to have 64 dot (8 byte) offset.
974		 * This might be able to be changed in kernel lunafb driver,
975		 * but current setting was pulled from 4.4BSD-Lite2/luna68k.
976		 */
977		fPtr->fbstart += 8;
978	}
979#endif
980
981	if (fPtr->shadowFB) {
982		fPtr->shadow = calloc(1, fPtr->fbi.fbi_stride * pScrn->virtualY);
983
984		if (!fPtr->shadow) {
985			xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
986			    "Failed to allocate shadow framebuffer\n");
987			return FALSE;
988		}
989	}
990
991	switch (pScrn->bitsPerPixel) {
992	case 1:
993		ret = fbScreenInit(pScreen,
994		    fPtr->fbstart,
995		    pScrn->virtualX, pScrn->virtualY,
996		    pScrn->xDpi, pScrn->yDpi,
997		    fPtr->fbi.fbi_stride * 8, pScrn->bitsPerPixel);
998		break;
999	case 4:
1000	case 8:
1001	case 16:
1002	case 24:
1003	case 32:
1004		ret = fbScreenInit(pScreen,
1005		    fPtr->shadowFB ? fPtr->shadow : fPtr->fbstart,
1006		    pScrn->virtualX, pScrn->virtualY,
1007		    pScrn->xDpi, pScrn->yDpi,
1008		    /* apparently fb wants stride in pixels, not bytes */
1009		    fPtr->fbi.fbi_stride / (pScrn->bitsPerPixel >> 3),
1010		    pScrn->bitsPerPixel);
1011		break;
1012	default:
1013		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1014			   "Unsupported bpp: %d", pScrn->bitsPerPixel);
1015		return FALSE;
1016	} /* case */
1017
1018	if (!ret)
1019		return FALSE;
1020
1021	if (pScrn->bitsPerPixel > 8) {
1022		/* Fixup RGB ordering. */
1023		visual = pScreen->visuals + pScreen->numVisuals;
1024		while (--visual >= pScreen->visuals) {
1025			if ((visual->class | DynamicClass) == DirectColor) {
1026				visual->offsetRed   = pScrn->offset.red;
1027				visual->offsetGreen = pScrn->offset.green;
1028				visual->offsetBlue  = pScrn->offset.blue;
1029				visual->redMask     = pScrn->mask.red;
1030				visual->greenMask   = pScrn->mask.green;
1031				visual->blueMask    = pScrn->mask.blue;
1032			}
1033		}
1034	}
1035
1036	if (pScrn->bitsPerPixel >= 8) {
1037		if (!fbPictureInit(pScreen, NULL, 0))
1038			xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
1039				   "RENDER extension initialisation failed.");
1040	}
1041	if (fPtr->shadowFB && !WsfbShadowInit(pScreen)) {
1042		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1043		    "shadow framebuffer initialization failed\n");
1044		return FALSE;
1045	}
1046
1047#ifdef XFreeXDGA
1048	if (!fPtr->rotate)
1049		WsfbDGAInit(pScrn, pScreen);
1050	else
1051		xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Rotated display, "
1052		    "disabling DGA\n");
1053#endif
1054	if (fPtr->rotate) {
1055		xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Enabling Driver Rotation, "
1056		    "disabling RandR\n");
1057#if 0
1058		xf86DisableRandR();
1059#endif
1060		if (pScrn->bitsPerPixel == 24)
1061			xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
1062			    "Rotation might be broken in 24 bpp\n");
1063	}
1064
1065	xf86SetBlackWhitePixels(pScreen);
1066	xf86SetBackingStore(pScreen);
1067
1068	/* Software cursor. */
1069	miDCInitialize(pScreen, xf86GetPointerScreenFuncs());
1070
1071	/* check for hardware cursor support */
1072	if (fPtr->HWCursor)
1073		WsfbSetupCursor(pScreen);
1074
1075	/*
1076	 * Colormap
1077	 *
1078	 * Note that, even on less than 8 bit depth frame buffers, we
1079	 * expect the colormap to be programmable with 8 bit values.
1080	 * As of now, this is indeed the case on all OpenBSD supported
1081	 * graphics hardware.
1082	 */
1083	if (!miCreateDefColormap(pScreen))
1084		return FALSE;
1085	flags = CMAP_RELOAD_ON_MODE_SWITCH;
1086
1087	ncolors = 0;
1088	if (fPtr->fbi.fbi_pixeltype == WSFB_CI) {
1089		ncolors = fPtr->fbi.fbi_subtype.fbi_cmapinfo.cmap_entries;
1090	}
1091
1092	/* On StaticGray visuals, fake a 256 entries colormap. */
1093	if (ncolors == 0)
1094		ncolors = 256;
1095
1096	if(!xf86HandleColormaps(pScreen, ncolors, 8, WsfbLoadPalette,
1097				NULL, flags))
1098		return FALSE;
1099
1100#if defined(__NetBSD__) && defined(WSDISPLAY_TYPE_LUNA)
1101	if (wstype == WSDISPLAY_TYPE_LUNA) {
1102		ncolors = fPtr->fbi.fbi_subtype.fbi_cmapinfo.cmap_entries;
1103		if (ncolors > 0) {
1104			/*
1105			 * Override palette to use 4bpp/8bpp framebuffers as
1106			 * monochrome server by using only the first plane.
1107			 * See also comment in WsfbPreInit().
1108			 */
1109			struct wsdisplay_cmap cmap;
1110			uint8_t r[256], g[256], b[256];
1111			int p;
1112
1113			for (p = 0; p < ncolors; p++)
1114				r[p] = g[p] = b[p] = (p & 1) ? 0xff : 0;
1115			cmap.index = 0;
1116			cmap.count = ncolors;
1117			cmap.red   = r;
1118			cmap.green = g;
1119			cmap.blue  = b;
1120			if (ioctl(fPtr->fd, WSDISPLAYIO_PUTCMAP, &cmap) == -1) {
1121				xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1122				   "ioctl WSDISPLAYIO_PUTCMAP: %s\n",
1123				   strerror(errno));
1124			}
1125		}
1126	}
1127#endif
1128
1129	pScreen->SaveScreen = WsfbSaveScreen;
1130
1131#ifdef XvExtension
1132	{
1133		XF86VideoAdaptorPtr *ptr;
1134
1135		int n = xf86XVListGenericAdaptors(pScrn,&ptr);
1136		if (n) {
1137			xf86XVScreenInit(pScreen,ptr,n);
1138		}
1139	}
1140#endif
1141
1142	/* Wrap the current CloseScreen function. */
1143	fPtr->CloseScreen = pScreen->CloseScreen;
1144	pScreen->CloseScreen = WsfbCloseScreen;
1145
1146	TRACE_EXIT("WsfbScreenInit");
1147	return TRUE;
1148}
1149
1150static Bool
1151WsfbCloseScreen(CLOSE_SCREEN_ARGS_DECL)
1152{
1153	ScrnInfoPtr pScrn = xf86ScreenToScrn(pScreen);
1154	PixmapPtr pPixmap;
1155	WsfbPtr fPtr = WSFBPTR(pScrn);
1156
1157
1158	TRACE_ENTER("WsfbCloseScreen");
1159
1160	pPixmap = pScreen->GetScreenPixmap(pScreen);
1161	if (fPtr->shadowFB)
1162		shadowRemove(pScreen, pPixmap);
1163
1164	if (pScrn->vtSema) {
1165		WsfbRestore(pScrn);
1166		if (munmap(fPtr->fbmem, fPtr->fbmem_len) == -1) {
1167			xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1168				   "munmap: %s\n", strerror(errno));
1169		}
1170
1171		fPtr->fbmem = NULL;
1172	}
1173#ifdef XFreeXDGA
1174	if (fPtr->pDGAMode) {
1175		free(fPtr->pDGAMode);
1176		fPtr->pDGAMode = NULL;
1177		fPtr->nDGAMode = 0;
1178	}
1179#endif
1180	pScrn->vtSema = FALSE;
1181
1182	/* Unwrap CloseScreen. */
1183	pScreen->CloseScreen = fPtr->CloseScreen;
1184	TRACE_EXIT("WsfbCloseScreen");
1185	return (*pScreen->CloseScreen)(CLOSE_SCREEN_ARGS);
1186}
1187
1188static void *
1189WsfbWindowLinear(ScreenPtr pScreen, CARD32 row, CARD32 offset, int mode,
1190		CARD32 *size, void *closure)
1191{
1192	ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
1193	WsfbPtr fPtr = WSFBPTR(pScrn);
1194
1195	/*
1196	 * XXX
1197	 * This should never happen. Is it really necessary?
1198	 */
1199	if (fPtr->fbi.fbi_stride)
1200		*size = fPtr->fbi.fbi_stride;
1201	else {
1202		if (ioctl(fPtr->fd, WSDISPLAYIO_LINEBYTES, size) == -1)
1203			return NULL;
1204		fPtr->fbi.fbi_stride = *size;
1205	}
1206	return ((CARD8 *)fPtr->fbmem + row * fPtr->fbi.fbi_stride + offset);
1207}
1208
1209static void
1210WsfbPointerMoved(SCRN_ARG_TYPE arg, int x, int y)
1211{
1212    SCRN_INFO_PTR(arg);
1213    WsfbPtr fPtr = WSFBPTR(pScrn);
1214    int newX, newY;
1215
1216    switch (fPtr->rotate)
1217    {
1218    case WSFB_ROTATE_CW:
1219	/* 90 degrees CW rotation. */
1220	newX = pScrn->pScreen->height - y - 1;
1221	newY = x;
1222	break;
1223
1224    case WSFB_ROTATE_CCW:
1225	/* 90 degrees CCW rotation. */
1226	newX = y;
1227	newY = pScrn->pScreen->width - x - 1;
1228	break;
1229
1230    case WSFB_ROTATE_UD:
1231	/* 180 degrees UD rotation. */
1232	newX = pScrn->pScreen->width - x - 1;
1233	newY = pScrn->pScreen->height - y - 1;
1234	break;
1235
1236    default:
1237	/* No rotation. */
1238	newX = x;
1239	newY = y;
1240	break;
1241    }
1242
1243    /* Pass adjusted pointer coordinates to wrapped PointerMoved function. */
1244    (*fPtr->PointerMoved)(arg, newX, newY);
1245}
1246
1247static Bool
1248WsfbEnterVT(VT_FUNC_ARGS_DECL)
1249{
1250	SCRN_INFO_PTR(arg);
1251	WsfbPtr fPtr = WSFBPTR(pScrn);
1252	int mode;
1253
1254	TRACE_ENTER("EnterVT");
1255	pScrn->vtSema = TRUE;
1256
1257	/* Restore the graphics mode. */
1258	mode = WSDISPLAYIO_MODE_DUMBFB;
1259	if (ioctl(fPtr->fd, WSDISPLAYIO_SMODE, &mode) == -1) {
1260		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1261			   "error setting graphics mode %s\n", strerror(errno));
1262	}
1263
1264	TRACE_EXIT("EnterVT");
1265	return TRUE;
1266}
1267
1268static void
1269WsfbLeaveVT(VT_FUNC_ARGS_DECL)
1270{
1271	SCRN_INFO_PTR(arg);
1272	WsfbPtr fPtr = WSFBPTR(pScrn);
1273	int mode;
1274
1275	TRACE_ENTER("LeaveVT");
1276
1277	/*
1278	 * stuff to do:
1279	 * - turn off hw cursor
1280	 * - restore colour map if WSFB_CI
1281	 * - ioctl(WSDISPLAYIO_MODE_EMUL) to notify the kernel driver that
1282	 *   we're backing off
1283	 */
1284
1285	if (fPtr->fbi.fbi_pixeltype == WSFB_CI &&
1286	    fPtr->fbi.fbi_subtype.fbi_cmapinfo.cmap_entries > 0) {
1287		/* reset colormap for text mode */
1288		if (ioctl(fPtr->fd, WSDISPLAYIO_PUTCMAP,
1289			  &(fPtr->saved_cmap)) == -1) {
1290			xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1291				   "error restoring colormap %s\n",
1292				   strerror(errno));
1293		}
1294	}
1295
1296	/* Restore the text mode. */
1297	mode = WSDISPLAYIO_MODE_EMUL;
1298	if (ioctl(fPtr->fd, WSDISPLAYIO_SMODE, &mode) == -1) {
1299		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1300			   "error setting text mode %s\n", strerror(errno));
1301	}
1302
1303	pScrn->vtSema = FALSE;
1304	TRACE_EXIT("LeaveVT");
1305}
1306
1307static Bool
1308WsfbSwitchMode(SWITCH_MODE_ARGS_DECL)
1309{
1310	TRACE_ENTER("SwitchMode");
1311	/* Nothing else to do. */
1312	return TRUE;
1313}
1314
1315static int
1316WsfbValidMode(SCRN_ARG_TYPE arg, DisplayModePtr mode, Bool verbose, int flags)
1317{
1318	TRACE_ENTER("ValidMode");
1319	return MODE_OK;
1320}
1321
1322static void
1323WsfbLoadPalette(ScrnInfoPtr pScrn, int numColors, int *indices,
1324	       LOCO *colors, VisualPtr pVisual)
1325{
1326	WsfbPtr fPtr = WSFBPTR(pScrn);
1327	struct wsdisplay_cmap cmap;
1328	unsigned char red[256],green[256],blue[256];
1329	int i, indexMin=256, indexMax=0;
1330
1331	TRACE_ENTER("LoadPalette");
1332
1333	/* nothing to do if there is no color palette support */
1334	if (fPtr->fbi.fbi_subtype.fbi_cmapinfo.cmap_entries == 0)
1335		return;
1336
1337	cmap.count   = 1;
1338	cmap.red   = red;
1339	cmap.green = green;
1340	cmap.blue  = blue;
1341
1342	if (numColors == 1) {
1343		/* Optimisation */
1344		cmap.index = indices[0];
1345		red[0]   = colors[indices[0]].red;
1346		green[0] = colors[indices[0]].green;
1347		blue[0]  = colors[indices[0]].blue;
1348		if (ioctl(fPtr->fd,WSDISPLAYIO_PUTCMAP, &cmap) == -1)
1349			ErrorF("ioctl FBIOPUTCMAP: %s\n", strerror(errno));
1350	} else {
1351		/*
1352		 * Change all colors in 2 ioctls
1353		 * and limit the data to be transfered.
1354		 */
1355		for (i = 0; i < numColors; i++) {
1356			if (indices[i] < indexMin)
1357				indexMin = indices[i];
1358			if (indices[i] > indexMax)
1359				indexMax = indices[i];
1360		}
1361		cmap.index = indexMin;
1362		cmap.count = indexMax - indexMin + 1;
1363		cmap.red = &red[indexMin];
1364		cmap.green = &green[indexMin];
1365		cmap.blue = &blue[indexMin];
1366		/* Get current map. */
1367		if (ioctl(fPtr->fd, WSDISPLAYIO_GETCMAP, &cmap) == -1)
1368			ErrorF("ioctl FBIOGETCMAP: %s\n", strerror(errno));
1369		/* Change the colors that require updating. */
1370		for (i = 0; i < numColors; i++) {
1371			red[indices[i]]   = colors[indices[i]].red;
1372			green[indices[i]] = colors[indices[i]].green;
1373			blue[indices[i]]  = colors[indices[i]].blue;
1374		}
1375		/* Write the colormap back. */
1376		if (ioctl(fPtr->fd,WSDISPLAYIO_PUTCMAP, &cmap) == -1)
1377			ErrorF("ioctl FBIOPUTCMAP: %s\n", strerror(errno));
1378	}
1379	TRACE_EXIT("LoadPalette");
1380}
1381
1382static Bool
1383WsfbSaveScreen(ScreenPtr pScreen, int mode)
1384{
1385	ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
1386	WsfbPtr fPtr = WSFBPTR(pScrn);
1387	int state;
1388
1389	TRACE_ENTER("SaveScreen");
1390
1391	if (!pScrn->vtSema)
1392		return TRUE;
1393
1394	if (mode != SCREEN_SAVER_FORCER) {
1395		state = xf86IsUnblank(mode)?WSDISPLAYIO_VIDEO_ON:
1396		                            WSDISPLAYIO_VIDEO_OFF;
1397		ioctl(fPtr->fd,
1398		      WSDISPLAYIO_SVIDEO, &state);
1399	}
1400	TRACE_EXIT("SaveScreen");
1401	return TRUE;
1402}
1403
1404
1405static void
1406WsfbSave(ScrnInfoPtr pScrn)
1407{
1408	WsfbPtr fPtr = WSFBPTR(pScrn);
1409
1410	TRACE_ENTER("WsfbSave");
1411
1412	/* nothing to save if we don't run in colour-indexed mode */
1413	if (fPtr->fbi.fbi_pixeltype != WSFB_CI)
1414		return;
1415
1416	/* nothing to do if no color palette support */
1417	if (fPtr->fbi.fbi_subtype.fbi_cmapinfo.cmap_entries == 0)
1418		return;
1419
1420	fPtr->saved_cmap.index = 0;
1421	fPtr->saved_cmap.count = fPtr->fbi.fbi_subtype.fbi_cmapinfo.cmap_entries;
1422	if (ioctl(fPtr->fd, WSDISPLAYIO_GETCMAP,
1423		  &(fPtr->saved_cmap)) == -1) {
1424		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1425			   "error saving colormap %s\n", strerror(errno));
1426	}
1427	TRACE_EXIT("WsfbSave");
1428
1429}
1430
1431static void
1432WsfbRestore(ScrnInfoPtr pScrn)
1433{
1434	WsfbPtr fPtr = WSFBPTR(pScrn);
1435	int mode;
1436
1437	TRACE_ENTER("WsfbRestore");
1438
1439	if (fPtr->fbi.fbi_pixeltype == WSFB_CI &&
1440	    fPtr->fbi.fbi_subtype.fbi_cmapinfo.cmap_entries > 0) {
1441		/* reset colormap for text mode */
1442		if (ioctl(fPtr->fd, WSDISPLAYIO_PUTCMAP,
1443			  &(fPtr->saved_cmap)) == -1) {
1444			xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1445				   "error restoring colormap %s\n",
1446				   strerror(errno));
1447		}
1448	}
1449
1450	/* Clear the screen. */
1451	memset(fPtr->fbmem, 0, fPtr->fbmem_len);
1452
1453	/* Restore the text mode. */
1454	mode = WSDISPLAYIO_MODE_EMUL;
1455	if (ioctl(fPtr->fd, WSDISPLAYIO_SMODE, &mode) == -1) {
1456		xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1457			   "error setting text mode %s\n", strerror(errno));
1458	}
1459	TRACE_EXIT("WsfbRestore");
1460}
1461
1462#ifdef XFreeXDGA
1463/***********************************************************************
1464 * DGA stuff
1465 ***********************************************************************/
1466
1467static Bool
1468WsfbDGAOpenFramebuffer(ScrnInfoPtr pScrn, char **DeviceName,
1469		       unsigned char **ApertureBase, int *ApertureSize,
1470		       int *ApertureOffset, int *flags)
1471{
1472	*DeviceName = NULL;		/* No special device */
1473	*ApertureBase = (unsigned char *)(pScrn->memPhysBase);
1474	*ApertureSize = pScrn->videoRam;
1475	*ApertureOffset = pScrn->fbOffset;
1476	*flags = 0;
1477
1478	return TRUE;
1479}
1480
1481static Bool
1482WsfbDGASetMode(ScrnInfoPtr pScrn, DGAModePtr pDGAMode)
1483{
1484	DisplayModePtr pMode;
1485	int scrnIdx = pScrn->pScreen->myNum;
1486	int frameX0, frameY0;
1487
1488	if (pDGAMode) {
1489		pMode = pDGAMode->mode;
1490		frameX0 = frameY0 = 0;
1491	} else {
1492		if (!(pMode = pScrn->currentMode))
1493			return TRUE;
1494
1495		frameX0 = pScrn->frameX0;
1496		frameY0 = pScrn->frameY0;
1497	}
1498
1499	if (!(*pScrn->SwitchMode)(SWITCH_MODE_ARGS(pScrn, pMode)))
1500		return FALSE;
1501	(*pScrn->AdjustFrame)(ADJUST_FRAME_ARGS(pScrn, frameX0, frameY0));
1502
1503	return TRUE;
1504}
1505
1506static void
1507WsfbDGASetViewport(ScrnInfoPtr pScrn, int x, int y, int flags)
1508{
1509	(*pScrn->AdjustFrame)(ADJUST_FRAME_ARGS(pScrn, x, y));
1510}
1511
1512static int
1513WsfbDGAGetViewport(ScrnInfoPtr pScrn)
1514{
1515	return (0);
1516}
1517
1518static DGAFunctionRec WsfbDGAFunctions =
1519{
1520	WsfbDGAOpenFramebuffer,
1521	NULL,       /* CloseFramebuffer */
1522	WsfbDGASetMode,
1523	WsfbDGASetViewport,
1524	WsfbDGAGetViewport,
1525	NULL,       /* Sync */
1526	NULL,       /* FillRect */
1527	NULL,       /* BlitRect */
1528	NULL,       /* BlitTransRect */
1529};
1530
1531static void
1532WsfbDGAAddModes(ScrnInfoPtr pScrn)
1533{
1534	WsfbPtr fPtr = WSFBPTR(pScrn);
1535	DisplayModePtr pMode = pScrn->modes;
1536	DGAModePtr pDGAMode;
1537
1538	do {
1539		pDGAMode = realloc(fPtr->pDGAMode,
1540				    (fPtr->nDGAMode + 1) * sizeof(DGAModeRec));
1541		if (!pDGAMode)
1542			break;
1543
1544		fPtr->pDGAMode = pDGAMode;
1545		pDGAMode += fPtr->nDGAMode;
1546		(void)memset(pDGAMode, 0, sizeof(DGAModeRec));
1547
1548		++fPtr->nDGAMode;
1549		pDGAMode->mode = pMode;
1550		pDGAMode->flags = DGA_CONCURRENT_ACCESS | DGA_PIXMAP_AVAILABLE;
1551		pDGAMode->byteOrder = pScrn->imageByteOrder;
1552		pDGAMode->depth = pScrn->depth;
1553		pDGAMode->bitsPerPixel = pScrn->bitsPerPixel;
1554		pDGAMode->red_mask = pScrn->mask.red;
1555		pDGAMode->green_mask = pScrn->mask.green;
1556		pDGAMode->blue_mask = pScrn->mask.blue;
1557		pDGAMode->visualClass = pScrn->bitsPerPixel > 8 ?
1558			TrueColor : PseudoColor;
1559		pDGAMode->xViewportStep = 1;
1560		pDGAMode->yViewportStep = 1;
1561		pDGAMode->viewportWidth = pMode->HDisplay;
1562		pDGAMode->viewportHeight = pMode->VDisplay;
1563
1564		if (fPtr->fbi.fbi_stride)
1565			pDGAMode->bytesPerScanline = fPtr->fbi.fbi_stride;
1566		else {
1567			ioctl(fPtr->fd, WSDISPLAYIO_LINEBYTES,
1568			      &fPtr->fbi.fbi_stride);
1569			pDGAMode->bytesPerScanline = fPtr->fbi.fbi_stride;
1570		}
1571
1572		pDGAMode->imageWidth = pMode->HDisplay;
1573		pDGAMode->imageHeight =  pMode->VDisplay;
1574		pDGAMode->pixmapWidth = pDGAMode->imageWidth;
1575		pDGAMode->pixmapHeight = pDGAMode->imageHeight;
1576		pDGAMode->maxViewportX = pScrn->virtualX -
1577			pDGAMode->viewportWidth;
1578		pDGAMode->maxViewportY = pScrn->virtualY -
1579			pDGAMode->viewportHeight;
1580
1581		pDGAMode->address = fPtr->fbstart;
1582
1583		pMode = pMode->next;
1584	} while (pMode != pScrn->modes);
1585}
1586
1587static Bool
1588WsfbDGAInit(ScrnInfoPtr pScrn, ScreenPtr pScreen)
1589{
1590	WsfbPtr fPtr = WSFBPTR(pScrn);
1591
1592	if (pScrn->depth < 8)
1593		return FALSE;
1594
1595	if (!fPtr->nDGAMode)
1596		WsfbDGAAddModes(pScrn);
1597
1598	return (DGAInit(pScreen, &WsfbDGAFunctions,
1599			fPtr->pDGAMode, fPtr->nDGAMode));
1600}
1601#endif
1602
1603static Bool
1604WsfbDriverFunc(ScrnInfoPtr pScrn, xorgDriverFuncOp op,
1605    pointer ptr)
1606{
1607	xorgHWFlags *flag;
1608
1609	switch (op) {
1610	case GET_REQUIRED_HW_INTERFACES:
1611		flag = (CARD32*)ptr;
1612		(*flag) = 0;
1613		return TRUE;
1614	default:
1615		return FALSE;
1616	}
1617}
1618
1619static inline void
1620memcpy32sw(void *dest, void *src, int len)
1621{
1622	uint32_t *d = dest, *s = src;
1623
1624#if DEBUG
1625	if ((((long)dest & 3) + ((long)src & 3) + (len & 3)) != 0) {
1626		xf86Msg(X_ERROR, "unaligned %s\n", __func__);
1627		return;
1628	}
1629#endif
1630	while (len > 0) {
1631		*d = bswap32(*s);
1632		d++;
1633		s++;
1634		len -= 4;
1635	}
1636}
1637
1638/* adapted from miext/shadow/shpacked.c::shadowUpdatePacked() */
1639void
1640WsfbShadowUpdateSwap32(ScreenPtr pScreen, shadowBufPtr pBuf)
1641{
1642    RegionPtr	damage = DamageRegion (pBuf->pDamage);
1643    PixmapPtr	pShadow = pBuf->pPixmap;
1644    int		nbox = RegionNumRects (damage);
1645    BoxPtr	pbox = RegionRects (damage);
1646    FbBits	*shaBase, *shaLine, *sha;
1647    FbStride	shaStride;
1648    int		scrBase, scrLine, scr;
1649    int		shaBpp;
1650    int		shaXoff, shaYoff; /* XXX assumed to be zero */
1651    int		x, y, w, h, width;
1652    int         i;
1653    FbBits	*winBase = NULL, *win;
1654    CARD32      winSize;
1655
1656    fbGetDrawable (&pShadow->drawable, shaBase, shaStride, shaBpp, shaXoff, shaYoff);
1657    while (nbox--)
1658    {
1659	x = pbox->x1 * shaBpp;
1660	y = pbox->y1;
1661	w = (pbox->x2 - pbox->x1) * shaBpp;
1662	h = pbox->y2 - pbox->y1;
1663
1664	scrLine = (x >> FB_SHIFT);
1665	shaLine = shaBase + y * shaStride + (x >> FB_SHIFT);
1666
1667	x &= FB_MASK;
1668	w = (w + x + FB_MASK) >> FB_SHIFT;
1669
1670	while (h--)
1671	{
1672	    winSize = 0;
1673	    scrBase = 0;
1674	    width = w;
1675	    scr = scrLine;
1676	    sha = shaLine;
1677	    while (width) {
1678		/* how much remains in this window */
1679		i = scrBase + winSize - scr;
1680		if (i <= 0 || scr < scrBase)
1681		{
1682		    winBase = (FbBits *) (*pBuf->window) (pScreen,
1683							  y,
1684							  scr * sizeof (FbBits),
1685							  SHADOW_WINDOW_WRITE,
1686							  &winSize,
1687							  pBuf->closure);
1688		    if(!winBase)
1689			return;
1690		    scrBase = scr;
1691		    winSize /= sizeof (FbBits);
1692		    i = winSize;
1693		}
1694		win = winBase + (scr - scrBase);
1695		if (i > width)
1696		    i = width;
1697		width -= i;
1698		scr += i;
1699		memcpy32sw(win, sha, i * sizeof(FbBits));
1700		sha += i;
1701	    }
1702	    shaLine += shaStride;
1703	    y++;
1704	}
1705	pbox++;
1706    }
1707}
1708
1709void
1710WsfbShadowUpdateSplit(ScreenPtr pScreen, shadowBufPtr pBuf)
1711{
1712    ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
1713    WsfbPtr 	fPtr = WSFBPTR(pScrn);
1714    RegionPtr	damage = DamageRegion (pBuf->pDamage);
1715    PixmapPtr	pShadow = pBuf->pPixmap;
1716    int		nbox = RegionNumRects (damage);
1717    BoxPtr	pbox = RegionRects (damage);
1718    FbBits	*shaBase, *shaLine, *sha;
1719    FbStride	shaStride;
1720    int		scrBase, scrLine, scr;
1721    int		shaBpp;
1722    int		shaXoff, shaYoff; /* XXX assumed to be zero */
1723    int		x, y, w, h, width;
1724    int         i;
1725    FbBits	*winBase = NULL, *win, *win2;
1726    unsigned long split = fPtr->fbi.fbi_fbsize / 2;
1727    CARD32      winSize;
1728
1729    fbGetDrawable (&pShadow->drawable, shaBase, shaStride, shaBpp, shaXoff, shaYoff);
1730    while (nbox--)
1731    {
1732	x = pbox->x1 * shaBpp;
1733	y = pbox->y1;
1734	w = (pbox->x2 - pbox->x1) * shaBpp;
1735	h = pbox->y2 - pbox->y1;
1736
1737	scrLine = (x >> FB_SHIFT);
1738	shaLine = shaBase + y * shaStride + (x >> FB_SHIFT);
1739
1740	x &= FB_MASK;
1741	w = (w + x + FB_MASK) >> FB_SHIFT;
1742
1743	while (h--)
1744	{
1745	    winSize = 0;
1746	    scrBase = 0;
1747	    width = w;
1748	    scr = scrLine;
1749	    sha = shaLine;
1750	    while (width) {
1751		/* how much remains in this window */
1752		i = scrBase + winSize - scr;
1753		if (i <= 0 || scr < scrBase)
1754		{
1755		    winBase = (FbBits *) (*pBuf->window) (pScreen,
1756							  y,
1757							  scr * sizeof (FbBits),
1758							  SHADOW_WINDOW_WRITE,
1759							  &winSize,
1760							  pBuf->closure);
1761		    if(!winBase)
1762			return;
1763		    scrBase = scr;
1764		    winSize /= sizeof (FbBits);
1765		    i = winSize;
1766		}
1767		win = winBase + (scr - scrBase);
1768		win2 = (FbBits *)(split + (unsigned long)win);
1769		if (i > width)
1770		    i = width;
1771		width -= i;
1772		scr += i;
1773		memcpy(win, sha, i * sizeof(FbBits));
1774		memcpy(win2, sha, i * sizeof(FbBits));
1775		sha += i;
1776	    }
1777	    shaLine += shaStride;
1778	    y++;
1779	}
1780	pbox++;
1781    }
1782}
1783