summaryrefslogtreecommitdiff
path: root/hw/xfree86/os-support/bsd/i386_video.c
blob: 42b90548366b02ee5459c083152d7e7bdc64f2ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
/*
 * Copyright 1992 by Rich Murphey <Rich@Rice.edu>
 * Copyright 1993 by David Wexelblat <dwex@goblin.org>
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the names of Rich Murphey and David Wexelblat 
 * not be used in advertising or publicity pertaining to distribution of 
 * the software without specific, written prior permission.  Rich Murphey and
 * David Wexelblat make no representations about the suitability of this 
 * software for any purpose.  It is provided "as is" without express or 
 * implied warranty.
 *
 * RICH MURPHEY AND DAVID WEXELBLAT DISCLAIM ALL WARRANTIES WITH REGARD TO 
 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND 
 * FITNESS, IN NO EVENT SHALL RICH MURPHEY OR DAVID WEXELBLAT BE LIABLE FOR 
 * ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER 
 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF 
 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN 
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#ifdef HAVE_XORG_CONFIG_H
#include <xorg-config.h>
#endif

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

#include <errno.h>
#include <sys/mman.h>

#ifdef HAS_MTRR_SUPPORT
#ifndef __NetBSD__
#include <sys/types.h>
#include <sys/memrange.h>
#else
#include "memrange.h"
#endif
#define X_MTRR_ID "XFree86"
#endif

#if defined(HAS_MTRR_BUILTIN) && defined(__NetBSD__)
#include <machine/mtrr.h>
#include <machine/sysarch.h>
#include <sys/queue.h>
#ifdef __x86_64__
#define i386_set_mtrr x86_64_set_mtrr
#define i386_get_mtrr x86_64_get_mtrr
#define i386_iopl x86_64_iopl
#endif
#endif

#if defined(__OpenBSD__) && defined(__amd64__)
#include <machine/mtrr.h>
#include <machine/sysarch.h>
#endif

#include "xf86_OSlib.h"
#include "xf86OSpriv.h"

#if defined(__NetBSD__) && !defined(MAP_FILE)
#define MAP_FLAGS MAP_SHARED
#else
#define MAP_FLAGS (MAP_FILE | MAP_SHARED)
#endif

#ifndef MAP_FAILED
#define MAP_FAILED ((caddr_t)-1)
#endif

#ifdef __OpenBSD__
#define SYSCTL_MSG "\tCheck that you have set 'machdep.allowaperture=1'\n"\
		   "\tin /etc/sysctl.conf and reboot your machine\n" \
		   "\trefer to xf86(4) for details"
#define SYSCTL_MSG2 \
		"Check that you have set 'machdep.allowaperture=2'\n" \
		"\tin /etc/sysctl.conf and reboot your machine\n" \
		"\trefer to xf86(4) for details"
#endif

/***************************************************************************/
/* Video Memory Mapping section                                            */
/***************************************************************************/

static Bool useDevMem = FALSE;
static int  devMemFd = -1;

#ifdef HAS_APERTURE_DRV
#define DEV_APERTURE "/dev/xf86"
#endif
#define DEV_MEM "/dev/mem"

static pointer mapVidMem(int, unsigned long, unsigned long, int);
static void unmapVidMem(int, pointer, unsigned long);

#ifdef HAS_MTRR_SUPPORT
static pointer setWC(int, unsigned long, unsigned long, Bool, MessageType);
static void undoWC(int, pointer);
static Bool cleanMTRR(void);
#endif
#if defined(HAS_MTRR_BUILTIN) && defined(__NetBSD__)
static pointer NetBSDsetWC(int, unsigned long, unsigned long, Bool,
			   MessageType);
static void NetBSDundoWC(int, pointer);
#endif
#if defined(__amd64__) && defined(__OpenBSD__)
static pointer amd64setWC(int, unsigned long, unsigned long, Bool, 
    MessageType);
static void amd64undoWC(int, pointer);
#endif

/*
 * Check if /dev/mem can be mmap'd.  If it can't print a warning when
 * "warn" is TRUE.
 */
