summaryrefslogtreecommitdiff
path: root/src/i830_driver.c
blob: fbbc585562ae1d585e291b5b948b1757cf9b7bee (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
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
/**************************************************************************

Copyright 2001 VA Linux Systems Inc., Fremont, California.
Copyright © 2002 by David Dawes

All Rights Reserved.

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
on the rights to use, copy, modify, merge, publish, distribute, sub
license, 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 (including the next
paragraph) shall be included in all copies or substantial portions of the
Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
THE COPYRIGHT HOLDERS AND/OR THEIR SUPPLIERS 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.

**************************************************************************/

/*
 * Authors: Jeff Hartmann <jhartmann@valinux.com>
 *          Abraham van der Merwe <abraham@2d3d.co.za>
 *          David Dawes <dawes@xfree86.org>
 *          Alan Hourihane <alanh@tungstengraphics.com>
 */

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

#ifndef PRINT_MODE_INFO
#define PRINT_MODE_INFO 0
#endif

#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

#include "xf86.h"
#include "xf86_OSproc.h"
#include "xf86Priv.h"
#include "xf86cmap.h"
#include "compiler.h"
#include "mibstore.h"
#include "vgaHW.h"
#include "mipointer.h"
#include "micmap.h"
#include "shadowfb.h"
#include <X11/extensions/randr.h>
#include "fb.h"
#include "miscstruct.h"
#include "dixstruct.h"
#include "xf86xv.h"
#include <X11/extensions/Xv.h>
#include "shadow.h"
#include "i830.h"
#include "i830_display.h"
#include "i830_bios.h"
#include "i830_video.h"
#if HAVE_SYS_MMAN_H && HAVE_MPROTECT
#include <sys/mman.h>
#endif

#ifdef INTEL_XVMC
#define _INTEL_XVMC_SERVER_
#include "i830_hwmc.h"
#endif

#include <sys/ioctl.h>
#include "i915_drm.h"
#include <xf86drmMode.h>

#define BIT(x) (1 << (x))
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define NB_OF(x) (sizeof (x) / sizeof (*x))

/* *INDENT-OFF* */
static SymTabRec I830Chipsets[] = {
   {PCI_CHIP_I830_M,		"i830"},
   {PCI_CHIP_845_G,		"845G"},
   {PCI_CHIP_I855_GM,		"852GM/855GM"},
   {PCI_CHIP_I865_G,		"865G"},
   {PCI_CHIP_I915_G,		"915G"},
   {PCI_CHIP_E7221_G,		"E7221 (i915)"},
   {PCI_CHIP_I915_GM,		"915GM"},
   {PCI_CHIP_I945_G,		"945G"},
   {PCI_CHIP_I945_GM,		"945GM"},
   {PCI_CHIP_I945_GME,		"945GME"},
   {PCI_CHIP_IGD_GM,		"Pineview GM"},
   {PCI_CHIP_IGD_G,		"Pineview G"},
   {PCI_CHIP_I965_G,		"965G"},
   {PCI_CHIP_G35_G,		"G35"},
   {PCI_CHIP_I965_Q,		"965Q"},
   {PCI_CHIP_I946_GZ,		"946GZ"},
   {PCI_CHIP_I965_GM,		"965GM"},
   {PCI_CHIP_I965_GME,		"965GME/GLE"},
   {PCI_CHIP_G33_G,		"G33"},
   {PCI_CHIP_Q35_G,		"Q35"},
   {PCI_CHIP_Q33_G,		"Q33"},
   {PCI_CHIP_GM45_GM,		"GM45"},
   {PCI_CHIP_IGD_E_G,		"4 Series"},
   {PCI_CHIP_G45_G,		"G45/G43"},
   {PCI_CHIP_Q45_G,		"Q45/Q43"},
   {PCI_CHIP_G41_G,		"G41"},
   {PCI_CHIP_B43_G,		"B43"},
   {PCI_CHIP_IGDNG_D_G,		"Clarkdale"},
   {PCI_CHIP_IGDNG_M_G,		"Arrandale"},
   {-1,				NULL}
};

static PciChipsets I830PciChipsets[] = {
   {PCI_CHIP_I830_M,		PCI_CHIP_I830_M,	NULL},
   {PCI_CHIP_845_G,		PCI_CHIP_845_G,		NULL},
   {PCI_CHIP_I855_GM,		PCI_CHIP_I855_GM,	NULL},
   {PCI_CHIP_I865_G,		PCI_CHIP_I865_G,	NULL},
   {PCI_CHIP_I915_G,		PCI_CHIP_I915_G,	NULL},
   {PCI_CHIP_E7221_G,		PCI_CHIP_E7221_G,	NULL},
   {PCI_CHIP_I915_GM,		PCI_CHIP_I915_GM,	NULL},
   {PCI_CHIP_I945_G,		PCI_CHIP_I945_G,	NULL},
   {PCI_CHIP_I945_GM,		PCI_CHIP_I945_GM,	NULL},
   {PCI_CHIP_I945_GME,		PCI_CHIP_I945_GME,	NULL},
   {PCI_CHIP_IGD_GM,		PCI_CHIP_IGD_GM,	NULL},
   {PCI_CHIP_IGD_G,		PCI_CHIP_IGD_G,		NULL},
   {PCI_CHIP_I965_G,		PCI_CHIP_I965_G,	NULL},
   {PCI_CHIP_G35_G,		PCI_CHIP_G35_G,		NULL},
   {PCI_CHIP_I965_Q,		PCI_CHIP_I965_Q,	NULL},
   {PCI_CHIP_I946_GZ,		PCI_CHIP_I946_GZ,	NULL},
   {PCI_CHIP_I965_GM,		PCI_CHIP_I965_GM,	NULL},
   {PCI_CHIP_I965_GME,		PCI_CHIP_I965_GME,	NULL},
   {PCI_CHIP_G33_G,		PCI_CHIP_G33_G,		NULL},
   {PCI_CHIP_Q35_G,		PCI_CHIP_Q35_G,		NULL},
   {PCI_CHIP_Q33_G,		PCI_CHIP_Q33_G,		NULL},
   {PCI_CHIP_GM45_GM,		PCI_CHIP_GM45_GM,	NULL},
   {PCI_CHIP_IGD_E_G,		PCI_CHIP_IGD_E_G,	NULL},
   {PCI_CHIP_G45_G,		PCI_CHIP_G45_G,		NULL},
   {PCI_CHIP_Q45_G,		PCI_CHIP_Q45_G,		NULL},
   {PCI_CHIP_G41_G,		PCI_CHIP_G41_G,		NULL},
   {PCI_CHIP_B43_G,		PCI_CHIP_B43_G,		NULL},
   {PCI_CHIP_IGDNG_D_G,		PCI_CHIP_IGDNG_D_G,		NULL},
   {PCI_CHIP_IGDNG_M_G,		PCI_CHIP_IGDNG_M_G,		NULL},
   {-1,				-1,			NULL}
};

/*
 * Note: "ColorKey" is provided for compatibility with the i810 driver.
 * However, the correct option name is "VideoKey".  "ColorKey" usually
 * refers to the tranparency key for 8+24 overlays, not for video overlays.
 */

typedef enum {
   OPTION_DRI,
   OPTION_VIDEO_KEY,
   OPTION_COLOR_KEY,
   OPTION_FALLBACKDEBUG,
   OPTION_TILING,
   OPTION_SWAPBUFFERS_WAIT,
#ifdef INTEL_XVMC
   OPTION_XVMC,
#endif
   OPTION_PREFER_OVERLAY,
   OPTION_DEBUG_FLUSH_BATCHES,
   OPTION_DEBUG_FLUSH_CACHES,
   OPTION_DEBUG_WAIT,
} I830Opts;

static OptionInfoRec I830Options[] = {
   {OPTION_DRI,		"DRI",		OPTV_BOOLEAN,	{0},	TRUE},
   {OPTION_COLOR_KEY,	"ColorKey",	OPTV_INTEGER,	{0},	FALSE},
   {OPTION_VIDEO_KEY,	"VideoKey",	OPTV_INTEGER,	{0},	FALSE},
   {OPTION_FALLBACKDEBUG, "FallbackDebug", OPTV_BOOLEAN, {0},	FALSE},
   {OPTION_TILING,	"Tiling",	OPTV_BOOLEAN,	{0},	TRUE},
   {OPTION_SWAPBUFFERS_WAIT, "SwapbuffersWait", OPTV_BOOLEAN,	{0},	TRUE},
#ifdef INTEL_XVMC
   {OPTION_XVMC,	"XvMC",		OPTV_BOOLEAN,	{0},	TRUE},
#endif
   {OPTION_PREFER_OVERLAY, "XvPreferOverlay", OPTV_BOOLEAN, {0}, FALSE},
   {OPTION_DEBUG_FLUSH_BATCHES, "DebugFlushBatches", OPTV_BOOLEAN, {0}, FALSE},
   {OPTION_DEBUG_FLUSH_CACHES, "DebugFlushCaches", OPTV_BOOLEAN, {0}, FALSE},
   {OPTION_DEBUG_WAIT, "DebugWait", OPTV_BOOLEAN, {0}, FALSE},
   {-1,			NULL,		OPTV_NONE,	{0},	FALSE}
};
/* *INDENT-ON* */

static void i830AdjustFrame(int scrnIndex, int x, int y, int flags);
static Bool I830CloseScreen(int scrnIndex, ScreenPtr screen);
static Bool I830EnterVT(int scrnIndex, int flags);

/* temporary */
extern void xf86SetCursor(ScreenPtr screen, CursorPtr pCurs, int x, int y);

#ifdef I830DEBUG
void
I830DPRINTF(const char *filename, int line, const char *function,
	    const char *fmt, ...)
{
	va_list ap;

	ErrorF("\n##############################################\n"
	       "*** In function %s, on line %d, in file %s ***\n",
	       function, line, filename);
	va_start(ap, fmt);
	VErrorF(fmt, ap);
	va_end(ap);
	ErrorF("##############################################\n\n");
}
#endif /* #ifdef I830DEBUG */

/* Export I830 options to i830 driver where necessary */
const OptionInfoRec *I830AvailableOptions(int chipid, int busid)
{
	int i;

	for (i = 0; I830PciChipsets[i].PCIid > 0; i++) {
		if (chipid == I830PciChipsets[i].PCIid)
			return I830Options;
	}
	return NULL;
}

static Bool I830GetRec(ScrnInfoPtr scrn)
{
	intel_screen_private *intel;

	if (scrn->driverPrivate)
		return TRUE;
	intel = scrn->driverPrivate = xnfcalloc(sizeof(intel_screen_private), 1);
	return TRUE;
}

static void I830FreeRec(ScrnInfoPtr scrn)
{
	intel_screen_private *intel;

	if (!scrn)
		return;
	if (!scrn->driverPrivate)
		return;

	intel = intel_get_screen_private(scrn);

	xfree(scrn->driverPrivate);
	scrn->driverPrivate = NULL;
}

static void
I830LoadPalette(ScrnInfoPtr scrn, int numColors, int *indices,
		LOCO * colors, VisualPtr pVisual)
{
	xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(scrn);
	int i, j, index;
	int p;
	uint16_t lut_r[256], lut_g[256], lut_b[256];

	DPRINTF(PFX, "I830LoadPalette: numColors: %d\n", numColors);

	for (p = 0; p < xf86_config->num_crtc; p++) {
		xf86CrtcPtr crtc = xf86_config->crtc[p];
		I830CrtcPrivatePtr intel_crtc = crtc->driver_private;

		/* Initialize to the old lookup table values. */
		for (i = 0; i < 256; i++) {
			lut_r[i] = intel_crtc->lut_r[i] << 8;
			lut_g[i] = intel_crtc->lut_g[i] << 8;
			lut_b[i] = intel_crtc->lut_b[i] << 8;
		}

		switch (scrn->depth) {
		case 15:
			for (i = 0; i < numColors; i++) {
				index = indices[i];
				for (j = 0; j < 8; j++) {
					lut_r[index * 8 + j] =
					    colors[index].red << 8;
					lut_g[index * 8 + j] =
					    colors[index].green << 8;
					lut_b[index * 8 + j] =
					    colors[index].blue << 8;
				}
			}
			break;
		case 16:
			for (i = 0; i < numColors; i++) {
				index = indices[i];

				if (index <= 31) {
					for (j = 0; j < 8; j++) {
						lut_r[index * 8 + j] =
						    colors[index].red << 8;
						lut_b[index * 8 + j] =
						    colors[index].blue << 8;
					}
				}

				for (j = 0; j < 4; j++) {
					lut_g[index * 4 + j] =
					    colors[index].green << 8;
				}
			}
			break;
		default:
			for (i = 0; i < numColors; i++) {
				index = indices[i];
				lut_r[index] = colors[index].red << 8;
				lut_g[index] = colors[index].green << 8;
				lut_b[index] = colors[index].blue << 8;
			}
			break;
		}

		/* Make the change through RandR */
#ifdef RANDR_12_INTERFACE
		RRCrtcGammaSet(crtc->randr_crtc, lut_r, lut_g, lut_b);
#else
		crtc->funcs->gamma_set(crtc, lut_r, lut_g, lut_b, 256);
#endif
	}
}

/**
 * Adjust the screen pixmap for the current location of the front buffer.
 * This is done at EnterVT when buffers are bound as long as the resources
 * have already been created, but the first EnterVT happens before
 * CreateScreenResources.
 */
static Bool i830CreateScreenResources(ScreenPtr screen)
{
	ScrnInfoPtr scrn = xf86Screens[screen->myNum];
	intel_screen_private *intel = intel_get_screen_private(scrn);

	screen->CreateScreenResources = intel->CreateScreenResources;
	if (!(*screen->CreateScreenResources) (screen))
		return FALSE;

	i830_uxa_create_screen_resources(screen);

	return TRUE;
}

static void PreInitCleanup(ScrnInfoPtr scrn)
{
	I830FreeRec(scrn);
}

/*
 * Adjust *width to allow for tiling if possible
 */
Bool i830_tiled_width(intel_screen_private *intel, int *width, int cpp)
{
	Bool tiled = FALSE;

	/*
	 * Adjust the display width to allow for front buffer tiling if possible
	 */
	if (intel->tiling) {
		if (IS_I965G(intel)) {
			int tile_pixels = 512 / cpp;
			*width = (*width + tile_pixels - 1) &
			    ~(tile_pixels - 1);
			tiled = TRUE;
		} else {
			/* Good pitches to allow tiling.  Don't care about pitches < 1024
			 * pixels.
			 */
			static const int pitches[] = {
				1024,
				2048,
				4096,
				8192,
				0
			};
			int i;

			for (i = 0; pitches[i] != 0; i++) {
				if (pitches[i] >= *width) {
					*width = pitches[i];
					tiled = TRUE;
					break;
				}
			}
		}
	}
	return tiled;
}

/*
 * Pad to accelerator requirement
 */
int i830_pad_drawable_width(int width, int cpp)
{
	return (width + 63) & ~63;
}

static Bool i830_xf86crtc_resize(ScrnInfoPtr scrn, int width, int height)
{
#ifdef DRI2
	intel_screen_private *intel = intel_get_screen_private(scrn);
	int old_width = scrn->displayWidth;
#endif
	int old_x = scrn->virtualX;
	int old_y = scrn->virtualY;

	if (old_x == width && old_y == height)
		return TRUE;

	scrn->virtualX = width;
	scrn->virtualY = height;
#ifdef DRI2
	if (intel->front_buffer) {
		i830_memory *new_front, *old_front;
		Bool tiled;
		ScreenPtr screen = screenInfo.screens[scrn->scrnIndex];

		scrn->displayWidth = i830_pad_drawable_width(width, intel->cpp);
		tiled = i830_tiled_width(intel, &scrn->displayWidth, intel->cpp);
		xf86DrvMsg(scrn->scrnIndex, X_INFO,
			   "Allocate new frame buffer %dx%d stride %d\n", width,
			   height, scrn->displayWidth);
		intel_sync(scrn);
		i830WaitForVblank(scrn);
		new_front = i830_allocate_framebuffer(scrn);
		if (!new_front) {
			scrn->virtualX = old_x;
			scrn->virtualY = old_y;
			scrn->displayWidth = old_width;
			return FALSE;
		}
		old_front = intel->front_buffer;
		intel->front_buffer = new_front;
		i830_set_pixmap_bo(screen->GetScreenPixmap(screen),
				   new_front->bo);
		scrn->fbOffset = intel->front_buffer->offset;

		screen->ModifyPixmapHeader(screen->GetScreenPixmap(screen),
					   width, height, -1, -1,
					   scrn->displayWidth * intel->cpp,
					   NULL);

		/* ick. xf86EnableDisableFBAccess smashes the screen pixmap devPrivate,
		 * so update the value it uses
		 */
		scrn->pixmapPrivate.ptr = NULL;
		xf86DrvMsg(scrn->scrnIndex, X_INFO,
			   "New front buffer at 0x%lx\n",
			   intel->front_buffer->offset);
		i830_set_new_crtc_bo(scrn);
		intel_sync(scrn);
		i830WaitForVblank(scrn);
		i830_free_memory(scrn, old_front);
	}
#endif
	return TRUE;
}

static const xf86CrtcConfigFuncsRec i830_xf86crtc_config_funcs = {
	i830_xf86crtc_resize
};

/*
 * DRM mode setting Linux only at this point... later on we could
 * add a wrapper here.
 */
static Bool i830_kernel_mode_enabled(ScrnInfoPtr scrn)
{
	struct pci_device *PciInfo;
	EntityInfoPtr pEnt;
	char *busIdString;
	int ret;

	pEnt = xf86GetEntityInfo(scrn->entityList[0]);
	PciInfo = xf86GetPciInfoForEntity(pEnt->index);

	if (!xf86LoaderCheckSymbol("DRICreatePCIBusID"))
		return FALSE;

	busIdString = DRICreatePCIBusID(PciInfo);

	ret = drmCheckModesettingSupported(busIdString);
	if (ret) {
		if (xf86LoadKernelModule("i915"))
			ret = drmCheckModesettingSupported(busIdString);
	}
	/* Be nice to the user and load fbcon too */
	if (!ret)
		(void)xf86LoadKernelModule("fbcon");
	xfree(busIdString);
	if (ret)
		return FALSE;

	return TRUE;
}

static void i830_detect_chipset(ScrnInfoPtr scrn)
{
	intel_screen_private *intel = intel_get_screen_private(scrn);
	MessageType from = X_PROBED;
	const char *chipname;
	uint32_t capid;

	switch (DEVICE_ID(intel->PciInfo)) {
	case PCI_CHIP_I830_M:
		chipname = "830M";
		break;
	case PCI_CHIP_845_G:
		chipname = "845G";
		break;
	case PCI_CHIP_I855_GM:
		/* Check capid register to find the chipset variant */
		pci_device_cfg_read_u32(intel->PciInfo, &capid, I85X_CAPID);
		intel->variant =
		    (capid >> I85X_VARIANT_SHIFT) & I85X_VARIANT_MASK;
		switch (intel->variant) {
		case I855_GM:
			chipname = "855GM";
			break;
		case I855_GME:
			chipname = "855GME";
			break;
		case I852_GM:
			chipname = "852GM";
			break;
		case I852_GME:
			chipname = "852GME";
			break;
		default:
			xf86DrvMsg(scrn->scrnIndex, X_INFO,
				   "Unknown 852GM/855GM variant: 0x%x)\n",
				   intel->variant);
			chipname = "852GM/855GM (unknown variant)";
			break;
		}
		break;
	case PCI_CHIP_I865_G:
		chipname = "865G";
		break;
	case PCI_CHIP_I915_G:
		chipname = "915G";
		break;
	case PCI_CHIP_E7221_G:
		chipname = "E7221 (i915)";
		break;
	case PCI_CHIP_I915_GM:
		chipname = "915GM";
		break;
	case PCI_CHIP_I945_G:
		chipname = "945G";
		break;
	case PCI_CHIP_I945_GM:
		chipname = "945GM";
		break;
	case PCI_CHIP_I945_GME:
		chipname = "945GME";
		break;
	case PCI_CHIP_IGD_GM:
		chipname = "Pineview GM";
		break;
	case PCI_CHIP_IGD_G:
		chipname = "Pineview G";
		break;
	case PCI_CHIP_I965_G:
		chipname = "965G";
		break;
	case PCI_CHIP_G35_G:
		chipname = "G35";
		break;
	case PCI_CHIP_I965_Q:
		chipname = "965Q";
		break;
	case PCI_CHIP_I946_GZ:
		chipname = "946GZ";
		break;
	case PCI_CHIP_I965_GM:
		chipname = "965GM";
		break;
	case PCI_CHIP_I965_GME:
		chipname = "965GME/GLE";
		break;
	case PCI_CHIP_G33_G:
		chipname = "G33";
		break;
	case PCI_CHIP_Q35_G:
		chipname = "Q35";
		break;
	case PCI_CHIP_Q33_G:
		chipname = "Q33";
		break;
	case PCI_CHIP_GM45_GM:
		chipname = "GM45";
		break;
	case PCI_CHIP_IGD_E_G:
		chipname = "4 Series";
		break;
	case PCI_CHIP_G45_G:
		chipname = "G45/G43";
		break;
	case PCI_CHIP_Q45_G:
		chipname = "Q45/Q43";
		break;
	case PCI_CHIP_G41_G:
		chipname = "G41";
		break;
	case PCI_CHIP_B43_G:
		chipname = "B43";
		break;
	case PCI_CHIP_IGDNG_D_G:
		chipname = "Clarkdale";
		break;
	case PCI_CHIP_IGDNG_M_G:
		chipname = "Arrandale";
		break;
	default:
		chipname = "unknown chipset";
		break;
	}
	xf86DrvMsg(scrn->scrnIndex, X_INFO,
		   "Integrated Graphics Chipset: Intel(R) %s\n", chipname);

	/* Set the Chipset and ChipRev, allowing config file entries to override. */
	if (intel->pEnt->device->chipset && *intel->pEnt->device->chipset) {
		scrn->chipset = intel->pEnt->device->chipset;
		from = X_CONFIG;
	} else if (intel->pEnt->device->chipID >= 0) {
		scrn->chipset = (char *)xf86TokenToString(I830Chipsets,
							   intel->pEnt->device->
							   chipID);
		from = X_CONFIG;
		xf86DrvMsg(scrn->scrnIndex, X_CONFIG,
			   "ChipID override: 0x%04X\n",
			   intel->pEnt->device->chipID);
		DEVICE_ID(intel->PciInfo) = intel->pEnt->device->chipID;
	} else {
		from = X_PROBED;
		scrn->chipset = (char *)xf86TokenToString(I830Chipsets,
							   DEVICE_ID(intel->
								     PciInfo));
	}

	if (intel->pEnt->device->chipRev >= 0) {
		xf86DrvMsg(scrn->scrnIndex, X_CONFIG, "ChipRev override: %d\n",
			   intel->pEnt->device->chipRev);
	}

	xf86DrvMsg(scrn->scrnIndex, from, "Chipset: \"%s\"\n",
		   (scrn->chipset != NULL) ? scrn->chipset : "Unknown i8xx");
}

static Bool I830GetEarlyOptions(ScrnInfoPtr scrn)
{
	intel_screen_private *intel = intel_get_screen_private(scrn);

	/* Process the options */
	xf86CollectOptions(scrn, NULL);
	if (!(intel->Options = xalloc(sizeof(I830Options))))
		return FALSE;
	memcpy(intel->Options, I830Options, sizeof(I830Options));
	xf86ProcessOptions(scrn->scrnIndex, scrn->options, intel->Options);

	intel->fallback_debug = xf86ReturnOptValBool(intel->Options,
						     OPTION_FALLBACKDEBUG,
						     FALSE);

	intel->debug_flush = 0;

	if (xf86ReturnOptValBool(intel->Options,
				 OPTION_DEBUG_FLUSH_BATCHES,
				 FALSE))
		intel->debug_flush |= DEBUG_FLUSH_BATCHES;

	if (xf86ReturnOptValBool(intel->Options,
				 OPTION_DEBUG_FLUSH_CACHES,
				 FALSE))
		intel->debug_flush |= DEBUG_FLUSH_CACHES;

	if (xf86ReturnOptValBool(intel->Options,
				 OPTION_DEBUG_WAIT,
				 FALSE))
		intel->debug_flush |= DEBUG_FLUSH_WAIT;

	return TRUE;
}

static void i830_check_dri_option(ScrnInfoPtr scrn)
{
	intel_screen_private *intel = intel_get_screen_private(scrn);
	intel->directRenderingType = DRI_NONE;
	if (!xf86ReturnOptValBool(intel->Options, OPTION_DRI, TRUE))
		intel->directRenderingType = DRI_DISABLED;

	if (scrn->depth != 16 && scrn->depth != 24) {
		xf86DrvMsg(scrn->scrnIndex, X_CONFIG,
			   "DRI is disabled because it "
			   "runs only at depths 16 and 24.\n");
		intel->directRenderingType = DRI_DISABLED;
	}
}

static Bool i830_open_drm_master(ScrnInfoPtr scrn)
{
	intel_screen_private *intel = intel_get_screen_private(scrn);
	struct pci_device *dev = intel->PciInfo;
	char *busid;
	drmSetVersion sv;
	struct drm_i915_getparam gp;
	int err, has_gem;

	/* We wish we had asprintf, but all we get is XNFprintf. */
	busid = XNFprintf("pci:%04x:%02x:%02x.%d",
			  dev->domain, dev->bus, dev->dev, dev->func);

	intel->drmSubFD = drmOpen("i915", busid);
	if (intel->drmSubFD == -1) {
		xfree(busid);
		xf86DrvMsg(scrn->scrnIndex, X_ERROR,
			   "[drm] Failed to open DRM device for %s: %s\n",
			   busid, strerror(errno));
		return FALSE;
	}

	xfree(busid);

	/* Check that what we opened was a master or a master-capable FD,
	 * by setting the version of the interface we'll use to talk to it.
	 * (see DRIOpenDRMMaster() in DRI1)
	 */
	sv.drm_di_major = 1;
	sv.drm_di_minor = 1;
	sv.drm_dd_major = -1;
	sv.drm_dd_minor = -1;
	err = drmSetInterfaceVersion(intel->drmSubFD, &sv);
	if (err != 0) {
		xf86DrvMsg(scrn->scrnIndex, X_ERROR,
			   "[drm] failed to set drm interface version.\n");
		drmClose(intel->drmSubFD);
		intel->drmSubFD = -1;
		return FALSE;
	}

	has_gem = FALSE;
	gp.param = I915_PARAM_HAS_GEM;
	gp.value = &has_gem;
	(void)drmCommandWriteRead(intel->drmSubFD, DRM_I915_GETPARAM,
				  &gp, sizeof(gp));
	if (!has_gem) {
		xf86DrvMsg(scrn->scrnIndex, X_ERROR,
			   "[drm] Failed to detect GEM.  Kernel 2.6.28 required.\n");
		drmClose(intel->drmSubFD);
		intel->drmSubFD = -1;
		return FALSE;
	}

	return TRUE;
}

static void i830_close_drm_master(ScrnInfoPtr scrn)
{
	intel_screen_private *intel = intel_get_screen_private(scrn);
	if (intel && intel->drmSubFD > 0) {
		drmClose(intel->drmSubFD);
		intel->drmSubFD = -1;
	}
}

static Bool I830DrmModeInit(ScrnInfoPtr scrn)
{
	intel_screen_private *intel = intel_get_screen_private(scrn);

	if (drmmode_pre_init(scrn, intel->drmSubFD, intel->cpp) == FALSE) {
		xf86DrvMsg(scrn->scrnIndex, X_ERROR,
			   "Kernel modesetting setup failed\n");
		PreInitCleanup(scrn);
		return FALSE;
	}

	i830_init_bufmgr(scrn);

	return TRUE;
}

static void I830XvInit(ScrnInfoPtr scrn)
{
	intel_screen_private *intel = intel_get_screen_private(scrn);
	MessageType from = X_PROBED;

	intel->XvPreferOverlay =
	    xf86ReturnOptValBool(intel->Options, OPTION_PREFER_OVERLAY, FALSE);

	if (xf86GetOptValInteger(intel->Options, OPTION_VIDEO_KEY,
				 &(intel->colorKey))) {
		from = X_CONFIG;
	} else if (xf86GetOptValInteger(intel->Options, OPTION_COLOR_KEY,
					&(intel->colorKey))) {
		from = X_CONFIG;
	} else {
		intel->colorKey =
		    (1 << scrn->offset.red) | (1 << scrn->offset.green) |
		    (((scrn->mask.blue >> scrn->offset.blue) - 1) <<
		     scrn->offset.blue);
		from = X_DEFAULT;
	}
	xf86DrvMsg(scrn->scrnIndex, from, "video overlay key set to 0x%x\n",
		   intel->colorKey);
}

/**
 * This is called before ScreenInit to do any require probing of screen
 * configuration.
 *
 * This code generally covers probing, module loading, option handling
 * card mapping, and RandR setup.
 *
 * Since xf86InitialConfiguration ends up requiring that we set video modes
 * in order to detect configuration, we end up having to do a lot of driver
 * setup (talking to the DRM, mapping the device, etc.) in this function.
 * As a result, we want to set up that server initialization once rather
 * that doing it per generation.
 */
static Bool I830PreInit(ScrnInfoPtr scrn, int flags)
{
	intel_screen_private *intel;
	rgb defaultWeight = { 0, 0, 0 };
	EntityInfoPtr pEnt;
	int flags24;
	Gamma zeros = { 0.0, 0.0, 0.0 };
	int drm_mode_setting;

	if (scrn->numEntities != 1)
		return FALSE;

	drm_mode_setting = i830_kernel_mode_enabled(scrn);
	if (!drm_mode_setting) {
		xf86DrvMsg(scrn->scrnIndex, X_ERROR,
			   "No kernel modesetting driver detected.\n");
		return FALSE;
	}

	pEnt = xf86GetEntityInfo(scrn->entityList[0]);

	if (flags & PROBE_DETECT)
		return TRUE;

	/* Allocate driverPrivate */
	if (!I830GetRec(scrn))
		return FALSE;

	intel = intel_get_screen_private(scrn);
	intel->pEnt = pEnt;

	scrn->displayWidth = 640;	/* default it */

	if (intel->pEnt->location.type != BUS_PCI)
		return FALSE;

	intel->PciInfo = xf86GetPciInfoForEntity(intel->pEnt->index);

	if (!i830_open_drm_master(scrn))
		xf86DrvMsg(scrn->scrnIndex, X_ERROR,
			   "Failed to become DRM master.\n");

	scrn->monitor = scrn->confScreen->monitor;
	scrn->progClock = TRUE;
	scrn->rgbBits = 8;

	flags24 = Support32bppFb | PreferConvert24to32 | SupportConvert24to32;

	if (!xf86SetDepthBpp(scrn, 0, 0, 0, flags24))
		return FALSE;

	switch (scrn->depth) {
	case 8:
	case 15:
	case 16:
	case 24:
		break;
	default:
		xf86DrvMsg(scrn->scrnIndex, X_ERROR,
			   "Given depth (%d) is not supported by I830 driver\n",
			   scrn->depth);
		return FALSE;
	}
	xf86PrintDepthBpp(scrn);

	if (!xf86SetWeight(scrn, defaultWeight, defaultWeight))
		return FALSE;
	if (!xf86SetDefaultVisual(scrn, -1))
		return FALSE;

	intel->cpp = scrn->bitsPerPixel / 8;

	if (!I830GetEarlyOptions(scrn))
		return FALSE;

	i830_detect_chipset(scrn);

	i830_check_dri_option(scrn);

	I830XvInit(scrn);

	if (!I830DrmModeInit(scrn))
		return FALSE;

	if (!xf86SetGamma(scrn, zeros)) {
		PreInitCleanup(scrn);
		return FALSE;
	}

	if (scrn->modes == NULL) {
		xf86DrvMsg(scrn->scrnIndex, X_ERROR, "No modes.\n");
		PreInitCleanup(scrn);
		return FALSE;
	}
	scrn->currentMode = scrn->modes;

	/* Set display resolution */
	xf86SetDpi(scrn, 0, 0);

	/* Load the required sub modules */
	if (!xf86LoadSubModule(scrn, "fb")) {
		PreInitCleanup(scrn);
		return FALSE;
	}

	/* Load the dri2 module if requested. */
	if (xf86ReturnOptValBool(intel->Options, OPTION_DRI, FALSE) &&
	    intel->directRenderingType != DRI_DISABLED) {
		xf86LoadSubModule(scrn, "dri2");
	}

	return TRUE;
}

enum pipe {
	PIPE_A = 0,
	PIPE_B,
};

/**
 * Intialiazes the hardware for the 3D pipeline use in the 2D driver.
 *
 * Some state caching is performed to avoid redundant state emits.  This
 * function is also responsible for marking the state as clobbered for DRI
 * clients.
 */
void IntelEmitInvarientState(ScrnInfoPtr scrn)
{
	intel_screen_private *intel = intel_get_screen_private(scrn);

	/* If we've emitted our state since the last clobber by another client,
	 * skip it.
	 */
	if (intel->last_3d != LAST_3D_OTHER)
		return;

	if (!IS_I965G(intel)) {
		if (IS_I9XX(intel))
			I915EmitInvarientState(scrn);
		else
			I830EmitInvarientState(scrn);
	}
}

static void
I830BlockHandler(int i, pointer blockData, pointer pTimeout, pointer pReadmask)
{
	ScreenPtr screen = screenInfo.screens[i];
	ScrnInfoPtr scrn = xf86Screens[i];
	intel_screen_private *intel = intel_get_screen_private(scrn);

	screen->BlockHandler = intel->BlockHandler;

	(*screen->BlockHandler) (i, blockData, pTimeout, pReadmask);

	intel->BlockHandler = screen->BlockHandler;
	screen->BlockHandler = I830BlockHandler;

	if (scrn->vtSema) {
		Bool flush = FALSE;

		/* Emit a flush of the rendering cache, or on the 965 and beyond
		 * rendering results may not hit the framebuffer until significantly
		 * later.
		 */
		if (intel->need_mi_flush || intel->batch_used)
			flush = TRUE;

		/* Flush the batch, so that any rendering is executed in a timely
		 * fashion.
		 */
		if (flush)
			intel_batch_pipelined_flush(scrn);
		intel_batch_flush(scrn);
		drmCommandNone(intel->drmSubFD, DRM_I915_GEM_THROTTLE);

		intel->need_mi_flush = FALSE;
	}

	i830_uxa_block_handler(screen);

	I830VideoBlockHandler(i, blockData, pTimeout, pReadmask);
}

static void i830_fixup_mtrrs(ScrnInfoPtr scrn)
{
#ifdef HAS_MTRR_SUPPORT
	intel_screen_private *intel = intel_get_screen_private(scrn);
	int fd;
	struct mtrr_gentry gentry;
	struct mtrr_sentry sentry;

	if ((fd = open("/proc/mtrr", O_RDONLY, 0)) != -1) {
		for (gentry.regnum = 0;
		     ioctl(fd, MTRRIOC_GET_ENTRY, &gentry) == 0;
		     ++gentry.regnum) {

			if (gentry.size < 1) {
				/* DISABLED */
				continue;
			}

			/* Check the MTRR range is one we like and if not - remove it.
			 * The Xserver common layer will then setup the right range
			 * for us.
			 */
			if (gentry.base == intel->LinearAddr &&
			    gentry.size < intel->FbMapSize) {

				xf86DrvMsg(scrn->scrnIndex, X_INFO,
					   "Removing bad MTRR range (base 0x%lx, size 0x%x)\n",
					   gentry.base, gentry.size);

				sentry.base = gentry.base;
				sentry.size = gentry.size;
				sentry.type = gentry.type;

				if (ioctl(fd, MTRRIOC_DEL_ENTRY, &sentry) == -1) {
					xf86DrvMsg(scrn->scrnIndex, X_ERROR,
						   "Failed to remove bad MTRR range\n");
				}
			}
		}
		close(fd);
	}
#endif
}

static Bool i830_try_memory_allocation(ScrnInfoPtr scrn)
{
	intel_screen_private *intel = intel_get_screen_private(scrn);
	Bool tiled = intel->tiling;

	xf86DrvMsg(scrn->scrnIndex, X_INFO,
		   "Attempting memory allocation with %stiled buffers.\n",
		   tiled ? "" : "un");

	if (!i830_allocate_2d_memory(scrn))
		goto failed;

	xf86DrvMsg(scrn->scrnIndex, X_INFO, "%siled allocation successful.\n",
		   tiled ? "T" : "Unt");
	return TRUE;

failed:
	xf86DrvMsg(scrn->scrnIndex, X_INFO, "%siled allocation failed.\n",
		   tiled ? "T" : "Unt");
	return FALSE;
}

/*
 * Try to allocate memory in several ways:
 *  1) If direct rendering is enabled, try to allocate enough memory for tiled
 *     surfaces by rounding up the display width to a tileable one.
 *  2) If that fails or the allocations themselves fail, try again with untiled
 *     allocations (if this works DRI will stay enabled).
 *  3) And if all else fails, disable DRI and try just 2D allocations.
 *  4) Give up and fail ScreenInit.
 */
static Bool i830_memory_init(ScrnInfoPtr scrn)
{
	intel_screen_private *intel = intel_get_screen_private(scrn);
	int savedDisplayWidth = scrn->displayWidth;
	Bool tiled = FALSE;

	tiled = i830_tiled_width(intel, &scrn->displayWidth, intel->cpp);
	/* Set up our video memory allocator for the chosen videoRam */
	if (!i830_allocator_init(scrn, scrn->videoRam * KB(1))) {
		xf86DrvMsg(scrn->scrnIndex, X_ERROR,
			   "Couldn't initialize video memory allocator\n");
		PreInitCleanup(scrn);
		return FALSE;
	}

	xf86DrvMsg(scrn->scrnIndex,
		   intel->pEnt->device->videoRam ? X_CONFIG : X_DEFAULT,
		   "VideoRam: %d KB\n", scrn->videoRam);

	/* Tiled first if we got a good displayWidth */
	if (tiled) {
		if (i830_try_memory_allocation(scrn))
			return TRUE;
		else {
			i830_reset_allocations(scrn);
			intel->tiling = FALSE;
		}
	}

	/* If tiling fails we have to disable FBC */
	scrn->displayWidth = savedDisplayWidth;

	if (i830_try_memory_allocation(scrn))
		return TRUE;

	return FALSE;
}

void i830_init_bufmgr(ScrnInfoPtr scrn)
{
	intel_screen_private *intel = intel_get_screen_private(scrn);
	int batch_size;

	if (intel->bufmgr)
		return;

	batch_size = 4096 * 4;

	/* The 865 has issues with larger-than-page-sized batch buffers. */
	if (IS_I865G(intel))
		batch_size = 4096;

	intel->bufmgr = intel_bufmgr_gem_init(intel->drmSubFD, batch_size);
	intel_bufmgr_gem_enable_reuse(intel->bufmgr);

	list_init(&intel->batch_pixmaps);
	list_init(&intel->flush_pixmaps);
}

Bool i830_crtc_on(xf86CrtcPtr crtc)
{
	ScrnInfoPtr scrn = crtc->scrn;
	xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(scrn);
	int i, active_outputs = 0;

	/* Kernel manages CRTC status based out output config */
	for (i = 0; i < xf86_config->num_output; i++) {
		xf86OutputPtr output = xf86_config->output[i];
		if (output->crtc == crtc &&
		    drmmode_output_dpms_status(output) == DPMSModeOn)
			active_outputs++;
	}

	if (active_outputs)
		return TRUE;
	return FALSE;
}

int i830_crtc_to_pipe(xf86CrtcPtr crtc)
{
	ScrnInfoPtr scrn = crtc->scrn;
	intel_screen_private *intel = intel_get_screen_private(scrn);

	return drmmode_get_pipe_from_crtc_id(intel->bufmgr, crtc);
}

static Bool
I830ScreenInit(int scrnIndex, ScreenPtr screen, int argc, char **argv)
{
	ScrnInfoPtr scrn = xf86Screens[screen->myNum];
	intel_screen_private *intel = intel_get_screen_private(scrn);
	VisualPtr visual;
	MessageType from;
	struct pci_device *const device = intel->PciInfo;
	int fb_bar = IS_I9XX(intel) ? 2 : 0;

	scrn->displayWidth =
	    i830_pad_drawable_width(scrn->virtualX, intel->cpp);

	/*
	 * The "VideoRam" config file parameter specifies the maximum amount of
	 * memory that will be used/allocated.  When not present, we allow the
	 * driver to allocate as much memory as it wishes to satisfy its
	 * allocations, but if agpgart support isn't available, it gets limited
	 * to the amount of pre-allocated ("stolen") memory.
	 *
	 * Note that in using this value for allocator initialization, we're
	 * limiting aperture allocation to the VideoRam option, rather than limiting
	 * actual memory allocation, so alignment and things will cause less than
	 * VideoRam to be actually used.
	 */
	if (intel->pEnt->device->videoRam == 0) {
		from = X_DEFAULT;
		scrn->videoRam = intel->FbMapSize / KB(1);
	} else {
#if 0
		from = X_CONFIG;
		scrn->videoRam = intel->pEnt->device->videoRam;
#else
		/* Disable VideoRam configuration, at least for now.  Previously,
		 * VideoRam was necessary to avoid overly low limits on allocated
		 * memory, so users created larger, yet still small, fixed allocation
		 * limits in their config files.  Now, the driver wants to allocate more,
		 * and the old intention of the VideoRam lines that had been entered is
		 * obsolete.
		 */
		from = X_DEFAULT;
		scrn->videoRam = intel->FbMapSize / KB(1);

		if (scrn->videoRam != intel->pEnt->device->videoRam) {
			xf86DrvMsg(scrn->scrnIndex, X_WARNING,
				   "VideoRam configuration found, which is no longer "
				   "recommended.\n");
			xf86DrvMsg(scrn->scrnIndex, X_INFO,
				   "Continuing with default %dkB VideoRam instead of %d "
				   "kB.\n",
				   scrn->videoRam,
				   intel->pEnt->device->videoRam);
		}
#endif
	}

	scrn->videoRam = device->regions[fb_bar].size / 1024;

#ifdef DRI2
	if (intel->directRenderingType == DRI_NONE
	    && I830DRI2ScreenInit(screen))
		intel->directRenderingType = DRI_DRI2;
#endif

	/* Enable tiling by default */
	intel->tiling = TRUE;

	/* Allow user override if they set a value */
	if (xf86IsOptionSet(intel->Options, OPTION_TILING)) {
		if (xf86ReturnOptValBool(intel->Options, OPTION_TILING, FALSE))
			intel->tiling = TRUE;
		else
			intel->tiling = FALSE;
	}

	/* SwapBuffers delays to avoid tearing */
	intel->swapbuffers_wait = TRUE;

	/* Allow user override if they set a value */
	if (xf86IsOptionSet(intel->Options, OPTION_SWAPBUFFERS_WAIT)) {
		if (xf86ReturnOptValBool
		    (intel->Options, OPTION_SWAPBUFFERS_WAIT, FALSE))
			intel->swapbuffers_wait = TRUE;
		else
			intel->swapbuffers_wait = FALSE;
	}

	xf86DrvMsg(scrn->scrnIndex, X_CONFIG, "Tiling %sabled\n",
		   intel->tiling ? "en" : "dis");
	xf86DrvMsg(scrn->scrnIndex, X_CONFIG, "SwapBuffers wait %sabled\n",
		   intel->swapbuffers_wait ? "en" : "dis");

	intel->last_3d = LAST_3D_OTHER;
	intel->overlayOn = FALSE;

	/*
	 * Set this so that the overlay allocation is factored in when
	 * appropriate.
	 */
	intel->XvEnabled = TRUE;

	if (!i830_memory_init(scrn)) {
		xf86DrvMsg(scrn->scrnIndex, X_ERROR,
			   "Couldn't allocate video memory\n");
		return FALSE;
	}

	i830_fixup_mtrrs(scrn);

	miClearVisualTypes();
	if (!miSetVisualTypes(scrn->depth,
			      miGetDefaultVisualMask(scrn->depth),
			      scrn->rgbBits, scrn->defaultVisual))
		return FALSE;
	if (!miSetPixmapDepths())
		return FALSE;

	DPRINTF(PFX, "assert( if(!I830EnterVT(scrnIndex, 0)) )\n");

	if (scrn->virtualX > scrn->displayWidth)
		scrn->displayWidth = scrn->virtualX;

	/* If the front buffer is not a BO, we need to
	 * set the initial framebuffer pixmap to point at
	 * it
	 */
	scrn->fbOffset = intel->front_buffer->offset;

	DPRINTF(PFX, "assert( if(!fbScreenInit(screen, ...) )\n");
	if (!fbScreenInit(screen, NULL,
			  scrn->virtualX, scrn->virtualY,
			  scrn->xDpi, scrn->yDpi,
			  scrn->displayWidth, scrn->bitsPerPixel))
		return FALSE;

	if (scrn->bitsPerPixel > 8) {
		/* Fixup RGB ordering */
		visual = screen->visuals + screen->numVisuals;
		while (--visual >= screen->visuals) {
			if ((visual->class | DynamicClass) == DirectColor) {
				visual->offsetRed = scrn->offset.red;
				visual->offsetGreen = scrn->offset.green;
				visual->offsetBlue = scrn->offset.blue;
				visual->redMask = scrn->mask.red;
				visual->greenMask = scrn->mask.green;
				visual->blueMask = scrn->mask.blue;
			}
		}
	}

	fbPictureInit(screen, NULL, 0);

	xf86SetBlackWhitePixels(screen);

	if (!I830AccelInit(screen)) {
		xf86DrvMsg(scrn->scrnIndex, X_ERROR,
			   "Hardware acceleration initialization failed\n");
		return FALSE;
	}

	if (IS_I965G(intel))
		intel->batch_flush_notify = i965_batch_flush_notify;
	else if (IS_I9XX(intel))
		intel->batch_flush_notify = i915_batch_flush_notify;
	else
		intel->batch_flush_notify = i830_batch_flush_notify;

	miInitializeBackingStore(screen);
	xf86SetBackingStore(screen);
	xf86SetSilkenMouse(screen);
	miDCInitialize(screen, xf86GetPointerScreenFuncs());

	xf86DrvMsg(scrn->scrnIndex, X_INFO, "Initializing HW Cursor\n");

	if (!xf86_cursors_init(screen, I810_CURSOR_X, I810_CURSOR_Y,
			       (HARDWARE_CURSOR_TRUECOLOR_AT_8BPP |
				HARDWARE_CURSOR_BIT_ORDER_MSBFIRST |
				HARDWARE_CURSOR_INVERT_MASK |
				HARDWARE_CURSOR_SWAP_SOURCE_AND_MASK |
				HARDWARE_CURSOR_AND_SOURCE_WITH_MASK |
				HARDWARE_CURSOR_SOURCE_MASK_INTERLEAVE_64 |
				HARDWARE_CURSOR_UPDATE_UNHIDDEN |
				HARDWARE_CURSOR_ARGB))) {
		xf86DrvMsg(scrn->scrnIndex, X_ERROR,
			   "Hardware cursor initialization failed\n");
	}

	/* Must force it before EnterVT, so we are in control of VT and
	 * later memory should be bound when allocating, e.g rotate_mem */
	scrn->vtSema = TRUE;

	if (!I830EnterVT(scrnIndex, 0))
		return FALSE;

	intel->BlockHandler = screen->BlockHandler;
	screen->BlockHandler = I830BlockHandler;

	screen->SaveScreen = xf86SaveScreen;
	intel->CloseScreen = screen->CloseScreen;
	screen->CloseScreen = I830CloseScreen;
	intel->CreateScreenResources = screen->CreateScreenResources;
	screen->CreateScreenResources = i830CreateScreenResources;

	if (!xf86CrtcScreenInit(screen))
		return FALSE;

	DPRINTF(PFX, "assert( if(!miCreateDefColormap(screen)) )\n");
	if (!miCreateDefColormap(screen))
		return FALSE;

	DPRINTF(PFX, "assert( if(!xf86HandleColormaps(screen, ...)) )\n");
	if (!xf86HandleColormaps(screen, 256, 8, I830LoadPalette, NULL,
				 CMAP_RELOAD_ON_MODE_SWITCH |
				 CMAP_PALETTED_TRUECOLOR)) {
		return FALSE;
	}

	xf86DPMSInit(screen, xf86DPMSSet, 0);

#ifdef INTEL_XVMC
	if (IS_I965G(intel))
		intel->XvMCEnabled = TRUE;
	from = ((intel->directRenderingType == DRI_DRI2) &&
		xf86GetOptValBool(intel->Options, OPTION_XVMC,
				  &intel->XvMCEnabled) ? X_CONFIG : X_DEFAULT);
	xf86DrvMsg(scrn->scrnIndex, from, "Intel XvMC decoder %sabled\n",
		   intel->XvMCEnabled ? "en" : "dis");
#endif
	/* Init video */
	if (intel->XvEnabled)
		I830InitVideo(screen);

#if defined(DRI2)
	switch (intel->directRenderingType) {
	case DRI_DRI2:
		intel->directRenderingOpen = TRUE;
		xf86DrvMsg(scrn->scrnIndex, X_INFO,
			   "direct rendering: DRI2 Enabled\n");
		break;
	case DRI_DISABLED:
		xf86DrvMsg(scrn->scrnIndex, X_INFO,
			   "direct rendering: Disabled\n");
		break;
	case DRI_NONE:
		xf86DrvMsg(scrn->scrnIndex, X_INFO,
			   "direct rendering: Failed\n");
		break;
	}
#else
	xf86DrvMsg(scrn->scrnIndex, X_INFO,
		   "direct rendering: Not available\n");
#endif

	if (serverGeneration == 1)
		xf86ShowUnusedOptions(scrn->scrnIndex, scrn->options);

	intel->suspended = FALSE;

	return TRUE;
}

static void i830AdjustFrame(int scrnIndex, int x, int y, int flags)
{
}

static void I830FreeScreen(int scrnIndex, int flags)
{
	ScrnInfoPtr scrn = xf86Screens[scrnIndex];
#ifdef INTEL_XVMC
	intel_screen_private *intel = intel_get_screen_private(scrn);
	if (intel && intel->XvMCEnabled)
		intel_xvmc_finish(xf86Screens[scrnIndex]);
#endif

	i830_close_drm_master(scrn);

	I830FreeRec(xf86Screens[scrnIndex]);
	if (xf86LoaderCheckSymbol("vgaHWFreeHWRec"))
		vgaHWFreeHWRec(xf86Screens[scrnIndex]);
}

static void I830LeaveVT(int scrnIndex, int flags)
{
	ScrnInfoPtr scrn = xf86Screens[scrnIndex];
	intel_screen_private *intel = intel_get_screen_private(scrn);
	int ret;

	DPRINTF(PFX, "Leave VT\n");

	xf86RotateFreeShadow(scrn);

	xf86_hide_cursors(scrn);

	intel_sync(scrn);

	intel_batch_teardown(scrn);

	if (IS_I965G(intel))
		gen4_render_state_cleanup(scrn);

	ret = drmDropMaster(intel->drmSubFD);
	if (ret)
		xf86DrvMsg(scrn->scrnIndex, X_WARNING,
			   "drmDropMaster failed: %s\n", strerror(errno));
}

/*
 * This gets called when gaining control of the VT, and from ScreenInit().
 */
static Bool I830EnterVT(int scrnIndex, int flags)
{
	ScrnInfoPtr scrn = xf86Screens[scrnIndex];
	intel_screen_private *intel = intel_get_screen_private(scrn);
	int ret;

	DPRINTF(PFX, "Enter VT\n");

	ret = drmSetMaster(intel->drmSubFD);
	if (ret) {
		if (errno == EINVAL) {
			xf86DrvMsg(scrn->scrnIndex, X_WARNING,
				   "drmSetMaster failed: 2.6.29 or newer kernel required for "
				   "multi-server DRI\n");
		} else {
			xf86DrvMsg(scrn->scrnIndex, X_WARNING,
				   "drmSetMaster failed: %s\n",
				   strerror(errno));
		}
	}

	if (!i830_bind_all_memory(scrn))
		return FALSE;

	i830_describe_allocations(scrn, 1, "");

	intel_batch_init(scrn);

	if (IS_I965G(intel))
		gen4_render_state_init(scrn);

	if (!xf86SetDesiredModes(scrn))
		return FALSE;

	/* Mark all state as being clobbered. */
	intel->last_3d = LAST_3D_OTHER;

	return TRUE;
}

static Bool I830SwitchMode(int scrnIndex, DisplayModePtr mode, int flags)
{
	ScrnInfoPtr scrn = xf86Screens[scrnIndex];

	return xf86SetSingleMode(scrn, mode, RR_Rotate_0);
}

static Bool I830CloseScreen(int scrnIndex, ScreenPtr screen)
{
	ScrnInfoPtr scrn = xf86Screens[scrnIndex];
	intel_screen_private *intel = intel_get_screen_private(scrn);

	if (scrn->vtSema == TRUE) {
		I830LeaveVT(scrnIndex, 0);
	}

	if (intel->uxa_driver) {
		uxa_driver_fini(screen);
		xfree(intel->uxa_driver);
		intel->uxa_driver = NULL;
	}
	if (intel->front_buffer) {
		i830_set_pixmap_bo(screen->GetScreenPixmap(screen), NULL);
		drmmode_closefb(scrn);
		i830_free_memory(scrn, intel->front_buffer);
		intel->front_buffer = NULL;
	}

	xf86_cursors_fini(screen);

	i830_allocator_fini(scrn);

	i965_free_video(scrn);

	screen->CloseScreen = intel->CloseScreen;
	(*screen->CloseScreen) (scrnIndex, screen);

	if (intel->directRenderingOpen
	    && intel->directRenderingType == DRI_DRI2) {
		intel->directRenderingOpen = FALSE;
		I830DRI2CloseScreen(screen);
	}

	xf86GARTCloseScreen(scrnIndex);

	scrn->vtSema = FALSE;
	return TRUE;
}

static ModeStatus
I830ValidMode(int scrnIndex, DisplayModePtr mode, Bool verbose, int flags)
{
	if (mode->Flags & V_INTERLACE) {
		if (verbose) {
			xf86DrvMsg(scrnIndex, X_PROBED,
				   "Removing interlaced mode \"%s\"\n",
				   mode->name);
		}
		return MODE_BAD;
	}
	return MODE_OK;
}

#ifndef SUSPEND_SLEEP
#define SUSPEND_SLEEP 0
#endif
#ifndef RESUME_SLEEP
#define RESUME_SLEEP 0
#endif

/*
 * This function is only required if we need to do anything differently from
 * DoApmEvent() in common/xf86PM.c, including if we want to see events other
 * than suspend/resume.
 */
static Bool I830PMEvent(int scrnIndex, pmEvent event, Bool undo)
{
	ScrnInfoPtr scrn = xf86Screens[scrnIndex];
	intel_screen_private *intel = intel_get_screen_private(scrn);

	DPRINTF(PFX, "Enter VT, event %d, undo: %s\n", event,
		BOOLTOSTRING(undo));

	switch (event) {
	case XF86_APM_SYS_SUSPEND:
	case XF86_APM_CRITICAL_SUSPEND:	/*do we want to delay a critical suspend? */
	case XF86_APM_USER_SUSPEND:
	case XF86_APM_SYS_STANDBY:
	case XF86_APM_USER_STANDBY:
		if (!undo && !intel->suspended) {
			scrn->LeaveVT(scrnIndex, 0);
			intel->suspended = TRUE;
			sleep(SUSPEND_SLEEP);
		} else if (undo && intel->suspended) {
			sleep(RESUME_SLEEP);
			scrn->EnterVT(scrnIndex, 0);
			intel->suspended = FALSE;
		}
		break;
	case XF86_APM_STANDBY_RESUME:
	case XF86_APM_NORMAL_RESUME:
	case XF86_APM_CRITICAL_RESUME:
		if (intel->suspended) {
			sleep(RESUME_SLEEP);
			scrn->EnterVT(scrnIndex, 0);
			intel->suspended = FALSE;
			/*
			 * Turn the screen saver off when resuming.  This seems to be
			 * needed to stop xscreensaver kicking in (when used).
			 *
			 * XXX DoApmEvent() should probably call this just like
			 * xf86VTSwitch() does.  Maybe do it here only in 4.2
			 * compatibility mode.
			 */
			SaveScreens(SCREEN_SAVER_FORCER, ScreenSaverReset);
		}
		break;
		/* This is currently used for ACPI */
	case XF86_APM_CAPABILITY_CHANGED:
		ErrorF("I830PMEvent: Capability change\n");

		SaveScreens(SCREEN_SAVER_FORCER, ScreenSaverReset);

		break;
	default:
		ErrorF("I830PMEvent: received APM event %d\n", event);
	}
	return TRUE;
}

xf86CrtcPtr i830_pipe_to_crtc(ScrnInfoPtr scrn, int pipe)
{
	xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR(scrn);
	int c;

	for (c = 0; c < config->num_crtc; c++) {
		xf86CrtcPtr crtc = config->crtc[c];
		I830CrtcPrivatePtr intel_crtc = crtc->driver_private;

		if (intel_crtc->pipe == pipe)
			return crtc;
	}

	return NULL;
}

void intel_init_scrn(ScrnInfoPtr scrn)
{
	scrn->PreInit = I830PreInit;
	scrn->ScreenInit = I830ScreenInit;
	scrn->SwitchMode = I830SwitchMode;
	scrn->AdjustFrame = i830AdjustFrame;
	scrn->EnterVT = I830EnterVT;
	scrn->LeaveVT = I830LeaveVT;
	scrn->FreeScreen = I830FreeScreen;
	scrn->ValidMode = I830ValidMode;
	scrn->PMEvent = I830PMEvent;
}