static void
checkDevMem(Bool warn)
{
	static Bool devMemChecked = FALSE;
	int fd;
	pointer base;

	if (devMemChecked)
	    return;
	devMemChecked = TRUE;

	if ((fd = open(DEV_MEM, O_RDWR)) >= 0)
	{
	    /* Try to map a page at the VGA address */
	    base = mmap((caddr_t)0, 4096, PROT_READ | PROT_WRITE,
				 MAP_FLAGS, fd, (off_t)0xA0000);
	
	    if (base != MAP_FAILED)
	    {
		munmap((caddr_t)base, 4096);
		devMemFd = fd;
		useDevMem = TRUE;
		return;
	    } else {
		/* This should not happen */
		if (warn)
		{
		    xf86Msg(X_WARNING, "checkDevMem: failed to mmap %s (%s)\n",
			    DEV_MEM, strerror(errno));
		}
		useDevMem = FALSE;
		return;
	    }
	}
#ifndef HAS_APERTURE_DRV
	if (warn)
	{ 
	    xf86Msg(X_WARNING, "checkDevMem: failed to open %s (%s)\n",
		    DEV_MEM, strerror(errno));
	} 
	useDevMem = FALSE;
	return;
#else
	/* Failed to open /dev/mem, try the aperture driver */
	if ((fd = open(DEV_APERTURE, O_RDWR)) >= 0)
	{
	    /* Try to map a page at the VGA address */
	    base = mmap((caddr_t)0, 4096, PROT_READ | PROT_WRITE,
			     MAP_FLAGS, fd, (off_t)0xA0000);
	
	    if (base != MAP_FAILED)
	    {
		munmap((caddr_t)base, 4096);
		devMemFd = fd;
		useDevMem = TRUE;
		xf86Msg(X_INFO, "checkDevMem: using aperture driver %s\n",
		        DEV_APERTURE);
		return;
	    } else {

		if (warn)
		{
		    xf86Msg(X_WARNING, "checkDevMem: failed to mmap %s (%s)\n",
			    DEV_APERTURE, strerror(errno));
		}
	    }
	} else {
	    if (warn)
	    {
#ifndef __OpenBSD__
		xf86Msg(X_WARNING, "checkDevMem: failed to open %s and %s\n"
			"\t(%s)\n", DEV_MEM, DEV_APERTURE, strerror(errno));
#else /* __OpenBSD__ */
		xf86Msg(X_WARNING, "checkDevMem: failed to open %s and %s\n"
			"\t(%s)\n%s", DEV_MEM, DEV_APERTURE, strerror(errno),
			SYSCTL_MSG);
#endif /* __OpenBSD__ */
	    }
	}
	
	useDevMem = FALSE;
	return;

#endif
}

void
xf86OSInitVidMem(VidMemInfoPtr pVidMem)
{
	checkDevMem(TRUE);
	pVidMem->linearSupported = useDevMem;
	pVidMem->mapMem = mapVidMem;
	pVidMem->unmapMem = unmapVidMem;

#ifdef HAS_MTRR_SUPPORT
	if (useDevMem) {
		if (cleanMTRR()) {
			pVidMem->setWC = setWC;
			pVidMem->undoWC = undoWC;
		}
	}
#endif
#if defined(HAS_MTRR_BUILTIN) && defined(__NetBSD__)
	pVidMem->setWC = NetBSDsetWC;
	pVidMem->undoWC = NetBSDundoWC;
#endif
#if defined(__amd64__) && defined(__OpenBSD__)
	pVidMem->setWC = amd64setWC;
	pVidMem->undoWC = amd64undoWC;
#endif
	pVidMem->initialised = TRUE;
}

static pointer
mapVidMem(int ScreenNum, unsigned long Base, unsigned long Size, int flags)
{
	pointer base;

	checkDevMem(FALSE);

	if (useDevMem)
	{
	    if (devMemFd < 0) 
	    {
		FatalError("xf86MapVidMem: failed to open %s (%s)",
			   DEV_MEM, strerror(errno));
	    }
	    base = mmap((caddr_t)0, Size,
			(flags & VIDMEM_READONLY) ?
			 PROT_READ : (PROT_READ | PROT_WRITE),
			MAP_FLAGS, devMemFd, (off_t)Base);
	    if (base == MAP_FAILED)
	    {
		FatalError("%s: could not mmap %s [s=%lx,a=%lx] (%s)",
			   "xf86MapVidMem", DEV_MEM, Size, Base, 
			   strerror(errno));
	    }
	    return(base);
	}
		
	/* else, mmap /dev/vga */
	if ((unsigned long)Base < 0xA0000 || (unsigned long)Base >= 0xC0000)
	{
		FatalError("%s: Address 0x%lx outside allowable range",
			   "xf86MapVidMem", Base);
	}
	base = mmap(0, Size,
		    (flags & VIDMEM_READONLY) ?
		     PROT_READ : (PROT_READ | PROT_WRITE),
		    MAP_FLAGS, xf86Info.screenFd,
		    (unsigned long)Base - 0xA0000
	    );
	if (base == MAP_FAILED)
	{
	    FatalError("xf86MapVidMem: Could not mmap /dev/vga (%s)",
		       strerror(errno));
	}
	return(base);
}

static void
unmapVidMem(int ScreenNum, pointer Base, unsigned long Size)
{
	munmap((caddr_t)Base, Size);
}

/*
 * Read BIOS via mmap()ing DEV_MEM
 */

_X_EXPORT int
xf86ReadBIOS(unsigned long Base, unsigned long Offset, unsigned char *Buf,
	     int Len)
{
	unsigned char *ptr;
	int psize;
	int mlen;

	checkDevMem(TRUE);
	if (devMemFd == -1) {
	    return(-1);
	}

	psize = getpagesize();
	Offset += Base & (psize - 1);
	Base &= ~(psize - 1);
	mlen = (Offset + Len + psize - 1) & ~(psize - 1);
	ptr = (unsigned char *)mmap((caddr_t)0, mlen, PROT_READ,
					MAP_SHARED, devMemFd, (off_t)Base);
	if ((long)ptr == -1)
	{
		xf86Msg(X_WARNING, 
			"xf86ReadBIOS: %s mmap[s=%x,a=%lx,o=%lx] failed (%s)\n",
			DEV_MEM, Len, Base, Offset, strerror(errno));
#ifdef __OpenBSD__
		if (Base < 0xa0000) {
		    xf86Msg(X_WARNING, SYSCTL_MSG2);
		} 
#endif
		return(-1);
	}
#ifdef DEBUG
	ErrorF("xf86ReadBIOS: BIOS at 0x%08x has signature 0x%04x\n",
		Base, ptr[0] | (ptr[1] << 8));
#endif
	(void)memcpy(Buf, (void *)(ptr + Offset), Len);
	(void)munmap((caddr_t)ptr, mlen);
#ifdef DEBUG
	xf86MsgVerb(X_INFO, 3, "xf86ReadBIOS(%x, %x, Buf, %x)"
		"-> %02x %02x %02x %02x...\n",
		Base, Offset, Len, Buf[0], Buf[1], Buf[2], Buf[3]);
#endif
	return(Len);
}

#ifdef USE_I386_IOPL
/***************************************************************************/
/* I/O Permissions section                                                 */
/***************************************************************************/

static Bool ExtendedEnabled = FALSE;

_X_EXPORT Bool
xf86EnableIO()
{
	if (ExtendedEnabled)
		return TRUE;

	if (i386_iopl(TRUE) < 0)
	{
#ifndef __OpenBSD__
		xf86Msg(X_WARNING,"%s: Failed to set IOPL for extended I/O",
			   "xf86EnableIO");
#else
		xf86Msg(X_WARNING,"%s: Failed to set IOPL for extended I/O\n%s",
			   "xf86EnableIO", SYSCTL_MSG);
#endif
		return FALSE;
	}
	ExtendedEnabled = TRUE;

	return TRUE;
}
	
_X_EXPORT void
xf86DisableIO()
{
	if (!ExtendedEnabled)
		return;

	i386_iopl(FALSE);
	ExtendedEnabled = FALSE;

	return;
}

#endif /* USE_I386_IOPL */

#ifdef USE_AMD64_IOPL
/***************************************************************************/
/* I/O Permissions section                                                 */
/***************************************************************************/

static Bool ExtendedEnabled = FALSE;

Bool
xf86EnableIO()
{
	if (ExtendedEnabled)
		return TRUE;

	if (amd64_iopl(TRUE) < 0)
	{
#ifndef __OpenBSD__
		xf86Msg(X_WARNING,"%s: Failed to set IOPL for extended I/O",
			   "xf86EnableIO");
#else
		xf86Msg(X_WARNING,"%s: Failed to set IOPL for extended I/O\n%s",
			   "xf86EnableIO", SYSCTL_MSG);
#endif
		return FALSE;
	}
	ExtendedEnabled = TRUE;

	return TRUE;
}
	
void
xf86DisableIO()
{
	if (!ExtendedEnabled)
		return;

	if (amd64_iopl(FALSE) == 0) {
		ExtendedEnabled = FALSE;
	}
	/* Otherwise, the X server has revoqued its root uid, 
	   and thus cannot give up IO privileges any more */
	   
	return;
}

#endif /* USE_AMD64_IOPL */

#ifdef USE_DEV_IO
static int IoFd = -1;

Bool
xf86EnableIO()
{
	if (IoFd >= 0)
		return TRUE;

	if ((IoFd = open("/dev/io", O_RDWR)) == -1)
	{
		xf86Msg(X_WARNING,"xf86EnableIO: "
				"Failed to open /dev/io for extended I/O");
		return FALSE;
	}
	return TRUE;
}

void
xf86DisableIO()
{
	if (IoFd < 0)
		return;

	close(IoFd);
	IoFd = -1;
	return;
}

#endif


/***************************************************************************/
/* Interrupt Handling section                                              */
/***************************************************************************/

_X_EXPORT Bool
xf86DisableInterrupts()
{

#ifdef __GNUC__
	__asm__ __volatile__("cli");
#else 
	asm("cli");
#endif /* __GNUC__ */

	return(TRUE);
}

_X_EXPORT void
xf86EnableInterrupts()
{

#ifdef __GNUC__
	__asm__ __volatile__("sti");
#else 
	asm("sti");
#endif /* __GNUC__ */

	return;
}


#ifdef __NetBSD__
/***************************************************************************/
/* Set TV output mode                                                      */
/***************************************************************************/
void
xf86SetTVOut(int mode)
{    
    switch (xf86Info.consType)
    {
#ifdef PCCONS_SUPPORT
	case PCCONS:{

	    if (ioctl (xf86Info.consoleFd, CONSOLE_X_TV_ON, &mode) < 0)
	    {
		xf86Msg(X_WARNING,
		    "xf86SetTVOut: Could not set console to TV output, %s\n",
		    strerror(errno));
	    }
	}
	break;
#endif /* PCCONS_SUPPORT */

	default:
	    FatalError("Xf86SetTVOut: Unsupported console");
	    break; 
    }
    return;
}

void
xf86SetRGBOut()
{    
    switch (xf86Info.consType)
    {
#ifdef PCCONS_SUPPORT
	case PCCONS:{
	    
	    if (ioctl (xf86Info.consoleFd, CONSOLE_X_TV_OFF, 0) < 0)
	    {
		xf86Msg(X_WARNING,
		    "xf86SetTVOut: Could not set console to RGB output, %s\n",
		    strerror(errno));
	    }
	}
	break;
#endif /* PCCONS_SUPPORT */

	default:
	    FatalError("Xf86SetTVOut: Unsupported console");
	    break; 
    }
    return;
}
#endif

#ifdef HAS_MTRR_SUPPORT
/* memory range (MTRR) support for FreeBSD */

/*
 * This code is experimental.  Some parts may be overkill, and other parts
 * may be incomplete.
 */

/*
 * getAllRanges returns the full list of memory ranges with attributes set.
 */

static struct mem_range_desc *
getAllRanges(int *nmr)
{
	struct mem_range_desc *mrd;
	struct mem_range_op mro;

	/*
	 * Find how many ranges there are.  If this fails, then the kernel
	 * probably doesn't have MTRR support.
	 */
	mro.mo_arg[0] = 0;
	if (ioctl(devMemFd, MEMRANGE_GET, &mro))
		return NULL;
	*nmr = mro.mo_arg[0];
	mrd = xnfalloc(*nmr * sizeof(struct mem_range_desc));
	mro.mo_arg[0] = *nmr;
	mro.mo_desc = mrd;
	if (ioctl(devMemFd, MEMRANGE_GET, &mro)) {
		xfree(mrd);
		return NULL;
	}
	return mrd;
}

/*
 * cleanMTRR removes any memory attribute that may be left by a previous
 * X server.  Normally there won't be any, but this takes care of the
 * case where a server crashed without being able finish cleaning up.
 */

static Bool
cleanMTRR()
{
	struct mem_range_desc *mrd;
	struct mem_range_op mro;
	int nmr, i;

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

	if (!(mrd = getAllRanges(&nmr)))
		return FALSE;

	for (i = 0; i < nmr; i++) {
		if (strcmp(mrd[i].mr_owner, X_MTRR_ID) == 0 &&
		    (mrd[i].mr_flags & MDF_ACTIVE)) {
#ifdef DEBUG
			ErrorF("Clean for (0x%lx,0x%lx)\n",
				(unsigned long)mrd[i].mr_base,
				(unsigned long)rd[i].mr_len);
#endif
			if (mrd[i].mr_flags & MDF_FIXACTIVE) {
				mro.mo_arg[0] = MEMRANGE_SET_UPDATE;
				mrd[i].mr_flags = MDF_UNCACHEABLE;
			} else {
				mro.mo_arg[0] = MEMRANGE_SET_REMOVE;
			}
			mro.mo_desc = mrd + i;
			ioctl(devMemFd, MEMRANGE_SET, &mro);
		}
	}
#ifdef DEBUG
	sleep(10);
#endif
	xfree(mrd);
	return TRUE;
}

typedef struct x_RangeRec {
	struct mem_range_desc	mrd;
	Bool			wasWC;
	struct x_RangeRec *	next;
} RangeRec, *RangePtr;

static void
freeRangeList(RangePtr range)
{
	RangePtr rp;

	while (range) {
		rp = range;
		range = rp->next;
		xfree(rp);
	}
}

static RangePtr
dupRangeList(RangePtr list)
{
	RangePtr new = NULL, rp, p;

	rp = list;
	while (rp) {
		p = xnfalloc(sizeof(RangeRec));
		*p = *rp;
		p->next = new;
		new = p;
		rp = rp->next;
	}
	return new;
}

static RangePtr
sortRangeList(RangePtr list)
{
	RangePtr rp1, rp2, copy, sorted = NULL, minp, prev, minprev;
	unsigned long minBase;

	/* Sort by base address */
	rp1 = copy = dupRangeList(list);
	while (rp1) {
		minBase = rp1->mrd.mr_base;
		minp = rp1;
		minprev = NULL;
		prev = rp1;
		rp2 = rp1->next;
		while (rp2) {
			if (rp2->mrd.mr_base < minBase) {
				minBase = rp2->mrd.mr_base;
				minp = rp2;
				minprev = prev;
			}
			prev = rp2;
			rp2 = rp2->next;
		}
		if (minprev) {
			minprev->next = minp->next;
			rp1 = copy;
		} else {
			rp1 = minp->next;
		}
		minp->next = sorted;
		sorted = minp;
	}
	return sorted;
}

/*
 * findRanges returns a list of ranges that overlap the specified range.
 */

static void
findRanges(unsigned long base, unsigned long size, RangePtr *ucp, RangePtr *wcp)
{
	struct mem_range_desc *mrd;
	int nmr, i;
	RangePtr rp, *p;
	
	if (!(mrd = getAllRanges(&nmr)))
		return;

	for (i = 0; i < nmr; i++) {
		if ((mrd[i].mr_flags & MDF_ACTIVE) &&
		    mrd[i].mr_base < base + size &&
		    mrd[i].mr_base + mrd[i].mr_len > base) {
			if (mrd[i].mr_flags & MDF_WRITECOMBINE)
				p = wcp;
			else if (mrd[i].mr_flags & MDF_UNCACHEABLE)
				p = ucp;
			else
				continue;
			rp = xnfalloc(sizeof(RangeRec));
			rp->mrd = mrd[i];
			rp->next = *p;
			*p = rp;
		}
	}
	xfree(mrd);
}

/*
 * This checks if the existing overlapping ranges fully cover the requested
 * range.  Is this overkill?
 */

static Bool
fullCoverage(unsigned long base, unsigned long size, RangePtr overlap)
{
	RangePtr rp1, sorted = NULL;
	unsigned long end;

	sorted = sortRangeList(overlap);
	/* Look for gaps */
	rp1 = sorted;
	end = base + size;
	while (rp1) {
		if (rp1->mrd.mr_base > base) {
			freeRangeList(sorted);
			return FALSE;
		} else {
			base = rp1->mrd.mr_base + rp1->mrd.mr_len;
		}
		if (base >= end) {
			freeRangeList(sorted);
			return TRUE;
		}
		rp1 = rp1->next;
	}
	freeRangeList(sorted);
	return FALSE;
}

static pointer
addWC(int screenNum, unsigned long base, unsigned long size, MessageType from)
{
	RangePtr uc = NULL, wc = NULL, retlist = NULL;
	struct mem_range_desc mrd;
	struct mem_range_op mro;

	findRanges(base, size, &uc, &wc);

	/* See of the full range is already WC */
	if (!uc && fullCoverage(base, size, wc)) {
		xf86DrvMsg(screenNum, from, 
		   "Write-combining range (0x%lx,0x%lx) was already set\n",
		    base, size);
		return NULL;
	}

	/* Otherwise, try to add the new range */
	mrd.mr_base = base;
	mrd.mr_len = size;
	strcpy(mrd.mr_owner, X_MTRR_ID);
	mrd.mr_flags = MDF_WRITECOMBINE;
	mro.mo_desc = &mrd;
	mro.mo_arg[0] = MEMRANGE_SET_UPDATE;
	if (ioctl(devMemFd, MEMRANGE_SET, &mro)) {
		xf86DrvMsg(screenNum, X_WARNING,
			   "Failed to set write-combining range "
			   "(0x%lx,0x%lx)\n", base, size);
		return NULL;
	} else {
		xf86DrvMsg(screenNum, from,
			   "Write-combining range (0x%lx,0x%lx)\n", base, size);
		retlist = xnfalloc(sizeof(RangeRec));
		retlist->mrd = mrd;
		retlist->wasWC = FALSE;
		retlist->next = NULL;
		return retlist;
	}
}

static pointer
delWC(int screenNum, unsigned long base, unsigned long size, MessageType from)
{
	RangePtr uc = NULL, wc = NULL, retlist = NULL;
	struct mem_range_desc mrd;
	struct mem_range_op mro;

	findRanges(base, size, &uc, &wc);

	/*
	 * See of the full range is already not WC, or if there is full
	 * coverage from UC ranges.
	 */
	if (!wc || fullCoverage(base, size, uc)) {
		xf86DrvMsg(screenNum, from, 
		   "Write-combining range (0x%lx,0x%lx) was already clear\n",
		    base, size);
		return NULL;
	}

	/* Otherwise, try to add the new range */
	mrd.mr_base = base;
	mrd.mr_len = size;
	strcpy(mrd.mr_owner, X_MTRR_ID);
	mrd.mr_flags = MDF_UNCACHEABLE;
	mro.mo_desc = &mrd;
	mro.mo_arg[0] = MEMRANGE_SET_UPDATE;
	if (ioctl(devMemFd, MEMRANGE_SET, &mro)) {
		xf86DrvMsg(screenNum, X_WARNING,
			   "Failed to remove write-combining range "
			   "(0x%lx,0x%lx)\n", base, size);
		/* XXX Should then remove all of the overlapping WC ranges */
		return NULL;
	} else {
		xf86DrvMsg(screenNum, from,
			   "Removed Write-combining range (0x%lx,0x%lx)\n",
			   base, size);
		retlist = xnfalloc(sizeof(RangeRec));
		retlist->mrd = mrd;
		retlist->wasWC = TRUE;
		retlist->next = NULL;
		return retlist;
	}
}

static pointer
setWC(int screenNum, unsigned long base, unsigned long size, Bool enable,
	MessageType from)
{
	if (enable)
		return addWC(screenNum, base, size, from);
	else
		return delWC(screenNum, base, size, from);
}

static void
undoWC(int screenNum, pointer list)
{
	RangePtr rp;
	struct mem_range_op mro;
	Bool failed;

	rp = list;
	while (rp) {
#ifdef DEBUG
		ErrorF("Undo for (0x%lx,0x%lx), %d\n",
			(unsigned long)rp->mrd.mr_base,
			(unsigned long)rp->mrd.mr_len, rp->wasWC);
#endif
		failed = FALSE;
		if (rp->wasWC) {
			mro.mo_arg[0] = MEMRANGE_SET_UPDATE;
			rp->mrd.mr_flags = MDF_WRITECOMBINE;
			strcpy(rp->mrd.mr_owner, "unknown");
		} else {
			mro.mo_arg[0] = MEMRANGE_SET_REMOVE;
		}
		mro.mo_desc = &rp->mrd;

		if (ioctl(devMemFd, MEMRANGE_SET, &mro)) {
			if (!rp->wasWC) {
				mro.mo_arg[0] = MEMRANGE_SET_UPDATE;
				rp->mrd.mr_flags = MDF_UNCACHEABLE;
				strcpy(rp->mrd.mr_owner, "unknown");
				if (ioctl(devMemFd, MEMRANGE_SET, &mro))
					failed = TRUE;
			} else
				failed = TRUE;
		}
		if (failed) {
			xf86DrvMsg(screenNum, X_WARNING,
				"Failed to restore MTRR range (0x%lx,0x%lx)\n",
				(unsigned long)rp->mrd.mr_base,
				(unsigned long)rp->mrd.mr_len);
		}
		rp = rp->next;
	}
}

#endif /* HAS_MTRR_SUPPORT */


#if defined(HAS_MTRR_BUILTIN) && defined(__NetBSD__)
static pointer
NetBSDsetWC(int screenNum, unsigned long base, unsigned long size, Bool enable,
	    MessageType from)
{
	struct mtrr *mtrrp;
	int n;

	xf86DrvMsg(screenNum, X_WARNING,
		   "%s MTRR %lx - %lx\n", enable ? "set" : "remove",
		   base, (base + size));

	mtrrp = xnfalloc(sizeof (struct mtrr));
	mtrrp->base = base;
	mtrrp->len = size;
	mtrrp->type = MTRR_TYPE_WC;

	/*
	 * MTRR_PRIVATE will make this MTRR get reset automatically
	 * if this process exits, so we have no need for an explicit
	 * cleanup operation when starting a new server.
	 */

	if (enable)
		mtrrp->flags = MTRR_VALID | MTRR_PRIVATE;
	else
		mtrrp->flags = 0;
	n = 1;

	if (i386_set_mtrr(mtrrp, &n) < 0) {
		xfree(mtrrp);
		return NULL;
	}
	return mtrrp;
}

static void
NetBSDundoWC(int screenNum, pointer list)
{
	struct mtrr *mtrrp = (struct mtrr *)list;
	int n;

	if (mtrrp == NULL)
		return;
	n = 1;
	mtrrp->flags &= ~MTRR_VALID;
	i386_set_mtrr(mtrrp, &n);
	xfree(mtrrp);
}
#endif

#if defined(__OpenBSD__) && defined(__amd64__)
static pointer
amd64setWC(int screenNum, unsigned long base, unsigned long size, Bool enable,
	    MessageType from)
{
	struct mtrr *mtrrp;
	int n;

	xf86DrvMsg(screenNum, X_WARNING,
		   "%s MTRR %lx - %lx\n", enable ? "set" : "remove",
		   base, (base + size));

	mtrrp = xnfalloc(sizeof (struct mtrr));
	mtrrp->base = base;
	mtrrp->len = size;
	mtrrp->type = MTRR_TYPE_WC;

	/*
	 * MTRR_PRIVATE will make this MTRR get reset automatically
	 * if this process exits, so we have no need for an explicit
	 * cleanup operation when starting a new server.
	 */

	if (enable)
		mtrrp->flags = MTRR_VALID | MTRR_PRIVATE;
	else
		mtrrp->flags = 0;
	n = 1;

	if (amd64_set_mtrr(mtrrp, &n) < 0) {
		xfree(mtrrp);
		return NULL;
	}
	return mtrrp;
}

static void
amd64undoWC(int screenNum, pointer list)
{
	struct mtrr *mtrrp = (struct mtrr *)list;
	int n;

	if (mtrrp == NULL)
		return;
	n = 1;
	mtrrp->flags &= ~MTRR_VALID;
	amd64_set_mtrr(mtrrp, &n);
	xfree(mtrrp);
}
#endif /* OpenBSD/amd64 */